Compare commits

...
Author SHA1 Message Date
dependabot[bot] 1c779c4731 build(deps): bump github/codeql-action from 4.39.3 to 4.39.4
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.3 to 4.39.4.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v4.39.3...v4.39.4)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 4.39.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-23 18:14:59 +00:00
430ca2b585 filer: path- and method-scoped gRPC tokens (scope enforcement, fail closed) (#12904)
* filer: path- and method-scoped tokens on the filesystem gRPC service

* filer: close scoped admission and compatibility gaps

* filer: test subscription key ambiguity and retained write success

* filer: assert verified peer chains survive subscription fallback

* filer: keep a hard link's count and chunks together under a scoped token

A scoped write may keep a hard link the target already has, but the link
count it sends was stored as is, and its chunks could stay on the name
with the link dropped. Either let a scoped token delete its own name and
take the chunks of a name outside its grants with it: the forged count
reaches zero, or the detached name owns the shared chunks.

The handler recheck now refuses a scoped write that changes a stored
link's count or keeps its chunks without the link. Dropping the link
together with the data, and appending to a linked file, are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: leave subscriptions with a non-scope bearer to the existing verifier

The stream interceptor refused a SubscribeMetadata or SubscribeLocalMetadata
call whose bearer does not verify under the filer key unless the bearer was
a subscription token, and it checked that token with the peer stripped. With
no subscription key, or on an mTLS peer, the existing verifier admits such a
call, so filer.sync sending another cluster's admin token stopped.

When the bearer is no filer scope, the subscription verifier now decides on
the original context, as before scoped tokens. A scoped token still reaches
the refusal for scoped subscriptions, and malformed metadata is still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse scoped writes that would make ancestors outside the grant

A scoped create, append or rename checked only its target. The filer then
creates the target's missing ancestors up to the first one it finds, and
turns that one into a directory if it is a file, dropping its ttl. A token
granted /data/proj/ws could so promote the file /data/proj, or create /q and
/q/r for a grant /q/r/ws.

The scope now walks the same ancestors before admitting the write and
refuses one outside the write grants that is missing or not a directory. A
create with skip_check_parent_directory makes no ancestors and is not
walked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: require write grants for scoped lock mutations

* filer: document scoped signatures and read-only token upgrades

* filer: enforce WORM retention for scoped mutations

* filer: refuse scoped writes through shared hard links

* filer: drop series notes from scope comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse scoped subtree mutations across WORM rules

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:45:34 -08:00
Chris LuandClaude Opus 5.5 7933dd2205 test(s3vectors): drop the worker and CLI flags #12906 removed (#12911)
* test(s3vectors): start weed-worker with only --admin

weed-worker no longer accepts --namespace, --masters or --filer-group; it
takes the Lance Namespace and the filers from admin. The worker jobs passed
all three, so the worker exited on its arguments before registering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(s3vectors): let weed-vector-cli find the namespace through the masters

weed-vector-cli dropped --namespace and looks the Lance Namespace up among
the gateways the masters list, so the index job test failed on its
arguments once the worker could register.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:41:44 -08:00
Chris LuandClaude Opus 5.5 2d570ccb2f weed-vector: compare cgroup limit paths with / separators in the test (#12919)
Windows joins with a backslash, so the Windows desktop build failed
looks_up_the_process_group_and_its_ancestors.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:41:17 -08:00
vic6996-webandvic6996-web 01df591d59 glog: make -stderrthreshold work under -logtostderr and the default -alsologtostderr (#12916)
* glog: honor an explicit -stderrthreshold under -logtostderr and the default -alsologtostderr

* glog: print the goroutine dump of a FATAL to stderr under -logtostderr

* glog: keep a FATAL's goroutine dump in JSON lines under -log_json

* glog: let an explicit -alsologtostderr=true win under -logtostderr too

---------

Co-authored-by: vic6996-web <320442181+vic6996-web@users.noreply.github.com>
2026-11-23 08:40:38 -08:00
Chris LuandClaude Opus 5.5 ae0f1a2525 mount: delete chunks overwritten before their first publication (#12910)
* mount: send covered chunks no stored entry named, so the filer deletes them

A flush compacts the handle's chunks before it publishes them, dropping
chunks later writes fully cover. The filer deletes only the chunks the
stored entry loses and the ones the request itself covers, so a chunk
uploaded and then overwritten before any publication named it (a file
rewritten in place before close, like FFmpeg's +faststart pass) was left
on the volume servers with no reference.

Both the close flush and the periodic metadata flush now carry those
chunks along in the request, after the base snapshot, when the request's
own plain chunks still cover them; the filer compacts them out and
deletes them after the commit. Chunks rewritten by a merge are stamped 0
and the filer does not look into manifests, so a chunk that would show
through again is not sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test that flushes hand covered unpublished chunks to the filer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check each covered chunk against the request's own chunks

The coverage check compacted the dropped chunks together with the
request's, so one dropped chunk could hide another. Only the request's
chunks reach the filer with it: after a merge, whose chunks are stamped
0, an older dropped chunk hidden only by a newer dropped one would show
through and the filer would delete the merged chunk instead.

Each dropped chunk is now sent only if newer visible plain chunks of the
request hide all of its range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:30:55 -08:00
Chris LuandClaude Opus 5.5 a551b7c7e6 weed-vector: size the caches itself, drop the tuning, config-dir and CLI namespace flags (#12906)
* master, s3: an S3 gateway advertises its Lance Namespace port

The gateway registers with the master already; it now says which port its
Lance Namespace listens on, and ListClusterNodes returns it, so admin can
tell workers where the catalog is instead of each deployment configuring it.

* admin: tell workers where the Lance Namespace is

Each S3 gateway that serves a Lance Namespace is now in the cluster context
admin sends with every request, and a preview request carries the context
too, so a worker can be pointed at admin alone.

* seaweed-worker: take the filers and the Lance Namespace from admin

Admin names both with every request, as it does for the Go worker, so
weed-worker needs only --admin. --namespace is used when admin names no
namespace, as an admin or gateways from before they could do so name none.
--masters and --filer-group are accepted and ignored; the filer group is the
one the filers report.

* helm: weed-worker needs only the admin address

The Lance container no longer derives a namespace URL or passes the masters
and filer group; worker.namespaceUrl, when set, is the worker's fallback.

* s3: advertise the Lance port only once its listener has bound

A gateway whose Lance port was taken kept advertising it, so workers that
picked that gateway sent every Lance request to a port nobody served.
The listener now binds before the master registration, and the port
reaches the master only when the bind succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: stop waiting for the cluster context at the caller's deadline

The admin provider builds the context with context.Background(), so a
master outage held a preview, which now loads the context before it is
sent, past its own deadline. Loading the context now returns when the
caller's context ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: keep giving the Lance worker its masters, group and namespace

A worker image pinned to 4.55 or older needs the masters and the
namespace and exits without them, and a 4.56 worker under an older admin
needs the namespace. The chart now passes all three through the
environment, which a 4.56 worker reads only when admin names nothing,
and the namespace again defaults to the S3 service's Lance port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: give admin the filer group

Admin lists filers and S3 gateways from its own group, and the Lance
worker now takes its filers from admin, so with filer.filerGroup set the
worker had no filers. Admin now gets the group; an -filerGroup in
admin.extraArgs still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-worker: drop --namespace, --masters and --filer-group

Admin names the namespace and the filers with every request, so the worker
takes them from there alone. Handlers and the preview hold the admin-fed
cluster, which also carries the signing key. The live tests get the filer
through WEED_FILER and feed it to the worker as admin would.

* helm: drop worker.namespaceUrl

A worker from 4.56 takes the namespace from admin and has no option for it,
so the value could only reach a pinned older image; the environment still
gives one the S3 service's namespace, masters and filer group.

* weed-vector: size the caches itself, and drop the tuning and config-dir flags

The engine caches a quarter of the memory it may use, its cgroup limit or
the machine's, split 2:4:1 between file reads, loaded indexes and table
metadata as the three flags' defaults were, so a small pod is not
overcommitted and a large host is used. --read-cache-mb, --index-cache-mb,
--metadata-cache-mb, --nprobes and --exact-match-limit are gone, and with
them the perf test's cold mode. --config-dir is gone too: weed mini passes
the security.toml it finds there.

* weed-vector-cli: find the Lance Namespace through the masters

A table id is looked up in the namespace of an S3 gateway the masters
list, so --namespace is gone; a local path still needs no cluster.

* helm: weed-vector sizes its own caches

vector.readCacheMB and vector.nprobes are gone with the engine's flags; an
older pinned image keeps its own defaults.

* weed-vector: size the caches from the process's own memory cgroup

A systemd service is limited in its own group below the cgroup root, which
the root's limit file does not show. The engine now reads its group from
/proc/self/cgroup and takes the smallest limit of it and its ancestors.

* mini: leave an explicit WEED_VECTOR_SECURITY_TOML to the engine

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:10:01 -08:00
6adc9f0a21 mount: read chunks with filer-issued exact-file read tokens (#12800)
* mount: read chunks with filer-issued exact-file read tokens

* mount: preserve read authorization across delayed lookups and hard links

* mount: retain response tokens across read cache eviction

* mount: keep a shared read-token lookup alive when its first caller is cancelled

Token refreshes for one entry share a singleflight lookup that ran under
the first caller's context. An interrupted read cancelled that lookup, so
every other read of the entry waiting on it got no token, went out
unauthenticated, and failed with EIO on a volume server enforcing read
JWTs. Run the lookup detached from the caller (each attempt stays bounded
by the filer RPC wait) and let a cancelled caller stop waiting at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: serve a cached chunk past the cache cutoff instead of fetching it

The full-chunk read path consulted the chunk cache only for chunks below
the cache size cutoff. Read-auth and peer-sharing mounts cache every
chunk they upload, so a read-after-write of a high-offset chunk went to
the volume, where a read-auth mount has no token before the entry is
published.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: re-track read tokens when this mount renames an open file

Writeback mounts skip their own rename event, so only the subscriber
path re-tracked an open handle's chunks. After a local rename a token
refresh looked up the vacated name and the read failed. The rename
response, the subscriber rename and the surviving hard link now share
ReadAuth.TrackHandle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:07:14 -08:00
Chris LuandClaude Opus 5.5 548d8f1b42 weed-worker: take the cluster from admin, need only --admin (#12905)
* master, s3: an S3 gateway advertises its Lance Namespace port

The gateway registers with the master already; it now says which port its
Lance Namespace listens on, and ListClusterNodes returns it, so admin can
tell workers where the catalog is instead of each deployment configuring it.

* admin: tell workers where the Lance Namespace is

Each S3 gateway that serves a Lance Namespace is now in the cluster context
admin sends with every request, and a preview request carries the context
too, so a worker can be pointed at admin alone.

* seaweed-worker: take the filers and the Lance Namespace from admin

Admin names both with every request, as it does for the Go worker, so
weed-worker needs only --admin. --namespace is used when admin names no
namespace, as an admin or gateways from before they could do so name none.
--masters and --filer-group are accepted and ignored; the filer group is the
one the filers report.

* helm: weed-worker needs only the admin address

The Lance container no longer derives a namespace URL or passes the masters
and filer group; worker.namespaceUrl, when set, is the worker's fallback.

* s3: advertise the Lance port only once its listener has bound

A gateway whose Lance port was taken kept advertising it, so workers that
picked that gateway sent every Lance request to a port nobody served.
The listener now binds before the master registration, and the port
reaches the master only when the bind succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: stop waiting for the cluster context at the caller's deadline

The admin provider builds the context with context.Background(), so a
master outage held a preview, which now loads the context before it is
sent, past its own deadline. Loading the context now returns when the
caller's context ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: keep giving the Lance worker its masters, group and namespace

A worker image pinned to 4.55 or older needs the masters and the
namespace and exits without them, and a 4.56 worker under an older admin
needs the namespace. The chart now passes all three through the
environment, which a 4.56 worker reads only when admin names nothing,
and the namespace again defaults to the S3 service's Lance port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: give admin the filer group

Admin lists filers and S3 gateways from its own group, and the Lance
worker now takes its filers from admin, so with filer.filerGroup set the
worker had no filers. Admin now gets the group; an -filerGroup in
admin.extraArgs still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-worker: drop --namespace, --masters and --filer-group

Admin names the namespace and the filers with every request, so the worker
takes them from there alone. Handlers and the preview hold the admin-fed
cluster, which also carries the signing key. The live tests get the filer
through WEED_FILER and feed it to the worker as admin would.

* helm: drop worker.namespaceUrl

A worker from 4.56 takes the namespace from admin and has no option for it,
so the value could only reach a pinned older image; the environment still
gives one the S3 service's namespace, masters and filer group.

* seaweed-worker: keep the last known namespaces while admin lists none

When a master call fails, admin still sends its cached filers but no S3
gateways. With no --namespace fallback left, that emptied the worker's
namespaces and failed every Lance job until the master answered again,
though the gateways serve the namespace without it. The namespaces are
now kept like the filers are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: run the Lance container for the filer's S3 gateway and an external admin

The container was left out whenever the chart's own S3 gateway served no
Lance namespace. A filer's embedded gateway serves one too, and an external
admin names its cluster's, so both now get it; the namespace variable for a
pinned older worker is set only when the chart's gateway serves one.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:05:54 -08:00
Chris LuandClaude Opus 5.5 381f8d2c94 volume, seaweed-volume: re-forward a deleted EC read's delete to the holders that read it deleted (#12903)
* storage: re-forward a deleted EC read's delete to the holders that read it deleted

The retry used first-success routing, which can stop at another copy of
the primary shard (a quarantined local one, or a replica that never saw
the delete) and leave the reporting holder's other disk live. Probe each
primary shard holder with a one-byte read and forward to those answering
deleted; with no such holder, fall back to normal routing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: re-forward a deleted EC read's delete to the holders that read it deleted

Mirror Go: probe each primary shard holder with a one-byte read and
forward the delete to those answering deleted, so the retry cannot stop
at another copy and leave the reporting holder's other disk live; with
no such holder, fall back to normal routing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: bound each delete-retry probe with the read-hint timeout

A holder that keeps the stream open without answering held the delete's
reply, even after the reporting holder took the delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: bound each delete-retry probe with the read-hint timeout

Mirror Go: a stalled holder's probe gives up after EC_READ_HINT_TIMEOUT
and the retry moves on to the next holder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: bound each delete a retry forwards

A holder that answers the probe deleted but stalls on the delete held the
reply and the holders after it. The Rust server already bounds this call
at 10 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:18:40 -08:00
137 changed files with 8243 additions and 831 deletions

No files matched your search

+3 -3
View File
@@ -33,7 +33,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4.39.3
uses: github/codeql-action/init@v4.39.4
# Override language selection by uncommenting this and choosing your languages
with:
languages: go
@@ -41,7 +41,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v4.39.3
uses: github/codeql-action/autobuild@v4.39.4
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -55,4 +55,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4.39.3
uses: github/codeql-action/analyze@v4.39.4
+1 -1
View File
@@ -434,7 +434,7 @@ jobs:
output: trivy-results.sarif
exit-code: '0'
- name: Upload Trivy scan results to GitHub Security
uses: github/codeql-action/upload-sarif@v4.39.3
uses: github/codeql-action/upload-sarif@v4.39.4
if: always()
with:
sarif_file: trivy-results.sarif
@@ -515,7 +515,7 @@ jobs:
- name: Upload Trivy scan results to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v4.39.3
uses: github/codeql-action/upload-sarif@v4.39.4
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
+1 -1
View File
@@ -729,7 +729,7 @@ global:
The engine registers its pod address with the masters and stores indexes through the filers and volume servers. Both Go and Rust volume servers use the same setup. The maintenance worker builds and updates ANN indexes; queries can scan data before indexing completes. Enabling filer write signing also requires clients writing directly to the filer HTTP API to supply a signed JWT.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The cache defaults to 512 MiB and is configured with `vector.readCacheMB`.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The engine sizes its caches to a quarter of its memory limit.
`global.seaweedfs.enableSecurity` provisions and mounts the vector certificate and shared security configuration. With external certificates, provide the `<fullname>-vector-cert` secret (`my-seaweedfs-vector-cert` for release `my`). `fullname` follows `seaweedfs.fullname`, including `fullnameOverride`, `nameOverride`, and DNS-name truncation. Provide this secret alongside the existing CA and client secrets.
@@ -189,6 +189,10 @@ spec:
{{- else }}
-masters={{ range $index := until (.Values.master.replicas | int) }}${SEAWEEDFS_FULLNAME}-master-{{ $index }}.${SEAWEEDFS_FULLNAME}-master.{{ include "seaweedfs.namespace" $ }}:{{ $.Values.master.port }}{{ if lt $index (sub ($.Values.master.replicas | int) 1) }},{{ end }}{{ end }} \
{{- end }}
{{- /* admin lists the filers and S3 gateways the workers use from this group */}}
{{- if .Values.filer.filerGroup }}
-filerGroup={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if $urlPrefix }}
-urlPrefix={{ $urlPrefix }} \
{{- end }}
@@ -269,15 +269,20 @@ true
{{- end -}}
{{- end -}}
{{/* Lance namespace URL the worker's Lance container maintains; empty when unreachable */}}
{{/* The S3 service's Lance namespace URL, for a worker pinned before 4.56; empty when it serves none */}}
{{- define "seaweedfs.worker.lanceNamespaceUrl" -}}
{{- if .Values.worker.namespaceUrl -}}
{{- .Values.worker.namespaceUrl -}}
{{- else if and .Values.s3.enabled .Values.s3.lancePort -}}
{{- if and .Values.s3.enabled .Values.s3.lancePort -}}
{{- printf "http://%s.%s:%d" (include "seaweedfs.componentName" (list . "s3")) (include "seaweedfs.namespace" .) (int .Values.s3.lancePort) -}}
{{- end -}}
{{- end -}}
{{/* "true" when the worker runs its Lance container: an S3 gateway of this release serves a Lance namespace, or the worker serves an external admin, which names its cluster's */}}
{{- define "seaweedfs.worker.lanceEnabled" -}}
{{- if or (include "seaweedfs.worker.lanceNamespaceUrl" .) .Values.filer.s3.enabled .Values.worker.adminServer -}}
true
{{- end -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -104,7 +104,7 @@
{{- if .Values.worker.metricsPort }}
{{- $ports = append $ports .Values.worker.metricsPort }}
{{- end }}
{{- if and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- if and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- $ports = append $ports .Values.worker.lanceMetricsPort }}
{{- end }}
{{- $targets = append $targets (dict "component" "worker" "ports" $ports) }}
@@ -56,13 +56,9 @@ spec:
- 'case "$POD_IP" in *:*) POD_IP="[$POD_IP]";; esac; exec /usr/bin/weed-vector --listen="$POD_IP:{{ .Values.vector.port }}" "$@"'
- vector
- {{ printf "--masters=%s" (.Values.vector.masters | default $masters) | quote }}
- {{ printf "--read-cache-mb=%d" (int .Values.vector.readCacheMB) | quote }}
{{- if .Values.filer.filerGroup }}
- {{ printf "--filer-group=%s" .Values.filer.filerGroup | quote }}
{{- end }}
{{- if .Values.vector.nprobes }}
- {{ printf "--nprobes=%d" (int .Values.vector.nprobes) | quote }}
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- --security-toml=/etc/seaweedfs/security.toml
{{- end }}
@@ -228,7 +228,7 @@ spec:
{{- if .Values.worker.containerSecurityContext.enabled }}
securityContext: {{- omit .Values.worker.containerSecurityContext "enabled" | toYaml | nindent 12 }}
{{- end }}
{{- if include "seaweedfs.worker.lanceNamespaceUrl" . }}
{{- if include "seaweedfs.worker.lanceEnabled" . }}
- name: worker-lance
image: {{ template "seaweedfs.worker.image" . }}
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
@@ -237,13 +237,21 @@ spec:
valueFrom:
fieldRef:
fieldPath: metadata.name
{{- /* the URL crosses a shell line; metacharacters must arrive as data, not syntax */}}
- name: LANCE_NAMESPACE_URL
value: {{ include "seaweedfs.worker.lanceNamespaceUrl" . | quote }}
{{- /* only a worker pinned before 4.56 reads these; later ones learn the cluster from admin */}}
{{- with include "seaweedfs.worker.lanceNamespaceUrl" . }}
- name: WEED_LANCE_NAMESPACE
value: {{ . | quote }}
{{- end }}
- name: WEED_MASTERS
value: {{ include "seaweedfs.masterServerArg" . | quote }}
{{- if .Values.filer.filerGroup }}
- name: WEED_FILER_GROUP
value: {{ .Values.filer.filerGroup | quote }}
{{- end }}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.worker "target" $mergedExtraEnvironmentVars) }}
{{- /* a duplicate would win over the chart's value and change --id or --namespace */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "LANCE_NAMESPACE_URL" }}
{{- /* a duplicate would win over the chart's value and change --id or the cluster */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "WEED_LANCE_NAMESPACE" "WEED_MASTERS" "WEED_FILER_GROUP" }}
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
{{- $value := index $mergedExtraEnvironmentVars $key }}
- name: {{ $key }}
@@ -272,11 +280,6 @@ spec:
{{- else }}
--admin={{ template "seaweedfs.fullname" . }}-admin.{{ include "seaweedfs.namespace" . }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
{{- end }}
--namespace="$LANCE_NAMESPACE_URL" \
--masters={{ include "seaweedfs.masterServerArg" . }} \
{{- if .Values.filer.filerGroup }}
--filer-group={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
--tls-ca=/usr/local/share/ca-certificates/ca/tls.crt \
--tls-cert=/usr/local/share/ca-certificates/worker/tls.crt \
@@ -299,7 +302,7 @@ spec:
- name: ca-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/ca/
{{- /* grpc.client, which the worker dials the masters and filers with */}}
{{- /* grpc.client, which the worker dials the filers with */}}
- name: client-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
@@ -342,7 +345,7 @@ spec:
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.worker.sidecars "context" $) | nindent 8 }}
{{- end }}
volumes:
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceNamespaceUrl" .) "")) | nindent 8 }}
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceEnabled" .) "")) | nindent 8 }}
{{- if eq .Values.worker.data.type "hostPath" }}
- name: worker-data
hostPath:
@@ -13,7 +13,7 @@ metadata:
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
spec:
clusterIP: None # Headless service
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- if or .Values.worker.metricsPort $lanceMetrics }}
ports:
{{- if .Values.worker.metricsPort }}
@@ -1,6 +1,6 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.worker.enabled }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- if or .Values.worker.metricsPort $lanceMetrics }}
{{- if .Values.global.seaweedfs.monitoring.enabled }}
apiVersion: monitoring.coreos.com/v1
+2 -7
View File
@@ -1161,7 +1161,7 @@ s3:
# Set to a port number to enable, or 0/null to disable
icebergPort: null
# Lance Namespace port; weed serves 9101 by default, 0 disables it
# (and, unless worker.namespaceUrl points elsewhere, the worker's Lance container)
# (and the worker's Lance container)
lancePort: 9101
loggingOverrideLevel: null
# enable user & permission to s3 (need to inject to all services)
@@ -1774,8 +1774,6 @@ vector:
port: 8090
metricsPort: 0
masters: ""
readCacheMB: 512
nprobes: null
extraArgs: []
extraEnvironmentVars: {}
podLabels: {}
@@ -1832,7 +1830,7 @@ worker:
# The lance_* jobs run in their own container, /usr/bin/weed-worker.
# amd64/arm64 only; pin mixed clusters with worker.affinity/nodeSelector.
# It keeps tables through the filers the masters list and reads
# Admin tells it the filers and the S3 gateways' Lance namespaces; it reads
# security.toml. The Lance namespace knows it by a token derived from
# jwt.filer_signing.key, which the chart renders only with
# global.seaweedfs.securityConfig.jwtSigning.filerWrite: true. When S3 has
@@ -1841,9 +1839,6 @@ worker:
# HTTP writes, so clients writing to the filer's HTTP API directly need a JWT
# signed with that key.
# Lance namespace URL override; empty derives it from s3.lancePort.
namespaceUrl: ""
# Metrics port for the Lance worker container; the Go worker keeps metricsPort
lanceMetricsPort: 9328
+3 -3
View File
@@ -15,12 +15,12 @@ Point an AWS S3 Vectors client at the S3 endpoint, normally `http://localhost:83
| `--masters` | Required | Comma-separated master addresses |
| `--listen` | `127.0.0.1:8090` | gRPC listener and registered address |
| `--filer-group` | Empty | Filer group used for table storage |
| `--read-cache-mb` | `512` | Immutable data/index read cache; zero disables it |
| `--nprobes` | Automatic | ANN partitions searched per query |
| `--metrics-port` | `0` | HTTP metrics and health listener; zero disables it |
| `--metrics-ip` | `127.0.0.1` | HTTP listener address |
| `--security-toml` | Discovered | Cluster certificates, signing keys and encryption keys |
The engine caches a quarter of the memory it may use (its cgroup limit, else the machine's), split 2:4:1 between file reads, loaded indexes and table metadata, and logs the sizes at startup. Each query probes a tenth of the index's partitions, at least 8, and more under a filter.
The HTTP listener provides `/health`, `/ready`, and `/metrics`. Readiness requires an active registration with the master. The gRPC listener also implements the standard health service for `vector_pb.VectorService` and the whole server. These health statuses follow master registration.
Metrics use the `SeaweedFS_vector_` prefix:
@@ -35,6 +35,6 @@ The S3 gateway separately publishes `SeaweedFS_s3_` request metrics with `type="
For mutual TLS, configure `[grpc.vector]` for the engine's server certificate, `[grpc.client]` for its master/filer connections, and the cluster CA. HTTPS volume reads also use `[https.client]`. The engine follows the same signing and encryption configuration as the other cluster clients.
Run the Lance maintenance worker against the same masters and Lance namespace to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
Run the Lance maintenance worker against the cluster's admin to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
The integration suite at `test/s3vectors` runs the same API and observability checks against both Go and Rust volume servers, including mutual TLS, signed volume reads, and encrypted volume data.
+73 -54
View File
@@ -2,35 +2,27 @@ use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use weed_lance_worker::catalog::{NamespaceClient, SigningKey, TableDescription, parse_id};
use weed_lance_worker::cluster::Cluster;
use weed_lance_worker::dataset::{self, Storage};
use weed_vector_core::coverage;
use weed_vector_core::index;
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
/// Mirrors `weed-worker`'s flags where the two touch the same thing: the
/// namespace that says where a table is, and the masters whose filers hold
/// it.
/// Finds everything through the masters: the S3 gateway whose Lance Namespace
/// says where a table is, and the filers that hold it.
#[derive(Parser, Debug)]
#[command(
name = "weed-vector",
about = "Describe, query and index S3 Vectors tables"
)]
struct Args {
/// Lance namespace the tables live in.
#[arg(
long,
default_value = "http://localhost:9101",
env = "WEED_LANCE_NAMESPACE"
)]
namespace: String,
/// Comma-separated master addresses, whose filers the tables are kept
/// through. A table named by a local URI needs none.
/// Comma-separated master addresses. A table named by a local path needs
/// none.
#[arg(long, alias = "master", env = "WEED_MASTERS")]
masters: Option<String>,
/// The filer group whose filers hold the tables.
/// The filer group whose gateways and filers hold the tables.
#[arg(
long,
alias = "filer.group",
@@ -45,7 +37,7 @@ struct Args {
filer_signing_key: Option<String>,
/// The cluster's security.toml; by default the file weed processes find
/// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
/// in ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<std::path::PathBuf>,
@@ -146,34 +138,44 @@ enum IndexAction {
},
}
/// `id` is a delimiter-joined table id; when it looks like a URI the dataset
/// is opened directly, skipping the namespace: an `s3://` URI on the
/// cluster's storage, a local path (`/path/...`, `file://...`) as it is.
async fn open_dataset(
client: &NamespaceClient,
id: &str,
storage: &Storage,
) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
}
if storage.0.is_none() {
bail!("{id} is kept on the cluster and needs --masters");
}
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
/// Where tables are found: through the cluster the masters name, or, for a
/// local path, nowhere in particular.
struct Tables {
cluster: Option<Cluster>,
storage: Storage,
signing_key: Option<SigningKey>,
}
impl Tables {
/// `id` is a delimiter-joined table id, looked up in the namespace of a
/// gateway the masters name; when it looks like a URI the dataset is
/// opened directly: an `s3://` URI on the cluster's storage, a local path
/// (`/path/...`, `file://...`) as it is.
async fn open(&self, id: &str) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
}
let Some(cluster) = &self.cluster else {
bail!("{id} is kept on the cluster and needs --masters");
};
return dataset::open_at(&description, storage.wrapper(id).await?, None).await;
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
};
return dataset::open_at(&description, self.storage.wrapper(id).await?, None).await;
}
let client = NamespaceClient::new(cluster.lance_namespace().await?)
.with_signing_key(self.signing_key.as_ref());
Ok(dataset::open(&client, &parse_id(id), &self.storage)
.await?
.dataset)
}
let table = dataset::open(client, &parse_id(id), storage).await?;
Ok(table.dataset)
}
#[tokio::main]
@@ -188,20 +190,26 @@ async fn main() -> Result<()> {
.init();
let args = Args::parse();
let security =
weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?;
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
let signing_key = SigningKey::new(
args.filer_signing_key
.or_else(|| security.get("jwt.filer_signing.key")),
);
let client = NamespaceClient::new(args.namespace).with_signing_key(signing_key.as_ref());
let storage = match &args.masters {
let tables = match &args.masters {
Some(masters) => {
let cluster =
weed_lance_worker::cluster::Cluster::new(masters, &args.filer_group, &security)?;
Storage(Some(cluster.storage(&security).await?))
let cluster = Cluster::new(masters, &args.filer_group, &security)?;
let storage = Storage(Some(cluster.storage(&security).await?));
Tables {
cluster: Some(cluster),
storage,
signing_key,
}
}
None => Storage::default(),
None => Tables {
cluster: None,
storage: Storage::default(),
signing_key,
},
};
match args.command {
@@ -210,7 +218,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = tables.open(&id).await?;
let schema: arrow_schema::Schema = dataset.schema().into();
let resolved =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref());
@@ -250,7 +258,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = tables.open(&id).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
let coverages = coverage::coverage(&dataset, &vector.vector_column).await?;
@@ -262,7 +270,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = tables.open(&id).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
for batch in query::get(&dataset, &vector, &keys, None).await? {
@@ -282,7 +290,7 @@ async fn main() -> Result<()> {
key_column,
nprobes,
} => {
let opened = open_dataset(&client, &id, &storage).await?;
let opened = tables.open(&id).await?;
let dataset = match version {
Some(v) => opened.checkout_version(v).await?,
None => opened,
@@ -327,7 +335,7 @@ async fn main() -> Result<()> {
id, vector_column, ..
} => (id.clone(), vector_column.clone()),
};
let mut dataset = open_dataset(&client, &id, &storage).await?;
let mut dataset = tables.open(&id).await?;
let table = VectorTable::resolve(&dataset, vector_column.as_deref(), None)?;
let started = std::time::Instant::now();
match action {
@@ -404,6 +412,17 @@ mod tests {
.unwrap();
assert_eq!(args.masters.as_deref(), Some("m:9333"));
assert_eq!(args.filer_group, "eu");
assert!(
Args::try_parse_from([
"weed-vector",
"--namespace",
"http://s3:9101",
"describe",
"t"
])
.is_err(),
"the namespace comes from the masters"
);
assert!(
Args::try_parse_from(["weed-vector", "--encryptVolumeData", "describe", "t"]).is_err(),
"volume encryption follows the filer"
+1
View File
@@ -22,6 +22,7 @@ pub mod master_pb {
tonic::include_proto!("master_pb");
}
pub mod master_client;
pub mod memory;
pub mod security {
pub use weed_lance_worker::security::*;
}
+16 -47
View File
@@ -5,6 +5,7 @@ use clap::Parser;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::transport::Server;
use weed_lance_worker::cluster::Cluster;
use weed_vector_server::memory::CacheSizes;
use weed_vector_server::pb::vector::vector_service_server::VectorServiceServer;
use weed_vector_server::read_cache::ReadCache;
use weed_vector_server::security::Security;
@@ -38,30 +39,11 @@ struct Args {
default_value = ""
)]
filer_group: String,
/// Memory for caching reads of write-once table files, in MiB; 0 disables.
#[arg(long, env = "WEED_VECTOR_READ_CACHE_MB", default_value_t = 512)]
read_cache_mb: u64,
/// Memory for indexes loaded by queries, kept for the next query, in MiB.
#[arg(long, env = "WEED_VECTOR_INDEX_CACHE_MB", default_value_t = 1024)]
index_cache_mb: usize,
/// Memory for table metadata (manifests, file footers) kept across
/// queries, in MiB.
#[arg(long, env = "WEED_VECTOR_METADATA_CACHE_MB", default_value_t = 256)]
metadata_cache_mb: usize,
/// Partitions each query probes in a table's vector index. Default: a
/// tenth of the index's partitions, at least 8; more under a filter.
#[arg(long, env = "WEED_VECTOR_NPROBES")]
nprobes: Option<std::num::NonZeroUsize>,
/// A filtered query whose indexed metadata keys match at most this many
/// rows scores them exactly instead of searching the vector index; 0
/// never does.
#[arg(long, env = "WEED_VECTOR_EXACT_MATCH_LIMIT", default_value_t = weed_vector_core::query::DEFAULT_EXACT_MATCH_LIMIT)]
exact_match_limit: usize,
/// The cluster's security.toml: [grpc.vector] for this server,
/// [grpc.client] for the masters and filers, https.client for volume
/// servers under HTTPS, jwt.signing.read.key for signed volume reads,
/// s3.sse.kek or s3.sse.key for SSE-S3 buckets. By default the file weed
/// processes find in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
/// processes find in ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<PathBuf>,
#[arg(
@@ -78,11 +60,6 @@ struct Args {
default_value = "127.0.0.1"
)]
metrics_ip: String,
/// The directory weed's -config_dir names, searched for security.toml
/// first.
#[arg(long, alias = "config_dir", env = "WEED_VECTOR_CONFIG_DIR")]
config_dir: Option<PathBuf>,
}
// weed tools take Go-style single-dash long flags; normalize_args converts
@@ -153,7 +130,7 @@ async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse_from(normalize_args(std::env::args().collect()));
weed_lance_worker::tls::install_default_crypto_provider();
let security = Security::load(args.security_toml.as_deref(), args.config_dir.as_deref())?;
let security = Security::load(args.security_toml.as_deref())?;
if let Some(path) = security.path() {
tracing::info!("security settings from {}", path.display());
}
@@ -171,16 +148,18 @@ async fn main() -> Result<()> {
let (health, health_service) = tonic_health::server::health_reporter();
let metrics = Metrics::new()?.with_health(health);
metrics.set_connected(false).await;
let cache = (args.read_cache_mb > 0)
.then(|| ReadCache::new(args.read_cache_mb << 20).with_metrics(metrics.clone()));
let mut service = VectorServer::new()
.with_nprobes(args.nprobes.map(std::num::NonZeroUsize::get))
.with_exact_match_limit(Some(args.exact_match_limit))
.with_lance_caches(args.index_cache_mb << 20, args.metadata_cache_mb << 20)
.with_storage(reads);
if let Some(cache) = &cache {
service = service.with_read_cache(cache.clone());
}
let sizes = CacheSizes::detect();
tracing::info!(
"caching {} MiB of file reads, {} MiB of indexes, {} MiB of table metadata",
sizes.read >> 20,
sizes.index >> 20,
sizes.metadata >> 20
);
let cache = ReadCache::new(sizes.read).with_metrics(metrics.clone());
let service = VectorServer::new()
.with_lance_caches(sizes.index as usize, sizes.metadata as usize)
.with_storage(reads)
.with_read_cache(cache.clone());
if args.metrics_port > 0 {
let ip = args
.metrics_ip
@@ -191,7 +170,7 @@ async fn main() -> Result<()> {
tokio::net::TcpListener::bind(std::net::SocketAddr::new(ip, args.metrics_port)).await?;
let metrics = metrics.clone();
tokio::spawn(async move {
if let Err(error) = metrics::serve_listener(metrics, listener, cache).await {
if let Err(error) = metrics::serve_listener(metrics, listener, Some(cache)).await {
tracing::error!(%error, "vector metrics server stopped");
}
});
@@ -263,16 +242,6 @@ mod tests {
);
}
#[test]
fn nprobes_must_be_positive() {
let parse = |nprobes: &str| {
Args::try_parse_from(["weed-vector", "--masters", "m:9333", "--nprobes", nprobes])
};
assert!(parse("0").is_err());
let args = parse("12").unwrap();
assert_eq!(args.nprobes.map(std::num::NonZeroUsize::get), Some(12));
}
#[test]
fn the_catalog_flags_are_gone() {
let parse = |extra: &[&str]| {
@@ -24,6 +24,7 @@ fn registration(client_addr: &str, filer_group: &str, metrics_port: u16) -> Keep
rack: String::new(),
leave_lock_ring: false,
metrics_port: metrics_port.into(),
lance_port: 0,
}
}
+155
View File
@@ -0,0 +1,155 @@
//! How much the engine caches: a share of the memory this process may use,
//! so a small pod is not overcommitted and a large host is not left idle.
use std::path::{Path, PathBuf};
/// The read, index and metadata caches, in bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheSizes {
pub read: u64,
pub index: u64,
pub metadata: u64,
}
/// Where no limit can be read, the sizes the flags used to default to.
const UNKNOWN_LIMIT_BUDGET: u64 = 1792 << 20;
impl CacheSizes {
/// A quarter of the memory limit, split 2:4:1 between file reads, loaded
/// indexes and table metadata.
pub fn for_limit(limit: Option<u64>) -> Self {
let budget = limit.map_or(UNKNOWN_LIMIT_BUDGET, |limit| limit / 4);
let seventh = budget / 7;
Self {
read: seventh * 2,
index: seventh * 4,
metadata: seventh,
}
}
pub fn detect() -> Self {
Self::for_limit(memory_limit())
}
}
/// The smallest of the machine's memory and the limits of this process's
/// memory cgroup and its ancestors: a systemd service is limited in its own
/// group, a container usually at the root it sees.
fn memory_limit() -> Option<u64> {
let read = |path: &Path| std::fs::read_to_string(path).ok();
let total = read(Path::new("/proc/meminfo")).and_then(|info| mem_total(&info));
let groups = read(Path::new("/proc/self/cgroup"))
.map(|groups| limit_files(&groups))
.unwrap_or_default();
groups
.iter()
.filter_map(|file| read(file).and_then(|limit| cgroup_limit(&limit)))
.chain(total)
.min()
}
/// The limit files of the memory cgroup `/proc/self/cgroup` names and of its
/// ancestors: v1's memory controller where it has one, else v2's unified group.
fn limit_files(self_cgroup: &str) -> Vec<PathBuf> {
let entries: Vec<(&str, &str)> = self_cgroup
.lines()
.filter_map(|line| {
let mut fields = line.splitn(3, ':');
fields.next()?;
Some((fields.next()?, fields.next()?))
})
.collect();
let v1 = entries
.iter()
.find(|(controllers, _)| controllers.split(',').any(|c| c == "memory"))
.map(|(_, group)| ("/sys/fs/cgroup/memory", *group, "memory.limit_in_bytes"));
let v2 = entries
.iter()
.find(|(controllers, _)| controllers.is_empty())
.map(|(_, group)| ("/sys/fs/cgroup", *group, "memory.max"));
let Some((root, group, file)) = v1.or(v2) else {
return Vec::new();
};
Path::new(group)
.ancestors()
.map(|dir| {
Path::new(root)
.join(dir.strip_prefix("/").unwrap_or(dir))
.join(file)
})
.collect()
}
fn mem_total(meminfo: &str) -> Option<u64> {
let line = meminfo.lines().find(|line| line.starts_with("MemTotal:"))?;
let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
Some(kib << 10)
}
/// cgroup v2 writes "max" for no limit; v1 writes a number near u64::MAX.
fn cgroup_limit(limit: &str) -> Option<u64> {
let bytes: u64 = limit.trim().parse().ok()?;
(bytes < 1 << 60).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_quarter_of_the_limit_split_two_four_one() {
let sizes = CacheSizes::for_limit(Some(28 << 30));
assert_eq!(sizes.read, 2 << 30);
assert_eq!(sizes.index, 4 << 30);
assert_eq!(sizes.metadata, 1 << 30);
}
#[test]
fn no_limit_keeps_the_former_defaults() {
let sizes = CacheSizes::for_limit(None);
assert_eq!(
(sizes.read, sizes.index, sizes.metadata),
(512 << 20, 1024 << 20, 256 << 20)
);
}
#[test]
fn looks_up_the_process_group_and_its_ancestors() {
let paths = |groups: &str| -> Vec<String> {
limit_files(groups)
.iter()
.map(|p| p.display().to_string().replace('\\', "/"))
.collect()
};
assert_eq!(
paths("0::/system.slice/weed-vector.service\n"),
[
"/sys/fs/cgroup/system.slice/weed-vector.service/memory.max",
"/sys/fs/cgroup/system.slice/memory.max",
"/sys/fs/cgroup/memory.max",
]
);
// A container's namespace shows its own group as the root.
assert_eq!(paths("0::/\n"), ["/sys/fs/cgroup/memory.max"]);
// On a hybrid host the memory controller is v1's.
assert_eq!(
paths("12:cpu,cpuacct:/a\n4:memory:/user.slice\n0::/user.slice\n"),
[
"/sys/fs/cgroup/memory/user.slice/memory.limit_in_bytes",
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
]
);
assert!(paths("").is_empty());
}
#[test]
fn reads_the_limits_the_kernel_writes() {
assert_eq!(
mem_total("MemTotal: 16384000 kB\nMemFree: 1 kB\n"),
Some(16_384_000 << 10)
);
assert_eq!(cgroup_limit("4294967296\n"), Some(4 << 30));
assert_eq!(cgroup_limit("max\n"), None);
assert_eq!(cgroup_limit("9223372036854771712\n"), None);
}
}
+3 -10
View File
@@ -705,7 +705,6 @@ pub struct VectorServer {
pub(crate) handles: moka::sync::Cache<(String, bool), (u64, Dataset)>,
lance_cache_bytes: (usize, usize),
leases: SharedLeases,
nprobes: Option<usize>,
exact_match_limit: Option<usize>,
filter_stats: crate::filter_stats::FilterStats,
/// URI schemes a table's location may have.
@@ -730,7 +729,6 @@ impl VectorServer {
lance_cache_bytes: (DEFAULT_INDEX_CACHE_BYTES, DEFAULT_METADATA_CACHE_BYTES),
handles: moka::sync::Cache::new(MAX_HANDLES),
leases: SharedLeases::default(),
nprobes: None,
exact_match_limit: None,
filter_stats: Default::default(),
schemes: &["s3"],
@@ -744,15 +742,10 @@ impl VectorServer {
self
}
/// Partitions every query probes, instead of the index's own default.
pub fn with_nprobes(mut self, nprobes: Option<usize>) -> Self {
self.nprobes = nprobes;
self
}
/// Matches of a filter's indexed metadata keys scored exactly instead of
/// searched through the vector index, at most; None keeps the default.
pub fn with_exact_match_limit(mut self, limit: Option<usize>) -> Self {
#[cfg(test)]
pub(crate) fn with_exact_match_limit(mut self, limit: Option<usize>) -> Self {
self.exact_match_limit = limit;
self
}
@@ -1180,7 +1173,7 @@ impl VectorService for VectorServer {
},
postfilter: req.postfilter,
distance,
nprobes: self.nprobes,
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: self.exact_match_limit,
+3
View File
@@ -234,6 +234,8 @@ message KeepConnectedRequest {
// it is not enabled. Advertised so the admin server can scrape it without
// exposing metrics on the client-facing service port.
uint32 metrics_port = 9;
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
uint32 lance_port = 10;
}
message VolumeLocation {
@@ -559,6 +561,7 @@ message ListClusterNodesResponse {
string address = 1;
string version = 2;
int64 created_at_ns = 4;
uint32 lance_port = 7;
string data_center = 5;
string rack = 6;
}
+93
View File
@@ -16038,6 +16038,99 @@ mod tests {
}
}
// The retry goes to the holder that answered the read deleted, not to the
// first holder that takes a delete.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_batch_delete_forwards_to_the_holder_reading_the_ec_needle_deleted() {
let (peer, peer_tmp) = make_service_with_two_disk_complete_ec_volume(7068);
let vid = VolumeId(7068);
let idx_dir = peer_tmp.path().join("data1");
let mut index_only = Vec::new();
for _ in 0..2 {
let (service, tmp) = make_local_service_with_volume("", None);
for name in ["7068.ecx", "7068.ecj", "7068.vif", "7068.ec13"] {
std::fs::copy(idx_dir.join(name), tmp.path().join(name)).unwrap();
}
service
.volume_ec_shards_mount(Request::new(
volume_server_pb::VolumeEcShardsMountRequest {
volume_id: 7068,
collection: String::new(),
shard_ids: vec![13],
source_disk_type: String::new(),
recover_missing_index: false,
},
))
.await
.unwrap();
index_only.push((service, tmp));
}
let (service, _tmp) = index_only.remove(0);
let (unreadable, _unreadable_tmp) = index_only.remove(0);
peer.state
.store
.write()
.unwrap()
.find_ec_volume_mut(vid)
.unwrap()
.journal_delete(NeedleId(3))
.unwrap();
let peer_state = peer.state.clone();
let unreadable_state = unreadable.state.clone();
let (port, _shutdown) = serve_source(peer).await;
let peer_addr = format!("127.0.0.1:{port}.{port}");
let (uport, _ushutdown) = serve_source(unreadable).await;
let unreadable_addr = format!("127.0.0.1:{uport}.{uport}");
{
let store = service.state.store.read().unwrap();
let ecv = store.find_ec_volume(vid).unwrap();
let (_, _, intervals) = ecv.locate_needle(NeedleId(3)).unwrap().unwrap();
let (primary, _) = ecv.interval_to_shard_id_and_offset(&intervals[0]);
ecv.merge_shard_locations(
(0u8..14)
.map(|sid| {
if sid == primary {
(sid, vec![unreadable_addr.clone(), peer_addr.clone()])
} else {
(sid, vec![peer_addr.clone()])
}
})
.collect(),
);
}
let fid = needle::FileId::new(vid, NeedleId(3), Cookie(3));
let resp = service
.batch_delete(Request::new(volume_server_pb::BatchDeleteRequest {
file_ids: vec![fid.to_string()],
skip_cookie_check: false,
fsync: false,
}))
.await
.unwrap()
.into_inner();
assert_eq!(resp.results[0].status, 404, "{:?}", resp.results);
{
let store = peer_state.store.read().unwrap();
for (i, ec_vol) in store.find_all_ec_volumes(vid).into_iter().enumerate() {
assert!(
ec_vol.is_needle_deleted(NeedleId(3)),
"peer copy {} still serves the deleted needle",
i
);
}
}
let store = unreadable_state.store.read().unwrap();
assert!(
!store
.find_ec_volume(vid)
.unwrap()
.is_needle_deleted(NeedleId(3)),
"the delete went to the holder that could not read the shard"
);
}
#[tokio::test]
async fn volume_delete_reports_absent_volume_as_not_found() {
let (service, _tmp) = make_service_with_seed_masters(&[]);
+78 -7
View File
@@ -441,16 +441,18 @@ pub async fn delete_ec_shard_needle_distributed(
)))
}
/// A delete whose read found no needle. A holder's read checks one disk's
/// deletion set, and a delete that failed part way can leave another of its
/// disks live, so forward again, best effort; holders skip copies already
/// recording it. Nothing is sent when this server's index has no live entry.
/// A delete whose read found the needle deleted, best effort. A holder's read
/// checks one disk's deletion set, and a delete that failed part way can leave
/// its other disks live, so the delete goes to the primary shard holders whose
/// read answers deleted, which skip the disks already recording it. Normal
/// routing could stop at another copy instead; it is used only when no holder
/// answers deleted. `forwardEcDeleteOfDeletedNeedle` in Go.
pub async fn forward_ec_delete_of_deleted_needle(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) {
if let Err(e) = delete_ec_shard_needle_distributed(state, vid, needle_id).await {
if let Err(e) = forward_ec_delete_to_holders_reading_deleted(state, vid, needle_id).await {
tracing::debug!(
"re-forward delete of deleted ec needle {}.{}: {}",
vid.0,
@@ -460,6 +462,74 @@ pub async fn forward_ec_delete_of_deleted_needle(
}
}
async fn forward_ec_delete_to_holders_reading_deleted(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) -> io::Result<()> {
let (probe, holders, collection, version) = {
let store = state.store.read().unwrap();
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} not mounted", vid.0),
)
})?;
let (_, _, intervals) = ecv.locate_needle(needle_id)?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("needle {} not in ec volume {}", needle_id, vid.0),
)
})?;
let (shard_id, shard_offset) = intervals
.first()
.map(|i| ecv.interval_to_shard_id_and_offset(i))
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no intervals for needle"))?;
let (locations, _) = ecv.shard_locations_snapshot();
(
EcInterval {
vid,
needle_id,
shard_id,
shard_offset,
size: 1,
expected_encode_ts_ns: ecv.encode_ts_ns,
},
locations.get(&shard_id).cloned().unwrap_or_default(),
ecv.collection.clone(),
ecv.version,
)
};
let target = EcDeleteTarget {
vid,
collection: &collection,
version,
needle_id,
};
let mut reported = false;
let mut last_err = None;
for addr in &holders {
if !matches!(
tokio::time::timeout(
EC_READ_HINT_TIMEOUT,
do_read_remote_ec_shard_interval(state, addr, probe),
)
.await,
Ok(Ok((_, true)))
) {
continue;
}
reported = true;
if let Err(e) = delete_on_remote_ec_shard(state, addr, &target).await {
last_err = Some(e);
}
}
if !reported {
return delete_ec_shard_needle_distributed(state, vid, needle_id).await;
}
last_err.map_or(Ok(()), Err)
}
/// `doDeleteNeedleFromRemoteEcShardServers` in Go. `Ok(false)` is the
/// shard-missing signal — no live holder anywhere — that triggers the
/// caller's fallback walk over the remaining shards.
@@ -1374,8 +1444,9 @@ struct EcShardMap<'a> {
parity_shards: usize,
}
/// Bounds asking a delisted holder, which may have stopped answering, before
/// the read reconstructs the shard (Go's `ecReadHintTimeout`).
/// Bounds a one-byte probe of a holder that may have stopped answering: a
/// delisted holder before the read reconstructs the shard, or a holder a
/// delete retry asks (Go's `ecReadHintTimeout`).
const EC_READ_HINT_TIMEOUT: Duration = Duration::from_secs(5);
/// Try direct peer read; on failure, reconstruct via Reed-Solomon
+10 -8
View File
@@ -35,7 +35,10 @@ binary for the runner's platform, resolved from the version in `Cargo.lock`.
## Running
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535
Admin is all it needs, as with `weed worker`: every request admin sends names
the filers, and the Lance Namespaces the S3 gateways serve.
The admin's *HTTP* address is what an operator has; the gRPC port is derived
from it the way the Go side does. Dialling the HTTP port fails as "frame with
@@ -49,7 +52,7 @@ Released builds do not need a toolchain. The worker ships inside the SeaweedFS
image, beside the Rust volume server, under the verb that mirrors
`volume-rust`:
docker run chrislusf/seaweedfs worker-rust --admin admin:12535 --masters master:9333
docker run chrislusf/seaweedfs worker-rust --admin admin:12535
and as `weed-worker_linux_{amd64,arm64}.tar.gz` on each GitHub release. Both are
linux amd64/arm64 only — lance, arrow and datafusion make every extra target an
@@ -59,7 +62,7 @@ entrypoint says so rather than failing as "not found".
## Metrics
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333 --metrics-port 9328
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --metrics-port 9328
Serves `/health`, `/ready` and `/metrics` on that port, the same three the Go
worker serves under `weed worker -metricsPort`, so one scrape config covers
@@ -90,9 +93,8 @@ running but is not going to do anything.
## Credentials
The worker holds no S3 credentials. The namespace tells it where a table is;
its files are read and written on the cluster's filers and volume servers,
which `--masters` names the masters of (`--filer-group` picks the filers). What
that takes comes from the same security.toml the weed processes use:
its files are read and written on the cluster's filers, which admin names, and
volume servers. What that takes comes from the same security.toml the weed processes use:
`grpc.client` for the filers, `https.client` for volume servers under HTTPS,
`jwt.signing.read.key` where volume reads are signed, and `s3.sse.kek` or
`s3.sse.key` where a bucket encrypts with SSE-S3. Chunks are encrypted for the
@@ -116,8 +118,8 @@ All three jobs are implemented and tested end to end against a live gateway:
`cargo test -p weed-lance-worker` runs them when `WEED_LANCE_NAMESPACE` names a
live namespace and skips otherwise, the way the Go integration tests skip
without Docker. A live namespace needs `WEED_MASTERS` naming its cluster's
masters, and `WEED_JWT_FILER_SIGNING_KEY` (or security.toml) where the
without Docker. A live namespace needs `WEED_FILER` naming its cluster's
filer as the master lists it (`host:port.grpc`), and `WEED_JWT_FILER_SIGNING_KEY` (or security.toml) where the
namespace authenticates cluster processes; the tests fail without the first
and are refused without the second. Each test seeds the table it needs, including building a vector
index and then appending rows outside it, so a run does not depend on what the
+1 -1
View File
@@ -26,6 +26,6 @@ pub mod pb {
pub use config::{TlsOptions, WorkerOptions};
pub use metrics::Metrics;
pub use registry::{JobHandler, Preview, PreviewProvider, Registry};
pub use registry::{ClusterObserver, JobHandler, Preview, PreviewProvider, Registry};
pub use senders::{DetectionSender, ExecutionSender};
pub use stream::run;
+60 -1
View File
@@ -4,7 +4,9 @@ use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use crate::pb::{ExecuteJobRequest, JobTypeCapability, JobTypeDescriptor, RunDetectionRequest};
use crate::pb::{
ClusterContext, ExecuteJobRequest, JobTypeCapability, JobTypeDescriptor, RunDetectionRequest,
};
use crate::senders::{DetectionSender, ExecutionSender};
/// One job type, worker side. Mirrors the Go JobHandler interface in
@@ -47,12 +49,20 @@ pub trait PreviewProvider: Send + Sync {
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview>;
}
/// Learns the cluster from admin, which describes it on every request, as the
/// Go worker reads request.ClusterContext. Runs before the request's handler.
#[async_trait]
pub trait ClusterObserver: Send + Sync {
async fn observe(&self, cluster: &ClusterContext);
}
/// The handlers one worker process serves. A process may serve several job
/// types, which is why WorkerHello carries a list of capabilities.
#[derive(Default, Clone)]
pub struct Registry {
handlers: HashMap<String, Arc<dyn JobHandler>>,
previews: HashMap<String, Arc<dyn PreviewProvider>>,
observer: Option<Arc<dyn ClusterObserver>>,
}
impl Registry {
@@ -71,6 +81,18 @@ impl Registry {
self
}
pub fn with_cluster_observer(mut self, observer: Arc<dyn ClusterObserver>) -> Self {
self.observer = Some(observer);
self
}
/// Hands a request's cluster context to the observer, if both exist.
pub async fn observe(&self, cluster: Option<&ClusterContext>) {
if let (Some(observer), Some(cluster)) = (&self.observer, cluster) {
observer.observe(cluster).await;
}
}
pub fn get(&self, job_type: &str) -> Option<Arc<dyn JobHandler>> {
self.handlers.get(job_type).cloned()
}
@@ -87,3 +109,40 @@ impl Registry {
self.handlers.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[derive(Default)]
struct Seen(Mutex<Vec<Vec<String>>>);
#[async_trait]
impl ClusterObserver for Seen {
async fn observe(&self, cluster: &ClusterContext) {
self.0.lock().unwrap().push(cluster.filer_addresses.clone());
}
}
#[tokio::test]
async fn observe_hands_the_context_to_the_observer() {
let seen = Arc::new(Seen::default());
let registry = Registry::new().with_cluster_observer(seen.clone());
registry
.observe(Some(&ClusterContext {
filer_addresses: vec!["f1:8888.18888".into()],
..Default::default()
}))
.await;
// An older admin, or a request without one, has nothing to say.
registry.observe(None).await;
Registry::new()
.observe(Some(&ClusterContext::default()))
.await;
assert_eq!(
*seen.0.lock().unwrap(),
vec![vec!["f1:8888.18888".to_string()]]
);
}
}
+3
View File
@@ -288,6 +288,7 @@ fn spawn_preview(
) {
tokio::spawn(async move {
let limit = request.row_limit.max(1) as usize;
registry.observe(request.cluster_context.as_ref()).await;
let response = match registry.preview_provider(&request.format) {
None => ObjectPreviewResponse {
request_id,
@@ -376,6 +377,7 @@ fn spawn_detection(
// Held until the sweep finishes, so the worker keeps to the capacity it
// advertised and the heartbeat reports the truth while it works.
let _permit = slots.detection.acquire().await;
registry.observe(request.cluster_context.as_ref()).await;
let metered = MeteredSender::new(&sender);
let started = Instant::now();
let outcome = handler.detect(&request, &metered).await;
@@ -429,6 +431,7 @@ fn spawn_execution(
let Some(handler) = registry.get(&job_type) else {
return;
};
registry.observe(request.cluster_context.as_ref()).await;
let metered = MeteredSender::new(&sender);
let started = Instant::now();
let outcome = handler.execute(&request, &metered).await;
@@ -0,0 +1,187 @@
//! The cluster as admin describes it with every request: where the Lance
//! Namespace is served and which filers keep the tables. A worker run under
//! admin needs to be told nothing else, as `weed worker` is told only -admin.
use std::hash::BuildHasher;
use std::sync::RwLock;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use seaweed_worker_core::ClusterObserver;
use seaweed_worker_core::pb::ClusterContext;
use crate::catalog::{NamespaceClient, SigningKey};
use crate::cluster::{filer_grpc_addr, open_storage};
use crate::dataset::Storage;
use crate::direct_read::{Connection, DirectReads};
pub struct AdminCluster {
connection: Connection,
signing_key: Option<SigningKey>,
/// Which of the gateways admin names this process uses, so the workers of
/// a cluster spread over them rather than all picking the first.
pick: usize,
namespaces: RwLock<Vec<String>>,
storage: RwLock<Option<DirectReads>>,
storage_error: RwLock<Option<String>>,
connecting: tokio::sync::Mutex<()>,
}
impl AdminCluster {
/// `connection` is everything but the filers, which admin supplies.
pub fn new(connection: Connection, signing_key: Option<SigningKey>) -> Self {
Self {
connection,
signing_key,
pick: std::collections::hash_map::RandomState::new().hash_one(()) as usize,
namespaces: RwLock::new(Vec::new()),
storage: RwLock::new(None),
storage_error: RwLock::new(None),
connecting: tokio::sync::Mutex::new(()),
}
}
/// One of the Lance Namespaces admin last named.
pub fn namespace_url(&self) -> Result<String> {
let namespaces = self.namespaces.read().unwrap();
match namespaces.len() {
0 => Err(anyhow!(
"admin names no Lance Namespace: no S3 gateway serves one, or they predate saying so"
)),
n => Ok(namespaces[self.pick % n].clone()),
}
}
pub fn client(&self) -> Result<NamespaceClient> {
Ok(NamespaceClient::new(self.namespace_url()?).with_signing_key(self.signing_key.as_ref()))
}
pub fn storage(&self) -> Result<Storage> {
if let Some(storage) = self.storage.read().unwrap().clone() {
return Ok(Storage(Some(storage)));
}
match self.storage_error.read().unwrap().clone() {
Some(err) => Err(anyhow!("no storage: {err}")),
None => Err(anyhow!("no storage: admin has named no filer yet")),
}
}
async fn take_filers(&self, addresses: &[String]) {
let filers: Vec<String> = addresses
.iter()
.filter_map(|address| match filer_grpc_addr(address) {
Ok(addr) => Some(addr),
Err(err) => {
tracing::warn!("admin names filer {address:?}: {err:#}");
None
}
})
.collect();
// Keep the last known filers while admin lists none.
if filers.is_empty() {
return;
}
let _connecting = self.connecting.lock().await;
let connected = self.storage.read().unwrap().clone();
if let Some(storage) = connected {
if let Err(err) = storage.set_filers(&filers) {
tracing::warn!("filers {}: {err:#}", filers.join(","));
}
return;
}
let mut conn = self.connection.clone();
conn.filers = filers;
match open_storage(&conn).await {
Ok(storage) => {
*self.storage.write().unwrap() = Some(storage);
*self.storage_error.write().unwrap() = None;
}
Err(err) => {
tracing::warn!("connecting to the filers admin names: {err:#}");
*self.storage_error.write().unwrap() = Some(format!("{err:#}"));
}
}
}
}
/// A cluster admin has said nothing about yet.
impl Default for AdminCluster {
fn default() -> Self {
Self::new(Connection::default(), None)
}
}
#[async_trait]
impl ClusterObserver for AdminCluster {
async fn observe(&self, cluster: &ClusterContext) {
// As with the filers, keep the last known namespaces while admin lists
// none: admin sends its cached filers but no gateways when a master
// call fails, and the gateways serve the namespace regardless.
if !cluster.lance_namespace_urls.is_empty() {
*self.namespaces.write().unwrap() = cluster.lance_namespace_urls.clone();
}
self.take_filers(&cluster.filer_addresses).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn admin() -> AdminCluster {
AdminCluster::default()
}
#[tokio::test]
async fn follows_the_namespaces_admin_names() {
let admin = admin();
let err = admin.namespace_url().unwrap_err().to_string();
assert!(err.contains("names no Lance Namespace"), "{err}");
admin
.observe(&ClusterContext {
lance_namespace_urls: vec!["http://10.0.0.5:9101".into()],
..Default::default()
})
.await;
assert_eq!(admin.namespace_url().unwrap(), "http://10.0.0.5:9101");
// A context naming no gateway, as admin sends when listing them from
// the master fails, keeps the namespace.
admin.observe(&ClusterContext::default()).await;
assert_eq!(admin.namespace_url().unwrap(), "http://10.0.0.5:9101");
admin
.observe(&ClusterContext {
lance_namespace_urls: vec!["http://10.0.0.6:9101".into()],
..Default::default()
})
.await;
assert_eq!(admin.namespace_url().unwrap(), "http://10.0.0.6:9101");
}
#[tokio::test]
async fn the_pick_stays_among_the_named_gateways() {
let admin = admin();
let urls: Vec<String> = (1..=3).map(|i| format!("http://10.0.0.{i}:9101")).collect();
admin
.observe(&ClusterContext {
lance_namespace_urls: urls.clone(),
..Default::default()
})
.await;
let first = admin.namespace_url().unwrap();
assert!(urls.contains(&first));
assert_eq!(
admin.namespace_url().unwrap(),
first,
"one process keeps one gateway"
);
}
#[test]
fn storage_before_admin_names_a_filer_is_an_error() {
let err = admin().storage().err().unwrap().to_string();
assert!(err.contains("no filer"), "{err}");
}
}
+113 -48
View File
@@ -10,6 +10,7 @@ use tonic::transport::{Channel, Endpoint};
use crate::direct_read::{Connection, DirectReads, FilerDialer};
use crate::grpc_tls;
use crate::master_pb::list_cluster_nodes_response::ClusterNode;
use crate::master_pb::{ListClusterNodesRequest, seaweed_client::SeaweedClient};
use crate::security::{GrpcTls, Security};
@@ -102,22 +103,32 @@ pub async fn list_filers(
}
}
async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Result<Vec<String>> {
/// The nodes of `client_type` in `filer_group` that `master` lists.
async fn cluster_nodes(
master: &str,
client_type: &str,
filer_group: &str,
tls: Option<&GrpcTls>,
) -> Result<Vec<ClusterNode>> {
let channel = connect(master, tls).await?;
let request = ListClusterNodesRequest {
client_type: "filer".into(),
client_type: client_type.into(),
filer_group: filer_group.into(),
..Default::default()
};
let nodes = tokio::time::timeout(
Ok(tokio::time::timeout(
CONNECT_TIMEOUT,
SeaweedClient::new(channel).list_cluster_nodes(request),
)
.await
.context("master did not answer")??
.into_inner()
.cluster_nodes;
Ok(nodes
.cluster_nodes)
}
async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Result<Vec<String>> {
Ok(cluster_nodes(master, "filer", filer_group, tls)
.await?
.iter()
.filter_map(|node| match filer_grpc_addr(&node.address) {
Ok(addr) => Some(addr),
@@ -129,6 +140,13 @@ async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Re
.collect())
}
/// Where an S3 gateway registered as `host:grpc` serves its Lance
/// Namespace, or None when it serves none.
fn lance_namespace_url(node: &ClusterNode) -> Option<String> {
let (host, _) = node.address.rsplit_once(':')?;
(node.lance_port > 0).then(|| format!("http://{host}:{}", node.lance_port))
}
/// A filer registers as `host:port.grpc`, or `host:port` with its gRPC at
/// port + 10000.
pub fn filer_grpc_addr(address: &str) -> Result<String> {
@@ -220,53 +238,33 @@ impl Cluster {
})
}
/// The Lance Namespace of an S3 gateway in the filer group, from the first
/// master that names one.
pub async fn lance_namespace(&self) -> Result<String> {
let mut last = None;
for master in &self.masters {
match cluster_nodes(master, "s3", &self.filer_group, self.master_tls.as_ref()).await {
Ok(nodes) => {
if let Some(url) = nodes.iter().find_map(lance_namespace_url) {
return Ok(url);
}
}
Err(err) => last = Some(err),
}
}
Err(last.unwrap_or_else(|| {
anyhow::anyhow!("the masters list no S3 gateway that serves a Lance Namespace")
}))
}
/// Connects to the cluster's storage and follows the masters' filer list.
/// Chunks are encrypted for the volume servers when the filer is
/// configured to (`weed filer -encryptVolumeData`), as `weed s3` does.
pub async fn storage(&self, security: &Security) -> Result<DirectReads> {
// The filers are dialed as the masters are: grpc.client's credentials
// and server allowlist, through this crate's own connector.
let filer_dialer: Option<FilerDialer> = security
.grpc_client_tls("grpc.client", "grpc.filer")?
.map(|tls| {
Arc::new(move |addr: &str| {
let channel = Endpoint::new(format!("http://{addr}"))?
.connect_timeout(Duration::from_secs(10))
.connect_with_connector_lazy(grpc_tls::connector(tls.clone()));
Ok(sw_client::FilerClient::from_channel(addr, channel))
}) as FilerDialer
});
let conn = Connection {
filers: discover_filers(&self.masters, &self.filer_group, self.master_tls.as_ref())
.await?,
read_jwt_key: security.jwt_read_key(),
sse: security.sse(),
grpc_tls: None,
https_tls: security.https_client_tls()?,
filer_dialer,
filer_group: self.filer_group.clone(),
};
let storage = DirectReads::connect(&conn)
.await
.context("direct storage")?;
tracing::info!(
"tables kept through {storage:?}; filer gRPC {}, volume servers {}; SSE-S3 objects {}",
if conn.filer_dialer.is_some() {
"over TLS"
} else {
"plaintext"
},
if conn.https_tls.is_some() {
"over HTTPS"
} else {
"over HTTP"
},
if storage.sse_s3_configured() {
"are readable"
} else {
"need s3.sse.kek or s3.sse.key"
},
);
let mut conn = connection(security, self.filer_group.clone())?;
conn.filers =
discover_filers(&self.masters, &self.filer_group, self.master_tls.as_ref()).await?;
let storage = open_storage(&conn).await?;
tokio::spawn(follow_filers(
storage.clone(),
self.masters.clone(),
@@ -277,10 +275,77 @@ impl Cluster {
}
}
/// How the storage is reached, from security.toml, before any filer is known.
pub fn connection(security: &Security, filer_group: String) -> Result<Connection> {
// The filers are dialed as the masters are: grpc.client's credentials
// and server allowlist, through this crate's own connector.
let filer_dialer: Option<FilerDialer> = security
.grpc_client_tls("grpc.client", "grpc.filer")?
.map(|tls| {
Arc::new(move |addr: &str| {
let channel = Endpoint::new(format!("http://{addr}"))?
.connect_timeout(Duration::from_secs(10))
.connect_with_connector_lazy(grpc_tls::connector(tls.clone()));
Ok(sw_client::FilerClient::from_channel(addr, channel))
}) as FilerDialer
});
Ok(Connection {
filers: Vec::new(),
read_jwt_key: security.jwt_read_key(),
sse: security.sse(),
grpc_tls: None,
https_tls: security.https_client_tls()?,
filer_dialer,
filer_group,
})
}
/// Connects to the storage `conn` describes, and says how.
pub async fn open_storage(conn: &Connection) -> Result<DirectReads> {
let storage = DirectReads::connect(conn).await.context("direct storage")?;
tracing::info!(
"tables kept through {storage:?}; filer gRPC {}, volume servers {}; SSE-S3 objects {}",
if conn.filer_dialer.is_some() {
"over TLS"
} else {
"plaintext"
},
if conn.https_tls.is_some() {
"over HTTPS"
} else {
"over HTTP"
},
if storage.sse_s3_configured() {
"are readable"
} else {
"need s3.sse.kek or s3.sse.key"
},
);
Ok(storage)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_gateway_serves_its_namespace_on_its_registered_host() {
let node = |address: &str, lance_port| ClusterNode {
address: address.into(),
lance_port,
..Default::default()
};
assert_eq!(
lance_namespace_url(&node("10.0.0.5:18333", 9101)).as_deref(),
Some("http://10.0.0.5:9101")
);
assert_eq!(
lance_namespace_url(&node("[fd00::5]:18333", 9101)).as_deref(),
Some("http://[fd00::5]:9101")
);
assert_eq!(lance_namespace_url(&node("10.0.0.5:18333", 0)), None);
}
#[test]
fn an_empty_master_list_is_refused() {
assert!(master_addresses("").is_err());
@@ -457,7 +457,7 @@ impl fmt::Debug for DirectReads {
/// What direct reads connect to, as the cluster's security.toml configures
/// weed processes.
#[derive(Default)]
#[derive(Default, Clone)]
pub struct Connection {
/// The filers' gRPC `host:port`s as the masters list them; see
/// [`DirectReads::set_filers`] for later changes.
@@ -472,7 +472,8 @@ pub struct Connection {
/// Dials the filers in place of `grpc_tls`, for a TLS setup sw-client
/// cannot express, such as a server allowlist.
pub filer_dialer: Option<FilerDialer>,
/// The filer group, which the gateway prefixes a bucket's collection with.
/// The filer group, which the gateway prefixes a bucket's collection with;
/// empty takes the group the filers report.
pub filer_group: String,
}
@@ -545,7 +546,11 @@ impl DirectReads {
let shared = Arc::get_mut(&mut reads.shared).expect("just created");
shared.chunk_size = chunk_size;
shared.cipher = config.cipher;
shared.filer_group = conn.filer_group.clone();
shared.filer_group = if conn.filer_group.is_empty() {
config.filer_group.clone()
} else {
conn.filer_group.clone()
};
}
reads.report_every(Duration::from_secs(30));
Ok(reads)
+13 -27
View File
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
@@ -14,7 +15,8 @@ use seaweed_worker_core::pb::{
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::admin_cluster::AdminCluster;
use crate::catalog::parse_id;
use crate::dataset;
use crate::jobs::purge::{self, Retention};
use crate::jobs::{clamp, string_list, table_id};
@@ -34,18 +36,14 @@ const MAX_MIN_VERSIONS: i64 = 1000;
/// retention in its own config, and may ask for a purge (see [`purge`]), which
/// this job carries out ahead of the retention window.
pub struct CleanupVersionsHandler {
namespace_url: String,
storage: dataset::Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
}
impl CleanupVersionsHandler {
pub fn new(namespace_url: String) -> Self {
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
signing_key: None,
cluster,
metrics: None,
}
}
@@ -54,20 +52,6 @@ impl CleanupVersionsHandler {
self.metrics = metrics;
self
}
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
self
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
}
}
/// The oldest version that may be removed while still leaving `min_versions`
@@ -188,13 +172,14 @@ impl JobHandler for CleanupVersionsHandler {
1,
MAX_MIN_VERSIONS,
) as usize;
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let tables = client.list_all_tables().await?;
let mut proposals = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &storage).await {
Ok(table) => table,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -311,8 +296,9 @@ impl JobHandler for CleanupVersionsHandler {
MAX_MIN_VERSIONS,
) as usize;
let client = self.client();
let mut table = dataset::open(&client, &id, &self.storage).await?;
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let mut table = dataset::open(&client, &id, &storage).await?;
let before = table.stats().await?;
if let Some(token) = purge::pending(table.dataset.config()) {
@@ -469,7 +455,7 @@ mod tests {
#[test]
fn a_purge_gets_a_builds_execution_timeout() {
let descriptor = CleanupVersionsHandler::new(String::new()).descriptor();
let descriptor = CleanupVersionsHandler::new(Default::default()).descriptor();
let defaults = descriptor.admin_runtime_defaults.unwrap();
assert_eq!(defaults.execution_timeout_seconds, 3600);
assert_eq!(defaults.job_type_max_runtime_seconds, 3600);
+12 -27
View File
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
@@ -12,7 +13,8 @@ use seaweed_worker_core::pb::{
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::admin_cluster::AdminCluster;
use crate::catalog::parse_id;
use crate::dataset;
use crate::jobs::{FORMAT, clamp, observation, string_list, table_id};
@@ -33,18 +35,14 @@ const MIN_FRAGMENTS_CEILING: i64 = 4096;
/// Lance writes one fragment per write batch, so a table fed by small appends
/// accumulates small files the same way an Iceberg table does.
pub struct CompactHandler {
namespace_url: String,
storage: dataset::Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
}
impl CompactHandler {
pub fn new(namespace_url: String) -> Self {
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
signing_key: None,
cluster,
metrics: None,
}
}
@@ -53,21 +51,6 @@ impl CompactHandler {
self.metrics = metrics;
self
}
/// Storage options to use where the namespace vends none.
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
self
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
}
}
#[async_trait]
@@ -145,14 +128,15 @@ impl JobHandler for CompactHandler {
MIN_FRAGMENTS_FLOOR,
MIN_FRAGMENTS_CEILING,
) as usize;
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let tables = client.list_all_tables().await?;
let mut proposals = Vec::new();
let mut observations = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &storage).await {
Ok(table) => table,
Err(err) => {
// A table that cannot be opened is the next run's problem,
@@ -266,10 +250,11 @@ impl JobHandler for CompactHandler {
TARGET_ROWS_CEILING,
) as usize;
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
// Re-resolve rather than trusting the location detection saw: the table
// may have been repointed, and the vended credentials have expired.
let mut table = dataset::open(&client, &id, &self.storage).await?;
let mut table = dataset::open(&client, &id, &storage).await?;
let before = table.stats().await?;
sender.send_progress(JobProgressUpdate {
+13 -27
View File
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
@@ -13,7 +14,8 @@ use seaweed_worker_core::pb::{
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::admin_cluster::AdminCluster;
use crate::catalog::parse_id;
use crate::dataset::{self, OpenTable};
use crate::jobs::vector_index::is_vector_table;
use crate::jobs::{clamp, string_list, table_id};
@@ -37,18 +39,14 @@ const MAX_UNINDEXED_CEILING: i64 = 100_000_000;
/// the reason a neglected Lance table is a correctness problem rather than a
/// slow one.
pub struct OptimizeIndicesHandler {
namespace_url: String,
storage: dataset::Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
}
impl OptimizeIndicesHandler {
pub fn new(namespace_url: String) -> Self {
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
signing_key: None,
cluster,
metrics: None,
}
}
@@ -57,20 +55,6 @@ impl OptimizeIndicesHandler {
self.metrics = metrics;
self
}
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
self
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
}
}
/// Rows the table's indices cover and rows they miss. A vector table's indices
@@ -194,13 +178,14 @@ impl JobHandler for OptimizeIndicesHandler {
MAX_UNINDEXED_FLOOR,
MAX_UNINDEXED_CEILING,
) as u64;
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let tables = client.list_all_tables().await?;
let mut proposals = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &storage).await {
Ok(table) => table,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -281,8 +266,9 @@ impl JobHandler for OptimizeIndicesHandler {
let id = table_id(&job.parameters)
.ok_or_else(|| anyhow!("job {} carried no table_id", job.job_id))?;
let client = self.client();
let mut table = dataset::open(&client, &id, &self.storage).await?;
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let mut table = dataset::open(&client, &id, &storage).await?;
let vector_table = is_vector_table(&id);
let before = index_rows(&table, vector_table)
.await?
@@ -359,7 +345,7 @@ mod tests {
#[test]
fn a_retrain_gets_a_builds_execution_timeout() {
let descriptor = OptimizeIndicesHandler::new(String::new()).descriptor();
let descriptor = OptimizeIndicesHandler::new(Default::default()).descriptor();
let defaults = descriptor.admin_runtime_defaults.unwrap();
assert_eq!(defaults.execution_timeout_seconds, 3600);
assert_eq!(defaults.job_type_max_runtime_seconds, 3600);
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Result, anyhow, bail};
use async_trait::async_trait;
@@ -11,7 +12,8 @@ use seaweed_worker_core::pb::{
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::admin_cluster::AdminCluster;
use crate::catalog::parse_id;
use crate::dataset;
use crate::jobs::vector_index::{
EXECUTION_TIMEOUT_SECONDS, declare_build_runtime, is_vector_table,
@@ -194,18 +196,14 @@ pub async fn run(
/// indexes, as each index's table records them. The admin dispatches a job
/// when an operator asks; detection finds the rest.
pub struct MetadataIndexHandler {
namespace_url: String,
storage: dataset::Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
}
impl MetadataIndexHandler {
pub fn new(namespace_url: String) -> Self {
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
signing_key: None,
cluster,
metrics: None,
}
}
@@ -214,20 +212,6 @@ impl MetadataIndexHandler {
self.metrics = metrics;
self
}
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
self
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
}
}
fn settings(values: &HashMap<String, ConfigValue>) -> (u64, u64) {
@@ -328,7 +312,8 @@ impl JobHandler for MetadataIndexHandler {
) -> Result<()> {
let (_, min_unindexed_rows) = settings(&request.worker_config_values);
let max_results = usize::try_from(request.max_results).unwrap_or(0);
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let mut proposals = Vec::new();
let mut has_more = false;
'tables: for encoded in &client.list_all_tables().await? {
@@ -336,7 +321,7 @@ impl JobHandler for MetadataIndexHandler {
if !is_vector_table(&id) {
continue;
}
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &storage).await {
Ok(table) => table,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -412,8 +397,9 @@ impl JobHandler for MetadataIndexHandler {
stage: format!("{} {key}", action.as_str()),
..Default::default()
})?;
let client = self.client();
let mut table = dataset::open(&client, &id, &self.storage).await?;
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let mut table = dataset::open(&client, &id, &storage).await?;
let summary = run(
&mut table.dataset,
&key,
+11 -36
View File
@@ -43,48 +43,23 @@ pub(crate) fn table_id(parameters: &HashMap<String, ConfigValue>) -> Option<Vec<
/// Every handler this worker serves. A worker process may serve several job
/// types, which is why WorkerHello carries a list.
pub fn handlers(
namespace_url: String,
storage: crate::dataset::Storage,
signing_key: Option<crate::catalog::SigningKey>,
cluster: Arc<crate::admin_cluster::AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
) -> Vec<Arc<dyn JobHandler>> {
vec![
Arc::new(compact::CompactHandler::new(cluster.clone()).with_metrics(metrics.clone())),
Arc::new(
compact::CompactHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_signing_key(signing_key.clone())
indices::OptimizeIndicesHandler::new(cluster.clone()).with_metrics(metrics.clone()),
),
Arc::new(
vector_index::VectorIndexHandler::new(cluster.clone()).with_metrics(metrics.clone()),
),
Arc::new(
metadata_index::MetadataIndexHandler::new(cluster.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
indices::OptimizeIndicesHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
vector_index::VectorIndexHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
metadata_index::MetadataIndexHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
sort::SortHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
cleanup::CleanupVersionsHandler::new(namespace_url)
.with_storage(storage)
.with_signing_key(signing_key)
.with_metrics(metrics),
),
Arc::new(sort::SortHandler::new(cluster.clone()).with_metrics(metrics.clone())),
Arc::new(cleanup::CleanupVersionsHandler::new(cluster).with_metrics(metrics)),
]
}
+11 -27
View File
@@ -23,7 +23,8 @@ use seaweed_worker_sort::{
};
use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::admin_cluster::AdminCluster;
use crate::catalog::parse_id;
use crate::dataset;
use crate::jobs::{FORMAT, clamp, observation, string_list, table_id};
@@ -52,18 +53,14 @@ const BYTES_PER_MB: u64 = 1024 * 1024;
/// so nothing but a rewrite establishes that order, and nothing but another
/// rewrite restores it once rows have been appended.
pub struct SortHandler {
namespace_url: String,
storage: dataset::Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
}
impl SortHandler {
pub fn new(namespace_url: String) -> Self {
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
signing_key: None,
cluster,
metrics: None,
}
}
@@ -72,21 +69,6 @@ impl SortHandler {
self.metrics = metrics;
self
}
/// Storage options to use where the namespace vends none.
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
self
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
}
}
/// The fragments a dataset holds, in fragment order, as the sort crate reads
@@ -198,14 +180,15 @@ impl JobHandler for SortHandler {
MIN_UNSORTED_ROWS_CEILING,
) as u64;
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let tables = client.list_all_tables().await?;
let mut proposals = Vec::new();
let mut observations = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &storage).await {
Ok(table) => table,
Err(err) => {
// One unreadable table must not end the sweep: the tables
@@ -355,11 +338,12 @@ impl JobHandler for SortHandler {
MAX_ROWS_PER_FILE_CEILING,
) as usize;
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
// Re-resolve rather than trusting what detection saw: the table may have
// been repointed, its declared order changed, and the vended credentials
// have expired.
let table = dataset::open(&client, &id, &self.storage).await?;
let table = dataset::open(&client, &id, &storage).await?;
let before = table.stats().await?;
let config = table.dataset.config().clone();
let spec = resolve(
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Result, anyhow, bail};
use async_trait::async_trait;
@@ -11,7 +12,8 @@ use seaweed_worker_core::pb::{
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::admin_cluster::AdminCluster;
use crate::catalog::parse_id;
use crate::dataset::{self, OpenTable};
use crate::jobs::{clamp, string_list, table_id};
use crate::vector_index::{INDEX_NAME, build, index_names, partitions_for};
@@ -44,18 +46,14 @@ pub(crate) fn declare_build_runtime(parameters: &mut HashMap<String, ConfigValue
/// written after a build, are searched exactly; `lance_optimize_indices` then
/// keeps the index covering.
pub struct VectorIndexHandler {
namespace_url: String,
storage: dataset::Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
metrics: Option<crate::metrics::LanceMetrics>,
}
impl VectorIndexHandler {
pub fn new(namespace_url: String) -> Self {
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
signing_key: None,
cluster,
metrics: None,
}
}
@@ -64,20 +62,6 @@ impl VectorIndexHandler {
self.metrics = metrics;
self
}
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
self
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
}
}
/// `<bucket>$vector$<index>`: a table the S3 Vectors API created.
@@ -167,7 +151,8 @@ impl JobHandler for VectorIndexHandler {
MIN_ROWS_CEILING,
) as usize;
let max_results = usize::try_from(request.max_results).unwrap_or(0);
let client = self.client();
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let tables = client.list_all_tables().await?;
let mut proposals = Vec::new();
@@ -177,7 +162,7 @@ impl JobHandler for VectorIndexHandler {
if !is_vector_table(&id) {
continue;
}
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &storage).await {
Ok(table) => table,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -269,8 +254,9 @@ impl JobHandler for VectorIndexHandler {
let id = table_id(&job.parameters)
.ok_or_else(|| anyhow!("job {} carried no table_id", job.job_id))?;
let client = self.client();
let mut table = dataset::open(&client, &id, &self.storage).await?;
let client = self.cluster.client()?;
let storage = self.cluster.storage()?;
let mut table = dataset::open(&client, &id, &storage).await?;
let rows = table.dataset.count_rows(None).await?;
let partitions = partitions_for(rows);
let mut output: HashMap<String, ConfigValue> = HashMap::new();
@@ -364,7 +350,7 @@ mod tests {
#[test]
fn a_build_gets_longer_than_the_default_execution_timeout() {
let descriptor = VectorIndexHandler::new(String::new()).descriptor();
let descriptor = VectorIndexHandler::new(Default::default()).descriptor();
let defaults = descriptor.admin_runtime_defaults.unwrap();
assert_eq!(defaults.execution_timeout_seconds, 3600);
assert_eq!(defaults.job_type_max_runtime_seconds, 3600);
+1
View File
@@ -9,6 +9,7 @@
// than the default to prove its future Send.
#![recursion_limit = "256"]
pub mod admin_cluster;
pub mod catalog;
pub mod cluster;
pub mod dataset;
+13 -31
View File
@@ -6,6 +6,7 @@ use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use seaweed_worker_core::{Metrics, Registry, TlsOptions, WorkerOptions};
use weed_lance_worker::admin_cluster::AdminCluster;
use weed_lance_worker::handlers;
use weed_lance_worker::metrics::LanceMetrics;
@@ -22,34 +23,14 @@ struct Args {
#[arg(long, default_value = "lance-worker", env = "WEED_WORKER_ID")]
id: String,
/// Lance namespace the worker lists tables from.
#[arg(
long,
default_value = "http://localhost:9101",
env = "WEED_LANCE_NAMESPACE"
)]
namespace: String,
#[arg(long, default_value = "10", env = "WEED_HEARTBEAT_SECONDS")]
heartbeat_seconds: u64,
#[arg(long, default_value = "1")]
max_concurrency: i32,
/// Comma-separated master addresses: the worker asks them for the filers
/// it keeps tables through.
#[arg(long, alias = "master", env = "WEED_MASTERS")]
masters: String,
/// The filer group whose filers the worker uses.
#[arg(
long,
alias = "filer.group",
env = "WEED_FILER_GROUP",
default_value = ""
)]
filer_group: String,
/// The cluster's security.toml; by default the file weed processes find
/// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
/// in ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_WORKER_SECURITY_TOML")]
security_toml: Option<std::path::PathBuf>,
@@ -150,8 +131,7 @@ async fn main() -> Result<()> {
let tls = args.tls()?;
// One security.toml for everything: the admin stream's and the catalog's
// signing key, and the cluster connection.
let security =
weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?;
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
let filer_signing = match args.filer_signing_key.filter(|key| !key.is_empty()) {
Some(key) => Some((key, 0)),
None => security
@@ -185,9 +165,10 @@ async fn main() -> Result<()> {
..Default::default()
};
let cluster =
weed_lance_worker::cluster::Cluster::new(&args.masters, &args.filer_group, &security)?;
let storage = weed_lance_worker::dataset::Storage(Some(cluster.storage(&security).await?));
let cluster = Arc::new(AdminCluster::new(
weed_lance_worker::cluster::connection(&security, String::new())?,
signing_key,
));
let metrics = Metrics::new(&options.worker_id, &options.worker_version)?;
let lance_metrics = LanceMetrics::new(&metrics)?;
@@ -198,11 +179,12 @@ async fn main() -> Result<()> {
);
}
let mut registry = Registry::new().with_preview(Arc::new(
weed_lance_worker::preview::LancePreview::new(args.namespace.clone(), storage.clone())
.with_signing_key(signing_key.clone()),
));
for handler in handlers(args.namespace, storage, signing_key, Some(lance_metrics)) {
let mut registry = Registry::new()
.with_cluster_observer(cluster.clone())
.with_preview(Arc::new(weed_lance_worker::preview::LancePreview::new(
cluster.clone(),
)));
for handler in handlers(cluster, Some(lance_metrics)) {
registry = registry.register(handler);
}
+9 -19
View File
@@ -10,28 +10,19 @@ use async_trait::async_trait;
use futures::TryStreamExt;
use seaweed_worker_core::{Preview, PreviewProvider};
use crate::catalog::{NamespaceClient, SigningKey};
use crate::dataset::{self, Storage};
use std::sync::Arc;
use crate::admin_cluster::AdminCluster;
use crate::dataset;
use crate::jobs::FORMAT;
pub struct LancePreview {
namespace_url: String,
storage: Storage,
signing_key: Option<SigningKey>,
cluster: Arc<AdminCluster>,
}
impl LancePreview {
pub fn new(namespace_url: String, storage: Storage) -> Self {
Self {
namespace_url,
storage,
signing_key: None,
}
}
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
self.signing_key = signing_key;
self
pub fn new(cluster: Arc<AdminCluster>) -> Self {
Self { cluster }
}
}
@@ -42,9 +33,8 @@ impl PreviewProvider for LancePreview {
}
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview> {
let client = NamespaceClient::new(self.namespace_url.clone())
.with_signing_key(self.signing_key.as_ref());
let table = dataset::open(&client, object_id, &self.storage).await?;
let client = self.cluster.client()?;
let table = dataset::open(&client, object_id, &self.cluster.storage()?).await?;
let total_rows = table.dataset.count_rows(None).await.unwrap_or(0) as i64;
let mut scanner = table.dataset.scan();
+12 -54
View File
@@ -1,5 +1,5 @@
//! The cluster's `security.toml`, found and read the way weed processes do:
//! the file in `-config_dir`, `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs`
//! the file in `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs`
//! or `/etc/seaweedfs`, with `WEED_*` environment variables over it.
use std::path::{Path, PathBuf};
@@ -77,23 +77,8 @@ impl std::fmt::Debug for Security {
}
}
// weed's util.ResolvePath for "~" and "~/..."
fn resolve_path(path: &Path, home: Option<&Path>) -> PathBuf {
match (path.strip_prefix("~"), home) {
(Ok(rest), Some(home)) => home.join(rest),
_ => path.to_path_buf(),
}
}
fn candidates(
config_dir: Option<&Path>,
current_dir: Option<&Path>,
home: Option<&Path>,
) -> Vec<PathBuf> {
fn candidates(current_dir: Option<&Path>, home: Option<&Path>) -> Vec<PathBuf> {
let mut found = Vec::new();
if let Some(dir) = config_dir {
found.push(resolve_path(dir, home).join(FILE_NAME));
}
if let Some(dir) = current_dir {
found.push(dir.join(FILE_NAME));
}
@@ -130,21 +115,17 @@ fn entry<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Value> {
}
impl Security {
/// Reads `path`, or the first `security.toml` where weed looks: the
/// `-config_dir`, then `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs`
/// and `/etc/seaweedfs`. Without one, only the environment applies.
pub fn load(path: Option<&Path>, config_dir: Option<&Path>) -> Result<Self> {
/// Reads `path`, or the first `security.toml` where weed looks: `.`,
/// `~/.seaweedfs`, `/usr/local/etc/seaweedfs` and `/etc/seaweedfs`.
/// Without one, only the environment applies.
pub fn load(path: Option<&Path>) -> Result<Self> {
let path = match path {
Some(path) => Some(path.to_path_buf()),
None => {
let home = std::env::var_os("HOME").map(PathBuf::from);
candidates(
config_dir,
std::env::current_dir().ok().as_deref(),
home.as_deref(),
)
.into_iter()
.find(|p| p.is_file())
candidates(std::env::current_dir().ok().as_deref(), home.as_deref())
.into_iter()
.find(|p| p.is_file())
}
};
Self::from_file(path, Box::new(|name| std::env::var(name).ok()))
@@ -559,15 +540,10 @@ mod tests {
#[test]
fn the_file_is_searched_where_weed_looks() {
let found = candidates(
Some(Path::new("/etc/weed")),
Some(Path::new("/cwd")),
Some(Path::new("/home/u")),
);
let found = candidates(Some(Path::new("/cwd")), Some(Path::new("/home/u")));
assert_eq!(
found,
[
"/etc/weed/security.toml",
"/cwd/security.toml",
"/home/u/.seaweedfs/security.toml",
"/usr/local/etc/seaweedfs/security.toml",
@@ -575,32 +551,14 @@ mod tests {
]
.map(PathBuf::from)
);
let home = Some(Path::new("/home/u"));
for (dir, want) in [
("~", "/home/u/security.toml"),
("~/cluster", "/home/u/cluster/security.toml"),
("~other/cluster", "~other/cluster/security.toml"),
("/srv/~/cluster", "/srv/~/cluster/security.toml"),
] {
assert_eq!(
candidates(Some(Path::new(dir)), None, home)[0],
PathBuf::from(want),
"{dir}"
);
}
}
#[test]
fn load_takes_the_config_dir_before_the_usual_places() {
fn an_explicit_file_wins() {
let dir = tempfile::tempdir().unwrap();
let in_config_dir = dir.path().join(FILE_NAME);
std::fs::write(&in_config_dir, "").unwrap();
let loaded = Security::load(None, Some(dir.path())).unwrap();
assert_eq!(loaded.path(), Some(in_config_dir.as_path()));
// An explicit file still wins.
let explicit = dir.path().join("other.toml");
std::fs::write(&explicit, "").unwrap();
let loaded = Security::load(Some(&explicit), Some(dir.path())).unwrap();
let loaded = Security::load(Some(&explicit)).unwrap();
assert_eq!(loaded.path(), Some(explicit.as_path()));
}
}
+31 -13
View File
@@ -6,14 +6,16 @@
#![allow(dead_code)]
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use seaweed_worker_core::pb::ClusterContext;
use seaweed_worker_core::pb::{
ActivityEvent, ConfigValue, DetectionComplete, DetectionProposals, JobCompleted,
JobProgressUpdate, JobProposal, ObjectObservation, WorkerObservations, config_value::Kind,
};
use seaweed_worker_core::{DetectionSender, ExecutionSender};
use seaweed_worker_core::{ClusterObserver, DetectionSender, ExecutionSender};
use weed_lance_worker::admin_cluster::AdminCluster;
use weed_lance_worker::catalog::{NamespaceClient, SigningKey};
/// Keeps everything a handler reports, so a test can assert on it afterwards.
@@ -82,22 +84,38 @@ pub fn int_config(name: &str, value: i64) -> HashMap<String, ConfigValue> {
values
}
/// The cluster's storage, from the masters WEED_MASTERS names. A live
/// namespace without them would have the tests seed tables through lance's
/// own S3 store, which reaches nothing, so the pair is required together.
pub async fn storage() -> weed_lance_worker::dataset::Storage {
let masters = std::env::var("WEED_MASTERS")
/// The cluster as admin would describe it to the worker: the namespace at
/// `url` and the filer WEED_FILER names, as the master lists it (`host:port` or
/// `host:port.grpc`). A live namespace without the filer would have the tests
/// seed tables through lance's own S3 store, which reaches nothing.
pub async fn cluster(url: &str) -> Arc<AdminCluster> {
let filer = std::env::var("WEED_FILER")
.ok()
.filter(|s| !s.is_empty())
.expect("WEED_LANCE_NAMESPACE names a live namespace; WEED_MASTERS must name its masters");
let security = security();
let cluster =
weed_lance_worker::cluster::Cluster::new(&masters, "", &security).expect("masters");
weed_lance_worker::dataset::Storage(Some(cluster.storage(&security).await.expect("storage")))
.expect("WEED_LANCE_NAMESPACE names a live namespace; WEED_FILER must name its filer");
let connection =
weed_lance_worker::cluster::connection(&security(), String::new()).expect("security.toml");
let cluster = AdminCluster::new(connection, signing_key());
cluster
.observe(&ClusterContext {
lance_namespace_urls: vec![url.to_string()],
filer_addresses: vec![filer],
..Default::default()
})
.await;
Arc::new(cluster)
}
/// The cluster's storage, for seeding and reading tables beside a handler.
pub async fn storage() -> weed_lance_worker::dataset::Storage {
cluster(&namespace_url().unwrap_or_default())
.await
.storage()
.expect("storage")
}
fn security() -> weed_lance_worker::security::Security {
weed_lance_worker::security::Security::load(None, None).expect("security.toml")
weed_lance_worker::security::Security::load(None).expect("security.toml")
}
/// The cluster token the namespace authenticates its processes by, from
@@ -15,7 +15,7 @@ use weed_lance_worker::jobs::indices::OptimizeIndicesHandler;
use weed_lance_worker::preview::LancePreview;
mod common;
use common::{Recorder, client, int_config, namespace_url, signing_key, storage};
use common::{Recorder, client, cluster, int_config, namespace_url, storage};
/// These tests drive one live gateway and one shared catalog: `list_all_tables`
/// sweeps everything, so a table another test is writing shows up in this test's
@@ -144,9 +144,7 @@ async fn compacts_a_fragmented_table() {
let encoded = seed_fragmented_table(&url, "compactme", 12)
.await
.expect("seed a fragmented table");
let handler = CompactHandler::new(url)
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = CompactHandler::new(cluster(&url).await);
let recorder = Recorder::default();
let request = RunDetectionRequest {
@@ -234,9 +232,7 @@ async fn cleans_up_old_versions() {
.await
.expect("seed a table with versions to clean");
let handler = CleanupVersionsHandler::new(url)
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = CleanupVersionsHandler::new(cluster(&url).await);
let recorder = Recorder::default();
let request = RunDetectionRequest {
@@ -300,9 +296,7 @@ async fn skips_tables_without_indices() {
.await
.expect("seed a table without an index");
let handler = OptimizeIndicesHandler::new(url)
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = OptimizeIndicesHandler::new(cluster(&url).await);
let recorder = Recorder::default();
let request = RunDetectionRequest {
@@ -341,9 +335,7 @@ async fn reindexes_rows_an_index_does_not_cover() {
let encoded = seed_table(&url, "reindexme", 2, 512, true)
.await
.expect("seed an indexed table with uncovered rows");
let handler = OptimizeIndicesHandler::new(url)
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = OptimizeIndicesHandler::new(cluster(&url).await);
let recorder = Recorder::default();
let request = RunDetectionRequest {
@@ -416,7 +408,7 @@ async fn previews_rows_of_a_table() {
.await
.expect("seed a table to preview");
let provider = LancePreview::new(url, storage().await);
let provider = LancePreview::new(cluster(&url).await);
let id = vec!["vec".to_string(), "ml".to_string(), "previewme".to_string()];
let preview = provider.preview(&id, 4).await.expect("preview the table");
@@ -18,7 +18,7 @@ use weed_lance_worker::jobs::cleanup::{self, CleanupVersionsHandler};
use weed_lance_worker::jobs::compact::{CompactHandler, JOB_TYPE as COMPACT_JOB_TYPE};
mod common;
use common::{Recorder, int_config, namespace_url, signing_key, storage};
use common::{Recorder, cluster, int_config, namespace_url};
fn table() -> Option<String> {
std::env::var("WEED_LANCE_TABLE")
@@ -40,18 +40,14 @@ async fn maintains_the_named_table() {
// anything above one fragment is worth merging here.
let mut config = int_config("min_fragments", 2);
config.extend(int_config("target_rows_per_fragment", 1_048_576));
let compact = CompactHandler::new(url.clone())
.with_storage(storage().await)
.with_signing_key(signing_key());
let compact = CompactHandler::new(cluster(&url).await);
run(&compact, COMPACT_JOB_TYPE, &name, config, true).await;
// Keep the current version and retain nothing else, so the versions
// compaction superseded are actually removed rather than counted.
let mut config = int_config("min_versions_to_keep", 1);
config.extend(int_config("retain_hours", 0));
let cleanup = CleanupVersionsHandler::new(url)
.with_storage(storage().await)
.with_signing_key(signing_key());
let cleanup = CleanupVersionsHandler::new(cluster(&url).await);
run(&cleanup, cleanup::JOB_TYPE, &name, config, true).await;
}
+5 -13
View File
@@ -12,7 +12,7 @@ use seaweed_worker_core::pb::{
use weed_lance_worker::jobs::sort::{JOB_TYPE, SortHandler};
mod common;
use common::{Recorder, client, namespace_url, signing_key, storage};
use common::{Recorder, client, cluster, namespace_url, storage};
/// One live gateway and one shared catalog, and `list_all_tables` sweeps
/// everything, so these tests take a lock the way the compaction ones do.
@@ -156,9 +156,7 @@ async fn sorts_a_table_and_stops_proposing_it() {
"the seeded table was already sorted, so the test proves nothing"
);
let handler = SortHandler::new(url.clone())
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = SortHandler::new(cluster(&url).await);
let recorder = Recorder::default();
let detection = RunDetectionRequest {
request_id: "detect-sort".to_string(),
@@ -253,9 +251,7 @@ async fn leaves_a_table_that_declares_no_order_alone() {
.await
.expect("seed a table with no declared order");
let handler = SortHandler::new(url.clone())
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = SortHandler::new(cluster(&url).await);
let recorder = Recorder::default();
handler
.detect(
@@ -298,9 +294,7 @@ async fn proposes_a_replacement_that_barely_changes_the_row_count() {
.await
.expect("seed an unsorted table");
let handler = SortHandler::new(url.clone())
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = SortHandler::new(cluster(&url).await);
// A threshold no realistic append would cross, so nothing but the identity
// of the data can be what proposes this table.
let detection = RunDetectionRequest {
@@ -393,9 +387,7 @@ async fn deletions_do_not_hide_appended_rows() {
.await
.expect("seed an unsorted table");
let handler = SortHandler::new(url.clone())
.with_storage(storage().await)
.with_signing_key(signing_key());
let handler = SortHandler::new(cluster(&url).await);
let detection = RunDetectionRequest {
request_id: "detect-delete".to_string(),
job_type: JOB_TYPE.to_string(),
@@ -83,13 +83,13 @@ func (env *environment) maintainLanceTable(t *testing.T, bucket, namespace, tabl
cmd := exec.CommandContext(ctx, "cargo", "test",
"-p", "weed-lance-worker", "--test", "lifecycle", "--", "--nocapture")
cmd.Dir = filepath.Join(env.rootDir, "seaweed-worker")
// The worker keeps the table through the filers and volume servers the
// masters name, and the namespace knows it by the cluster key; it holds
// no S3 credentials.
// The handlers are given the namespace and the filer as admin would name
// them, and the namespace knows the worker by the cluster key; it holds no
// S3 credentials.
cmd.Env = append(cmd.Environ(),
fmt.Sprintf("WEED_LANCE_NAMESPACE=http://127.0.0.1:%d", env.lancePort),
fmt.Sprintf("WEED_LANCE_TABLE=%s$%s$%s", bucket, namespace, table),
fmt.Sprintf("WEED_MASTERS=127.0.0.1:%d.%d", env.masterPort, env.masterGrpcPort),
fmt.Sprintf("WEED_FILER=127.0.0.1:%d.%d", env.filerPort, env.filerGrpcPort),
"WEED_JWT_FILER_SIGNING_KEY="+env.clusterKey,
)
out, err := cmd.CombinedOutput()
+4 -5
View File
@@ -333,11 +333,11 @@ def run_cluster(param, tmp_path_factory, identities):
return response.status == 200
wait_for(vector_ready, processes, "vector engine did not register with master")
def restart_engine(env=None):
"""Restart the single engine with `env` added to its environment."""
def restart_engine():
"""Restart the single engine, so a workload starts with empty caches."""
old = processes["vector"]
stop(old)
start("vector", old.args, env=env)
start("vector", old.args)
wait_for(vector_ready, processes, "vector engine did not come back")
if os.environ.get("VECTOR_TLS"):
@@ -379,8 +379,7 @@ def run_cluster(param, tmp_path_factory, identities):
if os.environ.get("VECTOR_TLS"):
tls_args = ["--tls-ca", str(directory / "ca.pem"), "--tls-cert", str(directory / "cert.pem"), "--tls-key", str(directory / "key.pem"), "--tls-server-name", "localhost"]
start("lance-worker", [lance_worker, "--admin", f"127.0.0.1:{admin}.{admin_grpc}",
"--namespace", f"http://127.0.0.1:{lance}", "--id", "vectors-test-worker",
"--masters", master_addr, "--filer-group", filer_group, *tls_args])
"--id", "vectors-test-worker", *tls_args])
wait_for(lambda: "lance_vector_index" in
[jt["job_type"] for jt in json.load(urllib.request.urlopen(f"{admin_url}/api/plugin/job-types", timeout=2))],
processes, "the Lance worker never registered with admin")
+47 -59
View File
@@ -33,10 +33,6 @@ one more index per locality, each row with an `author` key, and queries
(seed 5) over the whole index; "clustered": they are
consecutive keys, written together, so they land in
few fragments ("scattered"; both: "scattered,clustered")
PERF_FILTER_MODES "warm": engine restarted with default caches;
"cold": engine restarted with its read, index and
metadata caches at 0 MB, so every query reads again
("warm")
PERF_FILTER_ROUNDS rounds; each round runs every author and locality in
turn (1)
@@ -48,8 +44,7 @@ distance, responses without a `vectors` field (counted, and the test fails
after every scenario ran; results and recall then come from the same query
repeated, untimed, without returnDistance), and the reads per query: the engine's cache_requests_total misses,
storage_read_seconds count and storage_read_bytes_total (immutable files
only, and none when cold: they come from the read cache, which a 0 MB
setting removes) and the volume server's request_total (every request,
only) and the volume server's request_total (every request,
manifests included). The engine does not expose the partitions a query
probed.
@@ -93,10 +88,8 @@ NOISE = float(os.environ.get("PERF_NOISE", "0.3"))
INDEX = "perf"
FILTER_AUTHORS = os.environ.get("PERF_FILTER_AUTHORS", "alice=0.1,bob=0.01,carol=0.0001,dave=#5,nobody=#0")
FILTER_LOCALITY = os.environ.get("PERF_FILTER_LOCALITY", "scattered").split(",")
FILTER_MODES = os.environ.get("PERF_FILTER_MODES", "warm").split(",")
FILTER_ROUNDS = int(os.environ.get("PERF_FILTER_ROUNDS", "1"))
FILTER_SEED = 5
COLD = {"WEED_VECTOR_READ_CACHE_MB": "0", "WEED_VECTOR_INDEX_CACHE_MB": "0", "WEED_VECTOR_METADATA_CACHE_MB": "0"}
REPORT = {}
@@ -346,7 +339,6 @@ def test_query_filter_workload(perf):
s3v, data, queries, cluster = perf["client"], perf["data"], perf["queries"], perf["cluster"]
if cluster["mode"] != "single":
pytest.skip("restart_engine restarts one engine")
assert set(FILTER_MODES) <= {"warm", "cold"}, FILTER_MODES
unit = np.array([v for v, _ in data], dtype=np.float64)
unit /= np.linalg.norm(unit, axis=1, keepdims=True)
indexes, eligible, setup = {}, {}, {}
@@ -372,56 +364,52 @@ def test_query_filter_workload(perf):
assert {name: len(eligible[locality, name]) for name in planted} == planted
eligible.update({(locality, None): np.arange(VECTORS) for locality in FILTER_LOCALITY})
perf["report"]["filter_workload"] = report = {
"seed": FILTER_SEED, "authors": FILTER_AUTHORS, "eligible": planted, "modes": FILTER_MODES,
"seed": FILTER_SEED, "authors": FILTER_AUTHORS, "eligible": planted,
"rounds": FILTER_ROUNDS, "setup": setup, "partitions_probed": "not exposed by the engine", "runs": []}
for mode in FILTER_MODES:
cluster["restart_engine"](COLD if mode == "cold" else {})
for round_ in range(FILTER_ROUNDS):
for author in [None, *planted]:
for locality in FILTER_LOCALITY:
args = indexes[locality]
rows = eligible[locality, author]
keep = set(rows.tolist())
extra = {"filter": {"author": author}} if author else {}
s3v.query_vectors(**args, queryVector={"float32": queries[0]}, topK=TOPK, **extra)
latencies, recalls, results, nonfinite, without_vectors = [], [], [], 0, 0
reads = dict.fromkeys(engine_reads(cluster), 0.0)
for query in queries:
before = engine_reads(cluster)
seconds, response = timed(lambda: s3v.query_vectors(
**args, queryVector={"float32": query}, topK=TOPK, returnDistance=True, **extra))
after = engine_reads(cluster)
for name in reads:
reads[name] += after[name] - before[name]
latencies.append(seconds)
if "vectors" in response:
nonfinite += sum(1 for h in response["vectors"]
if not math.isfinite(h.get("distance", math.nan)))
else:
without_vectors += 1
response = s3v.query_vectors(**args, queryVector={"float32": query}, topK=TOPK, **extra)
hits = response["vectors"]
assert all(int(h["key"][1:]) in keep for h in hits), hits
assert len(hits) <= min(TOPK, len(rows)), hits
results.append(len(hits))
recalls.append(filtered_recall(unit, rows, query, TOPK, hits))
recalls = [r for r in recalls if r is not None]
row = {"mode": mode, "round": round_, "locality": locality, "author": author,
"eligible": len(rows), **summarize(latencies),
"recall_at_k": statistics.fmean(recalls) if recalls else None,
"min_recall_at_k": min(recalls) if recalls else None,
"results_mean": statistics.fmean(results), "results_min": min(results),
"nonfinite_distances": nonfinite, "responses_without_vectors": without_vectors,
**{f"{name}_per_query": value / len(queries) for name, value in reads.items()},
# Without a read cache the engine has no storage counters.
**({f"{name}_per_query": None for name in ("cache_misses", "storage_reads", "storage_bytes")}
if mode == "cold" else {}),
"load_1m": os.getloadavg()[0]}
report["runs"].append(row)
print(json.dumps(row))
assert INDEXED or not recalls or statistics.fmean(recalls) >= 0.9
if without_vectors:
empty.append(f"{mode} {locality} {author}: {without_vectors}")
cluster["restart_engine"]()
for round_ in range(FILTER_ROUNDS):
for author in [None, *planted]:
for locality in FILTER_LOCALITY:
args = indexes[locality]
rows = eligible[locality, author]
keep = set(rows.tolist())
extra = {"filter": {"author": author}} if author else {}
s3v.query_vectors(**args, queryVector={"float32": queries[0]}, topK=TOPK, **extra)
latencies, recalls, results, nonfinite, without_vectors = [], [], [], 0, 0
reads = dict.fromkeys(engine_reads(cluster), 0.0)
for query in queries:
before = engine_reads(cluster)
seconds, response = timed(lambda: s3v.query_vectors(
**args, queryVector={"float32": query}, topK=TOPK, returnDistance=True, **extra))
after = engine_reads(cluster)
for name in reads:
reads[name] += after[name] - before[name]
latencies.append(seconds)
if "vectors" in response:
nonfinite += sum(1 for h in response["vectors"]
if not math.isfinite(h.get("distance", math.nan)))
else:
without_vectors += 1
response = s3v.query_vectors(**args, queryVector={"float32": query}, topK=TOPK, **extra)
hits = response["vectors"]
assert all(int(h["key"][1:]) in keep for h in hits), hits
assert len(hits) <= min(TOPK, len(rows)), hits
results.append(len(hits))
recalls.append(filtered_recall(unit, rows, query, TOPK, hits))
recalls = [r for r in recalls if r is not None]
row = {"round": round_, "locality": locality, "author": author,
"eligible": len(rows), **summarize(latencies),
"recall_at_k": statistics.fmean(recalls) if recalls else None,
"min_recall_at_k": min(recalls) if recalls else None,
"results_mean": statistics.fmean(results), "results_min": min(results),
"nonfinite_distances": nonfinite, "responses_without_vectors": without_vectors,
**{f"{name}_per_query": value / len(queries) for name, value in reads.items()},
"load_1m": os.getloadavg()[0]}
report["runs"].append(row)
print(json.dumps(row))
assert INDEXED or not recalls or statistics.fmean(recalls) >= 0.9
if without_vectors:
empty.append(f"{locality} {author}: {without_vectors}")
finally:
cluster["restart_engine"]()
for args in indexes.values():
@@ -521,7 +509,7 @@ def print_report(combo, report, path):
f"p95 {r['p95_ms']:7.1f} ms")
for r in report.get("filter_workload", {}).get("runs", []):
recall_text = "n/a" if r["recall_at_k"] is None else f"{r['recall_at_k']:.3f}"
lines.append(f"filter {r['mode']} r{r['round']} {r['locality']:<9} {str(r['author']):<8} "
lines.append(f"filter r{r['round']} {r['locality']:<9} {str(r['author']):<8} "
f"{r['eligible']:>7} rows p50 {r['p50_ms']:7.1f} ms p95 {r['p95_ms']:7.1f} ms "
f"recall@k {recall_text} results {r['results_mean']:.1f} (min {r['results_min']}) "
f"empty {r['responses_without_vectors']} "
+4 -5
View File
@@ -143,15 +143,14 @@ def assert_engine_wrote_like_the_gateway(cluster, index):
def run_cli(cluster, *args):
"""weed-vector-cli's JSON answer. It reaches the cluster through the
namespace that names the tables, the masters whose filers hold them and the
cluster token's key, and finds security.toml and the read key where the
weed processes do."""
masters, whose gateways and filers hold the tables, and the cluster token's
key, and finds security.toml and the read key where the weed processes do."""
import os
import subprocess
from pathlib import Path
cli = Path(os.environ.get("VECTOR_CLI_BINARY", Path(__file__).resolve().parent / "weed-vector-cli")).resolve()
command = [str(cli), "--namespace", cluster["catalog"], "--masters", cluster["masters"],
"--filer-signing-key", cluster["filer_signing_key"], "--filer-group", os.environ.get("VECTOR_FILER_GROUP", ""), *args]
command = [str(cli), "--masters", cluster["masters"], "--filer-signing-key", cluster["filer_signing_key"],
"--filer-group", os.environ.get("VECTOR_FILER_GROUP", ""), *args]
return json.loads(subprocess.run(command, check=True, capture_output=True, text=True,
cwd=cluster["directory"], env=cluster["env"]).stdout)
+19
View File
@@ -16,8 +16,10 @@ import (
"github.com/seaweedfs/seaweedfs/weed/admin/plugin"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
@@ -781,6 +783,9 @@ func (s *AdminServer) parseOrBuildClusterContext(raw json.RawMessage) (*plugin_p
if len(contextMessage.S3GrpcAddresses) == 0 {
contextMessage.S3GrpcAddresses = append(contextMessage.S3GrpcAddresses, fallback.S3GrpcAddresses...)
}
if len(contextMessage.LanceNamespaceUrls) == 0 {
contextMessage.LanceNamespaceUrls = append(contextMessage.LanceNamespaceUrls, fallback.LanceNamespaceUrls...)
}
if contextMessage.Metadata == nil {
contextMessage.Metadata = map[string]string{}
}
@@ -857,6 +862,9 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
}
s3Seen[address] = struct{}{}
clusterContext.S3GrpcAddresses = append(clusterContext.S3GrpcAddresses, address)
if url := lanceNamespaceURL(address, node.GetLancePort()); url != "" {
clusterContext.LanceNamespaceUrls = append(clusterContext.LanceNamespaceUrls, url)
}
}
return nil
}); err != nil {
@@ -867,10 +875,21 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
sort.Strings(clusterContext.FilerAddresses)
sort.Strings(clusterContext.VolumeGrpcAddresses)
sort.Strings(clusterContext.S3GrpcAddresses)
sort.Strings(clusterContext.LanceNamespaceUrls)
return clusterContext
}
// lanceNamespaceURL is where the S3 gateway registered as gatewayAddress serves
// its Lance Namespace, or "" when it serves none. The catalog listens on the
// gateway's bind address, which is the host it registered under.
func lanceNamespaceURL(gatewayAddress string, lancePort uint32) string {
if lancePort == 0 {
return ""
}
return "http://" + util.JoinHostPort(pb.ServerAddress(gatewayAddress).ToHost(), int(lancePort))
}
const parseProtoJSONBodyMaxBytes = 1 << 20 // 1 MB
func parseProtoJSONBody(w http.ResponseWriter, r *http.Request, message proto.Message) error {
+20
View File
@@ -0,0 +1,20 @@
package dash
import "testing"
func TestLanceNamespaceURL(t *testing.T) {
for _, tc := range []struct {
address string
port uint32
want string
}{
{"10.0.0.5:18333", 9101, "http://10.0.0.5:9101"},
{"s3-0.s3.default:18333", 9200, "http://s3-0.s3.default:9200"},
{"[fd00::5]:18333", 9101, "http://[fd00::5]:9101"},
{"10.0.0.5:18333", 0, ""},
} {
if got := lanceNamespaceURL(tc.address, tc.port); got != tc.want {
t.Errorf("lanceNamespaceURL(%q, %d) = %q, want %q", tc.address, tc.port, got, tc.want)
}
}
}
@@ -0,0 +1,31 @@
package plugin
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
// cloneClusterContext copies field by field, so a field added to the message
// and not to the copy would vanish from every scheduled request.
func TestCloneClusterContextKeepsEveryField(t *testing.T) {
in := &plugin_pb.ClusterContext{}
m := in.ProtoReflect()
fields := m.Descriptor().Fields()
for i := 0; i < fields.Len(); i++ {
fd := fields.Get(i)
switch {
case fd.IsMap():
m.Mutable(fd).Map().Set(protoreflect.ValueOfString("k").MapKey(), protoreflect.ValueOfString("v"))
case fd.IsList() && fd.Kind() == protoreflect.StringKind:
m.Mutable(fd).List().Append(protoreflect.ValueOfString(string(fd.Name())))
default:
t.Fatalf("field %s has a shape this test does not fill; extend it", fd.Name())
}
}
if out := cloneClusterContext(in); !proto.Equal(in, out) {
t.Fatalf("clone dropped a field:\n in: %v\nout: %v", in, out)
}
}
@@ -0,0 +1,31 @@
package plugin
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// A provider stuck on master discovery must not hold a preview past its deadline.
func TestLoadClusterContextReturnsAtCallerDeadline(t *testing.T) {
release := make(chan struct{})
defer close(release)
r := &Plugin{clusterContextProvider: func(context.Context) (*plugin_pb.ClusterContext, error) {
<-release
return &plugin_pb.ClusterContext{}, nil
}}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
start := time.Now()
_, err := r.loadSchedulerClusterContext(ctx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want DeadlineExceeded", err)
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("returned after %v, want about the caller's 100ms deadline", elapsed)
}
}
+1
View File
@@ -116,6 +116,7 @@ func cloneClusterContext(in *plugin_pb.ClusterContext) *plugin_pb.ClusterContext
FilerAddresses: in.FilerAddresses,
VolumeGrpcAddresses: in.VolumeGrpcAddresses,
S3GrpcAddresses: in.S3GrpcAddresses,
LanceNamespaceUrls: in.LanceNamespaceUrls,
}
if in.Metadata != nil {
out.Metadata = make(map[string]string, len(in.Metadata))
+19 -3
View File
@@ -837,9 +837,25 @@ func (r *Plugin) loadSchedulerClusterContext(ctx context.Context) (*plugin_pb.Cl
clusterCtx, cancel := context.WithTimeout(ctx, defaultClusterContextTimeout)
defer cancel()
clusterContext, err := r.clusterContextProvider(clusterCtx)
if err != nil {
return nil, err
// The provider may block on master discovery without watching its context.
type loaded struct {
clusterContext *plugin_pb.ClusterContext
err error
}
done := make(chan loaded, 1)
go func() {
clusterContext, err := r.clusterContextProvider(clusterCtx)
done <- loaded{clusterContext, err}
}()
var clusterContext *plugin_pb.ClusterContext
select {
case result := <-done:
if result.err != nil {
return nil, result.err
}
clusterContext = result.clusterContext
case <-clusterCtx.Done():
return nil, fmt.Errorf("load cluster context: %w", clusterCtx.Err())
}
if clusterContext == nil {
return nil, fmt.Errorf("cluster context provider returned nil")
+12 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -53,14 +54,22 @@ func (r *Plugin) RequestObjectPreview(ctx context.Context, objectID []string, fo
r.pendingPreviewMu.Unlock()
}()
// A worker restarted since it reported the object knows nothing of the
// cluster until a request tells it.
clusterContext, err := r.loadSchedulerClusterContext(ctx)
if err != nil {
glog.V(1).Infof("preview %s: no cluster context: %v", requestID, err)
}
request := &plugin_pb.AdminToWorkerMessage{
RequestId: requestID,
SentAt: timestamppb.Now(),
Body: &plugin_pb.AdminToWorkerMessage_RequestObjectPreview{
RequestObjectPreview: &plugin_pb.RequestObjectPreview{
ObjectId: objectID,
Format: format,
RowLimit: requestedRows,
ObjectId: objectID,
Format: format,
RowLimit: requestedRows,
ClusterContext: clusterContext,
},
},
}
+14
View File
@@ -2,6 +2,7 @@ package cluster
import (
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
@@ -25,6 +26,7 @@ type Rack string
type ClusterNode struct {
Address pb.ServerAddress
Version string
LancePort atomic.Uint32 // set after the node is listed, so read atomically
counter int
CreatedTs time.Time
DataCenter DataCenter
@@ -203,3 +205,15 @@ func buildClusterNodeUpdateMessage(isAdd bool, filerGroup FilerGroupName, nodeTy
})
return
}
// SetLancePort records the Lance Namespace port a registered S3 gateway serves.
func (cluster *Cluster) SetLancePort(ns string, address pb.ServerAddress, port uint32) {
g := cluster.s3Groups
g.RLock()
defer g.RUnlock()
if m := g.getGroupMembers(FilerGroupName(ns), false); m != nil {
if node, found := m.members[address]; found {
node.LancePort.Store(port)
}
}
}
+27
View File
@@ -0,0 +1,27 @@
package cluster
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
func TestSetLancePort(t *testing.T) {
c := NewCluster()
gateway := pb.ServerAddress("10.0.0.30:18333")
// Registered directly, so the test does not depend on AddClusterNode's arguments.
c.s3Groups.getGroupMembers("group", true).members[gateway] = &ClusterNode{Address: gateway}
c.SetLancePort("group", gateway, 9101)
// A gateway of another group, or one that never registered, records nothing.
c.SetLancePort("", gateway, 9200)
c.SetLancePort("group", pb.ServerAddress("10.0.0.31:18333"), 9300)
nodes := c.ListClusterNode("group", S3Type)
if len(nodes) != 1 || nodes[0].LancePort.Load() != 9101 {
t.Fatalf("want the gateway listed with port 9101, got %d nodes", len(nodes))
}
if nodes := c.ListClusterNode("", S3Type); len(nodes) != 0 {
t.Fatalf("SetLancePort must not register a node, got %d", len(nodes))
}
}
+4 -1
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"github.com/seaweedfs/seaweedfs/weed/credential"
@@ -529,7 +530,9 @@ func (fo *FilerOptions) startFiler() {
if err != nil {
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
}
grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.filer"))
grpcTLSOption, grpcTLSReloadOption := security.LoadServerTLS(util.GetViper(), "grpc.filer")
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, fs.GrpcScopeServerOptions()...)
grpcS := pb.NewGrpcServer(grpcOptions...)
filer_pb.RegisterSeaweedFilerServer(grpcS, fs)
// IAM RPCs require a Bearer token signed with jwt.filer_signing.key when it
+4 -1
View File
@@ -55,7 +55,10 @@ func startMiniVector() error {
args = append(args, fmt.Sprintf("--metrics-port=%d", *miniVectorMetricsPort), "--metrics-ip="+bindIP)
}
if directory := util.ConfigurationFileDirectory.String(); directory != "" {
args = append(args, "--config-dir="+util.ResolvePath(directory))
path := filepath.Join(util.ResolvePath(directory), "security.toml")
if _, explicit := os.LookupEnv("WEED_VECTOR_SECURITY_TOML"); !explicit && util.FileExists(path) {
args = append(args, "--security-toml="+path)
}
}
command := exec.CommandContext(miniClientsCtx(), binary, args...)
command.Stdout, command.Stderr = os.Stdout, os.Stderr
+2
View File
@@ -20,6 +20,7 @@ type MountOptions struct {
chunkSizeLimitMB *int
concurrentWriters *int
concurrentReaders *int
volumeReadAuth *bool
readerCacheSizeMB *int64
memoryLimitMB *int64
cacheMetaTtlSec *int
@@ -110,6 +111,7 @@ func init() {
mountOptions.chunkSizeLimitMB = cmdMount.Flag.Int("chunkSizeLimitMB", 2, "local write buffer size, also chunk large files")
mountOptions.concurrentWriters = cmdMount.Flag.Int("concurrentWriters", 128, "limit concurrent goroutine writers")
mountOptions.concurrentReaders = cmdMount.Flag.Int("concurrentReaders", 128, "limit concurrent chunk fetches for read operations")
mountOptions.volumeReadAuth = cmdMount.Flag.Bool("volumeReadAuth", false, "read chunks with the exact-fid tokens the filer returns (LookupDirectoryEntries read_auth) instead of signing with jwt.signing.read.key")
mountOptions.memoryLimitMB = cmdMount.Flag.Int64("memoryLimitMB", 0, "soft Go runtime memory limit in MiB; 0 preserves GOMEMLIMIT; leave headroom below the container limit")
mountOptions.readerCacheSizeMB = cmdMount.Flag.Int64("readerCacheSizeMB", 256, "memory budget in MiB for downloaded and in-flight reader buffers across all files; must fit the largest pooled chunk buffer")
mountOptions.cacheDirForRead = cmdMount.Flag.String("cacheDir", os.TempDir(), "local cache directory for file chunks and meta data")
+1
View File
@@ -211,6 +211,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
FilerSigningKey: security.SigningKey(util.GetViper().GetString("jwt.filer_signing.key")),
FilerSigningExpiresAfterSec: util.GetViper().GetInt("jwt.filer_signing.expires_after_seconds"),
FilerMountRootPath: p.mountRoot,
VolumeReadAuth: option.volumeReadAuth != nil && *option.volumeReadAuth,
Collection: *option.collection,
Replication: *option.replication,
TtlSec: int32(*option.ttlSec),
+29 -10
View File
@@ -5,6 +5,7 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"net/http"
"os"
"runtime"
@@ -397,6 +398,8 @@ func (s3opt *S3Options) startS3Server() bool {
readerCacheSizeMB = *s3opt.readerCacheSizeMB
}
lanceListener, lanceLocalListener := s3opt.listenLance(listenOnLocalhost)
s3ApiServer, s3ApiServer_err = s3api.NewS3ApiServer(router, &s3api.S3ApiServerOption{
Filers: filerAddresses,
HomeFiler: pb.ServerAddress(s3opt.homeFiler),
@@ -430,6 +433,7 @@ func (s3opt *S3Options) startS3Server() bool {
AllowUntrustedRemoteEndpoints: *s3opt.allowUntrustedRemoteEndpoints,
AllowBackslashInKey: *s3opt.allowBackslashInKey,
LancePort: s3opt.lancePort(),
IamSelfServiceRequiresGrant: *s3opt.iamSelfServiceRequiresGrant,
RoutedLookupTimeout: *s3opt.routedLookupTimeout,
UnreachableOwnerTTL: *s3opt.unreachableOwnerTTL,
@@ -454,10 +458,8 @@ func (s3opt *S3Options) startS3Server() bool {
// The S3 Vectors API resolves its tables through the catalog in process,
// whether or not the catalog's own port is served.
s3opt.lanceServer = s3opt.newLanceServer(s3ApiServer)
if s3opt.portLance != nil && *s3opt.portLance > 0 {
if httpS := s3opt.startLanceServer(listenOnLocalhost); httpS != nil {
httpServers = append(httpServers, httpS)
}
if lanceListener != nil {
httpServers = append(httpServers, s3opt.startLanceServer(lanceListener, lanceLocalListener))
}
// The Vectors API rides the main -port listener whenever a weed-vector
@@ -736,21 +738,38 @@ func (s3opt *S3Options) newLanceServer(s3ApiServer *s3api.S3ApiServer) *lance.Se
return lanceServer
}
// startLanceServer serves the Lance Namespace catalog on its own port.
func (s3opt *S3Options) startLanceServer(listenOnLocalhost bool) *http.Server {
lanceRouter := mux.NewRouter().SkipClean(true)
lanceRouter.Use(util_http.EscapeSemicolonsInQuery)
s3opt.lanceServer.RegisterRoutes(lanceRouter)
// lancePort is the port the Lance Namespace is served on, or 0 when it is not.
func (s3opt *S3Options) lancePort() uint32 {
if !s3opt.lanceBound.Load() {
return 0
}
return uint32(*s3opt.portLance)
}
// listenLance binds the Lance Namespace port before the gateway registers
// with the master, so a port that failed to bind is never advertised.
func (s3opt *S3Options) listenLance(listenOnLocalhost bool) (lanceListener, lanceLocalListener net.Listener) {
if s3opt.portLance == nil || *s3opt.portLance <= 0 {
return nil, nil
}
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portLance)
lanceListener, lanceLocalListener, err := util.NewIpAndLocalListeners(
*s3opt.bindIp, *s3opt.portLance, idleTimeoutSeconds(s3opt.idleTimeout), listenOnLocalhost)
if err != nil {
glog.Errorf("Lance Namespace listener on %s error: %v", listenAddress, err)
return nil
return nil, nil
}
s3opt.lanceBound.Store(true)
return lanceListener, lanceLocalListener
}
// startLanceServer serves the Lance Namespace catalog on its own port.
func (s3opt *S3Options) startLanceServer(lanceListener, lanceLocalListener net.Listener) *http.Server {
lanceRouter := mux.NewRouter().SkipClean(true)
lanceRouter.Use(util_http.EscapeSemicolonsInQuery)
s3opt.lanceServer.RegisterRoutes(lanceRouter)
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portLance)
glog.V(0).Infof("Start Lance Namespace Server at http://%s", listenAddress)
httpS := newHttpServer(lanceRouter, nil)
+6 -4
View File
@@ -50,14 +50,16 @@ func TestAuxListenerBindFailureIsNonFatal(t *testing.T) {
if s3opt.icebergBound.Load() {
t.Error("icebergBound must stay false when the listener failed to bind")
}
s3opt.lanceServer = s3opt.newLanceServer(s3a)
if s := s3opt.startLanceServer(false); s != nil {
s.Close()
t.Error("startLanceServer on an occupied port should return nil")
if l, _ := s3opt.listenLance(false); l != nil {
l.Close()
t.Error("listenLance on an occupied port should return nil")
}
if s3opt.lanceBound.Load() {
t.Error("lanceBound must stay false when the listener failed to bind")
}
if port := s3opt.lancePort(); port != 0 {
t.Errorf("lancePort = %d for an unbound listener, want 0 so it is not advertised", port)
}
}
// -iceberg.credentialRole reaches the S3 server once, before either catalog
+8
View File
@@ -100,6 +100,14 @@ previous_key = ""
# write the IAM store under /etc/iam; if the filer gRPC port is reachable
# beyond a trusted network, enable [grpc.filer] mTLS below.
# the jwt defaults to expire after 10 seconds.
# Filesystem gRPC callers may send authorization: Bearer <token> signed with
# this key. allowed_prefixes grant read/write paths; read_prefixes grant reads.
# allowed_methods optionally restricts gRPC method names. Scoped tokens require
# jti and exp, cannot introduce new chunk ids, and cannot call unruled methods.
# Calls without a token retain their existing behavior. This is scope enforcement,
# not mandatory authentication; restrict network access to the filer as before.
# Rolling upgrades: older filers treat a read_prefixes-only token as an admin
# token. Mint read-only tokens only after every filer runs this version or newer.
[jwt.filer_signing]
key = ""
expires_after_seconds = 10 # seconds
+6 -7
View File
@@ -187,13 +187,12 @@ retry:
rc.RUnlock()
}
if shouldCache || rc.lookupFileIdFn == nil {
n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset))
if n > 0 {
// Served from the chunk cache: the stream has left its pinned chunk.
rc.unpin(stream.detach(nil))
return n, err
}
// shouldCache only admits new downloads: a chunk past the cutoff can still
// be cached (uploads on peer-sharing and read-auth mounts cache every chunk).
if n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset)); n > 0 {
// Served from the chunk cache: the stream has left its pinned chunk.
rc.unpin(stream.detach(nil))
return n, err
}
rc.Lock()
+2 -1
View File
@@ -285,7 +285,8 @@ func TestReaderCachePrefetchBufferDroppedAfterRead(t *testing.T) {
buffer[0] = 42
return len(buffer), nil
}
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewSize: 4 << 10, ChunkSize: 4 << 10}}, 1)
// Past the 1 MiB cache cutoff, so the prefetch does not land in the chunk cache.
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewOffset: 2 << 20, ViewSize: 4 << 10, ChunkSize: 4 << 10}}, 1)
buf := make([]byte, 4<<10)
n, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false)
+25
View File
@@ -1176,3 +1176,28 @@ func TestReaderCacheDestroyCancelsDownloadAfterItsLastStream(t *testing.T) {
t.Fatalf("orphaned download: got %v, want context.Canceled", err)
}
}
func TestReaderCacheServesCachedChunkPastCacheCutoff(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
testData := []byte("uploaded chunk cached before its entry is published")
cache.SetChunk("uploaded-file", testData)
var lookups int32
rc := NewReaderCache(10, cache, func(ctx context.Context, fileId string) ([]string, error) {
atomic.AddInt32(&lookups, 1)
return nil, fmt.Errorf("no read token for %s", fileId)
}, nil)
defer rc.destroy()
buffer := make([]byte, len(testData))
n, err := rc.ReadChunkAt(context.Background(), buffer, "uploaded-file", nil, false, 0, len(testData), false)
if err != nil {
t.Fatalf("read: %v", err)
}
if n != len(testData) || string(buffer) != string(testData) {
t.Fatalf("read %d bytes %q, want the cached chunk", n, buffer[:n])
}
if got := atomic.LoadInt32(&lookups); got != 0 {
t.Fatalf("looked up the volume %d times for a cached chunk", got)
}
}
+3
View File
@@ -45,6 +45,9 @@ func loadJwtConfig() {
// JwtForVolumeServer generates a JWT token for volume server read operations if jwt.signing.read is configured
func JwtForVolumeServer(fileId string) string {
if token, ok := security.VolumeReadToken(context.Background(), fileId); ok {
return token
}
loadJwtConfigOnce.Do(loadJwtConfig)
if len(jwtSigningReadKey) == 0 {
return ""
+80 -17
View File
@@ -41,11 +41,14 @@
//
// -logtostderr=false
// Logs are written to standard error instead of to files.
// -alsologtostderr=false
// -alsologtostderr=true
// Logs are written to standard error as well as to files.
// When not given, it is false if -stderrthreshold is given.
// -stderrthreshold=ERROR
// Log events at or above this severity are logged to standard
// error as well as to files.
// error as well as to files. When given, it also filters standard
// error under -logtostderr. When not given, it applies only with
// -alsologtostderr=false.
// -logdir=""
// Log files will be written to this directory instead of the
// default temporary directory.
@@ -148,9 +151,46 @@ func (s *severity) Set(value string) error {
threshold = severity(v)
}
logging.stderrThreshold.set(threshold)
atomic.StoreInt32(&logging.stderrThresholdSet, 1)
return nil
}
// presetBool is a boolean flag that remembers whether it was given explicitly,
// so a default can yield to a related flag the user did set.
type presetBool struct {
value bool
explicit bool
}
// String is part of the flag.Value interface.
func (b *presetBool) String() string {
if b == nil {
return "false"
}
return strconv.FormatBool(b.value)
}
// Get is part of the flag.Value interface.
func (b *presetBool) Get() interface{} {
return b.value
}
// Set is part of the flag.Value interface.
func (b *presetBool) Set(value string) error {
v, err := strconv.ParseBool(value)
if err != nil {
return err
}
b.value = v
b.explicit = true
return nil
}
// IsBoolFlag lets the flag be given as a bare -alsologtostderr.
func (b *presetBool) IsBoolFlag() bool {
return true
}
func severityByName(s string) (severity, bool) {
s = strings.ToUpper(s)
for i, name := range severityName {
@@ -397,9 +437,10 @@ type flushSyncWriter interface {
func init() {
flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files")
flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", true, "log to standard error as well as files")
logging.alsoToStderr.value = true
flag.Var(&logging.alsoToStderr, "alsologtostderr", "log to standard error as well as files; when not set, true unless -stderrthreshold is set")
flag.Var(&logging.verbosity, "v", "log levels [0|1|2|3|4], default to 0")
flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr [INFO|WARNING|ERROR|FATAL], also with -logtostderr; ERROR when -alsologtostderr=false and it is not set")
flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
@@ -420,12 +461,15 @@ type loggingT struct {
// Boolean flags. Not handled atomically because the flag.Value interface
// does not let us avoid the =true, and that shorthand is necessary for
// compatibility. TODO: does this matter enough to fix? Seems unlikely.
toStderr bool // The -logtostderr flag.
alsoToStderr bool // The -alsologtostderr flag.
toStderr bool // The -logtostderr flag.
alsoToStderr presetBool // The -alsologtostderr flag.
// Level flag. Handled atomically.
stderrThreshold severity // The -stderrthreshold flag.
// stderrThresholdSet is non-zero once -stderrthreshold was given. Handled atomically.
stderrThresholdSet int32
// freeList is a list of byte buffers, maintained under freeListMu.
freeList *buffer
// freeListMu maintains the free list. It is separate from the main mutex
@@ -722,6 +766,25 @@ func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToSt
l.output(s, buf, file, line, alsoToStderr)
}
// writesToStderr reports whether a message of severity s goes to standard error.
// An explicit -stderrthreshold filters standard error in every mode: with
// -logtostderr, and over the default -alsologtostderr=true. An explicit
// -alsologtostderr=true still sends everything. Messages bridged from the
// standard log package always go.
func (l *loggingT) writesToStderr(s severity, bridged bool) bool {
if bridged {
return true
}
thresholdSet := atomic.LoadInt32(&l.stderrThresholdSet) != 0
if l.alsoToStderr.value && (l.alsoToStderr.explicit || !thresholdSet) {
return true
}
if l.toStderr {
return !thresholdSet || s >= l.stderrThreshold.get()
}
return s >= l.stderrThreshold.get()
}
// output writes the data to the log files and releases the buffer.
func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
l.mu.Lock()
@@ -731,12 +794,10 @@ func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoTo
}
}
data := buf.Bytes()
if l.toStderr {
if l.writesToStderr(s, alsoToStderr) {
os.Stderr.Write(data)
} else {
if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
os.Stderr.Write(data)
}
}
if !l.toStderr {
if l.file[s] == nil {
if err := l.createFiles(s); err != nil {
os.Stderr.Write(data) // Make sure the message appears somewhere.
@@ -776,14 +837,16 @@ func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoTo
os.Exit(1)
}
// Dump all goroutine stacks before exiting.
// First, make sure we see the trace for the current goroutine on standard error.
// If -logtostderr has been specified, the loop below will do that anyway
// as the first stack in the full dump.
if !l.toStderr {
os.Stderr.Write(stacks(false))
// With -logtostderr there are no files, so the full dump goes to standard
// error; otherwise standard error gets the current goroutine's trace.
// In JSON mode each dump is one more FATAL record, so output stays JSON lines.
trace := l.fatalStackRecord(stacks(true), file, line)
if l.toStderr {
os.Stderr.Write(trace)
} else {
os.Stderr.Write(l.fatalStackRecord(stacks(false), file, line))
}
// Write the stack trace for all goroutines to the files.
trace := stacks(true)
logExitFunc = func(error) {} // If we get a write error, we'll still exit below.
for log := fatalLog; log >= infoLog; log-- {
if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.
+20
View File
@@ -90,6 +90,26 @@ func (l *loggingT) formatJSON(s severity, depth int) (*buffer, string, int) {
return buf, file, line
}
// fatalStackRecord returns a FATAL goroutine dump as written to the logs: the raw
// dump in text mode, or one FATAL JSON record carrying the fatal call's file and
// line in JSON mode. It is called with l.mu held, so it must not call output.
func (l *loggingT) fatalStackRecord(trace []byte, file string, line int) []byte {
if !IsJSONMode() {
return trace
}
var b strings.Builder
b.WriteString(`{"ts":"`)
b.WriteString(timeNow().UTC().Format(time.RFC3339Nano))
b.WriteString(`","level":"FATAL","file":"`)
b.WriteString(jsonEscapeString(file))
b.WriteString(`","line":`)
b.WriteString(itoa(line))
b.WriteString(`,"msg":"`)
b.WriteString(jsonEscapeString(strings.TrimRight(string(trace), "\n")))
b.WriteString("\"}\n")
return []byte(b.String())
}
// finishJSON closes the JSON object and adds a newline.
func finishJSON(buf *buffer) {
buf.WriteString("\"}\n")
+111
View File
@@ -18,12 +18,17 @@ package glog
import (
"bytes"
"encoding/json"
"errors"
"fmt"
stdLog "log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
@@ -466,3 +471,109 @@ func BenchmarkHeader(b *testing.B) {
logging.putBuffer(buf)
}
}
func TestWritesToStderr(t *testing.T) {
saved := struct {
toStderr bool
alsoToStderr presetBool
threshold severity
set int32
}{logging.toStderr, logging.alsoToStderr, logging.stderrThreshold.get(), atomic.LoadInt32(&logging.stderrThresholdSet)}
defer func() {
logging.toStderr = saved.toStderr
logging.alsoToStderr = saved.alsoToStderr
logging.stderrThreshold.set(saved.threshold)
atomic.StoreInt32(&logging.stderrThresholdSet, saved.set)
}()
// threshold "" means the flag was not given; want is indexed by severity.
tests := []struct {
name string
toStderr bool
alsoToStderr presetBool
threshold string
bridged bool
want [numSeverity]bool
}{
{"defaults", false, presetBool{value: true}, "", false, [4]bool{true, true, true, true}},
{"threshold over default alsologtostderr", false, presetBool{value: true}, "WARNING", false, [4]bool{false, true, true, true}},
{"explicit alsologtostderr=true wins", false, presetBool{value: true, explicit: true}, "FATAL", false, [4]bool{true, true, true, true}},
{"alsologtostderr=false keeps default ERROR", false, presetBool{value: false, explicit: true}, "", false, [4]bool{false, false, true, true}},
{"alsologtostderr=false with threshold", false, presetBool{value: false, explicit: true}, "INFO", false, [4]bool{true, true, true, true}},
{"logtostderr writes all", true, presetBool{value: true}, "", false, [4]bool{true, true, true, true}},
{"logtostderr with threshold", true, presetBool{value: true}, "ERROR", false, [4]bool{false, false, true, true}},
{"logtostderr with explicit alsologtostderr=true wins", true, presetBool{value: true, explicit: true}, "ERROR", false, [4]bool{true, true, true, true}},
{"logtostderr with alsologtostderr=false and threshold", true, presetBool{value: false, explicit: true}, "ERROR", false, [4]bool{false, false, true, true}},
{"bridged always written", true, presetBool{value: true}, "FATAL", true, [4]bool{true, true, true, true}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logging.toStderr = tt.toStderr
logging.alsoToStderr = tt.alsoToStderr
logging.stderrThreshold.set(errorLog)
atomic.StoreInt32(&logging.stderrThresholdSet, 0)
if tt.threshold != "" {
if err := logging.stderrThreshold.Set(tt.threshold); err != nil {
t.Fatal(err)
}
}
for s := infoLog; s <= fatalLog; s++ {
if got := logging.writesToStderr(s, tt.bridged); got != tt.want[s] {
t.Errorf("severity %s: got %v, want %v", severityName[s], got, tt.want[s])
}
}
})
}
}
func TestAlsoLogToStderrFlag(t *testing.T) {
var b presetBool
if b.explicit || !b.IsBoolFlag() {
t.Fatal("unexpected zero value")
}
if err := b.Set("false"); err != nil || b.value || !b.explicit {
t.Fatalf("Set(false): value=%v explicit=%v err=%v", b.value, b.explicit, err)
}
if err := b.Set("bogus"); err == nil {
t.Fatal("Set(bogus) succeeded")
}
}
// A FATAL under -log_json -logtostderr must leave only JSON lines on stderr,
// the goroutine dump included. Fatal exits, so it runs in a child process.
func TestFatalJSONStderrIsJSONLines(t *testing.T) {
if os.Getenv("GLOG_TEST_FATAL_JSON") == "1" {
logging.toStderr = true
SetJSONMode(true)
Fatal("fatal for test")
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestFatalJSONStderrIsJSONLines$")
cmd.Env = append(os.Environ(), "GLOG_TEST_FATAL_JSON=1")
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 255 {
t.Fatalf("child exit = %v, want status 255; stderr:\n%s", err, stderr.String())
}
lines := strings.Split(strings.TrimRight(stderr.String(), "\n"), "\n")
if len(lines) != 2 {
t.Fatalf("got %d stderr lines, want the fatal record and the dump record:\n%s", len(lines), stderr.String())
}
for i, ln := range lines {
var rec struct {
Level string `json:"level"`
Msg string `json:"msg"`
}
if err := json.Unmarshal([]byte(ln), &rec); err != nil {
t.Fatalf("stderr line %d is not JSON: %v\n%s", i, err, ln)
}
if rec.Level != "FATAL" {
t.Errorf("stderr line %d level = %q, want FATAL", i, rec.Level)
}
}
if !strings.Contains(lines[1], "goroutine ") {
t.Errorf("second record does not hold the goroutine dump: %s", lines[1])
}
}
+5
View File
@@ -175,6 +175,10 @@ func (fh *FileHandle) SetEntry(entry *filer_pb.Entry) {
if fh.entryChunkGroup != nil {
_ = fh.entryChunkGroup.Close()
}
// Record the chunk -> path index before the chunk group resolves any
// manifest chunk: that resolution reads the manifest from a volume server
// and needs the entry's read token.
fh.wfs.readAuth.Track(fh.FullPath(), entry.Chunks)
var resolveManifestErr error
fh.entryChunkGroup, resolveManifestErr = filer.NewChunkGroup(fh.wfs.LookupFn(), fh.wfs.chunkCache, entry.Chunks, fh.wfs.option.ConcurrentReaders, fh.wfs.CacheInvalidator(), fh.wfs.manifestCache, fh.wfs.readerCacheBudget)
if resolveManifestErr != nil {
@@ -409,6 +413,7 @@ func (fh *FileHandle) UpdateEntry(fn func(entry *filer_pb.Entry)) *filer_pb.Entr
}
func (fh *FileHandle) AddChunks(chunks []*filer_pb.FileChunk) {
fh.wfs.readAuth.Track(fh.FullPath(), chunks)
fh.entry.AppendChunks(chunks)
}
@@ -83,9 +83,13 @@ func SubscribeMetaEvents(mc *MetaCache, selfSignature int32, client filer_pb.Fil
StartTsNs: lastTsNs,
StopTsNs: 0,
EventErrorType: pb.FatalOnError,
LogFileReaderFn: func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
}
// A nil lookup asks for decoded events instead: a keyless mount cannot
// read raw metadata-log chunks with its entry-scoped volume tokens.
if lookupFn != nil {
metadataFollowOption.LogFileReaderFn = func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
return filer.NewChunkStreamReaderFromLookup(context.Background(), lookupFn, chunks), nil
},
}
}
util.RetryUntil("followMetaUpdates", func() error {
metadataFollowOption.ClientEpoch++
+228
View File
@@ -0,0 +1,228 @@
package mount
import (
"context"
"encoding/base64"
"encoding/json"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"golang.org/x/sync/singleflight"
)
const (
// readAuthRefreshMargin renews a token this long before it expires, so a
// read never starts on a token the volume server rejects mid-transfer.
readAuthRefreshMargin = 5 * time.Second
// readAuthMaxFids caps the fid indexes. Past it they are cleared and
// relearned: every open handle re-tracks its chunks on its next SetEntry,
// AddChunks, or truncate, and until then a read whose fid is not yet known
// fails closed and is retried rather than served without a token.
readAuthMaxFids = 1 << 20
)
type readAuthToken struct {
token string
expires time.Time
}
// ReadAuth holds the exact-fid volume read tokens this mount was granted. It
// learns which entry a fid belongs to from the file handles that read it, and
// on a miss asks the filer for that entry with LookupDirectoryEntries, whose
// read_auth carries one short-lived token per chunk. The mount never holds a
// signing key, so it can read only chunks of entries the filer (or a guard in
// front of it) let it look up. A nil *ReadAuth is disabled.
type ReadAuth struct {
wfs *WFS
mu sync.Mutex
paths map[string]util.FullPath
tokens map[string]readAuthToken
flight singleflight.Group
}
func newReadAuth(wfs *WFS) *ReadAuth {
return &ReadAuth{wfs: wfs, paths: map[string]util.FullPath{}, tokens: map[string]readAuthToken{}}
}
// Track records that chunks belong to the entry at path.
func (ra *ReadAuth) Track(path util.FullPath, chunks []*filer_pb.FileChunk) {
if ra == nil || path == "" {
return
}
ra.mu.Lock()
defer ra.mu.Unlock()
if len(ra.paths) > readAuthMaxFids {
ra.paths = map[string]util.FullPath{}
}
for _, chunk := range chunks {
if fid := chunk.GetFileIdString(); fid != "" {
ra.paths[fid] = path
}
}
}
// TrackHandle records that the chunks fh holds now belong to the entry at
// path, for a handle whose name moved without a new SetEntry.
func (ra *ReadAuth) TrackHandle(path util.FullPath, fh *FileHandle) {
if ra == nil {
return
}
le := fh.GetEntry()
if le == nil {
return
}
le.RLock()
defer le.RUnlock()
if le.Entry != nil {
ra.Track(path, le.Entry.Chunks)
}
}
// Token is the security.VolumeReadTokenProvider of this mount.
func (ra *ReadAuth) Token(ctx context.Context, fileId string) string {
if token, ok := ra.cached(fileId); ok {
return token
}
ra.mu.Lock()
path := ra.paths[fileId]
ra.mu.Unlock()
if path == "" {
glog.V(1).Infof("read auth: no entry known for chunk %s", fileId)
return ""
}
// Other reads of this entry wait on the same lookup, so the caller that
// started it must not cancel it for them.
flight := ra.flight.DoChan(string(path), func() (interface{}, error) {
return nil, ra.refresh(context.WithoutCancel(ctx), path)
})
select {
case <-flight:
case <-ctx.Done():
return ""
}
if token, ok := ra.cached(fileId); ok {
return token
}
// The refresh produced no token with more than the refresh margin left. A
// token that has not expired is still better than none: a read JWT lifetime
// at or below the margin (jwt.signing.read.expires_after_seconds small)
// would otherwise be discarded the instant it is stored, and every read of
// this chunk would go out without a credential the volume server accepts.
return ra.unexpiredToken(fileId)
}
func (ra *ReadAuth) cached(fileId string) (string, bool) {
ra.mu.Lock()
defer ra.mu.Unlock()
t, ok := ra.tokens[fileId]
if !ok || time.Until(t.expires) < readAuthRefreshMargin {
return "", false
}
return t.token, true
}
// unexpiredToken returns a stored token that is still valid even if it is
// within the refresh margin, so a refresh that could not mint a fresher one
// does not drop a credential the volume server would still accept.
func (ra *ReadAuth) unexpiredToken(fileId string) string {
ra.mu.Lock()
defer ra.mu.Unlock()
if t, ok := ra.tokens[fileId]; ok && time.Until(t.expires) > 0 {
return t.token
}
return ""
}
func (ra *ReadAuth) refresh(ctx context.Context, path util.FullPath) error {
dir, name := path.DirAndName()
var resp *filer_pb.LookupDirectoryEntriesResponse
// Token reads reach refresh with context.Background() (JwtForVolumeServer),
// so bound each attempt with filerRPCWait; a filer that accepts the lookup
// and then stalls must not block the read forever, nor the concurrent reads
// that singleflight holds behind this one.
err := ra.wfs.withFilerClient(ctx, false, ra.wfs.filerRPCWait(), func(callCtx context.Context, client filer_pb.SeaweedFilerClient) error {
var lookupErr error
resp, lookupErr = client.LookupDirectoryEntries(callCtx, &filer_pb.LookupDirectoryEntriesRequest{
Requests: []*filer_pb.LookupDirectoryEntryRequest{{Directory: dir, Name: name}},
})
return lookupErr
})
if err != nil {
glog.V(0).Infof("read auth: lookup %s: %v", path, err)
return err
}
ra.installRefreshResult(path, resp.GetReadAuth())
return nil
}
// installRefreshResult records the tokens a lookup of path returned. It
// keeps each fid's longest-lived usable token, but fills a path only for a fid
// that is not already mapped. Track owns path changes: a fid re-tracked to a newer path
// (a rename) while this lookup was in flight must keep it, not have the
// vacated path it was looked up under restored. The fids a lookup discovers
// that Track has not seen -- the data chunks behind a manifest -- are the
// ones still filled in here.
func (ra *ReadAuth) installRefreshResult(path util.FullPath, readAuth map[string]string) {
ra.mu.Lock()
defer ra.mu.Unlock()
previous := ra.tokens
if len(ra.tokens) > readAuthMaxFids {
ra.tokens = map[string]readAuthToken{}
}
for fid, token := range readAuth {
updated := readAuthToken{token: token, expires: jwtExpiry(token)}
// Compare against the old map even when capacity eviction reset it.
if held, ok := previous[fid]; ok && time.Until(held.expires) > 0 && updated.expires.Before(held.expires) {
updated = held
}
ra.tokens[fid] = updated
if _, known := ra.paths[fid]; !known {
ra.paths[fid] = path
}
}
}
// jwtExpiry reads the exp claim without verifying the token: the volume server
// verifies it; the mount only needs to know when to ask again.
func jwtExpiry(token string) time.Time {
fallback := time.Now().Add(readAuthRefreshMargin * 2)
parts := strings.Split(token, ".")
if len(parts) != 3 {
return fallback
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return fallback
}
var claims struct {
Exp int64 `json:"exp"`
}
if json.Unmarshal(payload, &claims) != nil || claims.Exp == 0 {
return fallback
}
return time.Unix(claims.Exp, 0)
}
func (wfs *WFS) installReadAuth() {
if !wfs.option.VolumeReadAuth {
return
}
wfs.readAuth = newReadAuth(wfs)
security.SetVolumeReadTokenProvider(wfs.readAuth.Token)
glog.V(0).Infof("volume reads use filer-issued exact-fid tokens")
}
func (wfs *WFS) metadataLogLookupFn() wdclient.LookupFileIdFunctionType {
// Log chunks have no entry path from which to request a read token.
// Let the filer decode and stream metadata events for keyless mounts.
if wfs.option.VolumeReadAuth {
return nil
}
return wfs.LookupFn()
}
+107
View File
@@ -0,0 +1,107 @@
package mount
import (
"context"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
type readAuthLookupFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
fid string
token string
calls atomic.Int32
entered chan struct{}
release chan struct{}
}
func (f *readAuthLookupFiler) LookupDirectoryEntries(ctx context.Context, req *filer_pb.LookupDirectoryEntriesRequest) (*filer_pb.LookupDirectoryEntriesResponse, error) {
f.calls.Add(1)
f.entered <- struct{}{}
select {
case <-f.release:
return &filer_pb.LookupDirectoryEntriesResponse{ReadAuth: map[string]string{f.fid: f.token}}, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// parkedTokenCallers counts goroutines blocked inside ReadAuth.Token, either
// waiting on a token lookup or running one.
func parkedTokenCallers() int {
buf := make([]byte, 1<<20)
buf = buf[:runtime.Stack(buf, true)]
parked := 0
for _, g := range strings.Split(string(buf), "\n\n") {
header, _, _ := strings.Cut(g, "\n")
if strings.Contains(g, "(*ReadAuth).Token(") && (strings.Contains(header, "[select") || strings.Contains(header, "WaitGroup.Wait")) {
parked++
}
}
return parked
}
// A read cancelled while its token lookup is in flight must not leave the
// other reads waiting on that lookup without a token.
func TestReadAuthCancelledCallerKeepsSharedLookup(t *testing.T) {
fid := "3,01637037d6"
fake := &readAuthLookupFiler{
fid: fid,
token: makeUnsignedJwtWithExp(t, time.Now().Add(time.Minute).Unix()),
entered: make(chan struct{}, 4),
release: make(chan struct{}),
}
wfs := newLookupCacheTestWFS(t, 60)
startFakeFiler(t, wfs, fake)
ra := newReadAuth(wfs)
ra.Track(util.FullPath("/dir/file"), []*filer_pb.FileChunk{{FileId: fid}})
cancelledCtx, cancel := context.WithCancel(context.Background())
defer cancel()
cancelled := make(chan string, 1)
go func() { cancelled <- ra.Token(cancelledCtx, fid) }()
select {
case <-fake.entered:
case <-time.After(10 * time.Second):
t.Fatal("token lookup never reached the filer")
}
waiter := make(chan string, 1)
go func() { waiter <- ra.Token(context.Background(), fid) }()
deadline := time.Now().Add(10 * time.Second)
for parkedTokenCallers() < 2 {
if time.Now().After(deadline) {
t.Fatal("second reader never joined the in-flight lookup")
}
runtime.Gosched()
}
cancel()
select {
case got := <-cancelled:
if got != "" {
t.Fatalf("cancelled caller got %q, want no token", got)
}
case <-time.After(10 * time.Second):
t.Fatal("cancelled caller kept waiting on the lookup")
}
close(fake.release)
select {
case got := <-waiter:
if got != fake.token {
t.Fatalf("waiting reader got %q, want the looked-up token", got)
}
case <-time.After(10 * time.Second):
t.Fatal("waiting reader never got a token")
}
if calls := fake.calls.Load(); calls != 1 {
t.Fatalf("filer lookups = %d, want 1 shared lookup", calls)
}
}
+249
View File
@@ -0,0 +1,249 @@
package mount
import (
"context"
"encoding/base64"
"encoding/json"
"strconv"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// makeUnsignedJwtWithExp builds a token in header.payload.signature shape whose
// payload carries the given exp claim, so jwtExpiry can parse it without a key.
func makeUnsignedJwtWithExp(t *testing.T, exp int64) string {
t.Helper()
payload, err := json.Marshal(struct {
Exp int64 `json:"exp"`
}{Exp: exp})
if err != nil {
t.Fatalf("marshal payload: %v", err)
}
enc := base64.RawURLEncoding
return enc.EncodeToString([]byte(`{"alg":"HS256"}`)) + "." + enc.EncodeToString(payload) + ".sig"
}
func newTestReadAuth() *ReadAuth {
return newReadAuth(&WFS{option: &Option{}})
}
// TestReadAuthCachedHonorsRefreshMargin checks that a token with comfortable
// life is served from the cache, while one inside the refresh margin is treated
// as stale so Token triggers a refresh.
func TestReadAuthCachedHonorsRefreshMargin(t *testing.T) {
ra := newTestReadAuth()
ra.tokens["fresh"] = readAuthToken{token: "fresh-token", expires: time.Now().Add(time.Minute)}
ra.tokens["stale"] = readAuthToken{token: "stale-token", expires: time.Now().Add(readAuthRefreshMargin / 2)}
if token, ok := ra.cached("fresh"); !ok || token != "fresh-token" {
t.Fatalf("fresh token: got (%q, %v), want (fresh-token, true)", token, ok)
}
if token, ok := ra.cached("stale"); ok || token != "" {
t.Fatalf("within-margin token must be stale: got (%q, %v)", token, ok)
}
}
// TestReadAuthUnexpiredTokenKeepsValidButShortToken is the core of the
// short-lifetime fix: a token inside the refresh margin but not yet expired is
// still usable, so a read JWT lifetime at or below the margin is not discarded
// the instant it is stored. An expired token is dropped.
func TestReadAuthUnexpiredTokenKeepsValidButShortToken(t *testing.T) {
ra := newTestReadAuth()
ra.tokens["short"] = readAuthToken{token: "short-token", expires: time.Now().Add(time.Second)}
ra.tokens["gone"] = readAuthToken{token: "gone-token", expires: time.Now().Add(-time.Second)}
if token := ra.unexpiredToken("short"); token != "short-token" {
t.Fatalf("unexpired short token: got %q, want short-token", token)
}
if token := ra.unexpiredToken("gone"); token != "" {
t.Fatalf("expired token must be dropped: got %q", token)
}
if token := ra.unexpiredToken("missing"); token != "" {
t.Fatalf("unknown fid must return empty: got %q", token)
}
}
// TestReadAuthTokenFallsBackToUnexpiredWhenRefreshCannotImprove drives Token
// end to end: the fid has a path and a still-valid but short-lived token, and
// the refresh cannot produce a fresher one (the test WFS has no filer). Token
// must return the unexpired token rather than fail the read.
func TestReadAuthTokenFallsBackToUnexpiredWhenRefreshCannotImprove(t *testing.T) {
ra := newTestReadAuth()
fid := "3,01637037d6"
ra.paths[fid] = util.FullPath("/bucket/object")
ra.tokens[fid] = readAuthToken{token: "short-token", expires: time.Now().Add(time.Second)}
if token := ra.Token(context.Background(), fid); token != "short-token" {
t.Fatalf("Token should fall back to the unexpired token: got %q", token)
}
}
// TestReadAuthTokenEmptyWhenPathUnknown confirms the fail-closed property: with
// no path learned for a fid and no cached token, Token returns no credential
// rather than guessing one.
func TestReadAuthTokenEmptyWhenPathUnknown(t *testing.T) {
ra := newTestReadAuth()
if token := ra.Token(context.Background(), "3,deadbeef"); token != "" {
t.Fatalf("unknown fid must yield no token: got %q", token)
}
}
// TestReadAuthTrackIndexesChunksByPath checks the fid->path index and its
// no-op guards.
func TestReadAuthTrackIndexesChunksByPath(t *testing.T) {
ra := newTestReadAuth()
path := util.FullPath("/bucket/object")
ra.Track(path, []*filer_pb.FileChunk{{FileId: "3,aaa"}, {FileId: "3,bbb"}, {FileId: ""}})
if ra.paths["3,aaa"] != path || ra.paths["3,bbb"] != path {
t.Fatalf("chunks not indexed to path: %v", ra.paths)
}
if _, ok := ra.paths[""]; ok {
t.Fatalf("empty fid must not be indexed")
}
// Empty path and nil receiver must be no-ops rather than panic.
ra.Track("", []*filer_pb.FileChunk{{FileId: "3,ccc"}})
if _, ok := ra.paths["3,ccc"]; ok {
t.Fatalf("empty path must not index chunks")
}
var nilRA *ReadAuth
nilRA.Track(path, []*filer_pb.FileChunk{{FileId: "3,ddd"}})
}
// TestReadAuthRefreshDoesNotClobberNewerTrackedPath reproduces the rename race:
// a refresh begins for the old path, a rename re-tracks the fid to the new path
// while the lookup is in flight, and the delayed lookup response then lands. The
// newer path must survive (so a later refresh looks up the live entry, not the
// vacated one) while the fresh token is still recorded. A fid the lookup
// discovers that was not tracked at all is still filled in under the looked-up
// path.
func TestReadAuthRefreshDoesNotClobberNewerTrackedPath(t *testing.T) {
ra := newTestReadAuth()
movedFid := "3,01637037d6"
discoveredFid := "7,0a0b0c0d0e" // a data chunk behind a manifest, never Tracked
chunk := &filer_pb.FileChunk{FileId: movedFid}
// The handle learns the fid under the old path (a refresh of it is now in
// flight), then a rename re-tracks the same fid under the new path.
ra.Track(util.FullPath("/dir/a"), []*filer_pb.FileChunk{chunk})
ra.Track(util.FullPath("/dir/b"), []*filer_pb.FileChunk{chunk})
// The delayed lookup of the old path returns fresh tokens for both the moved
// fid and a data fid Track never saw.
exp := time.Now().Add(time.Hour).Unix()
ra.installRefreshResult(util.FullPath("/dir/a"), map[string]string{
movedFid: makeUnsignedJwtWithExp(t, exp),
discoveredFid: makeUnsignedJwtWithExp(t, exp),
})
ra.mu.Lock()
defer ra.mu.Unlock()
if ra.paths[movedFid] != util.FullPath("/dir/b") {
t.Fatalf("rename-tracked path was clobbered: got %q, want /dir/b", ra.paths[movedFid])
}
if _, ok := ra.tokens[movedFid]; !ok {
t.Fatalf("refresh must still record the token for the moved fid")
}
if ra.paths[discoveredFid] != util.FullPath("/dir/a") {
t.Fatalf("a newly discovered fid must be filled under the looked-up path: got %q", ra.paths[discoveredFid])
}
}
func TestReadAuthRefreshKeepsLongestLivedToken(t *testing.T) {
for _, tt := range []struct {
name string
heldLifetime time.Duration
lateLifetime time.Duration
wantHeld bool
}{
{name: "older response", heldLifetime: 2 * time.Minute, lateLifetime: time.Minute, wantHeld: true},
{name: "expired response", heldLifetime: time.Minute, lateLifetime: -time.Minute, wantHeld: true},
{name: "newer response", heldLifetime: time.Minute, lateLifetime: 2 * time.Minute},
{name: "same expiry", heldLifetime: time.Minute, lateLifetime: time.Minute},
{name: "expired cache", heldLifetime: -time.Minute, lateLifetime: time.Minute},
{name: "empty cache", lateLifetime: time.Minute},
} {
t.Run(tt.name, func(t *testing.T) {
ra := newTestReadAuth()
fid := "3,01637037d6"
chunks := []*filer_pb.FileChunk{{FileId: fid}}
oldPath := util.FullPath("/dir/a")
newPath := util.FullPath("/dir/b")
now := time.Now()
held := makeUnsignedJwtWithExp(t, now.Add(tt.heldLifetime).Unix()) + "-held"
late := makeUnsignedJwtWithExp(t, now.Add(tt.lateLifetime).Unix()) + "-late"
// A lookup starts under the old path, then a rename allows another
// lookup to finish first. Install the delayed response last.
ra.Track(oldPath, chunks)
ra.Track(newPath, chunks)
if tt.heldLifetime != 0 {
ra.installRefreshResult(newPath, map[string]string{fid: held})
}
ra.installRefreshResult(oldPath, map[string]string{fid: late})
want := late
if tt.wantHeld {
want = held
}
if ra.Token(context.Background(), fid) != want {
t.Fatal("Token did not retain the usable token with the latest expiry")
}
if ra.paths[fid] != newPath {
t.Fatalf("late response restored stale path: got %q", ra.paths[fid])
}
})
}
}
func TestReadAuthRefreshPreservesResponseTokensAcrossCapacityReset(t *testing.T) {
ra := newTestReadAuth()
ra.tokens = make(map[string]readAuthToken, readAuthMaxFids+3)
for i := 0; i <= readAuthMaxFids; i++ {
ra.tokens[strconv.Itoa(i)] = readAuthToken{}
}
now := time.Now()
held := makeUnsignedJwtWithExp(t, now.Add(time.Minute).Unix())
fresher := makeUnsignedJwtWithExp(t, now.Add(2*time.Minute).Unix())
expired := makeUnsignedJwtWithExp(t, now.Add(-time.Minute).Unix())
ra.tokens["retained"] = readAuthToken{token: held, expires: jwtExpiry(held)}
ra.tokens["renewed"] = readAuthToken{token: held, expires: jwtExpiry(held)}
path := util.FullPath("/dir/file")
ra.installRefreshResult(path, map[string]string{
"retained": expired,
"renewed": fresher,
"discovered": fresher,
})
for fid, want := range map[string]string{"retained": held, "renewed": fresher, "discovered": fresher} {
if ra.Token(context.Background(), fid) != want {
t.Errorf("wrong token after capacity reset for %s", fid)
}
if ra.paths[fid] != path {
t.Errorf("response fid %s was not indexed to its path", fid)
}
}
if len(ra.tokens) != 3 {
t.Fatalf("capacity reset retained unrelated entries: got %d tokens, want 3", len(ra.tokens))
}
}
// TestJwtExpiryReadsExpClaim checks the unverified exp parse and its fallback.
func TestJwtExpiryReadsExpClaim(t *testing.T) {
exp := time.Now().Add(42 * time.Second).Unix()
token := makeUnsignedJwtWithExp(t, exp)
if got := jwtExpiry(token); got.Unix() != exp {
t.Fatalf("jwtExpiry: got %d, want %d", got.Unix(), exp)
}
// A malformed token falls back to a near-future expiry rather than the zero
// time, so a token the mount cannot parse is still retried, not trusted
// forever.
if got := jwtExpiry("not-a-jwt"); !got.After(time.Now()) {
t.Fatalf("malformed token must fall back to a future expiry, got %v", got)
}
}
+29 -20
View File
@@ -45,25 +45,28 @@ type Option struct {
FilerSigningKey security.SigningKey
FilerSigningExpiresAfterSec int
FilerMountRootPath string
Collection string
Replication string
TtlSec int32
DiskType types.DiskType
ChunkSizeLimit int64
ConcurrentWriters int
ConcurrentReaders int
ReaderCacheSizeMB int64
CacheDirForRead string
CacheSizeMBForRead int64
CacheDirForWrite string
WriteBufferSizeMB int64
CacheMetaTTlSec int
CacheDirMaxEntries int
DataCenter string
Umask os.FileMode
Quota int64
DisableXAttr bool
IsMacOs bool
// VolumeReadAuth reads chunks with the exact-fid read tokens the filer
// returns from LookupDirectoryEntries instead of signing them locally.
VolumeReadAuth bool
Collection string
Replication string
TtlSec int32
DiskType types.DiskType
ChunkSizeLimit int64
ConcurrentWriters int
ConcurrentReaders int
ReaderCacheSizeMB int64
CacheDirForRead string
CacheSizeMBForRead int64
CacheDirForWrite string
WriteBufferSizeMB int64
CacheMetaTTlSec int
CacheDirMaxEntries int
DataCenter string
Umask os.FileMode
Quota int64
DisableXAttr bool
IsMacOs bool
// LogicalDiskUsage reports data sizes rather than the space they occupy,
// for both df and the quota. See WFS.diskSizes.
@@ -144,6 +147,7 @@ type Option struct {
}
type WFS struct {
readAuth *ReadAuth
// Metadata-only refusal token, detached at final Forget; no live resources retained.
writebackContentErrors sync.Map
// https://dl.acm.org/doi/fullHtml/10.1145/3310148
@@ -485,6 +489,7 @@ func NewSeaweedFileSystem(option *Option) *WFS {
wfs.startAsyncFlushWorkers(numWorkers)
}
wfs.streamMutate = newStreamMutateMux(wfs)
wfs.installReadAuth()
wfs.copyBufferPool.New = func() any {
return make([]byte, option.ChunkSizeLimit)
}
@@ -506,7 +511,7 @@ func (wfs *WFS) StartBackgroundTasks() error {
}
startTime := time.Now()
go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.LookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, func(lastTsNs int64, err error) {
go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, func(lastTsNs int64, err error) {
glog.Warningf("meta events follow retry from %v: %v", time.Unix(0, lastTsNs), err)
// A subscription gap may have dropped events, so distrust every cached
// listing. Reset the flags first (safe — it never deletes entries), then
@@ -1089,6 +1094,9 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
}
})
}
// A read-only handle never reaches SetEntry, AddChunks, or truncate
// again, so its token refreshes must look up the new name.
wfs.readAuth.TrackHandle(invalidation.RenamedTo, fh)
}
}
@@ -1200,6 +1208,7 @@ func (wfs *WFS) followSurvivingLink(fh *FileHandle, removed util.FullPath) bool
survivor, ok := wfs.inodeToPath.RemoveAlias(removed)
if ok {
fh.RememberPath(survivor)
wfs.readAuth.TrackHandle(survivor, fh)
}
return ok
}
+1
View File
@@ -160,6 +160,7 @@ func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse
// set the new chunks and reset entry cache
entry.Chunks = chunks
if fh != nil {
fh.wfs.readAuth.Track(fh.FullPath(), chunks)
fh.entryChunkGroup.SetChunks(chunks)
}
}
+48 -2
View File
@@ -6,6 +6,8 @@ import (
"errors"
"fmt"
"io"
"math"
"sort"
"syscall"
"time"
@@ -333,7 +335,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
snapshot := entry.GetChunks()
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(snapshot)
chunks, _, err := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
chunks, covered, err := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
if err != nil {
return fmt.Errorf("compact chunks of %s: %w", fileFullPath, err)
}
@@ -356,7 +358,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
}
snapshot = entry.GetChunks()
manifestChunks, nonManifestChunks = filer.SeparateManifestChunks(snapshot)
if chunks, _, err = filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks); err != nil {
if chunks, covered, err = filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks); err != nil {
return fmt.Errorf("compact chunks of %s: %w", fileFullPath, err)
}
}
@@ -405,6 +407,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
// Snapshot with local ids before the request mapping mutates the clone:
// on ack this becomes the handle's base, judged against future events.
baseSnapshot := proto.Clone(requestEntry).(*filer_pb.Entry)
requestEntry.Chunks = append(requestEntry.Chunks, fh.unpublishedChunks(covered, requestEntry.Chunks)...)
wfs.mapPbIdFromLocalToFiler(request.Entry)
// The chunk merge and the manifest above read and upload chunks, which can
@@ -715,6 +718,49 @@ func contentFileIdKey(c *filer_pb.FileChunk) string {
return fmt.Sprintf("%d,%x,%x", fid.VolumeId, fid.FileKey, fid.Cookie)
}
// unpublishedChunks returns the chunks of dropped that the handle's base does
// not name and that chunks still covers. A commit deletes what it leaves out
// of the stored entry and what its own chunk list covers, so a covered chunk no
// stored entry ever named is only deleted if the request carries it. The filer
// compacts only plain chunks, and merged chunks carry no modification time, so
// each one is sent only if newer plain chunks of the request hide all of it.
func (fh *FileHandle) unpublishedChunks(dropped, chunks []*filer_pb.FileChunk) (unpublished []*filer_pb.FileChunk) {
inBase := make(map[string]bool)
for _, c := range fh.baseEntry.Load().GetChunks() {
inBase[contentFileIdKey(c)] = true
}
var visibles []*filer.Interval[*filer.VisibleInterval]
resolved := false
for _, c := range dropped {
if inBase[contentFileIdKey(c)] {
continue
}
if !resolved {
resolved = true
_, plain := filer.SeparateManifestChunks(chunks)
list, err := filer.NonOverlappingVisibleIntervals(context.Background(), nil, plain, 0, math.MaxInt64)
if err != nil {
return nil
}
for x := list.Front(); x != nil; x = x.Next {
visibles = append(visibles, x)
}
}
start, stop := c.Offset, c.Offset+int64(c.Size)
i := sort.Search(len(visibles), func(i int) bool { return visibles[i].StopOffset > start })
for ; i < len(visibles) && start < stop; i++ {
if visibles[i].StartOffset > start || visibles[i].TsNs <= c.ModifiedTsNs {
break
}
start = visibles[i].StopOffset
}
if start >= stop {
unpublished = append(unpublished, c)
}
}
return unpublished
}
// ackedBase is the base an acknowledged create leaves: the entry the filer
// stored, in local ids. The filer stamps commit_ts_ns, crtime, inode and atime
// and may rewrite chunks, so the requested entry would never match it again.
@@ -0,0 +1,125 @@
package mount
import (
"context"
"slices"
"testing"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/protobuf/proto"
)
// compactingFiler compacts a create's chunks like the filer does and records
// the chunks the commit would delete as covered.
type compactingFiler struct {
contentFlushConditionFiler
sent [][]uint64
deleted []uint64
}
func (s *compactingFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
compacted, covered, err := filer.CompactFileChunks(ctx, nil, r.Entry.GetChunks())
if err != nil {
return nil, err
}
s.mu.Lock()
s.sent = append(s.sent, chunkFileKeys(r.Entry))
s.mu.Unlock()
r = proto.Clone(r).(*filer_pb.CreateEntryRequest)
r.Entry.Chunks = compacted
resp, err := s.contentFlushConditionFiler.CreateEntry(ctx, r)
if err == nil && resp.GetErrorCode() == filer_pb.FilerError_OK {
s.mu.Lock()
for _, c := range covered {
s.deleted = append(s.deleted, c.GetFid().GetFileKey())
}
s.mu.Unlock()
}
return resp, err
}
func coveredChunksEntry(chunks ...[3]int64) *filer_pb.Entry {
e := &filer_pb.Entry{Name: "file", Attributes: &filer_pb.FuseAttributes{Inode: 42, FileMode: 0644, Uid: 2000, Gid: 20, FileSize: 2}}
for _, c := range chunks {
e.Chunks = append(e.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(c[0]), Cookie: 1}, Offset: c[1], Size: 1, ModifiedTsNs: c[0]})
}
return e
}
// A chunk overwritten before any publication named it is dropped by the
// mount's compaction; the request must still carry it so the filer deletes it.
// A covered chunk the stored entry already names is left to the filer's diff.
func TestFlushSendsUnpublishedCoveredChunks(t *testing.T) {
for _, name := range []string{"close", "periodic"} {
t.Run(name, func(t *testing.T) {
wfs := newInvalidateTestWFS(t)
stored := coveredChunksEntry([3]int64{1, 0})
fake := &compactingFiler{contentFlushConditionFiler: contentFlushConditionFiler{entry: proto.Clone(stored).(*filer_pb.Entry)}}
startFakeFiler(t, wfs, fake)
observed := proto.Clone(stored).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
live := coveredChunksEntry([3]int64{1, 0}, [3]int64{2, 0}, [3]int64{3, 1}, [3]int64{4, 1})
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.dirtyMetadata = true
fh.RememberPath(util.FullPath("/dir/file"))
if name == "close" {
if code := wfs.doFlush(context.Background(), fh, 1000, 20, false, 0); code != fuse.OK {
t.Fatal(code)
}
} else if err := wfs.flushFileMetadata(fh); err != nil {
t.Fatal(err)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.sent) != 1 || !slices.Equal(fake.sent[0], []uint64{2, 4, 3}) {
t.Fatalf("sent chunks %v, want [[2 4 3]]", fake.sent)
}
if !slices.Equal(fake.deleted, []uint64{3}) {
t.Fatalf("filer deletes %v, want [3]", fake.deleted)
}
if got := chunkFileKeys(fake.entry); !slices.Equal(got, []uint64{2, 4}) {
t.Fatalf("stored chunks %v", got)
}
if got := chunkFileKeys(fh.GetEntry().GetEntry()); !slices.Equal(got, []uint64{2, 4}) {
t.Fatalf("handle chunks %v", got)
}
})
}
}
// A dropped chunk goes out only while newer plain chunks of the request hide
// all of it: merged chunks are stamped 0, the filer does not look into a
// manifest, and another dropped chunk is not sent to hide it either.
func TestUnpublishedChunksStayCovered(t *testing.T) {
chunk := func(key uint64, offset, size, ts int64) *filer_pb.FileChunk {
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: key, Cookie: 1}, Offset: offset, Size: uint64(size), ModifiedTsNs: ts}
}
published := chunk(1, 0, 2, 1)
dropped := []*filer_pb.FileChunk{published, chunk(2, 0, 2, 2), chunk(3, 0, 2, 3)}
for _, tt := range []struct {
name string
chunks []*filer_pb.FileChunk
want []uint64
}{
{"covered", []*filer_pb.FileChunk{chunk(4, 0, 1, 4), chunk(5, 1, 1, 5)}, []uint64{2, 3}},
{"between", []*filer_pb.FileChunk{chunk(4, 0, 2, 3)}, []uint64{2}},
{"partly", []*filer_pb.FileChunk{chunk(4, 0, 1, 4)}, nil},
{"merged", []*filer_pb.FileChunk{chunk(4, 0, 2, 0)}, nil},
{"manifest", []*filer_pb.FileChunk{{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 4, Cookie: 1}, Size: 2, ModifiedTsNs: 4, IsChunkManifest: true}}, nil},
} {
t.Run(tt.name, func(t *testing.T) {
fh := &FileHandle{}
fh.baseEntry.Store(&filer_pb.Entry{Chunks: []*filer_pb.FileChunk{proto.Clone(published).(*filer_pb.FileChunk)}})
got := chunkFileKeys(&filer_pb.Entry{Chunks: fh.unpublishedChunks(dropped, tt.chunks)})
if !slices.Equal(got, tt.want) {
t.Fatalf("unpublished %v, want %v", got, tt.want)
}
})
}
}
@@ -0,0 +1,135 @@
package mount
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// TestRenameReTracksReadAuthUnderNewPath covers the read-token index across a
// rename. A read-only handle never reaches SetEntry/AddChunks/truncate again,
// so if the rename did not re-track its chunks, a later token refresh would
// look up the vacated old path, find nothing, and the read would lose its
// credential. After the rename the handle's chunk must map to the new path.
func TestRenameReTracksReadAuthUnderNewPath(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.readAuth = newReadAuth(wfs)
const fid = "3,abc"
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: "file",
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
Chunks: []*filer_pb.FileChunk{{FileId: fid, Size: 200}},
}, 0, 0)
// Precondition: the chunk is indexed under the original path, as SetEntry
// would have done when the handle was opened.
wfs.readAuth.Track(fh.FullPath(), []*filer_pb.FileChunk{{FileId: fid}})
if got := wfs.readAuth.paths[fid]; got != util.FullPath("/dir/file") {
t.Fatalf("precondition: chunk indexed to %q, want /dir/file", got)
}
rename := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: 1500,
EventNotification: &filer_pb.EventNotification{
OldEntry: &filer_pb.Entry{Name: "file"},
NewEntry: &filer_pb.Entry{Name: "renamed", Attributes: &filer_pb.FuseAttributes{FileSize: 200}, Chunks: []*filer_pb.FileChunk{{FileId: fid, Size: 200}}},
NewParentPath: "/dir",
},
}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), rename, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply rename: %v", err)
}
wfs.metaCache.WaitForEntryInvalidations()
if got := fh.FullPath(); got != util.FullPath("/dir/renamed") {
t.Fatalf("handle path = %q, want /dir/renamed", got)
}
if got := wfs.readAuth.paths[fid]; got != util.FullPath("/dir/renamed") {
t.Fatalf("chunk still indexed to %q after rename, want /dir/renamed", got)
}
}
func TestSurvivingHardLinkReTracksReadAuthUnderNewPath(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.readAuth = newReadAuth(wfs)
const fid = "3,abc"
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
wfs.inodeToPath.AddPath(inode, util.FullPath("/dir/survivor"))
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: "file",
HardLinkId: []byte("link"),
HardLinkCounter: 2,
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
Chunks: []*filer_pb.FileChunk{{FileId: fid, Size: 200}},
}, 0, 0)
// Precondition: the chunk is indexed to the name that the open handle was
// using when the peer removed that name.
wfs.readAuth.Track(fh.FullPath(), []*filer_pb.FileChunk{{FileId: fid}})
deleteResp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: 1500,
EventNotification: &filer_pb.EventNotification{
OldEntry: &filer_pb.Entry{
Name: "file",
HardLinkId: []byte("link"),
HardLinkCounter: 2,
},
},
}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), deleteResp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply hard-link delete: %v", err)
}
wfs.metaCache.WaitForEntryInvalidations()
if got := fh.FullPath(); got != util.FullPath("/dir/survivor") {
t.Fatalf("handle path = %q, want /dir/survivor", got)
}
if got := wfs.readAuth.paths[fid]; got != util.FullPath("/dir/survivor") {
t.Fatalf("chunk still indexed to %q after hard-link delete, want /dir/survivor", got)
}
}
// A writeback mount skips its own rename event, so the local rename response
// is the only place the open handle's chunks move to the new name.
func TestLocalRenameReTracksReadAuthUnderNewPath(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.readAuth = newReadAuth(wfs)
const fid = "3,abc"
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: "file",
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
Chunks: []*filer_pb.FileChunk{{FileId: fid, Size: 200}},
}, 0, 0)
wfs.readAuth.Track(fh.FullPath(), []*filer_pb.FileChunk{{FileId: fid}})
resp := &filer_pb.StreamRenameEntryResponse{
Directory: "/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: &filer_pb.Entry{Name: "file"},
NewEntry: &filer_pb.Entry{Name: "renamed", Attributes: &filer_pb.FuseAttributes{FileSize: 200, Inode: inode}, Chunks: []*filer_pb.FileChunk{{FileId: fid, Size: 200}}},
NewParentPath: "/dir",
},
}
if err := wfs.handleRenameResponse(context.Background(), resp, util.FullPath("/dir/renamed"), nil); err != nil {
t.Fatalf("handle rename response: %v", err)
}
if got := fh.FullPath(); got != util.FullPath("/dir/renamed") {
t.Fatalf("handle path = %q, want /dir/renamed", got)
}
if got := wfs.readAuth.paths[fid]; got != util.FullPath("/dir/renamed") {
t.Fatalf("chunk still indexed to %q after local rename, want /dir/renamed", got)
}
}
+54 -16
View File
@@ -3,6 +3,7 @@ package mount
import (
"bytes"
"context"
"github.com/seaweedfs/seaweedfs/weed/security"
"net"
"net/http"
"net/http/httptest"
@@ -28,10 +29,12 @@ import (
// server it is meant to reach only through -volumeServerAccess=filerProxy.
type proxyFilerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
chunk *filer_pb.FileChunk
subscriptions atomic.Int32
volumeLookups atomic.Int32
stop chan struct{}
chunk *filer_pb.FileChunk
event *filer_pb.SubscribeMetadataResponse
supportsChunks chan bool
subscriptions atomic.Int32
volumeLookups atomic.Int32
stop chan struct{}
}
func (s *proxyFilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error {
@@ -39,6 +42,10 @@ func (s *proxyFilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequ
<-s.stop
return nil
}
s.supportsChunks <- req.ClientSupportsMetadataChunks
if !req.ClientSupportsMetadataChunks {
return stream.Send(s.event)
}
return stream.Send(&filer_pb.SubscribeMetadataResponse{
LogFileRefs: []*filer_pb.LogFileChunkRef{{
FilerId: "5319c0e8",
@@ -71,17 +78,34 @@ func buildLogFileData(events ...*filer_pb.SubscribeMetadataResponse) []byte {
return buf.Bytes()
}
// TestSubscribeMetaEventsReplaysThroughFilerProxy pins the replay to the lookup
// the mount was given: resolving volume servers here fails every subscription
// of a filerProxy mount, which then resubscribes a second later, forever.
func TestSubscribeMetaEventsReplaysThroughFilerProxy(t *testing.T) {
logData := buildLogFileData(&filer_pb.SubscribeMetadataResponse{
// TestMountMetadataReplayAuthorization checks the advertised replay capability
// and the resulting cache entry. Ordinary proxy mounts fetch log chunks through
// the filer; keyless mounts receive decoded events without reading log chunks.
func TestMountMetadataReplayAuthorization(t *testing.T) {
for _, tc := range []struct {
name, access string
readAuth bool
}{
{"ordinary filer proxy", "filerProxy", false},
{"keyless direct", "direct", true},
{"keyless filer proxy", "filerProxy", true},
} {
t.Run(tc.name, func(t *testing.T) {
testMountMetadataReplayAuthorization(t, tc.access, tc.readAuth)
})
}
}
func testMountMetadataReplayAuthorization(t *testing.T, access string, readAuth bool) {
t.Helper()
event := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: time.Now().UnixNano(),
EventNotification: &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{Name: "file", Attributes: &filer_pb.FuseAttributes{FileSize: 7}},
},
})
}
logData := buildLogFileData(event)
var proxiedChunkIds atomic.Value
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -102,8 +126,10 @@ func TestSubscribeMetaEventsReplaysThroughFilerProxy(t *testing.T) {
t.Cleanup(func() { _ = listener.Close() })
testServer := &proxyFilerServer{
chunk: &filer_pb.FileChunk{FileId: "4471,ce598bfff8416e", Size: uint64(len(logData))},
stop: make(chan struct{}),
event: event,
supportsChunks: make(chan bool, 1),
chunk: &filer_pb.FileChunk{FileId: "4471,ce598bfff8416e", Size: uint64(len(logData))},
stop: make(chan struct{}),
}
server := pb.NewGrpcServer()
filer_pb.RegisterSeaweedFilerServer(server, testServer)
@@ -132,7 +158,8 @@ func TestSubscribeMetaEventsReplaysThroughFilerProxy(t *testing.T) {
option: &Option{
ChunkSizeLimit: 1024,
ConcurrentReaders: 1,
VolumeServerAccess: "filerProxy",
VolumeServerAccess: access,
VolumeReadAuth: readAuth,
FilerMountRootPath: "/",
FilerAddresses: []pb.ServerAddress{
pb.NewServerAddressWithGrpcPort(proxyUrl.Host, listener.Addr().(*net.TCPAddr).Port),
@@ -140,6 +167,10 @@ func TestSubscribeMetaEventsReplaysThroughFilerProxy(t *testing.T) {
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
if readAuth {
wfs.installReadAuth()
t.Cleanup(func() { security.SetVolumeReadTokenProvider(nil) })
}
wfs.metaCache = meta_cache.NewMetaCache(
filepath.Join(t.TempDir(), "meta"),
uidGidMapper,
@@ -158,7 +189,7 @@ func TestSubscribeMetaEventsReplaysThroughFilerProxy(t *testing.T) {
followed := make(chan struct{})
go func() {
defer close(followed)
meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.LookupFn(), wfs.option.FilerMountRootPath, 0, false, nil)
meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, 0, false, nil)
}()
select {
@@ -170,8 +201,15 @@ func TestSubscribeMetaEventsReplaysThroughFilerProxy(t *testing.T) {
if got := testServer.volumeLookups.Load(); got != 0 {
t.Errorf("filerProxy mount resolved %d volume locations, want 0", got)
}
if got, _ := proxiedChunkIds.Load().(string); got != testServer.chunk.FileId {
t.Errorf("filer proxy served chunk %q, want %q", got, testServer.chunk.FileId)
if got := <-testServer.supportsChunks; got == readAuth {
t.Errorf("metadata chunk capability = %v, want %v", got, !readAuth)
}
wantChunk := testServer.chunk.FileId
if readAuth {
wantChunk = ""
}
if got, _ := proxiedChunkIds.Load().(string); got != wantChunk {
t.Errorf("filer proxy served chunk %q, want %q", got, wantChunk)
}
entry, _, err := wfs.metaCache.FindEntry(context.Background(), util.FullPath("/dir/file"))
+2 -1
View File
@@ -148,7 +148,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(snapshotChunks)
// Compact chunks to remove fully overlapped ones
compactedChunks, _, err := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
compactedChunks, covered, err := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
if err != nil {
return fmt.Errorf("compact chunks of %s: %w", fileFullPath, err)
}
@@ -188,6 +188,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
// Snapshot with local ids before the request mapping mutates the clone:
// on ack this becomes the handle's base, judged against future events.
baseSnapshot := proto.Clone(requestEntry).(*filer_pb.Entry)
requestEntry.Chunks = append(requestEntry.Chunks, fh.unpublishedChunks(covered, requestEntry.Chunks)...)
wfs.mapPbIdFromLocalToFiler(request.Entry)
resp, merged, err := wfs.createContentEntry(context.Background(), fh, request, baseSnapshot, true, &contentPublication{})
+3
View File
@@ -538,6 +538,9 @@ func (wfs *WFS) handleRenameResponse(ctx context.Context, resp *filer_pb.StreamR
// Keep the saved handle path current so any flush fallback
// after Forget uses the post-rename location, not the old one.
fh.RememberPath(newPath)
// Writeback mounts skip their own rename event, so the
// subscriber never re-tracks this handle.
wfs.readAuth.TrackHandle(newPath, fh)
// Migrate the DLM lock from old path to new path so the
// lock key matches the current file location. Hold the
+16 -10
View File
@@ -12,6 +12,19 @@ import (
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// shouldCacheUploadedChunk decides whether a just-uploaded chunk's bytes are
// put in the local chunk cache. The first chunk (small files) is always cached.
// Peer sharing needs every chunk cached so it can be served back on FetchChunk.
// A read-auth mount needs every chunk cached too: it holds no volume read key
// and reads a chunk with a filer-issued per-fid token the filer can mint only
// after the chunk's entry is published, so a chunk this handle just uploaded
// has no token until the next metadata flush; caching it lets a read-after-write
// of that chunk be served locally instead of failing on a token-less volume
// fetch. Gated on chunkCache != nil (-cacheCapacityMB=0 disables the cache).
func (wfs *WFS) shouldCacheUploadedChunk(offset int64) bool {
return wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil || wfs.readAuth != nil)
}
func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType {
// Backstop: FUSE entry points sanitize names before they reach
@@ -66,16 +79,9 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
}
// When peer sharing is enabled we need EVERY chunk in the
// local cache so we can actually serve it back to peers on
// FetchChunk — otherwise the directory would advertise us as
// a holder and the fetcher would get NOT_FOUND from our
// chunk cache. When peer sharing is off we preserve the
// original behavior of caching only the first chunk (small
// files) to avoid blowing the cache on large uploads. Both
// paths gate on chunkCache != nil: -cacheCapacityMB=0 disables
// the cache entirely, in which case SetChunk would panic.
shouldCache := wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil)
// shouldCacheUploadedChunk explains when and why every uploaded
// chunk is cached (peer sharing, and read-auth read-after-write).
shouldCache := wfs.shouldCacheUploadedChunk(offset)
if shouldCache {
wfs.chunkCache.SetChunk(fileId, data)
}
+37
View File
@@ -0,0 +1,37 @@
package mount
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
)
// TestShouldCacheUploadedChunk pins the chunk-caching decision. The read-auth
// case is the one 0005 adds: a keyless mount must cache every uploaded chunk
// (not only the first) so a read-after-write of a non-first chunk is served
// from the cache before the chunk's entry is published and a token exists.
func TestShouldCacheUploadedChunk(t *testing.T) {
cache := &chunk_cache.TieredChunkCache{}
for _, tc := range []struct {
name string
chunkCache *chunk_cache.TieredChunkCache
peerAnnouncer *PeerAnnouncer
readAuth *ReadAuth
offset int64
want bool
}{
{"no cache configured", nil, nil, nil, 0, false},
{"first chunk, plain mount", cache, nil, nil, 0, true},
{"non-first chunk, plain mount", cache, nil, nil, 1 << 20, false},
{"non-first chunk, peer sharing", cache, &PeerAnnouncer{}, nil, 1 << 20, true},
{"non-first chunk, read-auth mount", cache, nil, &ReadAuth{}, 1 << 20, true},
{"read-auth but cache disabled", nil, nil, &ReadAuth{}, 1 << 20, false},
} {
t.Run(tc.name, func(t *testing.T) {
wfs := &WFS{chunkCache: tc.chunkCache, peerAnnouncer: tc.peerAnnouncer, readAuth: tc.readAuth}
if got := wfs.shouldCacheUploadedChunk(tc.offset); got != tc.want {
t.Fatalf("shouldCacheUploadedChunk(offset=%d)=%v, want %v", tc.offset, got, tc.want)
}
})
}
}
+3
View File
@@ -234,6 +234,8 @@ message KeepConnectedRequest {
// it is not enabled. Advertised so the admin server can scrape it without
// exposing metrics on the client-facing service port.
uint32 metrics_port = 9;
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
uint32 lance_port = 10;
}
message VolumeLocation {
@@ -559,6 +561,7 @@ message ListClusterNodesResponse {
string address = 1;
string version = 2;
int64 created_at_ns = 4;
uint32 lance_port = 7;
string data_center = 5;
string rack = 6;
}
+29 -7
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v3.21.12
// protoc v7.35.0
// source: master.proto
package master_pb
@@ -1043,7 +1043,9 @@ type KeepConnectedRequest struct {
// Port of this node's Prometheus /metrics listener (-metricsPort), or 0 when
// it is not enabled. Advertised so the admin server can scrape it without
// exposing metrics on the client-facing service port.
MetricsPort uint32 `protobuf:"varint,9,opt,name=metrics_port,json=metricsPort,proto3" json:"metrics_port,omitempty"`
MetricsPort uint32 `protobuf:"varint,9,opt,name=metrics_port,json=metricsPort,proto3" json:"metrics_port,omitempty"`
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
LancePort uint32 `protobuf:"varint,10,opt,name=lance_port,json=lancePort,proto3" json:"lance_port,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1134,6 +1136,13 @@ func (x *KeepConnectedRequest) GetMetricsPort() uint32 {
return 0
}
func (x *KeepConnectedRequest) GetLancePort() uint32 {
if x != nil {
return x.LancePort
}
return 0
}
type VolumeLocation struct {
state protoimpl.MessageState `protogen:"open.v1"`
Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
@@ -5040,6 +5049,7 @@ type ListClusterNodesResponse_ClusterNode struct {
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"`
CreatedAtNs int64 `protobuf:"varint,4,opt,name=created_at_ns,json=createdAtNs,proto3" json:"created_at_ns,omitempty"`
LancePort uint32 `protobuf:"varint,7,opt,name=lance_port,json=lancePort,proto3" json:"lance_port,omitempty"`
DataCenter string `protobuf:"bytes,5,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"`
Rack string `protobuf:"bytes,6,opt,name=rack,proto3" json:"rack,omitempty"`
unknownFields protoimpl.UnknownFields
@@ -5097,6 +5107,13 @@ func (x *ListClusterNodesResponse_ClusterNode) GetCreatedAtNs() int64 {
return 0
}
func (x *ListClusterNodesResponse_ClusterNode) GetLancePort() uint32 {
if x != nil {
return x.LancePort
}
return 0
}
func (x *ListClusterNodesResponse_ClusterNode) GetDataCenter() string {
if x != nil {
return x.DataCenter
@@ -5314,7 +5331,7 @@ const file_master_proto_rawDesc = "" +
"\x04data\x18\x01 \x01(\rR\x04data\x12\x16\n" +
"\x06parity\x18\x02 \x01(\rR\x06parity\x12\x1d\n" +
"\n" +
"volume_ids\x18\x03 \x03(\rR\tvolumeIds\"\x99\x02\n" +
"volume_ids\x18\x03 \x03(\rR\tvolumeIds\"\xb8\x02\n" +
"\x14KeepConnectedRequest\x12\x1f\n" +
"\vclient_type\x18\x01 \x01(\tR\n" +
"clientType\x12%\n" +
@@ -5326,7 +5343,10 @@ const file_master_proto_rawDesc = "" +
"dataCenter\x12\x12\n" +
"\x04rack\x18\a \x01(\tR\x04rack\x12&\n" +
"\x0fleave_lock_ring\x18\b \x01(\bR\rleaveLockRing\x12!\n" +
"\fmetrics_port\x18\t \x01(\rR\vmetricsPort\"\x9e\x03\n" +
"\fmetrics_port\x18\t \x01(\rR\vmetricsPort\x12\x1d\n" +
"\n" +
"lance_port\x18\n" +
" \x01(\rR\tlancePort\"\x9e\x03\n" +
"\x0eVolumeLocation\x12\x10\n" +
"\x03url\x18\x01 \x01(\tR\x03url\x12\x1d\n" +
"\n" +
@@ -5586,13 +5606,15 @@ const file_master_proto_rawDesc = "" +
"clientType\x12\x1f\n" +
"\vfiler_group\x18\x02 \x01(\tR\n" +
"filerGroup\x12\x14\n" +
"\x05limit\x18\x04 \x01(\x05R\x05limit\"\x8d\x02\n" +
"\x05limit\x18\x04 \x01(\x05R\x05limit\"\xac\x02\n" +
"\x18ListClusterNodesResponse\x12T\n" +
"\rcluster_nodes\x18\x01 \x03(\v2/.master_pb.ListClusterNodesResponse.ClusterNodeR\fclusterNodes\x1a\x9a\x01\n" +
"\rcluster_nodes\x18\x01 \x03(\v2/.master_pb.ListClusterNodesResponse.ClusterNodeR\fclusterNodes\x1a\xb9\x01\n" +
"\vClusterNode\x12\x18\n" +
"\aaddress\x18\x01 \x01(\tR\aaddress\x12\x18\n" +
"\aversion\x18\x02 \x01(\tR\aversion\x12\"\n" +
"\rcreated_at_ns\x18\x04 \x01(\x03R\vcreatedAtNs\x12\x1f\n" +
"\rcreated_at_ns\x18\x04 \x01(\x03R\vcreatedAtNs\x12\x1d\n" +
"\n" +
"lance_port\x18\a \x01(\rR\tlancePort\x12\x1f\n" +
"\vdata_center\x18\x05 \x01(\tR\n" +
"dataCenter\x12\x12\n" +
"\x04rack\x18\x06 \x01(\tR\x04rack\"\xc5\x01\n" +
+3
View File
@@ -361,6 +361,8 @@ message ClusterContext {
repeated string volume_grpc_addresses = 3;
map<string, string> metadata = 4;
repeated string s3_grpc_addresses = 5;
// Lance Namespace base URLs, one per S3 gateway that serves one.
repeated string lance_namespace_urls = 6;
}
message ActivityEvent {
@@ -499,6 +501,7 @@ message RequestObjectPreview {
// can decline instead of guessing.
string format = 2;
int32 row_limit = 3;
ClusterContext cluster_context = 4;
}
// ObjectPreviewResponse carries the sample back, already rendered as text. The
+53 -33
View File
@@ -3643,8 +3643,10 @@ type ClusterContext struct {
VolumeGrpcAddresses []string `protobuf:"bytes,3,rep,name=volume_grpc_addresses,json=volumeGrpcAddresses,proto3" json:"volume_grpc_addresses,omitempty"`
Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
S3GrpcAddresses []string `protobuf:"bytes,5,rep,name=s3_grpc_addresses,json=s3GrpcAddresses,proto3" json:"s3_grpc_addresses,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// Lance Namespace base URLs, one per S3 gateway that serves one.
LanceNamespaceUrls []string `protobuf:"bytes,6,rep,name=lance_namespace_urls,json=lanceNamespaceUrls,proto3" json:"lance_namespace_urls,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClusterContext) Reset() {
@@ -3712,6 +3714,13 @@ func (x *ClusterContext) GetS3GrpcAddresses() []string {
return nil
}
func (x *ClusterContext) GetLanceNamespaceUrls() []string {
if x != nil {
return x.LanceNamespaceUrls
}
return nil
}
type ActivityEvent struct {
state protoimpl.MessageState `protogen:"open.v1"`
Source ActivitySource `protobuf:"varint,1,opt,name=source,proto3,enum=plugin.ActivitySource" json:"source,omitempty"`
@@ -4154,10 +4163,11 @@ type RequestObjectPreview struct {
ObjectId []string `protobuf:"bytes,1,rep,name=object_id,json=objectId,proto3" json:"object_id,omitempty"`
// The format admin believes this object is, so a worker that does not own it
// can decline instead of guessing.
Format string `protobuf:"bytes,2,opt,name=format,proto3" json:"format,omitempty"`
RowLimit int32 `protobuf:"varint,3,opt,name=row_limit,json=rowLimit,proto3" json:"row_limit,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
Format string `protobuf:"bytes,2,opt,name=format,proto3" json:"format,omitempty"`
RowLimit int32 `protobuf:"varint,3,opt,name=row_limit,json=rowLimit,proto3" json:"row_limit,omitempty"`
ClusterContext *ClusterContext `protobuf:"bytes,4,opt,name=cluster_context,json=clusterContext,proto3" json:"cluster_context,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RequestObjectPreview) Reset() {
@@ -4211,6 +4221,13 @@ func (x *RequestObjectPreview) GetRowLimit() int32 {
return 0
}
func (x *RequestObjectPreview) GetClusterContext() *ClusterContext {
if x != nil {
return x.ClusterContext
}
return nil
}
// ObjectPreviewResponse carries the sample back, already rendered as text. The
// worker is the only thing that knows the object's types, so it formats them;
// admin displays what it is given.
@@ -4697,13 +4714,14 @@ const file_plugin_proto_rawDesc = "" +
"\asummary\x18\x02 \x01(\tR\asummary\x1aT\n" +
"\x11OutputValuesEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12)\n" +
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xcc\x02\n" +
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xfe\x02\n" +
"\x0eClusterContext\x122\n" +
"\x15master_grpc_addresses\x18\x01 \x03(\tR\x13masterGrpcAddresses\x12'\n" +
"\x0ffiler_addresses\x18\x02 \x03(\tR\x0efilerAddresses\x122\n" +
"\x15volume_grpc_addresses\x18\x03 \x03(\tR\x13volumeGrpcAddresses\x12@\n" +
"\bmetadata\x18\x04 \x03(\v2$.plugin.ClusterContext.MetadataEntryR\bmetadata\x12*\n" +
"\x11s3_grpc_addresses\x18\x05 \x03(\tR\x0fs3GrpcAddresses\x1a;\n" +
"\x11s3_grpc_addresses\x18\x05 \x03(\tR\x0fs3GrpcAddresses\x120\n" +
"\x14lance_namespace_urls\x18\x06 \x03(\tR\x12lanceNamespaceUrls\x1a;\n" +
"\rMetadataEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xb9\x02\n" +
@@ -4757,11 +4775,12 @@ const file_plugin_proto_rawDesc = "" +
"observedAt\x1aR\n" +
"\x0fAttributesEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12)\n" +
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"h\n" +
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xa9\x01\n" +
"\x14RequestObjectPreview\x12\x1b\n" +
"\tobject_id\x18\x01 \x03(\tR\bobjectId\x12\x16\n" +
"\x06format\x18\x02 \x01(\tR\x06format\x12\x1b\n" +
"\trow_limit\x18\x03 \x01(\x05R\browLimit\"\xd6\x01\n" +
"\trow_limit\x18\x03 \x01(\x05R\browLimit\x12?\n" +
"\x0fcluster_context\x18\x04 \x01(\v2\x16.plugin.ClusterContextR\x0eclusterContext\"\xd6\x01\n" +
"\x15ObjectPreviewResponse\x12\x1d\n" +
"\n" +
"request_id\x18\x06 \x01(\tR\trequestId\x12\x18\n" +
@@ -5013,29 +5032,30 @@ var file_plugin_proto_depIdxs = []int32{
47, // 90: plugin.WorkerObservations.observations:type_name -> plugin.ObjectObservation
71, // 91: plugin.ObjectObservation.attributes:type_name -> plugin.ObjectObservation.AttributesEntry
72, // 92: plugin.ObjectObservation.observed_at:type_name -> google.protobuf.Timestamp
50, // 93: plugin.ObjectPreviewResponse.rows:type_name -> plugin.PreviewRow
23, // 94: plugin.JobTypeDescriptor.WorkerDefaultValuesEntry.value:type_name -> plugin.ConfigValue
23, // 95: plugin.ConfigForm.DefaultValuesEntry.value:type_name -> plugin.ConfigValue
23, // 96: plugin.ValueMap.FieldsEntry.value:type_name -> plugin.ConfigValue
23, // 97: plugin.RunDetectionRequest.AdminConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 98: plugin.RunDetectionRequest.WorkerConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 99: plugin.JobProposal.ParametersEntry.value:type_name -> plugin.ConfigValue
23, // 100: plugin.ExecuteJobRequest.AdminConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 101: plugin.ExecuteJobRequest.WorkerConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 102: plugin.JobSpec.ParametersEntry.value:type_name -> plugin.ConfigValue
23, // 103: plugin.JobProgressUpdate.MetricsEntry.value:type_name -> plugin.ConfigValue
23, // 104: plugin.JobResult.OutputValuesEntry.value:type_name -> plugin.ConfigValue
23, // 105: plugin.ActivityEvent.DetailsEntry.value:type_name -> plugin.ConfigValue
23, // 106: plugin.PersistedJobTypeConfig.AdminConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 107: plugin.PersistedJobTypeConfig.WorkerConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 108: plugin.ObjectObservation.AttributesEntry.value:type_name -> plugin.ConfigValue
7, // 109: plugin.PluginControlService.WorkerStream:input_type -> plugin.WorkerToAdminMessage
8, // 110: plugin.PluginControlService.WorkerStream:output_type -> plugin.AdminToWorkerMessage
110, // [110:111] is the sub-list for method output_type
109, // [109:110] is the sub-list for method input_type
109, // [109:109] is the sub-list for extension type_name
109, // [109:109] is the sub-list for extension extendee
0, // [0:109] is the sub-list for field type_name
41, // 93: plugin.RequestObjectPreview.cluster_context:type_name -> plugin.ClusterContext
50, // 94: plugin.ObjectPreviewResponse.rows:type_name -> plugin.PreviewRow
23, // 95: plugin.JobTypeDescriptor.WorkerDefaultValuesEntry.value:type_name -> plugin.ConfigValue
23, // 96: plugin.ConfigForm.DefaultValuesEntry.value:type_name -> plugin.ConfigValue
23, // 97: plugin.ValueMap.FieldsEntry.value:type_name -> plugin.ConfigValue
23, // 98: plugin.RunDetectionRequest.AdminConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 99: plugin.RunDetectionRequest.WorkerConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 100: plugin.JobProposal.ParametersEntry.value:type_name -> plugin.ConfigValue
23, // 101: plugin.ExecuteJobRequest.AdminConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 102: plugin.ExecuteJobRequest.WorkerConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 103: plugin.JobSpec.ParametersEntry.value:type_name -> plugin.ConfigValue
23, // 104: plugin.JobProgressUpdate.MetricsEntry.value:type_name -> plugin.ConfigValue
23, // 105: plugin.JobResult.OutputValuesEntry.value:type_name -> plugin.ConfigValue
23, // 106: plugin.ActivityEvent.DetailsEntry.value:type_name -> plugin.ConfigValue
23, // 107: plugin.PersistedJobTypeConfig.AdminConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 108: plugin.PersistedJobTypeConfig.WorkerConfigValuesEntry.value:type_name -> plugin.ConfigValue
23, // 109: plugin.ObjectObservation.AttributesEntry.value:type_name -> plugin.ConfigValue
7, // 110: plugin.PluginControlService.WorkerStream:input_type -> plugin.WorkerToAdminMessage
8, // 111: plugin.PluginControlService.WorkerStream:output_type -> plugin.AdminToWorkerMessage
111, // [111:112] is the sub-list for method output_type
110, // [110:111] is the sub-list for method input_type
110, // [110:110] is the sub-list for extension type_name
110, // [110:110] is the sub-list for extension extendee
0, // [0:110] is the sub-list for field type_name
}
func init() { file_plugin_proto_init() }
+4
View File
@@ -83,6 +83,9 @@ type S3ApiServerOption struct {
// AllowBackslashInKey keeps '\' a literal object-key character instead of
// normalizing it to '/', matching AWS S3 where the two are distinct keys.
AllowBackslashInKey bool
// LancePort is advertised to the master so admin can point workers at the
// Lance Namespace; 0 when this gateway serves none.
LancePort uint32
// IamSelfServiceRequiresGrant makes managing one's own access keys
// (CreateAccessKey, DeleteAccessKey, UpdateAccessKey, ListAccessKeys,
// GetUser) need an explicit iam: grant instead of being allowed to every
@@ -265,6 +268,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
masterClient.SetOnPeerUpdateFn(filerClient.OnPeerUpdate)
masterClient.SetOnVolumeLocationChangeFn(filerClient.OnVolumeLocationChange)
masterClient.SetOnVidMapResetFn(filerClient.OnVidMapReset)
masterClient.SetLancePort(option.LancePort)
// Start the master client connection loop - required for GetMaster() to work
go masterClient.KeepConnectedToMaster(context.Background())
+1 -1
View File
@@ -101,7 +101,7 @@ func IsFilerAdminToken(signingKey SigningKey, token EncodedJwt, previousKeys ...
return false
}
claims, ok := parsed.Claims.(*SeaweedFilerAdminClaims)
return ok && claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0
return ok && claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0 && len(claims.ReadPrefixes) == 0
}
// GrpcAdminPeerCredentials returns outgoing metadata carrying a Bearer token
+32 -19
View File
@@ -38,12 +38,12 @@ func TestCheckGrpcAdminPeer(t *testing.T) {
wantCode codes.Code
}{
"no peer info, no key": {context.Background(), nil, codes.Unauthenticated},
"loopback, no key": {peerCtx(loopback), nil, codes.OK},
"remote, no key": {peerCtx(remote), nil, codes.Unauthenticated},
"remote + valid token": {bearerCtx(remote, key), key, codes.OK},
"loopback, no key": {peerCtx(loopback), nil, codes.OK},
"remote, no key": {peerCtx(remote), nil, codes.Unauthenticated},
"remote + valid token": {bearerCtx(remote, key), key, codes.OK},
"remote + no metadata, key set": {peerCtx(remote), key, codes.Unauthenticated},
"remote + bad token": {metadata.NewIncomingContext(peerCtx(remote), metadata.Pairs("authorization", "Bearer wrong")), key, codes.Unauthenticated},
"unix socket, no key": {peerCtx(&net.UnixAddr{Name: "/tmp/s.sock"}), nil, codes.OK},
"remote + bad token": {metadata.NewIncomingContext(peerCtx(remote), metadata.Pairs("authorization", "Bearer wrong")), key, codes.Unauthenticated},
"unix socket, no key": {peerCtx(&net.UnixAddr{Name: "/tmp/s.sock"}), nil, codes.OK},
"mtls verified peer": {peer.NewContext(context.Background(), &peer.Peer{
Addr: remote,
AuthInfo: credentials.TLSInfo{State: tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{}}}},
@@ -60,6 +60,16 @@ func TestCheckGrpcAdminPeer(t *testing.T) {
}
}
func TestCheckGrpcAdminPeerRefusesReadOnlyFilerToken(t *testing.T) {
key := SigningKey("test-signing-key-0123456789abcdef")
remote := &net.TCPAddr{IP: net.ParseIP("203.0.113.9"), Port: 5000}
token := GenJwtForFilerScope(key, time.Hour, "lease-1", nil, []string{"/buckets/alice"})
ctx := metadata.NewIncomingContext(peerCtx(remote), metadata.Pairs("authorization", "Bearer "+string(token)))
if err := CheckGrpcAdminPeer(ctx, key); status.Code(err) != codes.Unauthenticated {
t.Fatalf("read-only scoped token accepted as admin peer: %v", err)
}
}
func TestGrpcAdminPeerCredentials(t *testing.T) {
if md := GrpcAdminPeerCredentials(nil, 0); len(md) != 0 {
t.Errorf("expected nil metadata without signing key, got %v", md)
@@ -97,26 +107,29 @@ func TestCheckGrpcAdminToken(t *testing.T) {
}
pathScoped := scoped(SeaweedFilerClaims{AllowedPrefixes: []string{"/tenants/t1"}})
methodScoped := scoped(SeaweedFilerClaims{AllowedMethods: []string{"GET"}})
readOnlyScoped := scoped(SeaweedFilerClaims{ReadPrefixes: []string{"/tenants/t1"}})
unscoped := scoped(SeaweedFilerClaims{})
for name, tc := range map[string]struct {
values []string
wantErr string
}{
"stale then fresh": {[]string{stale, fresh}, ""},
"fresh then garbage": {[]string{fresh, "garbage"}, ""},
"expired then fresh": {[]string{"Bearer " + expired, fresh}, ""},
"only expired": {[]string{"Bearer " + expired}, "invalid admin token"},
"only stale": {[]string{stale}, "invalid admin token"},
"same-key session": {[]string{"Bearer " + session}, "invalid admin token"},
"path-scoped": {[]string{pathScoped}, "invalid admin token"},
"method-scoped": {[]string{methodScoped}, "invalid admin token"},
"scoped then fresh": {[]string{pathScoped, fresh}, ""},
"unscoped filer": {[]string{unscoped}, ""},
"basic then stale": {[]string{"Basic dXNlcjpwYXNz", stale}, "invalid admin token"},
"no bearer value": {[]string{"Basic dXNlcjpwYXNz", "garbage"}, "authorization header must use Bearer scheme"},
"lowercase scheme ok": {[]string{"bearer " + fresh[len("Bearer "):]}, ""},
"fresh past the cap": {append(slices.Repeat([]string{stale}, maxGrpcAdminAuthValues), fresh), "invalid admin token"},
"stale then fresh": {[]string{stale, fresh}, ""},
"fresh then garbage": {[]string{fresh, "garbage"}, ""},
"expired then fresh": {[]string{"Bearer " + expired, fresh}, ""},
"only expired": {[]string{"Bearer " + expired}, "invalid admin token"},
"only stale": {[]string{stale}, "invalid admin token"},
"same-key session": {[]string{"Bearer " + session}, "invalid admin token"},
"path-scoped": {[]string{pathScoped}, "invalid admin token"},
"method-scoped": {[]string{methodScoped}, "invalid admin token"},
"read-only-scoped": {[]string{readOnlyScoped}, "invalid admin token"},
"read-only then fresh": {[]string{readOnlyScoped, fresh}, ""},
"scoped then fresh": {[]string{pathScoped, fresh}, ""},
"unscoped filer": {[]string{unscoped}, ""},
"basic then stale": {[]string{"Basic dXNlcjpwYXNz", stale}, "invalid admin token"},
"no bearer value": {[]string{"Basic dXNlcjpwYXNz", "garbage"}, "authorization header must use Bearer scheme"},
"lowercase scheme ok": {[]string{"bearer " + fresh[len("Bearer "):]}, ""},
"fresh past the cap": {append(slices.Repeat([]string{stale}, maxGrpcAdminAuthValues), fresh), "invalid admin token"},
} {
ctx := metadata.NewIncomingContext(context.Background(), metadata.MD{"authorization": tc.values})
err := CheckGrpcAdminToken(ctx, key)
+40
View File
@@ -33,12 +33,45 @@ type SeaweedFileIdClaims struct {
type SeaweedFilerClaims struct {
AllowedPrefixes []string `json:"allowed_prefixes,omitempty"`
AllowedMethods []string `json:"allowed_methods,omitempty"`
ReadPrefixes []string `json:"read_prefixes,omitempty"`
// SessionId is present only on STS session tokens; a token carrying it is
// an S3 session credential, not a filer API credential.
SessionId string `json:"sid,omitempty"`
jwt.RegisteredClaims
}
// IsScoped reports whether the token restricts the paths it may touch.
func (c *SeaweedFilerClaims) IsScoped() bool {
return c != nil && (len(c.AllowedPrefixes) > 0 || len(c.ReadPrefixes) > 0)
}
// GenJwtForFilerScope mints a filer credential restricted to allowedPrefixes
// (read and write) and readPrefixes (read only). id becomes the "jti" claim:
// the identity used in authorization diagnostics. Returns an empty string
// if the signing key is not configured, the token would not expire, or no
// path grant was supplied.
func GenJwtForFilerScope(signingKey SigningKey, expiresAfter time.Duration, id string, allowedPrefixes, readPrefixes []string) EncodedJwt {
if len(signingKey) == 0 || expiresAfter <= 0 || len(allowedPrefixes) == 0 && len(readPrefixes) == 0 {
return ""
}
claims := SeaweedFilerClaims{
AllowedPrefixes: allowedPrefixes,
ReadPrefixes: readPrefixes,
RegisteredClaims: jwt.RegisteredClaims{
ID: id,
IssuedAt: jwt.NewNumericDate(time.Now()),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiresAfter)),
},
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
encoded, e := t.SignedString([]byte(signingKey))
if e != nil {
glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
return ""
}
return EncodedJwt(encoded)
}
// SeaweedFilerAdminClaims is presented by callers of the filer's IAM gRPC
// service to prove they are authorised to administer users, access keys, and
// policies. The token is signed with the filer write-signing key
@@ -55,6 +88,7 @@ type SeaweedFilerAdminClaims struct {
// A filer token scoped to paths or methods is not an admin credential.
AllowedPrefixes []string `json:"allowed_prefixes,omitempty"`
AllowedMethods []string `json:"allowed_methods,omitempty"`
ReadPrefixes []string `json:"read_prefixes,omitempty"`
jwt.RegisteredClaims
}
@@ -178,6 +212,12 @@ func verificationKeySet(signingKey SigningKey, previousKeys []SigningKey) jwt.Ve
return keySet
}
// DecodeJwtWith verifies a filer token with optional previous-key and clock
// leeway support, using the same verification path as DecodeJwt.
func DecodeJwtWith(signingKey, previousKey SigningKey, tokenString EncodedJwt, claims jwt.Claims, leeway time.Duration) (*jwt.Token, error) {
return decodeJwt(signingKey, []SigningKey{previousKey}, tokenString, claims, jwt.WithLeeway(leeway))
}
// FilerJwtProvider signs the credential a filer's HTTP API expects. A nil
// provider means the process-wide jwt.filer_signing configuration applies.
type FilerJwtProvider func(isWrite bool) EncodedJwt
+111
View File
@@ -0,0 +1,111 @@
package security
import (
"errors"
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v5"
)
func TestGenJwtForFilerScopeCarriesReadWriteAndReadOnlyClaims(t *testing.T) {
token := GenJwtForFilerScope(SigningKey("scope-test-signing-key"), time.Hour, "lease-1", []string{"/write"}, []string{"/read"})
if token == "" {
t.Fatal("GenJwtForFilerScope returned an empty token")
}
claims := &SeaweedFilerClaims{}
parsed, err := DecodeJwt(SigningKey("scope-test-signing-key"), token, claims)
if err != nil || parsed == nil || !parsed.Valid {
t.Fatalf("decode scoped token: valid=%v err=%v", parsed != nil && parsed.Valid, err)
}
if claims.ID != "lease-1" || !claims.IsScoped() {
t.Fatalf("claims = %+v, want scoped lease-1 claims", claims)
}
if len(claims.AllowedPrefixes) != 1 || claims.AllowedPrefixes[0] != "/write" {
t.Fatalf("allowed prefixes = %v", claims.AllowedPrefixes)
}
if len(claims.ReadPrefixes) != 1 || claims.ReadPrefixes[0] != "/read" {
t.Fatalf("read prefixes = %v", claims.ReadPrefixes)
}
}
func TestGenJwtForFilerScopeRequiresKeyAndPositiveExpiry(t *testing.T) {
for _, tc := range []struct {
name string
key SigningKey
age time.Duration
}{
{name: "missing key", age: time.Hour},
{name: "zero expiry", key: SigningKey("scope-test-signing-key")},
{name: "negative expiry", key: SigningKey("scope-test-signing-key"), age: -time.Second},
} {
t.Run(tc.name, func(t *testing.T) {
if got := GenJwtForFilerScope(tc.key, tc.age, "lease-1", []string{"/write"}, nil); got != "" {
t.Fatal("expected no token")
}
})
}
}
func TestGenJwtForFilerScopeRequiresAPathGrant(t *testing.T) {
for _, tc := range []struct {
name string
allowed []string
readOnly []string
}{
{name: "nil grants"},
{name: "empty grants", allowed: []string{}, readOnly: []string{}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := GenJwtForFilerScope(SigningKey("scope-test-signing-key"), time.Hour, "lease-1", tc.allowed, tc.readOnly); got != "" {
t.Fatal("expected no token without a path grant")
}
})
}
}
func TestDecodeJwtWithAcceptsCurrentAndPreviousScopeKeys(t *testing.T) {
current := SigningKey("current-scope-key")
previous := SigningKey("previous-scope-key")
other := SigningKey("other-scope-key")
for _, tc := range []struct {
name string
signedBy SigningKey
previousKey SigningKey
wantErr bool
}{
{name: "current key", signedBy: current},
{name: "previous key", signedBy: previous, previousKey: previous},
{name: "wrong previous key", signedBy: previous, previousKey: other, wantErr: true},
} {
t.Run(tc.name, func(t *testing.T) {
token := GenJwtForFilerScope(tc.signedBy, time.Hour, "lease-1", []string{"/write"}, nil)
claims := &SeaweedFilerClaims{}
parsed, err := DecodeJwtWith(current, tc.previousKey, token, claims, 0)
if tc.wantErr {
if err == nil || parsed != nil && parsed.Valid {
t.Fatalf("wrong previous key accepted token: parsed=%v err=%v", parsed, err)
}
return
}
if err != nil || parsed == nil || !parsed.Valid {
t.Fatalf("scope key rotation decode: parsed=%v err=%v", parsed, err)
}
})
}
expiredPayload, err := jwt.NewWithClaims(jwt.SigningMethodHS256, SeaweedFilerClaims{
AllowedPrefixes: []string{"/write"},
RegisteredClaims: jwt.RegisteredClaims{
ID: "lease-1",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
},
}).SignedString([]byte(previous))
if err != nil {
t.Fatalf("sign expired token: %v", err)
}
_, err = DecodeJwtWith(current, previous, EncodedJwt(expiredPayload), &SeaweedFilerClaims{}, 0)
if !errors.Is(err, jwt.ErrTokenExpired) {
t.Fatalf("expired previous-key token error = %v, want ErrTokenExpired", err)
}
}
+35
View File
@@ -0,0 +1,35 @@
package security
import (
"context"
"sync/atomic"
)
// VolumeReadTokenProvider supplies the volume read credential for one file id.
// A client that must not hold jwt.signing.read.key -- a mount whose filer hands
// it exact-fid read capabilities (LookupDirectoryEntries read_auth) -- installs
// one; while installed it replaces local signing wherever a chunk is read
// directly from a volume server.
type VolumeReadTokenProvider func(ctx context.Context, fileId string) string
var volumeReadTokenProvider atomic.Pointer[VolumeReadTokenProvider]
// SetVolumeReadTokenProvider installs p process-wide; nil removes it.
func SetVolumeReadTokenProvider(p VolumeReadTokenProvider) {
if p == nil {
volumeReadTokenProvider.Store(nil)
return
}
volumeReadTokenProvider.Store(&p)
}
// VolumeReadToken returns the installed provider's token for fileId, and
// whether a provider is installed. An installed provider that has no token
// returns "", so the read fails closed instead of falling back to a key.
func VolumeReadToken(ctx context.Context, fileId string) (string, bool) {
p := volumeReadTokenProvider.Load()
if p == nil {
return "", false
}
return (*p)(ctx, fileId), true
}
+632
View File
@@ -0,0 +1,632 @@
package weed_server
// Scoped filer tokens on the filesystem gRPC service. Tokenless calls retain
// their existing behavior. A verified scoped token is confined to its path and
// method grants, and may only retain data already stored at the target path.
// Unruled methods are refused. Streams recheck expiry on every message.
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"reflect"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"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/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
const (
scopePosixLockKeyPrefix = "s3.fuse.lock:"
scopeErrnoEACCES = 13
// scopeFilerConfDir and scopeFilerConfName locate the filer's per-path
// storage rules (collection, replication, ttl, read-only), which weed
// mount looks up once at start. A scoped token is answered "not found"
// without a lookup: the mount then uses its defaults, the filer applies
// the same rules itself in AssignVolume (detectStorageOption), and the
// rule list, which names every path on the filer, stays with the filer.
scopeFilerConfDir = "/etc/seaweedfs"
scopeFilerConfName = "filer.conf"
)
// scopeBackend is what the rules need from the filer: the entry currently
// stored at a path, and the hard-link registry. The FilerServer implements it;
// tests use a fake.
type scopeBackend interface {
// scopeFindEntry returns the entry at the canonical path p, or nil when
// there is none.
scopeFindEntry(ctx context.Context, p string) (*filer_pb.Entry, error)
// scopeKvGet returns the value stored under key, or nil when there is none.
scopeKvGet(ctx context.Context, key []byte) ([]byte, error)
}
// scopeConfig is the jwt.filer_signing configuration the scope reads, as
// functions so that a reload is seen at once.
type scopeConfig struct {
signingKey func() security.SigningKey
verificationKeys func() (security.SigningKey, security.SigningKey)
subscriptionScope func(context.Context, string) (*security.MetadataSubscriptionScope, error)
}
// filerGrpcScope holds the interceptors. It keeps no state across calls.
type filerGrpcScope struct {
cfg scopeConfig
backend scopeBackend
}
func newFilerGrpcScope(cfg scopeConfig, backend scopeBackend) *filerGrpcScope {
return &filerGrpcScope{cfg: cfg, backend: backend}
}
// ServerOptions returns the gRPC server options that install the scope on a
// server. They chain behind whatever interceptors the server already has.
func (s *filerGrpcScope) ServerOptions() []grpc.ServerOption {
return []grpc.ServerOption{
grpc.ChainUnaryInterceptor(s.unary),
grpc.ChainStreamInterceptor(s.stream),
}
}
// scope is the resolved authority of one call: the token's holder, expiry and
// grants. A nil *scope means the call is unscoped.
type scope struct {
id string
exp time.Time
grants []scopeGrant
// methods, when non-empty, are the gRPC method short names this token may
// call (allowed_methods). A lookup-only token cannot mutate entries under
// its prefixes. An empty list means no additional method restriction.
methods []string
peer string
}
// methodAllowed reports whether the token may call fullMethod. A token without
// allowed_methods may call any method the per-method rules admit; one with
// allowed_methods may call only those, matched by the gRPC method's short name
// (the part after the last "/").
func (sc *scope) methodAllowed(fullMethod string) bool {
if len(sc.methods) == 0 {
return true
}
short := fullMethod[strings.LastIndex(fullMethod, "/")+1:]
for _, m := range sc.methods {
if m == short {
return true
}
}
return false
}
func (sc *scope) expired() bool { return !time.Now().Before(sc.exp) }
// scopeExpiredError ends a call or stream whose token passed its expiry while
// in use; the holder reconnects with a renewed token.
func scopeExpiredError(sc *scope) error {
glog.V(1).Infof("filer grpc: token %s (%s) expired", sc.id, sc.peer)
return status.Errorf(codes.Unauthenticated, "filer: token %s expired", sc.id)
}
// bearerFromMetadata distinguishes absent credentials from malformed or
// ambiguous credentials. Only the former retains tokenless compatibility.
func bearerFromMetadata(ctx context.Context) (string, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", nil
}
values := md.Get("authorization")
if len(values) == 0 {
return "", nil
}
if len(values) != 1 {
return "", status.Error(codes.Unauthenticated, "filer: exactly one authorization value is required")
}
parts := strings.Fields(values[0])
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return "", status.Error(codes.Unauthenticated, "filer: malformed bearer authorization")
}
return parts[1], nil
}
func scopePeer(ctx context.Context) string {
if p, ok := peer.FromContext(ctx); ok && p.Addr != nil {
return p.Addr.String()
}
return "unknown"
}
// resolve authenticates the call. It returns (nil, nil) for an unscoped call,
// a *scope for a scoped token, and an error that refuses the call.
func (s *filerGrpcScope) resolve(ctx context.Context) (*scope, error) {
var key, previous security.SigningKey
if s.cfg.verificationKeys != nil {
key, previous = s.cfg.verificationKeys()
} else if s.cfg.signingKey != nil {
key = s.cfg.signingKey()
}
if len(key) == 0 {
return nil, nil
}
raw, authErr := bearerFromMetadata(ctx)
if authErr != nil {
return nil, authErr
}
if raw == "" {
return nil, nil
}
claims := &security.SeaweedFilerClaims{}
token, err := security.DecodeJwtWith(key, previous, security.EncodedJwt(raw), claims, 0)
if errors.Is(err, jwt.ErrTokenExpired) {
// The claims are parsed before validation, so the id names the holder.
glog.V(1).Infof("filer grpc: token %s (%s) expired", claims.ID, scopePeer(ctx))
return nil, status.Errorf(codes.Unauthenticated, "filer: token %s expired", claims.ID)
}
if err != nil || token == nil || !token.Valid {
glog.V(1).Infof("filer grpc: refused call from %s: invalid token: %v", scopePeer(ctx), err)
return nil, status.Error(codes.Unauthenticated, "filer: invalid bearer token")
}
if claims.SessionId != "" {
return nil, status.Error(codes.Unauthenticated, "filer: an STS session token is not a filer credential")
}
// A token with neither prefixes nor allowed_methods has full access.
// allowed_methods alone also scopes the token (so a method restriction is
// enforced even without a path grant); IsScoped stays prefix-only so the
// HTTP path authorization of a method-only token is unchanged.
if !claims.IsScoped() && len(claims.AllowedMethods) == 0 {
return nil, nil
}
if claims.ID == "" {
return nil, status.Error(codes.PermissionDenied, "filer: a scoped token must carry an id (jti)")
}
if claims.ExpiresAt == nil {
return nil, status.Error(codes.PermissionDenied, "filer: a scoped token must expire")
}
grants, err := scopeGrantsFromClaims(claims.AllowedPrefixes, claims.ReadPrefixes)
if err != nil {
return nil, status.Errorf(codes.PermissionDenied, "filer: scoped token: %v", err)
}
return &scope{id: claims.ID, exp: claims.ExpiresAt.Time, grants: grants, methods: claims.AllowedMethods, peer: scopePeer(ctx)}, nil
}
// deny logs and builds the refusal of a scoped call.
func (sc *scope) deny(method, reason string) error {
glog.V(1).Infof("filer grpc: scoped token %s (%s) refused %s: %s", sc.id, sc.peer, method, reason)
return status.Errorf(codes.PermissionDenied, "filer: %s: %s", method, reason)
}
// checkPath resolves directory+name and applies the path rule.
func (sc *scope) checkPath(method, dir, name string, write bool) (string, error) {
p, err := scopeFullPath(dir, name)
if err != nil {
return "", sc.deny(method, err.Error())
}
if !scopePathAllowed(sc.grants, p, write) {
mode := "read"
if write {
mode = "write"
}
return "", sc.deny(method, fmt.Sprintf("%s of %s is outside the token's scope", mode, p))
}
return p, nil
}
func (sc *scope) checkProtectedPath(method, p string, descendants bool) error {
if scopeProtectedPath(p, descendants) {
return sc.deny(method, "filer.conf is protected from scoped mutations")
}
return nil
}
// checkClientEntry admits only chunks already stored at the checked target.
// A hard-link id may be retained there, or a fresh id may be introduced by an
// update of an existing unlinked entry. Attaching another path's id is refused.
// Client signatures stay allowed so mounts can filter their own events.
func (s *filerGrpcScope) checkClientEntry(ctx context.Context, sc *scope, method, p string, e *filer_pb.Entry, allowNewHardLink bool) error {
if err := scopeCheckEntryShape(e); err != nil {
return sc.deny(method, err.Error())
}
if err := sc.checkProtectedPath(method, p, false); err != nil {
return err
}
var stored *filer_pb.Entry
loaded := false
load := func() error {
if loaded {
return nil
}
loaded = true
var err error
stored, err = s.backend.scopeFindEntry(ctx, p)
if err != nil {
return sc.deny(method, fmt.Sprintf("the entry stored at %s could not be read: %v", p, err))
}
if err := scopeWritesSharedHardLink(stored, e); err != nil {
return sc.deny(method, err.Error())
}
return nil
}
// Inline content and chunk references are rechecked against the locked
// entry by the handlers as well as against this admission snapshot.
if len(e.GetContent()) > 0 || len(e.GetChunks()) > 0 {
if err := load(); err != nil {
return err
}
if err := scopeRetainsData(stored, e); err != nil {
return sc.deny(method, err.Error())
}
}
if len(e.HardLinkId) == 0 {
return nil
}
if err := load(); err != nil {
return err
}
if stored != nil && bytes.Equal(stored.HardLinkId, e.HardLinkId) {
return nil
}
if !allowNewHardLink || stored == nil || len(stored.HardLinkId) > 0 || !scopeLooksLikeNewHardLinkId(e.HardLinkId) {
return sc.deny(method, fmt.Sprintf("hard link %x cannot be attached to %s", e.HardLinkId, p))
}
value, kvErr := s.backend.scopeKvGet(ctx, e.HardLinkId)
if kvErr != nil {
return sc.deny(method, fmt.Sprintf("hard link registry unavailable: %v", kvErr))
}
if len(value) > 0 {
return sc.deny(method, fmt.Sprintf("hard link %s already exists elsewhere", hex.EncodeToString(e.HardLinkId)))
}
return nil
}
func (s *filerGrpcScope) checkCreate(ctx context.Context, sc *scope, m string, req *filer_pb.CreateEntryRequest) error {
if req.GetEntry() == nil || req.GetEntry().GetName() == "" {
return sc.deny(m, "a named entry is required")
}
if req.GetIsFromOtherCluster() || req.GetIsMoved() {
return sc.deny(m, "is_from_other_cluster and is_moved are not allowed")
}
p, err := sc.checkPath(m, req.GetDirectory(), req.GetEntry().GetName(), true)
if err != nil {
return err
}
if !req.GetSkipCheckParentDirectory() {
if err := s.checkAncestors(ctx, sc, m, p); err != nil {
return err
}
}
return s.checkClientEntry(ctx, sc, m, p, req.GetEntry(), false)
}
func (s *filerGrpcScope) checkUpdate(ctx context.Context, sc *scope, m string, req *filer_pb.UpdateEntryRequest) error {
if req.GetEntry() == nil || req.GetEntry().GetName() == "" {
return sc.deny(m, "a named entry is required")
}
if req.GetIsFromOtherCluster() || req.GetIsMoved() {
return sc.deny(m, "is_from_other_cluster and is_moved are not allowed")
}
p, err := sc.checkPath(m, req.GetDirectory(), req.GetEntry().GetName(), true)
if err != nil {
return err
}
return s.checkClientEntry(ctx, sc, m, p, req.GetEntry(), true)
}
func (s *filerGrpcScope) checkAppend(ctx context.Context, sc *scope, m string, req *filer_pb.AppendToEntryRequest) error {
p, err := sc.checkPath(m, req.GetDirectory(), req.GetEntryName(), true)
if err != nil {
return err
}
if err := s.checkAncestors(ctx, sc, m, p); err != nil {
return err
}
return s.checkClientEntry(ctx, sc, m, p, &filer_pb.Entry{Name: req.GetEntryName(), Chunks: req.GetChunks()}, false)
}
// checkAncestors refuses a write at p that would make an ancestor outside the
// write grants: the filer creates the missing ancestors of p up to the first
// one it finds, and turns that one into a directory if it is a file.
func (s *filerGrpcScope) checkAncestors(ctx context.Context, sc *scope, m, p string) error {
for dir, _ := scopeSplitPath(p); dir != "/"; dir, _ = scopeSplitPath(dir) {
entry, err := s.backend.scopeFindEntry(ctx, dir)
if err != nil {
return sc.deny(m, fmt.Sprintf("the entry stored at %s could not be read: %v", dir, err))
}
if entry != nil && entry.GetIsDirectory() {
return nil
}
if !scopePathAllowed(sc.grants, dir, true) {
return sc.deny(m, fmt.Sprintf("%s is outside the token's scope and is not a directory", dir))
}
if entry != nil {
return nil
}
}
return nil
}
func (sc *scope) checkDelete(m string, req *filer_pb.DeleteEntryRequest) error {
if req.GetIsFromOtherCluster() || req.GetIsMoved() {
return sc.deny(m, "is_from_other_cluster and is_moved are not allowed")
}
p, err := sc.checkPath(m, req.GetDirectory(), req.GetName(), true)
if err != nil {
return err
}
return sc.checkProtectedPath(m, p, true)
}
func (s *filerGrpcScope) checkRename(ctx context.Context, sc *scope, m, oldDir, oldName, newDir, newName string) error {
oldPath, err := sc.checkPath(m, oldDir, oldName, true)
if err != nil {
return err
}
if err := sc.checkProtectedPath(m, oldPath, true); err != nil {
return err
}
newPath, err := sc.checkPath(m, newDir, newName, true)
if err != nil {
return err
}
if err := sc.checkProtectedPath(m, newPath, true); err != nil {
return err
}
return s.checkAncestors(ctx, sc, m, newPath)
}
// checkPosixLock admits locks on paths inside the scope and on hard links
// the registry knows (their ids are random, so a holder only has those it
// read from an entry; a lock serializes, it reads nothing).
func (s *filerGrpcScope) checkPosixLock(ctx context.Context, sc *scope, m string, req *filer_pb.PosixLockRequest) error {
if req.GetIsMoved() || req.GetCoolingProbe() {
return sc.deny(m, "internal lock flags are not allowed")
}
// Only GET_LK is a read: the sid is client-supplied, so a read grant must
// not release or renew another session's locks.
write := req.GetOp() != filer_pb.PosixLockOp_GET_LK
key := req.GetKey()
if !strings.HasPrefix(key, scopePosixLockKeyPrefix) {
return sc.deny(m, fmt.Sprintf("lock key %q has no %q prefix", key, scopePosixLockKeyPrefix))
}
rest := strings.TrimPrefix(key, scopePosixLockKeyPrefix)
if strings.HasPrefix(rest, "hl:") {
if write {
hasWriteGrant := false
for _, grant := range sc.grants {
if grant.readWrite {
hasWriteGrant = true
break
}
}
if !hasWriteGrant {
return sc.deny(m, "write lock on a hard link requires a read-write scope")
}
}
id, decErr := hex.DecodeString(strings.TrimPrefix(rest, "hl:"))
if decErr != nil || len(id) == 0 {
return sc.deny(m, fmt.Sprintf("lock on hard link %q: malformed id", rest))
}
value, kvErr := s.backend.scopeKvGet(ctx, id)
if kvErr != nil {
return sc.deny(m, fmt.Sprintf("hard link registry unavailable: %v", kvErr))
}
if len(value) == 0 {
return sc.deny(m, fmt.Sprintf("lock on hard link %q: no such link", rest))
}
return nil
}
dir, name := scopeSplitPath(rest)
_, err := sc.checkPath(m, dir, name, write)
return err
}
// scopeFilerMethodPrefix is the gRPC path prefix of the filesystem service.
// Other services on the same server retain their own authorization.
const scopeFilerMethodPrefix = "/filer_pb.SeaweedFiler/"
// unary is the unary server interceptor.
func (s *filerGrpcScope) unary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if !strings.HasPrefix(info.FullMethod, scopeFilerMethodPrefix) {
return handler(ctx, req)
}
sc, err := s.resolve(ctx)
if err != nil {
return nil, err
}
if sc == nil {
return handler(ctx, req)
}
if sc.expired() {
return nil, scopeExpiredError(sc)
}
if !sc.methodAllowed(info.FullMethod) {
return nil, sc.deny(info.FullMethod, "method is not in the token's allowed_methods")
}
method := strings.TrimPrefix(info.FullMethod, scopeFilerMethodPrefix)
expected, ok := scopeUnaryMethods[method]
if !ok || reflect.TypeOf(req) != expected {
return nil, sc.deny(info.FullMethod, "not available to a scoped token")
}
return s.unaryScoped(withScopeKeepOnly(ctx), sc, req, handler)
}
// isScopeFilerConf reports whether (dir, name) is the filer's per-path config
// file, which is hidden from a scoped token on every read path: single and
// batch lookup and directory listing.
func isScopeFilerConf(dir, name string) bool {
p, err := scopeFullPath(dir, name)
return err == nil && p == scopeFilerConfDir+"/"+scopeFilerConfName
}
// unaryScoped applies the per-method path rule before calling the handler.
func (s *filerGrpcScope) unaryScoped(ctx context.Context, sc *scope, req any, handler grpc.UnaryHandler) (any, error) {
switch r := req.(type) {
case *filer_pb.LookupDirectoryEntryRequest:
const m = "LookupDirectoryEntry"
if isScopeFilerConf(r.GetDirectory(), r.GetName()) {
return nil, filer_pb.ErrNotFound
}
if _, err := sc.checkPath(m, r.GetDirectory(), r.GetName(), false); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.LookupDirectoryEntriesRequest:
const m = "LookupDirectoryEntries"
if err := validateFilerBatchLookupRequest(r); err != nil {
return nil, err
}
reqs := r.GetRequests()
kept := make([]*filer_pb.LookupDirectoryEntryRequest, 0, len(reqs))
hidden := make([]bool, len(reqs))
for i, lookup := range reqs {
// filer.conf is hidden from a scoped token on every read path, as in
// the single LookupDirectoryEntry above. Results are positional and
// carry no request key, so a hidden slot must still produce one miss
// result in its place rather than shortening the response.
if isScopeFilerConf(lookup.GetDirectory(), lookup.GetName()) {
hidden[i] = true
continue
}
if _, err := sc.checkPath(m, lookup.GetDirectory(), lookup.GetName(), false); err != nil {
return nil, err
}
kept = append(kept, lookup)
}
if len(kept) == len(reqs) {
return handler(ctx, req)
}
// Every request hidden: an empty forwarded batch is rejected, so answer
// all-miss without calling the handler.
if len(kept) == 0 {
results := make([]*filer_pb.LookupDirectoryEntryResult, len(reqs))
for i := range results {
results[i] = &filer_pb.LookupDirectoryEntryResult{Found: false}
}
return &filer_pb.LookupDirectoryEntriesResponse{Results: results}, nil
}
resp, err := handler(ctx, &filer_pb.LookupDirectoryEntriesRequest{
Requests: kept,
UnavailableVolumeIsMiss: r.GetUnavailableVolumeIsMiss(),
})
if err != nil {
return nil, err
}
out, ok := resp.(*filer_pb.LookupDirectoryEntriesResponse)
if !ok {
return resp, nil
}
// Splice a miss into each hidden slot so the results line up with the
// original request order; the handler returns one result per kept request.
spliced := make([]*filer_pb.LookupDirectoryEntryResult, 0, len(reqs))
j := 0
for i := range reqs {
if !hidden[i] && j < len(out.GetResults()) {
spliced = append(spliced, out.GetResults()[j])
j++
continue
}
spliced = append(spliced, &filer_pb.LookupDirectoryEntryResult{Found: false})
}
out.Results = spliced
return out, nil
case *filer_pb.TouchAccessTimeRequest:
p, err := sc.checkPath("TouchAccessTime", r.GetDirectory(), r.GetName(), false)
if err != nil {
return nil, err
}
if err := sc.checkProtectedPath("TouchAccessTime", p, false); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.CreateEntryRequest:
if err := s.checkCreate(ctx, sc, "CreateEntry", r); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.UpdateEntryRequest:
if err := s.checkUpdate(ctx, sc, "UpdateEntry", r); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.AppendToEntryRequest:
if err := s.checkAppend(ctx, sc, "AppendToEntry", r); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.DeleteEntryRequest:
if err := sc.checkDelete("DeleteEntry", r); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.AtomicRenameEntryRequest:
if err := s.checkRename(ctx, sc, "AtomicRenameEntry", r.GetOldDirectory(), r.GetOldName(), r.GetNewDirectory(), r.GetNewName()); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.PosixLockRequest:
if err := s.checkPosixLock(ctx, sc, "PosixLock", r); err != nil {
return nil, err
}
return handler(ctx, req)
case *filer_pb.PingRequest:
// The filer answers for itself; a scoped client cannot make it probe an
// address it names.
r.Target, r.TargetType = "", ""
return handler(ctx, req)
case *filer_pb.LookupVolumeRequest, *filer_pb.GetFilerConfigurationRequest, *filer_pb.StatisticsRequest:
// No file paths or chunk ids. MountRegister is deliberately absent: a
// scoped token must not write the shared mount peer registry (other
// mounts read it via MountList for HRW seeding), so it falls to the
// default-deny below, exactly as MountList does.
return handler(ctx, req)
}
return nil, sc.deny(fmt.Sprintf("%T", req), "not available to a scoped token")
}
// scopeFindEntry implements scopeBackend on the filer.
func (fs *FilerServer) scopeFindEntry(ctx context.Context, p string) (*filer_pb.Entry, error) {
entry, err := fs.filer.FindEntry(ctx, util.FullPath(p))
if err == filer_pb.ErrNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
return entry.ToProtoEntry(), nil
}
// scopeKvGet implements scopeBackend on the filer.
func (fs *FilerServer) scopeKvGet(ctx context.Context, key []byte) ([]byte, error) {
value, err := fs.filer.Store.KvGet(ctx, key)
if err == filer.ErrKvNotFound {
return nil, nil
}
return value, err
}
// GrpcScopeServerOptions returns the server options that enforce scoped
// tokens on the filer's filesystem gRPC service.
func (fs *FilerServer) GrpcScopeServerOptions() []grpc.ServerOption {
return fs.grpcScope.ServerOptions()
}
@@ -0,0 +1,88 @@
package weed_server
import (
"context"
"os"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func scopedCreate(t *testing.T, fs *FilerServer, scope *filerGrpcScope, grant string, req *filer_pb.CreateEntryRequest) error {
t.Helper()
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
"authorization", "Bearer "+scopedToken("ancestors", time.Hour, []string{grant}, nil)))
_, err := scope.unary(ctx, req, &grpc.UnaryServerInfo{
FullMethod: scopeFilerMethodPrefix + "CreateEntry",
}, func(handlerCtx context.Context, handlerReq any) (any, error) {
return fs.CreateEntry(handlerCtx, handlerReq.(*filer_pb.CreateEntryRequest))
})
return err
}
func insertScopeTestEntry(t *testing.T, fs *FilerServer, p string, mode os.FileMode, ttlSec int32) {
t.Helper()
now := time.Now()
e := &filer.Entry{FullPath: util.FullPath(p), Attr: filer.Attr{Mode: mode, TtlSec: ttlSec, Crtime: now, Mtime: now}}
if err := fs.filer.Store.InsertEntry(context.Background(), e); err != nil {
t.Fatalf("insert %s: %v", p, err)
}
}
func TestScopeCreateCannotMakeAncestorsOutsideGrant(t *testing.T) {
t.Run("file ancestor is not promoted", func(t *testing.T) {
fs, scope := newScopeRetentionServer(t, newRenameTestStore())
insertScopeTestEntry(t, fs, "/data", os.ModeDir|0755, 0)
insertScopeTestEntry(t, fs, "/data/proj", 0644, 3600)
err := scopedCreate(t, fs, scope, "/data/proj/ws", &filer_pb.CreateEntryRequest{Directory: "/data/proj/ws", Entry: &filer_pb.Entry{Name: "x"}})
if status.Code(err) != codes.PermissionDenied {
t.Fatalf("create under a file ancestor err=%v, want PermissionDenied", err)
}
got, findErr := fs.filer.FindEntry(context.Background(), "/data/proj")
if findErr != nil || got.IsDirectory() || got.TtlSec != 3600 {
t.Fatalf("/data/proj = %+v err=%v, want the file with ttl 3600", got, findErr)
}
})
t.Run("missing ancestors are not created", func(t *testing.T) {
fs, scope := newScopeRetentionServer(t, newRenameTestStore())
err := scopedCreate(t, fs, scope, "/q/r/ws", &filer_pb.CreateEntryRequest{Directory: "/q/r/ws", Entry: &filer_pb.Entry{Name: "x"}})
if status.Code(err) != codes.PermissionDenied {
t.Fatalf("create under missing ancestors err=%v, want PermissionDenied", err)
}
if _, findErr := fs.filer.FindEntry(context.Background(), "/q"); findErr != filer_pb.ErrNotFound {
t.Fatalf("/q lookup err=%v, want not found", findErr)
}
})
t.Run("missing ancestors inside the grant are created", func(t *testing.T) {
fs, scope := newScopeRetentionServer(t, newRenameTestStore())
insertScopeTestEntry(t, fs, "/data", os.ModeDir|0755, 0)
insertScopeTestEntry(t, fs, "/data/proj", os.ModeDir|0755, 0)
err := scopedCreate(t, fs, scope, "/data/proj/ws", &filer_pb.CreateEntryRequest{Directory: "/data/proj/ws/a", Entry: &filer_pb.Entry{Name: "x"}})
if err != nil {
t.Fatalf("create with in-grant ancestors missing: %v", err)
}
if got, findErr := fs.filer.FindEntry(context.Background(), "/data/proj/ws/a"); findErr != nil || !got.IsDirectory() {
t.Fatalf("/data/proj/ws/a = %+v err=%v, want a directory", got, findErr)
}
})
}
func TestScopeRenameCannotMakeAncestorsOutsideGrant(t *testing.T) {
h := newScopeHarness(t)
c := h.client(scopedToken("alice", time.Hour, []string{aliceWS, "/q/r/ws"}, nil))
h.fake.putDir(aliceWS)
_, err := c.AtomicRenameEntry(scopeCtx(t), &filer_pb.AtomicRenameEntryRequest{
OldDirectory: aliceWS, OldName: "old", NewDirectory: "/q/r/ws", NewName: "new",
})
expectScopeCode(t, "rename under missing ancestors", err, codes.PermissionDenied)
if got := len(h.fake.received("AtomicRenameEntry")); got != 0 {
t.Fatalf("refused rename reached the handler %d times", got)
}
}
@@ -0,0 +1,136 @@
package weed_server
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func authMetadataContext(values ...string) context.Context {
if len(values) == 0 {
return context.Background()
}
md := metadata.MD{}
for _, value := range values {
md.Append("authorization", value)
}
return metadata.NewIncomingContext(context.Background(), md)
}
func TestScopeRejectsMalformedOrDuplicateAuthorizationWithSigningKey(t *testing.T) {
scope := newFilerGrpcScope(scopeConfig{
signingKey: func() security.SigningKey { return security.SigningKey(scopeTestKey) },
}, newScopeFakeFiler())
cases := []struct {
name string
ctx context.Context
}{
{name: "malformed scheme", ctx: authMetadataContext("Basic opaque")},
{name: "bare bearer", ctx: authMetadataContext("Bearer")},
{name: "empty bearer", ctx: authMetadataContext("Bearer ")},
{name: "duplicate valid", ctx: authMetadataContext("Bearer "+unscopedToken(), "Bearer "+unscopedToken())},
{name: "malformed plus valid", ctx: authMetadataContext("Basic opaque", "Bearer "+unscopedToken())},
}
for _, tc := range cases {
t.Run(tc.name+" unary", func(t *testing.T) {
called := false
_, err := scope.unary(tc.ctx, &filer_pb.PingRequest{}, &grpc.UnaryServerInfo{
FullMethod: filer_pb.SeaweedFiler_Ping_FullMethodName,
}, func(context.Context, any) (any, error) {
called = true
return &filer_pb.PingResponse{}, nil
})
if status.Code(err) != codes.Unauthenticated || called {
t.Fatalf("unary err=%v called=%v, want Unauthenticated before dispatch", err, called)
}
})
t.Run(tc.name+" stream", func(t *testing.T) {
called := false
stream := &scopeExpiryServerStream{ctx: tc.ctx}
err := scope.stream(nil, stream, &grpc.StreamServerInfo{
FullMethod: filer_pb.SeaweedFiler_ListEntries_FullMethodName,
}, func(any, grpc.ServerStream) error {
called = true
return nil
})
if status.Code(err) != codes.Unauthenticated || called {
t.Fatalf("stream err=%v called=%v, want Unauthenticated before dispatch", err, called)
}
})
}
}
func TestScopeAcceptsAbsentAuthorizationWithSigningKey(t *testing.T) {
scope := newFilerGrpcScope(scopeConfig{
signingKey: func() security.SigningKey { return security.SigningKey(scopeTestKey) },
}, newScopeFakeFiler())
calledUnary := false
if _, err := scope.unary(context.Background(), &filer_pb.PingRequest{}, &grpc.UnaryServerInfo{
FullMethod: filer_pb.SeaweedFiler_Ping_FullMethodName,
}, func(context.Context, any) (any, error) {
calledUnary = true
return &filer_pb.PingResponse{}, nil
}); err != nil || !calledUnary {
t.Fatalf("absent unary authorization err=%v called=%v, want passthrough", err, calledUnary)
}
calledStream := false
err := scope.stream(nil, &scopeExpiryServerStream{ctx: context.Background()}, &grpc.StreamServerInfo{
FullMethod: filer_pb.SeaweedFiler_ListEntries_FullMethodName,
}, func(any, grpc.ServerStream) error {
calledStream = true
return nil
})
if err != nil || !calledStream {
t.Fatalf("absent stream authorization err=%v called=%v, want passthrough", err, calledStream)
}
}
func TestScopeKeylessSigningBypassesAuthorizationParsing(t *testing.T) {
scope := newFilerGrpcScope(scopeConfig{
signingKey: func() security.SigningKey { return nil },
}, newScopeFakeFiler())
cases := []struct {
name string
ctx context.Context
}{
{name: "absent", ctx: context.Background()},
{name: "malformed", ctx: authMetadataContext("Basic opaque")},
{name: "bare bearer", ctx: authMetadataContext("Bearer")},
{name: "empty bearer", ctx: authMetadataContext("Bearer ")},
{name: "duplicate", ctx: authMetadataContext("Bearer one", "Bearer two")},
}
for _, tc := range cases {
t.Run(tc.name+" unary", func(t *testing.T) {
called := false
_, err := scope.unary(tc.ctx, &filer_pb.PingRequest{}, &grpc.UnaryServerInfo{
FullMethod: filer_pb.SeaweedFiler_Ping_FullMethodName,
}, func(context.Context, any) (any, error) {
called = true
return &filer_pb.PingResponse{}, nil
})
if err != nil || !called {
t.Fatalf("keyless unary err=%v called=%v, want passthrough", err, called)
}
})
t.Run(tc.name+" stream", func(t *testing.T) {
called := false
err := scope.stream(nil, &scopeExpiryServerStream{ctx: tc.ctx}, &grpc.StreamServerInfo{
FullMethod: filer_pb.SeaweedFiler_ListEntries_FullMethodName,
}, func(any, grpc.ServerStream) error {
called = true
return nil
})
if err != nil || !called {
t.Fatalf("keyless stream err=%v called=%v, want passthrough", err, called)
}
})
}
}
+18
View File
@@ -0,0 +1,18 @@
package weed_server
import "context"
// scopeKeepOnlyContextKey marks a handler call admitted for a scoped token.
// It is deliberately unexported so callers cannot manufacture the marker
// through a public context contract; the gRPC scope interceptor is the only
// producer.
type scopeKeepOnlyContextKey struct{}
func withScopeKeepOnly(ctx context.Context) context.Context {
return context.WithValue(ctx, scopeKeepOnlyContextKey{}, true)
}
func scopeKeepOnly(ctx context.Context) bool {
keepOnly, _ := ctx.Value(scopeKeepOnlyContextKey{}).(bool)
return keepOnly
}
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more