Compare commits

..
Author SHA1 Message Date
Chris Lu f35caf8be3 mq: read a recorded offset range that ends at offset 0
The broker and the Kafka gateway each scanned a partition's files for
the high water mark and counted a maximum only when it was above 0, so
a partition holding one message still read as empty. Both now share
mq.OffsetRange, which tracks whether a range was found apart from its
value.
2026-11-30 13:45:28 -08:00
Chris Lu 89f70bb012 mq: record the offset range of a partition's first window
The flush wrote offset_min/offset_max only when minOffset > 0, using 0
as "no range given". A partition's first window starts at offset 0, so
its file never got a range. A restarted broker derives the high water
mark from those ranges, so a partition whose data was all in its first
file read as empty.
2026-11-30 13:38:14 -08:00
Tiago PosseandClaude Opus 5.5 0964dd7713 filer: put a finished download on the budget's idle list before waking readers (#13147)
A download closed done and then moved its reservation to the budget's
idle list, so a reader woken by done could ask the budget for room
before the chunk it had just read was evictable.
TestReaderCacheBudgetLendsScratchToHedges failed this way about 1 in
1000 runs under -race ("hedge buffers did not evict the idle chunks").
The download now completes in the budget first.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:30:56 -08:00
Tiago PosseandClaude Opus 5.5 411e9a8542 filer: keep a copy of the entry in the path-specific test store (#13146)
The stub store kept the caller's entry, which the path translator changes
back after the insert, so TestNameInAPathSpecificStoreCreatedTwiceIsCountedOnce
raced with a lookup under -race.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:29:50 -08:00
68072eff8a webdav: set mtime when a file is created (#13144)
* webdav: set mtime when a file is created

OpenFile created the entry with Mtime 0 and only Close after a Write set
the real time, so an empty PUT, or one truncating a file to empty, left
it at 1970. The "new entry" marker for a failed first upload is now a
field on the file.

* webdav: keep a failed upload from removing another writer's version

With every new entry carrying an mtime, a failed first upload removed
whatever the path held at the first Write, including a version another
writer stored after this open created it. The open now records the
commit stamp of the entry it created, and the first Write keeps the
removal only when the loaded entry still has that stamp.

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

* webdav: check the entry's commit stamp when the upload fails

The first Write's lookup left a gap: a version another writer stored
after it was still removed by a later failed flush. Flushes only append
chunks locally, so the stored entry keeps the create's stamp until
Close; the failed flush now reads it then and removes it only while it
still has that stamp.

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-30 13:27:33 -08:00
guagucai 53206f16be fix: reject NaN minimum free-space percentages (#13153)
Signed-off-by: guagucai <guagucai@outlook.com>
2026-11-30 13:25:40 -08:00
Song Bian 0025e7177f fix(filer): preserve chunk ordering on 32-bit systems (#13175) 2026-11-30 13:24:21 -08:00
1a2be918bf s3api: reset the circuit breaker when its config is deleted (#13148)
* s3api: reset the circuit breaker when its config is deleted

The delete handler parsed an empty file, which always fails, so the old
limits stayed in place. It now loads an empty config.

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

* s3api: read and swap the circuit breaker limits under its lock

A config change or delete replaced Enabled and the limitations map while
requests read them without a lock. The swap now holds the breaker's
write lock, and requests read both under the read lock that
loadCounterAndCompare already took for the counters.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 13:14:34 -08:00
Chris LuandClaude Opus 5.5 c637d60dfc filer.sync: keep an informational replay cursor on the source, and let the log purge honor it (#13176)
* filer.sync: save the sync position on the source filer as a replay cursor

The position stays authoritative on the target. The source copy holds the
last position the target checkpoint stored (a fresh sync without one holds
just before the first event it received) and is rewritten hourly while the
sync runs, even when the position does not move.

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

* filer.sync: do not replicate the sync cursors of the source

A target never holds cursors that describe the source's log. A rename into
or out of the cursor directory replicates the ordinary side.

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

* metadata log purge: keep the logs a filer.sync still needs

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

* filer.sync: describe the sync in its source cursor

The source cursor is informational: besides the position it records the
source and target filers and paths, exclusions, host, version, when the
sync started, whether the position is a target checkpoint, and the
processed and failed event times, for display in admin tools. The
target checkpoint stays authoritative.

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

* filer.sync: save the first sync cursor when the first event arrives and retry failed saves

A fresh sync only saved its cursor on the next minute tick, and a failed
save still pushed the next attempt out by an hour, leaving the purge
without a cursor while the sync replayed old log days.

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

* filer.backup: do not seed the source's sync cursors in the initial snapshot

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

* metadata log purge: say that a position not saved for 7 days stops holding the log

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

* filer.backup test: lock the recording sink for concurrent snapshot workers

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

* filer.sync: leave the sync cursors out of the metadata log gap check

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:09:23 -08:00
bcd678271e mount: authorize filer calls with a pre-issued token file (#13118)
* security: filer token source read from a file

FilerTokenFile is the token source of a client that holds a pre-issued
filer token rather than a signing key. It reads the file on every call,
so an atomic replacement that keeps size and mtime takes effect on the
next attempt, and trims surrounding whitespace. A missing, unreadable,
empty or malformed file fails the call: there is no fallback to anonymous
or admin authority, and errors name the path but not the contents.

FilerTokenClaims decodes a token's claims without a key, and
FilerTokenGrantCovers compares two grants, so a client can plan
reconnects before expiry and know when a replacement narrows what it
may see.

* mount: -filer.tokenFile authorizes filer calls with a pre-issued token

A mount that should not hold a filer signing key can now present a
token issued for it. -filer.tokenFile (or -o filer.tokenFile=) names the
file; it is read for every filer gRPC attempt, so a replaced file takes
effect on the next call or retry without a restart, and a missing or
empty file fails the call locally.

The source reaches every filer client the mount builds: the startup
handshake, each attempt of WithFilerClient, the volume location client,
the SSE-S3 reader's configuration call, the peer registrar dial and the
lock client. It is attached per call, never to the cached channel, and
never to master, volume or peer mount RPCs.

The filer refuses MountRegister, MountList and distributed locks to
scoped tokens, so the mount refuses to start when -filer.tokenFile is
combined with -peer.enable or -dlm instead of failing at run time.
Server-side copy_file_range signs its filer HTTP request with the HTTP
key, not this token, and is unsupported with it.

Without the flag the mount behaves as before.

* mount: resubscribe metadata with a replaced filer token

A metadata subscription keeps the authority it opened with, so a mount
reading -filer.tokenFile would follow with the old token until the filer
ended the stream at expiry, and every such end took the gap path that
distrusts all cached listings.

SubscribeMetaEvents now takes the credentials of each attempt. The mount
opens each subscription with the token current at that moment and
watches the file; once it holds a different token the attempt ends and
the follow resubscribes at once from its checkpoint. This planned
resubscribe is not a gap: cached listings stay, unless the new grant may
show less than the old one or either token cannot be decoded, in which
case they are read again so nothing the old grant showed outlives it.

The filer walk treats a resubscribe like a stopped follow, so the same
attempt is not replayed on the next filer. Without a token file nothing
changes.

* mount: hand the mutation stream over to a replaced filer token

The mutation stream keeps the token it opened with, and a filer refuses
to send on a scoped stream once that token has expired. A mutation
applied at that moment loses its reply, the mount reads that as a
transport failure, and the unary fallback sends it again.

The stream now opens with a snapshot of the token source. Before
admitting a request it checks the source: when the file holds another
token, or the stream's token would expire before a reply could come
back, the stream is retired. New requests wait while the admitted ones
are answered, the stream is half-closed so the filer finishes it, and a
successor opens with the new token. The waits give up only after
filerRPCWait without a response, so a rename that keeps answering is not
cut short. A request is never resent by the handover: one still
unanswered when the wait gives up fails as on any lost stream, as
before.

A token too close to expiry to open a stream with is refused before
anything is sent, so the request goes out once as a unary call, which
the filer checks when it starts. Without a token file nothing changes.

* mount: review fixes for the filer token file

- A distrust of cached listings now also discards the directory builds in
  flight, in the meta cache's apply loop: such a build publishes nothing,
  its entries are wiped and the visit lists the directory again, so a
  listing read under a grant that has since narrowed is never cached after
  the distrust. The cached flags are reset again in the loop, after any
  build that completed before it.
- Retiring the mutation stream runs in the background, and a request that
  waits for the retirement gives up on its own context, unadmitted.
- With a token file and no filer signing key, server-side whole-file copy
  is not tried: its filer HTTP request would go out unsigned and fail as
  ambiguous. The copy streams through the chunk path instead.
- On Windows the token file is opened with delete sharing, so a renewer
  can replace it by rename while a read holds it open; the missing-file
  test checks os.ErrNotExist instead of Unix wording.

* mount: review fixes for the mutation stream handover

A request admitted to the mutation stream with just over one RPC wait
left on its token could wait behind a slow send until that margin was
gone; its reply could then be refused at expiry and the request was
resent over unary. The send loop now checks the margin again right
before sending and holds back a request that no longer has it, which is
safe to send over unary because the filer never saw it. A sent request
whose reply is lost while the token has one RPC wait or less left now
fails with EIO instead of a transport error: the filer may have applied
it, so it is not resent. Losses with the margin intact fall back to
unary as before.

A newly opened stream now admits its first request through the same
checks as an open one, so a token file replaced, or a token that neared
expiry, while the stream opened is caught before anything is sent.

A retirement keeps a cancel handle for its stream. Close uses it, so
unmount no longer waits for admitted requests to be answered, and a
waiter that gives up on a retiring stream stops it as it would stop an
open one, so a request still queued there is never sent after that
waiter fell back to unary. An ordinary rotation still drains admitted
requests.

* mount: drop kernel listings when the filer token's grant narrows

A replacement token whose grant may not cover the old one already
distrusts the mount's own cached listings. The kernel kept its own copy:
OpenDir sets FOPEN_CACHE_DIR | FOPEN_KEEP_CACHE, so a directory still
reachable under the new grant was listed again from the page cache with
names the new grant may hide, until something else invalidated it.

On a narrowed or undecodable grant the mount now also notifies the
kernel for every directory inode it holds, from the subscription
goroutine as the metadata apply path already does, so the next readdir
reaches the mount. A readdir already under way on an open handle still
finishes from what it read.

* mount: drop kernel listings after a subscription gap too

distrustCachedListings serves both the narrowed-grant path and the gap
path. A gap can lose the very events that would have dropped the kernel's
cached listings one directory at a time, and with FOPEN_KEEP_CACHE on
OpenDir the kernel then serves those listings on every reopen. Move the
kernel drop into distrustCachedListings so both paths get it.

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-30 13:02:28 -08:00
05d9242f3c s3api: answer NoSuchBucket to a denied authenticated request on a missing bucket (#13139)
* s3api: optionally answer NoSuchBucket to a denied signed request on a missing bucket

## Problem

AWS S3 answers 404 NoSuchBucket to an authenticated caller that is denied on a bucket that does not exist. SeaweedFS answers 403 AccessDenied. S3-compatibility test suites run by data platforms (which create, probe and clean up buckets with a scoped key) flag the difference, and a client that maps 404 to "create it" or "skip it" takes the 403 for a permissions problem instead.

Answering 404 tells every authenticated identity whether a bucket name exists, which a multi-tenant deployment may not want, so the default stays 403.

## Fix

A new option, off by default: `-s3.noSuchBucketWhenDenied` on `weed server`, `weed filer` and `weed mini`, `-noSuchBucketWhenDenied` on `weed s3` (`S3ApiServerOption.NoSuchBucketWhenDenied`).

With it set, `refineDenial` extends `refineDenialForBucketName` (400 InvalidBucketName) with the NoSuchBucket answer, in `Auth`, `AuthPostPolicy` and the POST policy handler:

- only after authentication succeeded with a signature or a token (signed, presigned, V2, streaming signed, streaming-unsigned with a signed header, JWT). The anonymous identity keeps 403 under any auth type, so an anonymous caller still learns nothing about which buckets exist;
- a bucket-level PUT (CreateBucket, configuring a bucket) keeps 403, as AWS answers a refused create;
- the lookup goes through the bucket config cache, which the authorization path has usually just filled, so a denied request rarely costs a filer lookup; a failed lookup is "unknown" and keeps 403;
- an allowed request never looks a bucket up.

`Auth` now keeps the auth type it used to discard; the POST policy handler, which verifies the form signature itself, passes `authTypeSigned`.

With the option off nothing changes.

## Tests

`weed/s3api/auth_no_such_bucket_test.go`:

- `TestRefineDenialThroughAuth`: through `iam.Auth`, a signed caller denied on another identity's existing bucket gets 403 and on a missing bucket 404 (GET, PUT, a signed streaming-unsigned PUT); a bucket-level PUT stays 403; the caller's own bucket is allowed with no lookup.
- `TestRefineDenialAnonymousLearnsNothing`: anonymous requests answer 403 for a missing and an existing bucket alike and never drive a lookup.
- `TestRefineDenialRules`: presigned and JWT callers, failed authentication, allowed requests, a missing bucket name, a failed lookup, and the option off (no lookup wired) all keep their answer.
- `TestPostPolicyDeniedNoSuchBucket`: a verified browser POST form denied on a missing bucket answers NoSuchBucket; a bad signature stays SignatureDoesNotMatch; an existing bucket stays AccessDenied.

`TestRefineDenialThroughAuth`, `TestRefineDenialRules` and `TestPostPolicyDeniedNoSuchBucket` fail without the NoSuchBucket answer. `go vet` reports nothing in the touched files; `go test ./weed/s3api/ ./weed/command/`: ok. `go build ./weed`: ok.

* s3api: count streaming-unsigned as signed only with a SigV4 or JWT credential

A client-certificate identity that streamed its body unsigned answered
NoSuchBucket on a denied missing bucket, while the same request without
the body-encoding header answered 403.

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

* s3api: tell the anonymous identity by name, without the unlocked pointer read

isAnonymousIdentity compared against iam.identityAnonymous without iam.m,
racing a configuration reload. The configured anonymous identity always
has the anonymous name and account, which the check already covers.

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

* command: keep allowBackslashInKeyUsage's doc comment on its const

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

* s3api: answer NoSuchBucket to a denied request on a missing bucket by default

AWS S3 answers it this way, so drop the -s3.noSuchBucketWhenDenied flag
and always wire the bucket lookup.

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

* s3api: answer NoSuchBucket to a client-certificate identity too

The AWS answer now goes to every authenticated identity, so it no
longer depends on how the caller authenticated. The anonymous identity
keeps 403, as anonymous object reads mask a missing bucket.

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

* s3api: fold the NoSuchBucket answer into refineDenialForBucketName

One refinement for the bucket a denied request names: 400 for a
malformed name, 404 for a missing one. The anonymous read paths keep
their answer, since the anonymous identity never gets the 404.

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-30 13:00:01 -08:00
Chris LuandClaude Opus 5.5 2b0bff0135 filer.sync: warn when the source metadata log no longer covers the sync (#13143)
* filer.sync: warn when the source metadata log no longer covers the sync

A sync replays the source's metadata log from its saved position, or from
the oldest log file when it has none. Once older log days are purged, a
position older than the log silently skips the purged changes, and a fresh
sync never copies entries whose last change was purged, so the target ends
up incomplete without any sign of it.

At start, compare the position with the oldest log file the source keeps;
for a fresh sync, look for a child of the source path whose last change
(commit time, or mtime for entries without one) predates the log, and log
a warning naming it.

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

* filer.sync: skip excluded and multipart upload entries in the log gap check

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

* filer.sync: run the log gap check without delaying the subscription

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:56:31 -08:00
50f7c73101 s3 backend: HTTP/1.1 client defaults for disable_http2 (#13126)
* s3 backend: HTTP/1.1 client defaults for disable_http2

## Problem

`disable_http2` (#11897) keeps the cloud tier's S3 client on HTTP/1.1, so every tier upload and range read gets a connection of its own. The rest of the client still has the defaults sized for one multiplexed HTTP/2 connection:

- Go's idle pool keeps only 2 connections per host, so a burst of concurrent range reads redials TLS for almost every request once the burst is over and the next one starts;
- the wait for response headers is the 60 s bound every tier client has;
- the SDK retries 3 times.

On a Ceph RGW-based S3 service, HTTP/2's small flow-control window held tier uploads at 18 MB/s and made 24 concurrent cold scans take 52 s each; on HTTP/1.1 they took 3.7 s each, but only with a larger idle pool, a shorter header bound and more retries for the 503 SlowDown answers that the extra parallelism draws.

## Fix

With `disable_http2 = true` the tier client also gets:

- an idle pool of 100 (`MaxIdleConns` and `MaxIdleConnsPerHost`);
- `ResponseHeaderTimeout` of 30 s;
- `MaxRetries` 5, so the SDK's retryer backs off on 5xx, SlowDown and throttling.

`max_connections` and `idle_connection_timeout_seconds` apply as before. Without `disable_http2` the client is unchanged. The scaffold `master.toml` mentions the defaults.

## Tests

`TestS3BackendHTTP1ClientDefaults` in `weed/storage/backend/s3_backend/s3_sessions_test.go`: with `disable_http2` the transport has the idle pool and the 30 s header bound, and the client 5 retries; without it (and with `max_connections` set) the client keeps the SDK's retries, the default idle pool and `s3ReadTimeout`. It fails without the change.

`go vet ./weed/storage/backend/s3_backend/` and `go test ./weed/storage/backend/s3_backend/`: ok. `go build ./weed`: ok.

* s3 backend: keep the larger idle pool for every tier client

A tier client on a plain http:// endpoint, or on a TLS service that offers
no HTTP/2, speaks HTTP/1.1 without disable_http2 and had the same 2 idle
connections per host, so each burst of concurrent reads redialed. HTTP/2
keeps one connection, so the pool size does not change it. The header
bound and retries stay with disable_http2.

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-30 12:53:24 -08:00
dependabot[bot]andChris Lu faffb0d291 build(deps): bump github.com/jackc/pgx/v5 from 5.10.0 to 5.13.0 (#13164)
Bumps [github.com/jackc/pgx/v5](https://github.com/jackc/pgx) from 5.10.0 to 5.13.0.
- [Release notes](https://github.com/jackc/pgx/releases)
- [Changelog](https://github.com/jackc/pgx/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jackc/pgx/compare/v5.10.0...v5.13.0)

---
updated-dependencies:
- dependency-name: github.com/jackc/pgx/v5
  dependency-version: 5.13.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 12:48:51 -08:00
dependabot[bot] 5f65cd0859 build(deps): bump go.mongodb.org/mongo-driver from 1.17.9 to 1.17.10 (#13163)
Bumps [go.mongodb.org/mongo-driver](https://github.com/mongodb/mongo-go-driver) from 1.17.9 to 1.17.10.
- [Release notes](https://github.com/mongodb/mongo-go-driver/releases)
- [Commits](https://github.com/mongodb/mongo-go-driver/compare/v1.17.9...v1.17.10)

---
updated-dependencies:
- dependency-name: go.mongodb.org/mongo-driver
  dependency-version: 1.17.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:48:04 -08:00
dependabot[bot] 184860a4c3 build(deps): bump golang.org/x/oauth2 from 0.37.0 to 0.38.0 (#13165)
Bumps [golang.org/x/oauth2](https://github.com/golang/oauth2) from 0.37.0 to 0.38.0.
- [Commits](https://github.com/golang/oauth2/compare/v0.37.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/oauth2
  dependency-version: 0.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:44 -08:00
dependabot[bot] 1924ce9f06 build(deps): bump github.com/aws/aws-sdk-go-v2 from 1.48.0 to 1.48.1 (#13166)
Bumps [github.com/aws/aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2) from 1.48.0 to 1.48.1.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/v1.48.0...v1.48.1)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go-v2
  dependency-version: 1.48.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:34 -08:00
dependabot[bot] 3993cb38c3 build(deps): bump github.com/jhump/protoreflect from 1.18.1 to 1.19.0 (#13167)
Bumps [github.com/jhump/protoreflect](https://github.com/jhump/protoreflect) from 1.18.1 to 1.19.0.
- [Release notes](https://github.com/jhump/protoreflect/releases)
- [Commits](https://github.com/jhump/protoreflect/compare/v1.18.1...v1.19.0)

---
updated-dependencies:
- dependency-name: github.com/jhump/protoreflect
  dependency-version: 1.19.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:24 -08:00
dependabot[bot] 62d6127d6e build(deps): bump actions/download-artifact from 7 to 8 (#13169)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 7 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:15 -08:00
dependabot[bot] a07f774e6f build(deps): bump github/codeql-action from 4.39.4 to 4.39.5 (#13170)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.4 to 4.39.5.
- [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.4...v4.39.5)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:05 -08:00
dependabot[bot] b066c31172 build(deps): bump sigstore/cosign-installer from 4.1.3 to 4.1.4 in /.github/actions/sign-image (#13171)
build(deps): bump sigstore/cosign-installer

Bumps [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) from 4.1.3 to 4.1.4.
- [Release notes](https://github.com/sigstore/cosign-installer/releases)
- [Commits](https://github.com/sigstore/cosign-installer/compare/v4.1.3...v4.1.4)

---
updated-dependencies:
- dependency-name: sigstore/cosign-installer
  dependency-version: 4.1.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:46:53 -08:00
672ba10b2b iceberg: parse each table metadata version once and encode the load response once (#13129)
* iceberg: parse each table metadata version once and encode the load response once

Under an Iceberg commit load, about half of the S3/Iceberg server's CPU went into the JSON of the same metadata document. A writer loads a table and then commits to it, and each request parsed the stored metadata again (`table.ParseMetadataBytes`, 17% of CPU in a profile). The load then marshalled it, `json.Marshal` compacted and validated the whole document again around the `json.RawMessage` inside `MarshalJSON`, and the response encoder did that once more around the result (8%). The cost grows with a table's snapshot history.

Changes:

- `tableMetadataCache` keeps the parsed form (and, lazily, the rendered response form) of recently read metadata documents, keyed by bucket and metadata location and bounded at 64 MiB (an entry is charged 6x its source size; a document over a quarter of the bound is never cached). An entry is used only when the stored bytes are byte-identical to the bytes it was parsed from, so a hit returns exactly what parsing would; the key only finds the candidate, and a parse error is never cached. Load table, commit table and commit transaction read through it.
- The parsed metadata is shared read-only between requests: iceberg-go guards its lazily decoded snapshots with its own `sync.Once` and lock, and the metadata builder copies what it changes (`TestMetadataCacheSharedEntryUnderConcurrency`, run with `-race`).
- A table commit remembers the version it stored (parsed from exactly those bytes), so the next load of it is a hit, and drops the version it replaced; a transaction commit drops the versions it replaced.
- `LoadTableResult.MarshalJSON` assembles the response around the rendered metadata instead of re-encoding it as a `RawMessage`, and `writeLoadResult` writes those bytes without the encoder's extra pass. The rendering is used only while `Metadata` is still the cache entry's own parsed metadata; a filtered (`?snapshots=refs`) or replaced `Metadata` is marshalled as before. An encoding failure is now a 500 rather than an empty 200.

The response bytes are the same as before: `TestLoadTableResultMarshalBytes` compares them with the previous encoding, including HTML and U+2028 escaping, with and without a metadata location, config and storage credentials. `TestMetadataCacheHitsOnlyIdenticalBytes` covers the byte check, parse errors, eviction and the commit remember/forget path.

Measured on one server at 8 concurrent writers, about 20 commits/s, CPU sampled over 20 s: 30.0 s before, 21.7 s after.

`go vet ./weed/s3api/iceberg`, `go test ./weed/s3api/iceberg` and `go test -race -run 'MetadataCache|LoadTableResult' ./weed/s3api/iceberg` pass; `go build ./weed` builds.

* iceberg: the shared-entry concurrency test shares one entry

The test started from an empty cache, so each worker could miss and parse
its own copy, and it passed without readers and builders ever sharing an
object. The entry is now parsed before the workers start, and each worker
checks that it was handed that entry. A cache that returns a fresh copy now
fails the test.

* iceberg: keep the snapshots=refs check inline and log the parse error directly

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

* iceberg: shorten the metadata cache comments

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-30 11:50:59 -08:00
a2d6b07d3c filer: refuse a non-recursive delete of a bucket that has children (#13122)
* filer: refuse a non-recursive delete of a bucket that has children

A non-recursive delete of a folder that has children fails with
ErrNonEmptyFolder: doBatchDeleteFolderMetaAndData lists the folder's
first page and refuses. For a bucket on a store that keeps each bucket
apart (leveldb3, the SQL stores with bucket tables, ArangoDB, YDB with
bucket tables), it skipped that listing, because such a store drops a
deleted bucket's children in one call and a recursive delete needs no
walk. The non-recursive delete then went through: DeleteFolderChildren
dropped the bucket's objects, the bucket entry was deleted, and
DeleteEntryMetaAndData deleted the bucket's collection, so the objects'
volumes went with them.

rmdir on a weed mount, fs.rm without -r and a filer HTTP DELETE without
recursive=true each send such a delete. On the other stores the same
request is refused.

A non-recursive delete now lists a bucket on these stores the way it
lists any other folder, and is refused when the bucket has children. An
empty bucket is still dropped by the store, which frees what the store
keeps per bucket, and a recursive delete still drops a bucket without a
walk.

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

* filer: say why a non-recursive bucket delete still sweeps

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 11:50:00 -08:00
8bb5c069ec iceberg, s3tables: new tables take only fresh locations (#13160)
* s3tables, iceberg, lance: the catalog assigns every new location; an existing name answers only a reader

A REST create without a location gets <ns>/<name>-<uuid> (#12475) and a
location another record holds is refused (#12473), but a location a
client names is still taken: the REST create's location field and
warehouse property, S3 Tables CreateTable and CreateView with a
MetadataLocation, the Lance declare's location. A free location a client
picks can be one another caller holds staged write credentials for
(stage markers are not claims), or files no record claims any more.
Separately, CreateTable of a name that already holds a table returns
that table (ARN, version token, metadata location) to any caller who may
create, including one who may not read it.

- A REST create or create view naming a location (field or property,
  stage-create or not, the bare bucket included) is refused with 400
  before anything is written; the location is always placeNewEntry's:
  <ns>/<name>-<uuid> in the bucket, or under the operator's
  ICEBERG_WAREHOUSE (no longer under a client's warehouse property).
- A create commit uses a stage marker only when its assign-uuid matches
  the staged table's UUID (PyIceberg and Java send it); any other create
  commit is placed at a fresh <name>-<uuid>, never at the bare name path
  and never at another caller's staged location. Its updates may not set
  another location than the one assigned (400).
- S3 Tables CreateTable and CreateView naming a MetadataLocation are
  refused with 400 (ErrClientTableLocation) unless the call is the
  process's own (WithCatalogAssignedLocation: the REST create, create
  view and create commit at the location they placed; the Lance declare
  at the dataset's name path and register at an existing dataset). AWS's
  CreateTable takes no location either.
- A Lance declare naming a location is refused with 400 (register is for
  existing datasets).
- CreateTable of an existing name answers the table only to a caller who
  may GetTable it; a caller who may only create gets 409
  TableAlreadyExists and nothing about it.

Tests: TestAClientCreateNamesNoLocation (positive controls: a client
create without a location, the catalog's own create with one),
TestARESTCreateNamesNoLocation, TestACreateCommitCannotSetAnotherLocation,
TestACreateCommitTakesOnlyItsOwnStage (the stager's own commit is the
positive control), TestCreateExistingTableAnswersOnlyAReaderWithIt (a
reader gets the table). Existing tests adapted: the s3tables fixtures and
request helpers run as the catalog's own calls (assignedCtx), as do the
iceberg tests that seed tables through the manager;
iceberg_create_table_conflict_test.go's creates send no location and
newConflictEnv points placeNewEntry at conflictLocation, so its races
still collide on one location; TestCreatePathsRefuseAnotherTablesLocation
expects 400 for the three create paths and 409 for the register;
TestCreateTableWithoutLocationUsesItsOwnDirectory drops the bare-bucket
body; lance TestIcebergTablesAreInvisible seeds its Iceberg table as the
catalog; TestDeclareOfAnExistingTableKeepsItsLocation expects 400 for a
declare naming the index's location; TestDeregisterAndReregisterNeedUpdateTable
(#12552) expects 409 instead of 404 for the register and the declare of
a caller without GetTable: the table stays deregistered and nothing is
vended. Each rule is red with it undone.

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

* iceberg: a create may name a fresh location

A REST CreateTable naming a location (Trino always sends one built from
the namespace location, Spark LOCATION, PyIceberg location=) is accepted
again when nothing is stored under it and no live stage holds it; a used
or staged location answers 400. The check runs after the create's
authorization and before anything is written. A bare-bucket location
still gets the assigned <name>-<uuid>. CreateView always uses the
assigned location: a view holds only metadata files.

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

* lance: a declare may restate its name path as its location

pylance and other namespace clients may send the location they expect;
the dataset's own name path is accepted, any other location still
answers 400.

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

* iceberg: a commit cannot set another location on an existing table

CommitTable and CommitTransaction applied a set-location update, so a
table's metadata could name a location outside the directory its record
holds. Such a commit now answers 400 and nothing is written.

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

* iceberg: the fresh-location check pages through every stage marker

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

* iceberg: a fresh location stays apart from stages and tables above or under it

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

* iceberg: a create checks its location again after claiming it

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

* s3tables, iceberg: a live stage holds its location against every create

The catalog counts each live stage-create as a root of the record it
would commit to, so a native create, register, rename or move over a
stage's location is refused. The fresh-location check reads the same
roots, so a stage also backs out of a record that claimed an ancestor
after its first check. A location held by a record or stage answers 409,
as the create gate already did.

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

* iceberg: a create removes only the stages its location covers

A create or commit used to drop every stage marker of its name, which
freed the location of a stage whose credentials were still live.
Expired markers now go with their staged metadata.

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

* iceberg: an assigned stage location checks its claim again too

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

* iceberg: a stage marker lasts as long as its vended credentials

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

* iceberg: test a create that runs while a stage checks its claim

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

* iceberg: a stage holds its location against a create of the same name

A live stage-create now counts under its marker rather than under the
record of its name, so a same-name create over its location is refused
and a stage refuses a same-name table created over its location. Only a
staged commit takes the location its own stage holds.

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

* s3tables: a stage holds only its location against its own record's create

A live stage keeps the path of the record it would commit to away from
other records' files, but a create of that same record writes it: the
stage then holds only its location against it. A stage at its name path
can commit while a later stage of its name, elsewhere, is live.

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

* iceberg: a staged commit's create gate reads its location as a create does

The gate maps a metadata file's location to its table directory, so the
bare location of a stage under a metadata directory resolved to the
namespace and conflicted with the stage's own claim.

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

* iceberg, lance: tests from master create through the catalog's own call

Their creates name a location, which only the catalog's own calls may, and
a caller who may only create gets 409 for an existing name whatever
location its register names.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:47:29 -08:00
Javier de la TorreandClaude Opus 5.5 aa006fa228 iceberg: answer vended credentials with Cache-Control: no-store (#13137)
A table or view load (and create) answered with `X-Iceberg-Access-Delegation: vended-credentials` carries live S3 session credentials in `config` and `storage-credentials`. The response sends `Vary: X-Iceberg-Access-Delegation` but no `Cache-Control`, so a shared HTTP cache in front of the catalog may store it and hand one caller's table-scoped session to another caller of the same URL that sends the same delegation header. The OAuth token endpoint already answers `Cache-Control: no-store` for the same reason (RFC 6749 §5.1).

`writeLoadResult` sets `Cache-Control: no-store` when the response holds credentials: a non-empty `storage-credentials`, or `s3.access-key-id` / `s3.secret-access-key` / `s3.session-token` in `config` (tables and views, values or pointers). Responses without credentials are unchanged.

`TestVendedLoadAnswerIsNoStore` (vended and not vended, table and view responses): red with the header removed. `go vet ./weed/s3api/iceberg/` and `go test -race ./weed/s3api/iceberg/` pass, and `weed` builds.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:36:25 -08:00
3da9c41404 iceberg maintenance: worker setting for the row-group size of compacted files (#13128)
* iceberg maintenance: worker setting for the row-group size of compacted files

Compaction takes a compacted file's row-group size from the table property `write.parquet.row-group-size-bytes`, and falls back to Iceberg's default, 128 MB, when the table sets none. Most tables set none, and the default target file size is also around 128 MB, so a compacted file usually comes out as a single row group. A reader's column filter (a time range, an id range) can then skip the whole file or nothing inside it.

Setting the property table by table is the only way to change that today. This adds a worker setting, `row_group_size_mb`, that sets the size for tables without the property:

- default 0 = Iceberg's 128 MB, so nothing changes unless an operator sets it;
- the table property still wins over it, so an engine or a user that chose a size keeps it;
- `write.parquet.row-group-limit` (rows) is untouched.

For example, `row_group_size_mb = 64` gives about two row groups per 128 MB compacted file.

Test: `TestRowGroupSizeWorkerSettingAndTableOverride` (the default is 0, the setting is read, a table without the property gets the worker's size, the property wins).

`go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg maintenance: raise the descriptor version with row_group_size_mb

The admin keeps a stored descriptor unless the new one's version is not
lower. With both at 1, an older worker serving a descriptor refresh during a
rolling upgrade replaced the form and row_group_size_mb disappeared. The
test fails at version 1.

* iceberg maintenance: say row_group_size_mb also caps the spatial row group size

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

* iceberg maintenance: keep at least one row per row group when a row outgrows the byte size

With an explicit row limit the estimate had no floor, so a byte size
smaller than one row gave 0, which parquet-go takes as no limit.

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

* iceberg maintenance: say row_group_size_mb only caps a spatial rewrite's row groups

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-30 11:33:32 -08:00
4cda7ca0a4 iceberg: a transaction's rollback never overwrites a later write (#13162)
* iceberg: a transaction's rollback never overwrites a later write

CommitTransaction rolls an already flipped table back with an
UpdateTable that names no version token: a commit that landed on the
table after the flip is overwritten, and the transaction's metadata file,
which that commit may build on, is deleted with it. A table that had no
metadata location before the transaction (created without one, never
committed) is not put back at all (an update leaves an empty location as
it is), yet its restore is reported done and the file it still points at
is deleted: the table then fails every load. And when the failing flip
lost a version race, the client was answered 409 CommitFailedException
even though a table left unrestored kept the transaction's change: a
client that refreshes and retries applies it twice.

- The flip records the version token it wrote, and the restore is
  conditional on it (it fails, and the file is kept, when anything wrote
  since).
- A table that had no metadata location before the transaction is
  reported unrestored, so it keeps the transaction's metadata and file.
- When any table is left unrestored the answer is 500
  CommitStateUnknownException; a full rollback still answers 409.

Tests: TestARolledBackTransactionNeverOverwritesALaterWrite (a write
before the rollback and one during the restore's write are both kept;
the file stays while referenced) and
TestARolledBackTransactionKeepsTheFileOfATableItCannotRestore (the table
still loads; the flip fails with a version race and the answer is 500).
The test filer (memFiler in iceberg_create_view_test.go) now answers a
lookup with a copy and refuses a conditional UpdateEntry whose
ExpectedExtended no longer holds, as the filer does; without it no
conditional write could fail in these tests. Red with the restore
unconditional, with the no-location table restored, and with 409 for an
unrestored table.

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

* iceberg: the failing-flip test filer fails only record writes

A storage marker written on a table's own directory carries the record
it read unchanged; failing or counting it moved the injected failure
and the concurrent write off the flip and the restore.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:31:38 -08:00
8f4663f516 iceberg: a Lance record loads with read-only credentials (#13159)
iceberg: the Iceberg REST catalog keeps off Lance tables

A Lance dataset's catalog record lives in the same table bucket as
Iceberg tables, and the Iceberg REST endpoint serves it as a table:
LoadTable vends write credentials over the dataset's directory to anyone
who may update the table, and CommitTable or CommitTransaction on it
writes Iceberg metadata into the dataset's directory and repoints the
record at it. Reproduced on master: the record's metadataLocation became
finance/vec/metadata/v2.metadata.json, its format still LANCE.

notIcebergTable now refuses a commit and a transaction on a record of
another format with 400, after the commit's authorization; LoadTable
serves a catalog-only record as an empty table (its metadata is never
read as Iceberg) with read-only credentials. A REST create of the name
already answered 409.

Test: TestIcebergRESTKeepsOffLanceTables: an Iceberg table's owner gets
write credentials (positive control), the Lance table read-only ones;
commit and transaction 400; the Lance record unchanged. Red with each of
the three rules undone.

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:30:50 -08:00
d29b0d430c lance: a register of a new name needs a dataset at its location (#13158)
* lance: a register of a new name needs a Lance dataset at its location

A Lance register of a new name takes any free location in the table's
namespace (#12473 refuses one another record holds), so it can claim an
empty location, or a dropped table's emptied root, in the catalog's
stead.

A register of a name without a record now authorizes the create with its
location (AuthorizeCreateTable: the permission, the namespace check and
the refusal of a claimed location run before anything is read, so a
location in another namespace is answered alike whether it holds a
dataset or not), then refuses with 400 a location holding no Lance
dataset (no _versions/). A name that has a record, readable by the
caller or not (deregistered, or without GetTable), keeps the existing
path: CreateTable answers for it and bringing it back needs UpdateTable
(#12552).

Test: TestRegisterNeedsALanceDataset: an empty location 400; a caller
who may not create 403; a dropped table's root 400; another namespace's
path answers the same with and without a dataset; a written dataset
registers (positive control). Red with the dataset check removed, the
authorization skipped, or the location left out of the authorization;
TestDeregisterAndReregisterNeedUpdateTable is red when the dataset check
also runs for a name that has a record.

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

* lance: a register of a name with a record keeps the CreateTable path

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

* lance: a register needs _versions to be a directory

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:30:17 -08:00
10c66011c8 iceberg: vended credentials list only the table's directory (#13157)
s3: vended credentials list only inside their table's directory

A vended session's s3:ListBucket is conditioned on s3:prefix
{prefix, prefix/*}. The bare table path (ns/t) also matches every
sibling whose name starts with it, so a session vended for ns/t lists the
object names of ns/t2/..., ns/t_x/... and ns/t-<uuid>/... (the catalog's
own placements of other tables).

The condition is now {prefix/, prefix/*}: the table's directory only. A
client listing the table's location without the trailing slash (Java's
S3FileIO.listPrefix(location), used by remove_orphan_files) is refused
with vended credentials; reads, writes and listings of the table's
directory are unaffected.

Test: TestTablePrefixSessionPolicyRestrictsListing now expects the
slash-terminated pair; red with the bare prefix back.

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:29:52 -08:00
79b4a8ab31 s3tables: keep a table's root on update and rename (#13156)
* s3tables, lance: an update cannot move a table's or view's root

UpdateTable and UpdateView may move a record to another root (the move is
reserved while it happens: moveCatalogRecord, ExtendedKeyMoving). The old
root is then claimed by no record, although the table's older snapshots
still name files under it: a table registered or created over it loads
them and is vended credentials for them, and its drop purges them.
Reproduced on master: table u moved from ns/udir to ns/u2, an alias
created at ns/udir, the alias dropped: u's first snapshot's data file is
gone.

An update whose metadata location gives the record another root is now
refused with 400 InvalidRequest (ErrLocationMove) before anything is
written. No client path needs a move: a commit writes under the location
the record has (a table created without a location commits at its
assigned directory; a table renamed into another namespace keeps
committing at its directory, #12515). Lance's Overwrite register at
another dataset goes through UpdateTable and is refused the same way; an
Overwrite at the table's own location still works. The move reservation
stays (a reservation a crashed move left is still cleared by the next
update).

Tests: TestUpdateCannotMoveATablesRoot (the move refused, an alias over
the old root refused, the old snapshot's file kept, an update under the
table's own root works). Existing tests adapted to the rule, none
deleted: the UpdateTable refusals of TestLocationOwnedByOneRecord, the
moving subtests of TestLocationRaceBacksOut and
TestMoveReservationLeftBehind expect 400 with nothing written;
TestUpdateAfterRenameAcrossNamespacesRefusesAnotherTablesDirectory and
TestUpdateAfterRenameAcrossNamespacesMayMoveIntoItsNamespace expect
ErrLocationMove; vector_namespace_test.go's UpdateTable keeps the index's
root so its write reaches the fence it tests; lance
TestRegisterOverwriteKeepsTheOldDataset expects 400 for an Overwrite at
another dataset, the location unchanged and the dataset kept. Each
refusal is red with it replaced by the claim check.

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

* s3tables: a record without a stored location is not renamed

A rename moves the catalog record and leaves the files where they are. A
record with neither a metadata location nor a warehouse location (every
Lance dataset, which lives at its name path; an Iceberg table created at
its name path by an older build) takes the root of its record path, so
after a rename it claims its new, empty name path and the files at the
old one belong to no record: a table created under the old name sits on
them. Reproduced on master: Lance table l renamed to l2, ns.l declared
again, l2's _versions/1.manifest is under the new ns.l.

A rename whose record would claim another root at its destination than
at its source is now refused with 400 InvalidRequest, after the
authorization checks (a caller without rights is answered as before). A
record with a stored location keeps its root and renames as before,
within its namespace or into another. In the vector namespace of a
vector bucket the read-only answer its fence gives stays the answer.

Tests: TestRenameRefusesARecordWithoutAStoredLocation: a Lance dataset
renamed in its namespace and a location-less Iceberg table renamed into
another are refused, both records and the dataset's files stay; a table
with a stored location renames (positive control). Adapted: the rename
subtest of TestLocationRaceBacksOut (its table has no stored location)
expects 400 with nothing written. Red with the refusal removed, and
TestVectorNamespaceIsReadOnlyOverLance/rename_out with the vector
namespace's answer skipped.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:29:04 -08:00
442e0a24c6 iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s (#13138)
* iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s

## Problem

The Iceberg REST catalog vends table-scoped S3 sessions on load and create with one process-wide lifetime, `-iceberg.credentialDurationSeconds` (default 3600). A client has no way to ask for less, and nothing can go below STS's 900 s floor. Some deployments want short sessions for some callers (a one-off read, a session handed to a less trusted process) without shortening them for every client: a process-wide 900 already breaks clients that keep a loaded table object for longer than its session (PyIceberg does not refresh vended credentials; DuckDB, Spark and Trino re-load and are fine).

The Iceberg REST spec has no parameter for a credential lifetime. The precedent is `DurationSeconds` on AWS STS and on Lake Formation's `GetTemporaryGlueTableCredentials`.

## Fix

- **Request header** `X-SeaweedFS-Credential-Duration-Seconds` on a load or create that asks for vended credentials (`X-Iceberg-Access-Delegation: vended-credentials`). A positive whole number of at most 9 digits is passed to the vendor; a missing, malformed, zero, signed or overlong value is ignored without an error, so clients that never send it see no change.
- **It can only shorten a session.** The vended lifetime is `min(asked, configured)`; with no configured duration the ceiling is STS's `TokenDuration`, capped at `MaxSessionLength` as STS caps it. A request at or above the ceiling changes nothing (the configured duration is sent, as before).
- **Floor:** new `-iceberg.credentialMinDurationSeconds` (`-s3.iceberg.credentialMinDurationSeconds` on `weed server` and `weed mini`), **default 900, which keeps today's behaviour exactly.** A request below the floor is raised to it. Values outside 1-900 mean 900, with a warning at startup; the setting can only lower the floor.
- **STS:** `AssumeRoleForPrincipalRequest` gains `MinDurationSeconds`, a per-request floor honoured only within (0, 900]. Only the catalog's vend sets it, and only when the client actually shortened the session: a vend at the configured duration keeps the 900 s floor (so a configured `credentialDurationSeconds` under 900 is still refused), and AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials and every other action keep 900 through the unchanged `validateSessionDurationSeconds`. `MinSessionDurationSeconds` names the 900.
- **Caching:** load answers now send `Vary: X-Iceberg-Access-Delegation, X-SeaweedFS-Credential-Duration-Seconds`, so a cache never hands a session vended for one lifetime to a request that asked for another.
- The client learns the lifetime it got from `s3.session-token-expires-at-ms`, as today. The Lance namespace vend passes 0 (unchanged).

## Tests

- `weed/s3api`: `TestVendDurationRequestOnlyShortensTheSession` (real STS and trust policy; the lifetime read from the session JWT's `exp - iat` and `max_dur`): nothing asked keeps 3600; 120 honoured; 60 at a floor of 60; 7200 capped to 3600; 30 raised to a floor of 60; floor unset, 900 or 1200 keeps 900. `TestVendFloorDoesNotLowerAssumeRole`: with the floor at 60 the vend mints 60 s (positive control) while AssumeRole and AssumeRoleWithCredentials on the same server refuse 60 s. `TestVendDurationRequestRespectsMaxSessionLength`, `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`.
- `weed/iam/sts`: `TestSessionFloorIsLoweredOnlyForTheRequestThatAsks`.
- `weed/s3api/iceberg`: `TestCredentialDurationHeaderReachesTheVendor` (the accepted and ignored header forms), and the Vary test updated.
- Each rule undone turns its test red (request ignored: `TestVendDurationRequestOnlyShortensTheSession`, `…RespectsMaxSessionLength`; floor applied to every vend: `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`).
- `go vet` and `go test` of `weed/s3api`, `weed/s3api/iceberg`, `weed/iam/sts`, `weed/iam/integration`, `weed/command` pass, `-race` on `weed/s3api/iceberg`, and `weed` builds.

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

* iceberg: let a shortened vend fit a caller credential with less than 900 s left

A vend the caller shortened below 900 s (with a lower catalog floor)
needs only that floor of the caller's credential to remain, not 900 s.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 10:52:41 -08:00
81f9231e2f iceberg compact: optional spatial clustering of geometry tables (#13135)
* iceberg compact: optional spatial clustering of geometry tables

Compaction of an Iceberg v3 table with a geometry column merges files in
manifest order (bin-pack) or by a declared sort order. Neither keeps nearby
geometries together: after a bin-pack every output file and row group spans
the whole extent of the table, so a reader can skip nothing by the geometry
bounds and row-group geospatial statistics. In one measurement a point lookup
on a table of places read 4.59 MB after bin-pack compaction and 0.55 MB after
a spatial one. A declared sort order cannot express this either: Iceberg v3
has no spatial sort transform, a geometry cannot be a sort source, and DuckDB
refuses INSERTs into a table that declares a sort order.

This adds an opt-in spatial order to the compaction job.

Spatial clustering (`spatial_clustering`, off by default). When on, a v3
table with no declared sort order and exactly one top-level geometry column
is rewritten in the Hilbert order of each row's bounding-box centre, whatever
`rewrite_strategy` says (a declared sort order is still honoured, since such a
table does not qualify):

- The 62-bit key (31 bits per axis) is computed from the WKB while the rows
  stream through the merge, carried as an extra last column through
  parquet-go's sorting writer into a temporary file in `sort_spill_dir`, and
  dropped when a plain writer copies the rows to the output. Row lineage is
  mapped before the key is added. The grid is the globe for a lon/lat CRS and
  the union of the bin's file bounds for a projected one. Null, empty and
  unreadable geometries sort last. The key only orders rows; pruning stays on
  the geometry bounds, so a poor key costs speed, never results.
- Files are listed by the key of their bound's centre before binning, so the
  bins of one partition cover compact areas.
- Row groups target `spatial_row_group_size_mb` (2 MB, capped by the table's
  `write.parquet.row-group-size-bytes`, at least 16 rows; an explicit
  `write.parquet.row-group-limit` still wins). A row group is what a spatial
  filter skips, and a row of a large polygon can be tens of kilobytes.
- A bin the order cannot be laid over (a projected column whose files carry
  no bounds, a geometry column the merge cannot find, e.g. after a rename in
  files without field ids) is bin-packed in bin-pack row groups.
- The table property `seaweedfs.compaction.spatial-column` names the column
  when a table has several, or opts a table out with `none`.
- The snapshot summary records `rewrite-strategy=spatial` and
  `spatial-column`, or `binpack` when every bin fell back, and
  `spatial-fallback-bins` when some did. The planning
  index's config hash covers the new settings.

Open time partitions (`spatial_hold_open_partitions`, default true, and
`spatial_open_partition_grace_minutes`, default 120; both only matter with
spatial clustering on). A spatially ordered partition has every row group
spanning its whole time range. On a day of vehicle positions, "where is every
vehicle now" read 2.51 MB of the spatially compacted day against 0.04 MB of
the files as written, while an area query on a closed day read 2.74 MB
against 19.35 MB. So a day or hour partition is left in write order until it
has ended plus the grace (late batches still land in it), and is ordered in
space after that. The job and detection hold the same bins; the planning
index caches its answer only until the first held partition is released, so
a table nobody writes to after midnight still gets its last day ordered.
Coarser time partitions and the other strategies are unchanged.

`github.com/twpayne/go-geom` (already in the module graph) becomes a direct
requirement for its WKB parser.

Tests:

- spatial_order_test.go: the Hilbert curve, plan resolution (version, sort
  order, one or several geometry columns, the property, opt-out), 2,400
  scattered points compacted end to end in spatial order with row ids kept
  and no key column written, the job setting off as control, nulls last, a
  projected CRS with and without file bounds, file ordering, and the
  row-group sizing.
- spatial_fallback_test.go: the bin-pack fallback uses bin-pack row groups;
  a geometry column the merge cannot find falls back, with the summary
  saying so.
- spatial_open_test.go: partition ends for day and hour across the value
  types a manifest reader returns and far from 1970; the hold, the grace and
  their controls; the planning index release time and config hash; on the
  fake filer, a day-partitioned geometry table where the job compacts the
  past day in spatial order and leaves today's files, a table of only today
  commits nothing, and the index records midnight UTC plus the grace (each
  with the hold off as control); spatial clustering is off by default.
- Mutation checks: a constant key fails the spatial order tests; disabling
  the hold fails four open-partition tests.
- go vet and go test (also with -race) of weed/worker/tasks/iceberg pass;
  go build ./weed passes.

* iceberg compact: give the spatial sort key a name no table column has

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

* iceberg compact: report spatial order only for bins it wrote

A bin skipped after a read or merge error no longer counts as
spatially ordered in the snapshot summary or the job result.

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

* iceberg compact: do not hold an open partition the spatial order cannot cover

A projected geometry column whose files carry no bounds is bin-packed,
so holding its open day or hour partition only left small files behind.

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

* iceberg compact: do not hold a drop-only bin in an open partition

A bin whose rows are all deleted removes its files and writes nothing, so
there is no spatial rewrite for an open day or hour partition to wait for.

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

* iceberg compact: pack delete-heavy files in the spatial file order

Delete-heavy bins took the table's order while the other bins of a spatial
plan list their files by the Hilbert key of their geometry bounds, so a
partition split into several delete-heavy bins merged overlapping areas.

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-30 10:51:16 -08:00
ec2d96888d pb: use the slot allocator as gRPC's buffer pool (#13136)
* pb: power-of-two gRPC buffer tiers up to 1 MB

## Problem

gRPC's default buffer pool has tiers of 256 B, 4 KB, 16 KB, 32 KB and 1 MB, and zeroes a pooled buffer's whole capacity on every `Get`. Every message between 32 KB and 1 MB therefore zeroes 1 MB, in the proto codec's marshal and in every receive. A filer entry that holds a table's Iceberg metadata (inline content, extended attributes) is such a message, several times per commit.

Profiled on `weed mini` under an Iceberg commit load (8 DuckDB writers, one table each, 30 s CPU profile): `runtime.memclrNoHeapPointers` under `sizedBufferPool.Get` was 2.39 s of 30.0 s sampled, 8% of the process's CPU. With the tiers below it is 0.74 s of 22.2 s.

## Fix

`weed/pb` sets the process-wide default pool at init (`experimental.SetDefaultBufferPool`, which gRPC documents as init-time only) to a binary tiered pool with every power of two from 4 KB to 1 MB (plus 256 B), so zeroing is bounded by twice the message size. Buffers are still zeroed; only the tier sizes change. The proto codec reads only the default pool; `NewGrpcServer` and `GrpcDial` also pass the pool as an option (`experimental.BufferPool`, `experimental.WithBufferPool`), because gRPC's own default server and dial options captured the old pool before this package's init ran.

Messages up to 32 KB and above 1 MB use the same tiers as before. Each extra tier is a `sync.Pool`, emptied by the GC like the others.

## Tests

`weed/pb/grpc_buffer_pool_test.go`:

- `TestGrpcBufferPoolIsTheDefault`: the default pool is the tiered one.
- `BenchmarkGrpcBufferPoolGet`: a `Get`+`Put` with gRPC's default tiers against these (Apple M-series, `go test -bench GrpcBufferPool -count 3 ./weed/pb/`):

| message | default tiers | power-of-two tiers |
|---|---|---|
| 40 KB | 9.8–10.1 µs | 0.59–0.71 µs |
| 100 KB | 10.1–10.8 µs | 1.24–1.29 µs |
| 300 KB | 11.1–14.7 µs | 5.6–5.7 µs |

`go vet ./weed/pb/` reports nothing in the touched files; `go test ./weed/pb/`: ok. `go build ./weed`: ok.

* pb: test the buffer capacity each gRPC pool tier hands out

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

* pb: rely on the default pool for dials, which read it per connection

grpc's defaultDialOptions() reads mem.DefaultBufferPool() at dial time,
so only the server, whose defaults were captured at grpc's init, needs
the pool passed as an option.

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

* mem: return only slot-sized buffers to the slot pools

Free put any buffer into the slot its capacity rounds up to, so a nil or
odd-capacity buffer made a later Allocate of that slot panic.

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

* mem: serve the slots through a Get/Put pool type

SlotPool satisfies gRPC's mem.BufferPool, and Allocate and Free now go
through it.

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

* pb: use the slot pool as gRPC's buffer pool

The slots round up to the next power of two and do not zero, so gRPC
shares buffers with Allocate and no longer clears them on every Get.

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-30 10:50:31 -08:00
Yip LeoandClaude Opus 5.5 c3f7f24684 mount: wake an upload parked on a read when the read ends (#13123)
* mount: wake an upload parked on a read when the read ends

An upload that finishes while a read holds its chunk waits in its own
goroutine until the read lets go (`for up.IsLocked(index) {
up.readerCountCond.Wait() }`), and only then drops the sealed chunk and
returns its executor slot. The only wake-up came from MaybeReadDataAt,
which a read calls before it lets go of the chunk. UnlockForRead, where
the read does let go, woke nobody. So:

- A read that returns before its dirty-page pass never wakes the
  upload. readDataByFileHandleWithContext skips readFromDirtyPages when
  the chunk read fails, and the kernel interrupts a FUSE read, which
  cancels it, whenever a signal reaches the reading thread.
- A read that does call MaybeReadDataAt wakes the upload while it still
  holds the chunk, so the upload goes back to waiting unless the read
  releases the chunk before the upload gets the lock back.

Only a later read of the same file then moves the upload on. When none
comes, because the file was closed or is no longer read, the upload
stays parked for good. It keeps its sealed chunk (and its share of
-writeBufferSizeMB, when that is set) and a slot of the
concurrentWriters executor, which every file of the mount shares (128
by default). Once parked uploads hold every slot, each new upload of
the mount waits for one, and writes and flushes behind them hang.

UnlockForRead now broadcasts when the last read of a chunk ends, which
is the only place the condition changes, and MaybeReadDataAt no longer
signals. It broadcasts rather than signals: a read across a chunk
boundary releases two chunks, and an upload may be parked on each.

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

* mount: wait for the uploads to park instead of sleeping in the wake-up tests

parkUploads slept 100ms and assumed the uploads were waiting on the read
by then. An upload that had not got there yet would find the read gone
and go on without a wake-up, so the tests could pass with the wake-up
missing. It now watches the goroutines' stacks until each upload waits
on readerCountCond, counting out uploads an earlier test left waiting.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:49:25 -08:00
576eb98ce9 mount: leave -cacheMinFreeSpace free on the chunk cache's disk (#13124)
* mount: leave -cacheMinFreeSpace free on the chunk cache's disk

weed mount sizes its on-disk chunk cache by -cacheCapacityMB alone and
preallocates each cache file in full when it creates it. With a capacity
larger than the free space of the disk holding -cacheDir, the cache takes
that disk down to nothing: the preallocations run until fallocate fails,
and chunk writes fill the rest. The mount's metadata cache (a leveldb
store under -cacheDir) and the swap files of dirty pages (-cacheDirWrite,
which defaults to -cacheDir) live on the same disk, so once it is full
their writes fail with ENOSPC, and writes whose dirty pages spill to
swap return EIO to the application. The same happens when several mounts
share a cache disk and together are configured beyond it.

-cacheMinFreeSpace is the free space the cache leaves on that disk,
written like the volume server's -minFreeSpace: a percentage like 1 or a
size like 10GiB, 1 by default, as for volume servers.

- When the cache opens, its disk layers shrink to the space above the
  floor, counting the cache files already in the directory as the cache's
  own. With no room the disk tier keeps no files.
- Each new cache file preallocates only what the disk holds above the
  floor at that moment, so the files of one cache, or the caches of
  several mounts opening together, stop reserving at the floor.
- A chunk write that lands in blocks its file already holds, preallocated
  or written, goes ahead as before, even with the disk under the floor.
  A write that takes new disk space, into a file a rotation truncated or
  where nothing could be preallocated, goes ahead only while the space
  above the floor covers it. The disk is read at most once a second, and
  the cache counts what it takes in between, so it cannot run past the
  floor between readings. A rotation gives the truncated file's blocks
  back, so the write after it reads the disk again.

A chunk the cache cannot place is not cached, like any other miss. The
webdav server's cache passes no floor and behaves as before.

* mount: read the cache disk on every write that takes space, leave the index files room

Review follow-ups.

- take reads the disk each time, instead of once a second less what the
  cache took since, so a write sees what other mounts sharing the disk
  wrote, and what a rotation gave back. It runs only for writes past the
  blocks a file already holds, and a statfs costs little next to the
  write.
- The index files (.idx and the leveldb maps) grow by a few dozen bytes a
  chunk beside the data files that the cache size counts. Sizing leaves
  them a sixteenth of the room above the floor.
- The cache's own files count as room by the blocks they hold, so a file
  that was preallocated but not yet written when the mount exited counts
  in full when the cache reopens.
- weed fuse checks -o cacheMinFreeSpace in the parent as well: the parent
  waits for the child's signal, and a child that rejects the value never
  sends it.

* mount: keep the resolveCacheDirs doc comment on resolveCacheDirs

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

* mount: say -cacheMinFreeSpace stops new disk space, not every chunk

Under the floor the cache still fills the blocks its files already hold.

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-30 10:48:28 -08:00
Tiago PosseandClaude Opus 5.5 7a5c12a8b0 filer: order finished reader cache downloads by a counter (#13125)
Eviction picked the oldest finished download by the wall clock time it
finished at, and only counted downloads that finished before
time.Now(). A download that finished in the same clock tick as the
eviction didn't count, so the loop fell back to a chunk a stream was
still reading, and two pinned downloads that finished in the same tick
tied. After a wall clock step back, downloads that finished before the
step didn't count either, and with none of them pinned nothing was
evicted and the cache grew past its limit.

Finished downloads now take the next value of a counter on the cache,
which never ties or steps back.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:46:16 -08:00
Yip LeoandClaude Opus 5.5 ecd0493906 mount: keep following the metadata log when the cache refuses an event (#13141)
* mount: keep following the metadata log when the cache refuses an event

The mount applies each event of the filer's metadata log to its local
metadata cache, a leveldb store under -cacheDir. Once that disk is full
every write to the store fails, and an event the cache refuses goes one
of two ways:

- An event the stream delivers fails the follow, which the mount runs
  with FatalOnError: glog.Fatalf ends the process, every file open on
  the mount goes with it, and the mount does not come back when the disk
  has room again.
- An event replayed from the persisted log is returned to the follow
  loop, which resubscribes from it and fails on it again: the mount
  stays up, but no later event reaches its cache, so its listings stop
  changing.

A local change whose apply fails (create, mkdir, unlink, rmdir) drops
its directory's cached listing with InvalidateChildrenCache and goes on.
An event from the log now does the same: the cached listings it
changes, the parents it leaves and enters and a directory it creates,
moves or deletes, are dropped, so the next lookup reads the filer and
the next listing rebuilds them, and the event's kernel invalidations
still go out. The follow goes on. A warning reports the first such
event and then at most one a minute.

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

* mount: handle a refused event in the apply step that refused it

Review of the previous commit found two gaps.

A rename into a directory whose listing is being built applies the part
leaving the source at once and keeps the part entering the building
directory for the build to replay. When the part applied at once was
refused, the other part was not kept, and the build published its
listing without the renamed file. It is now kept whatever happens to
the part applied at once.

The listings a refused event changes were dropped, and its kernel
invalidations sent, by the follow's event function after the apply
returned. By then the apply loop could have taken a later request, such
as this mount's own create of the name a rename left, and the rename's
invalidation would then move the new file. The apply step that fails
now does both before it returns, as it sends the side effects of an
event the store takes, and on the apply loop, which owns buildingDirs
and is the only one to feed the invalidate worker. A local change whose
apply fails gets the same; its caller still drops its directory's
listing as before.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:42:25 -08:00
3c7b3fc16f mount: fail an unlink or rename the filer did not apply (#13140)
* mount: fail an unlink the filer did not apply

* mount: hold an unlinked handle's flushes until the filer answers

* mount: mark a rename's replaced handle once the filer answers

* mount: read a draining handle's unlink mark under its lock

Unlink now sets the mark after the delete answers, while a close queued
before it can be draining, so the worker's bare read raced the write.

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

* mount: drop the unlink comment about marking before the delete

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

* mount: wait for the close to block on the handle lock in the unlink and rename tests

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

* mount: wait on the handle lock with the untagged helper in the rename close test

waitAttributeReadFrame lives in a !freebsd test file, so the FreeBSD test
build failed on weedfs_rename_publish_test.go.

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-30 10:41:22 -08:00
Chris LuandClaude Opus 5.5 d4a21cef59 weed: flush buffered log lines when a command exits (#13151)
exit() ends the process with os.Exit, which skips deferred calls, and
glog writes its files only every 30s. A short-lived command such as a
piped weed shell session lost every log line it buffered, including the
daily_run summary of s3.lifecycle.run-shard.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:39:05 -08:00
edbcc718d3 iceberg: read remote-only metadata files, and fail a table whose metadata cannot be read (#13134)
* iceberg: read remote-only metadata files, and fail a table whose metadata cannot be read

## Problem

In a remote-mounted bucket (`remote.mount` + `filer.remote.sync`), a table's `metadata.json` that is not cached locally is a filer entry holding only its `RemoteEntry`: no inline content, no chunks. The Iceberg REST catalog read metadata files as inline content (and, for a register, chunks), so such a file read as empty bytes, and an empty read was then treated as "no metadata":

- a table stored with its metadata location alone (registered, or created through the S3 Tables API) loaded as an empty table: no schema, no snapshots, and clients read no rows;
- a commit to it was refused on a table UUID mismatch for ever, and a commit without requirements replaced the table's history with an empty one;
- registering such a file failed with `unexpected end of JSON input`.

The same empty stand-ins were served when the file was gone or unreadable, and a synthetic empty table when stored metadata did not parse, with the same consequences.

## Fix

- `loadMetadataFile` (and through it `currentMetadataBytes` and RegisterTable) reads a remote-only file of a mounted bucket: its remote size is checked against a 64 MiB bound before anything is fetched, it is cached into the cluster with `CacheRemoteObjectToLocalCluster` (one retry: a cache can race an uncache or a write-back), then inline content or chunks are read.
- An empty file is `errEmptyMetadataFile`. A staged create's empty placeholder is still treated as absent where the staged commit reads it.
- A location whose file is gone or unreadable, or stored metadata that does not parse, fails load, commit and transaction instead of serving an empty stand-in a writer could commit over. A table created without a location (no metadata yet) still loads as a new empty table, and a catalog-only record (Lance) is never read as Iceberg.
- RegisterTable refuses, before anything is read, a metadata location that is not a file directly in a table's `metadata/` directory (a deeper path was read as the same-named file there), and refuses metadata whose own `location` is not the table location it is registered from (a file copied from another table names that table's files).
- The table UUID a commit or a transaction stores is the base metadata's, not a record's that disagrees with it.

`loadTableMetadataBlob` (used only by the manifest repair) is unchanged.

## Tests

- New `iceberg_register_load_test.go` (inline and remote-only files; a location-only table loads from its file and fails with the file gone; commits and transactions keep the history, and fail leaving the table unchanged when the file is gone; oversized remote files and nested locations refused) and `TestACommitStoresTheBaseMetadatasUUID`. Each rule is red with it undone, except the refusal of an entry still remote-only after two cache calls, which fails closed anyway (it reads as an empty file).
- Adapted: the fixtures of `iceberg_register_table_test.go` (`seedRegistrableMetadata`, `seedOversizedMetadata`) give the metadata the table's own location; `TestLoadTableResultOmitsConfigForCredentialVendingClients` and `seedOwnedTable` store the table with its metadata; `TestBuildLoadTableResultNeverReturnsNilMetadata` now expects an error for a location whose file cannot be read and for unparseable metadata, and keeps the empty-metadata and no-location cases.
- `go vet ./weed/s3api/iceberg/`, `go test -race ./weed/s3api/iceberg/` pass, and `weed` builds.

No unit test reads a chunked `metadata.json` (the in-memory filer has no volume servers); that path was checked against a real cluster with a remote-mounted bucket.

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

* iceberg: refuse commits to catalog-only tables

A Lance table loads as an empty Iceberg table, and a commit built on that
placeholder wrote Iceberg metadata and repointed the record's location
(the Lance dataset root) to it. Both commit paths now answer 400.

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

* iceberg: pass the metadata size limit to the remote cache request

The size check ran on the entry the lookup returned. A remote refresh
between the lookup and the cache call could swap in a larger object, which
the filer then downloaded whole. With MaxSize the filer checks the entry
it actually downloads.

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

* iceberg: apply the metadata size limit to inline content

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 10:36:13 -08:00
f4931605e0 s3tables: say why a write the table bucket layout refuses is refused (#13133)
* s3tables: say why a write the table bucket layout refuses is refused

## Problem

A table bucket accepts only Iceberg files under `<namespace>/<table>/(data|metadata)/`. A PutObject, CopyObject or CreateMultipartUpload of any other key is refused with a bare 403 AccessDenied, which a client that put a plain file there (a README, a CSV next to the table) reads as a permissions problem and goes looking for a missing grant.

## Fix

Those three refusals now carry a message:

    table buckets accept only Iceberg files under <namespace>/<table>/data/ or <namespace>/<table>/metadata/; put other objects in a general purpose bucket

Status and code are unchanged (403 AccessDenied).

The message tells the caller that the bucket is a table bucket, so it goes only to a caller the bucket policy lets write that key (`checkPolicyWithEntry`). A caller the policy denies gets the policy's own refusal, identical to the one for a key the layout accepts, so the answer never tells a table bucket from another bucket to someone who could not write there.

A PUT of the volume verification key that the layout accepts but `volumeVerifyPutAllowed` refuses (outside its window, too large, stored headers) is not a layout refusal and keeps the bare AccessDenied.

## Tests

`weed/s3api/table_bucket_layout_message_test.go`:

- `TestTableBucketLayoutRefusalExplainsItself`: PUT, copy and multipart initiation of `ns/t/data/notes.txt` answer 403 AccessDenied with the message. Fails without the change.
- `TestTableBucketLayoutRefusalIsBareWhenPolicyDenies`: with a bucket policy denying the write, the refusal of a layout-refused key is byte-for-byte the refusal of a valid `.parquet` key.
- `TestTableBucketVerifyRefusalIsNotALayoutRefusal`: a stale verification key keeps the bare refusal.

`go vet ./weed/s3api/` reports nothing in the touched files; `go test ./weed/s3api/`: ok. `go build ./weed`: ok.

* s3api: load the bucket before a layout refusal checks its policy

With authentication off nothing loads the bucket before the handler, so a
stored Deny was not in the engine yet and the first layout-refused write
after a restart got the table-bucket explanation.

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

* s3api: apply existing-object tag conditions before a layout refusal explains itself

A Deny on s3:ExistingObjectTag is deferred by the first policy check and
applied only by the later lookup recheck, which the layout refusal skipped,
so a tag-denied writer still learned the bucket is a table bucket.

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

* s3api: name the format-owned directories in the table layout refusal

Table buckets also accept a table format's own _-prefixed directories
(Lance's _versions, _transactions, _indices), so telling a Lance writer that
only Iceberg data/ and metadata/ files are accepted misleads it.

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-30 10:33:15 -08:00
bf14326c3c iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files (#13131)
* iceberg maintenance: recognise deletion vectors whose format is written in lowercase

Iceberg maintenance tells a Puffin deletion vector from a Parquet position-delete file by its `file_format`, compared exactly with iceberg-go's constant `PUFFIN`. DuckDB records the format in lowercase, `puffin` (as it records `parquet`, which compaction already compares without case). Such a vector was never taken for a vector:

- the data file it covers was not kept out of compaction bins, and
- the vector itself was handed to the Parquet position-delete reader, which cannot read a Puffin file, so compacting any table holding one failed (and the position-delete rewrite tried to read it the same way).

The fix adds `isPuffin`, a case-insensitive comparison, and uses it at the four places that compared the format.

Test: `TestLowercasePuffinDeletionVector` wraps a deletion-vector entry so its format reads `puffin` (as the Avro reader passes it through) and checks that the data file it covers is excluded and that `collectPositionDeletes` does not try to read the vector. It fails without the change (`dv paths = map[]`).

`go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files

Compaction has no reader for Puffin deletion vectors (DVs), so every data file a vector covers is kept out of compaction for good (`excludeDeletionVectorFiles`). A format-version 3 table that is reloaded with DELETE + INSERT (DuckDB writes a vector hiding all of the old file) keeps the old file and its vector forever, and every reader pays for both. Bins also form only from `min_input_files` small files per partition, so deleted rows never enter the decision.

This builds on #13127 (the case-insensitive `puffin` format check); the first commit on this branch is that PR.

Changes:

- **Vectors are applied.** The vectors of the compaction candidates are read with iceberg-go's `table/dv` (length, magic and CRC checked, and the decoded cardinality checked against the manifest's `record_count`) and joined with the Parquet position deletes the merge already applies. A vector that does not decode keeps its file out of every bin, as before, so a file never merges without its deletes. One Puffin file is read once per run even when it holds several vectors.
- **A consumed vector leaves with its data file.** When the snapshot removes a data file, the delete manifests holding its vector are rewritten (that vector `DELETED`, the other entries `EXISTING`); manifests without one are carried as they are. Vectors are matched by the data file they cover, never by the Puffin file path, because one Puffin file may hold the vectors of several data files (Spark writes them that way) and the vectors of files left in place must stay.
- **A bin whose deletes leave no row writes no empty file**; its files are just removed.
- **New setting `delete_ratio_threshold_percent`** (default 0 = off, so bin selection is unchanged unless set; Iceberg's own `rewrite_data_files` uses 30%). When set, a Parquet file whose vector deletes at least that share of its rows is rewritten in a bin of its own, whatever `min_input_files` says, packed by live bytes up to the target size. A file whose decoded vector deletes exactly positions 0..n-1 is dropped without being read; a manifest count that says "all" with positions that do not is rewritten row by row instead. Only files under the target file size are taken (the merge reads a file whole into memory), except a file dropped unread.
- **Detection reads no vector**: a DV's `record_count` is its cardinality, which is all the ratio needs. With `apply_deletes` off, planning ignores vectors (execution skips tables with deletes then). The planning-index cache key includes the ratio.

Tests (`deletion_vector_test.go`):

- a vector with a lowercase `puffin` format is matched to its data file under either path spelling;
- a merge with a vector and a Parquet position delete: every file merges minus its deleted rows, row ids kept, and the delete files leave the table (ratio off);
- a reloaded table: the wholly deleted file and its vector are dropped without the file being read (it is not even present), the new file untouched;
- ratio past / under / vector not decodable / manifest count says all but positions do not / partly deleted file past the target size left alone;
- two vectors in one Puffin file, only one data file compacted: the other file's vector stays;
- detection with the ratio on and off.

Each was checked red against a mutation of the rule it covers (exact format compare, vectors not applied, vector consumed by Puffin path, size check skipped, whole-file check skipped). `go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg compact: check a deletion vector's blob range without overflow

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

* iceberg detection: key the cached compaction plan on apply_deletes

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

* iceberg detection: skip a table with deletes while apply_deletes is off

Execution already skips it, so detection proposed a job that never ran.

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

* iceberg compact: a drop-only bin is not held to the sort input cap

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

* iceberg compact: split delete-heavy bins at the sort input cap

The packer counted live bytes only, so two partly deleted files could
share a bin the sort input cap then dropped on every run.

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

* iceberg compact: compare the delete ratio in whole rows

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

* iceberg compact: merge delete-heavy files in the order of their bounds

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

* iceberg compact: read only the vectors of files a bin can take

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

* iceberg compact: pack a vector whose count and positions disagree by its whole size

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-30 10:22:30 -08:00
347f1cf705 deps: bump parquet-go to v0.33.0 (#13130)
* deps: bump parquet-go to v0.33.0

parquet-go v0.33.0 fixes several bugs that Iceberg compaction runs into:

- BOOLEAN columns that Arrow and parquet-mr write with data page v2 are
  RLE-encoded. v0.32.0 decoded such runs wrong (a run's value byte expanded
  bit by bit, runs taken as multiples of 8 values), so compaction rewrote the
  flags wrong, and it wrote its own runs of trues with the value byte 0xFF,
  which DuckDB refuses to read ("Payload value bigger than allowed")
  (parquet-go/parquet-go#617, fixed by parquet-go/parquet-go#620).
- A column chunk without a dictionary lists the level encoding RLE next to
  PLAIN. v0.32.0 took RLE as the column's encoding, so the schema derived from
  a non-dictionary INT32 or DATE file could not write ("RLE: cannot encode
  INT32 with invalid bit-width=0") and such files never compacted
  (parquet-go/parquet-go#603, fixed by parquet-go/parquet-go#611).
- The sorting writer dropped the row groups' geospatial statistics when a
  bin fit in its sort buffer, so a sorted rewrite of a geometry table wrote
  files without a geometry bound (parquet-go/parquet-go#627, fixed by parquet-go/parquet-go#693 and parquet-go/parquet-go#700).
- A null in a list of required values wrote no value and shifted the rest of
  the page (parquet-go/parquet-go#616, fixed by parquet-go/parquet-go#618); a short data page read leftover
  values from a pooled buffer instead of failing (parquet-go/parquet-go#624, fixed by
  parquet-go/parquet-go#731).
- A geometry or geography column declared without a CRS is now written
  without one rather than with OGC:CRS84 spelled out (parquet-go/parquet-go#628, fixed
  by parquet-go/parquet-go#688).

Changes that follow from the bump:

- A corrupt data page now fails with an error rather than a panic. The
  position and equality delete readers returned that error without the file
  name; they now name the file, as the data file merge already does.
- The default-CRS tests built their "spelled out" inputs with
  parquet.Geometry(""), which now writes no CRS; they declare OGC:CRS84
  explicitly. The footer rewrite in geometry_crs.go is still needed when an
  input spells the default out, since the output schema comes from an input.

Tests:

- compact_rle_boolean_test.go with four pyarrow fixtures: two files with
  v2-page RLE booleans (with nulls) read back and compacted with every flag
  kept, and two non-dictionary INT32/DATE files compacted with every value
  kept. All three tests fail on v0.32.0 (3005 of 6000 flags wrong; "no bins
  successfully compacted").
- TestCompactSortedGeometryBoundCoversEveryRow only checked a bound when
  there was one, so it passed with the statistics dropped. It now requires a
  geometry bound on the data file and geometry statistics in the footer; it
  fails on v0.32.0 and passes on v0.33.0.
- go vet and go test of every package that imports parquet-go
  (weed/admin/dash, weed/mq/logstore, weed/mq/schema, weed/query/engine,
  weed/worker/tasks/iceberg) pass; -race on weed/worker/tasks/iceberg and
  weed/mq/logstore passes; go build ./weed passes.

* iceberg: fail the Arrow fixture tests on a read error

Both row-reading loops ended on any error, so rows decoded next to an
error could still pass the value checks.

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

* iceberg: check each fixture row comes out of compaction exactly once

A row replaced by a copy of another kept the row count and passed the
value checks, which use the row's own id.

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-30 10:18:24 -08:00
5017a07475 iceberg maintenance: whole-pass tests of equality deletes on a partitioned table (#13132)
* iceberg maintenance: whole-pass tests of equality deletes on a partitioned table

The equality-delete tests call the pieces (`collectEqualityDeletes`, `eqDeleteGroupsForBin`, `mergeParquetFiles`) one at a time. These run `compactDataFiles` end to end and check what a reader sees after the commit, including the deletes carried for files left uncompacted and the sequence numbers of the merged files. Tests only; no code changes.

The table has three partition specs: 0 unpartitioned, and 1 and 2 both `identity(name)` on the same partition field, so only the spec ID tells their deletes apart. It is written as a writer commits it: one snapshot per data sequence number, its manifests carrying the number and their ADDED entries inheriting it. Its equality deletes come in every scope: partition-scoped, global, by another column, and with keys that live in other partitions or specs. Each test reads the table before and after the pass with its own merge-on-read (each delete applies to data files with a lower data sequence number, under an unpartitioned spec or the same spec and partition) and compares the rows.

- Every two-file bin compacts, bin-packed and sorted; one partition's single file does not. The live rows are unchanged and the deletes are carried for the file left as it was (a merged file given an input's lower sequence number would lose rows to the carried deletes).
- Every file compacts: the rows are unchanged and the deletes leave the table.
- An unreadable partition delete fails the pass, names the file, and commits nothing; once the file is back the table reads as before.
- A delete under a spec the table does not list fails the pass and commits nothing.

Checked red against a mutation of the sequence-number rule (equality deletes applied whatever the sequence numbers): the first two tests fail. `go vet` and `go test ./weed/worker/tasks/iceberg` pass.

* iceberg maintenance: whole-pass table snapshot IDs differ from its sequence numbers

The fixture gave each commit's snapshot the ID of its data sequence number,
so a compaction that read an entry's snapshot ID in place of its sequence
number still kept the right rows. The IDs now count down as the sequence
numbers count up.

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

* iceberg maintenance: a whole-pass name-keyed delete that removes a live row

The only name-keyed delete matched no row, so a pass that ignored deletes
keyed by name still kept the right rows. u1 now holds a "zz" row that a
global name-keyed delete removes.

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-30 10:17:18 -08:00
Chris LuandClaude Opus 5.5 2acd49ba27 s3api: end a vended table session no later than the caller's credential (#13161)
* s3api: record the verified credential's expiry in the request context

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

* s3api: cap a vended table session at the caller's credential expiry

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

* sts: let a principal session request cap the session's expiry

AssumeRoleForPrincipal takes an absolute NotAfter. issueSession caps both
the credentials and the signed token at it, so a cap computed before the
trust-policy lookup is not stretched by the time that lookup takes.

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

* s3api: hand the caller's credential expiry to STS as an absolute cap

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:15:36 -08:00
Chris LuandClaude Opus 5.5 df59c81a8c master: record when the cluster started (#13121)
* topology: record when the cluster started

StartedAt rides on MaxVolumeIdCommand; the first non-zero value wins so
replayed or racing entries cannot move it, and the max volume id mirror
file keeps it across raft state loss.

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

* master: carry StartedAt through raft apply and snapshots

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

* master: leader records StartedAt once per cluster

The leader records it right after the topology id. A cluster that predates
the record gets the time its first upgraded leader runs. /dir/status shows it.

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

* test: use current StartedAt values

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

* topology: never lower the mirrored max volume id

A mirror rewrite for a StartedAt change could carry a bound older than
one already persisted. Keep the highest bound, and read StartedAt under
the file lock.

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

* topology: let the latest applied StartedAt win

With first-wins, a master that restored an older-version snapshot without
the field could record a second value while the others kept the first.
Following the raft order makes every master converge on the same value.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:12:46 -08:00
Chris LuandClaude Opus 5.5 d49876a7aa filer: every filer store reads KV keys in batches (#13119)
* filer: read KV keys a few at a time for a store without batch reads

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

* abstract_sql: read KV keys with one query

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

* redis: read KV keys in one pipeline

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

* etcd: read KV keys in read-only transactions

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

* mongodb: read KV keys with one query

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

* cassandra: read KV keys concurrently

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

* hbase: read KV keys concurrently

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

* elastic: read KV keys concurrently

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

* arangodb: read KV keys with one request

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

* foundationdb: read KV keys in one transaction

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

* ydb: read KV keys with one query

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

* tarantool: send KV reads before waiting for any

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

* filer: every filer store reads KV keys in batches

KvBatchGet moves from the optional KvBatchReader onto FilerStore. A listing
now reads the hard link records of its waiting entries together from any
store, a path-specific one included.

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

* tikv: count only the record reads of a listing in its test

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

* filer: return every batched key that pads to the same stored row

SQL, MongoDB and YDB pad a short KV key with zero bytes, so "short" and
"short\x00" read the same row. KvBatchGet kept only the last such key.

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

* filer: read keys in a plain loop when KvGetEach runs one at a time

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:10:49 -08:00
github-actions[bot] 604d391012 4.56 2026-11-30 02:49:57 +00:00
Chris LuandClaude Opus 5.5 689e98ea4c test: fall back to a Maven Central mirror for the S3 Spark suite (#13120)
Spark resolved hadoop-aws and the AWS SDK bundle through Ivy from Maven
Central only, so a refused Central request failed the suite with
"module not found" before any test ran. spark.jars.repositories adds the
Google mirror after Central in Ivy's resolver chain.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:32:08 -08:00
f905b33f19 tikv: read a key from TiKV once per transaction (#13115)
* tikv: read a key from TiKV once per transaction

Inside one store transaction the filer reads the same key more than once:
a rename looks its source up when it starts and again to delete it, and
its target before the create and again in it. On TiKV a second read cannot
differ from the first. A transaction reads the store as it was when the
transaction began, and its own writes are answered from its buffer. Each
of those reads was still a request to TiKV, because the client keeps what
a batch get read with the transaction's snapshot and not what a get read.

Inside a caller's transaction a key is now read as a batch get of that one
key, and the next read of it is answered from the snapshot. A read outside
a caller's transaction is a transaction of its own and keeps the plain
get.

With the store on the client library's in-process TiKV, a rename of a file
to a new name sends 4 reads instead of 7, and one over an existing file 4
instead of 6.

The tests run the store on that in-process TiKV, which needs
pingcap/goleveldb as an indirect dependency.

* tikv: shorten the comment on the transaction read

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:50:09 -08:00
cb958290c8 filer: read the hard link records of a listing in batches (#13117)
* filer: read the hard link records of a listing in batches

A hard-linked entry keeps its attributes and chunks in a record the file's
names share, and a listing reads that record for every hard-linked entry
it lists. It read them one at a time from the callback of the store's
listing: a round trip to the store for each such name, each waiting for
the one before, so a directory of hard-linked files listed far slower than
one of as many plain files.

A store may now say that it reads several KV keys in one round trip
(KvBatchReader). For a listing by such a store the wrapper holds the
entries back from the first hard-linked one on, up to 256 of them, reads
their records together and hands them on. The caller of the listing gets
the same entries in the same order, and the name of the entry it ended
the listing at.

TiKV implements it with the client's batch get. With the store on the
client library's in-process TiKV, the records of a directory of 200
hard-linked names take one batch get instead of 200 gets.

The TiKV tests run the store on that in-process TiKV, which needs
pingcap/goleveldb as an indirect dependency.

* filer: end a listing where its caller ended it, whatever the store met behind

The store goes on past the entry its caller ends the listing at, to the
entries that wait for their records with it, and may fail there. The
listing then returned the store's error, though a caller handed each entry
as it arrived would have stopped the store before it got that far. The
listing now ends at the entry its caller ended it at, and a caller that
fails among the waiting entries gets its own error, not the store's.

The same holds for the step a store takes after it is told to stop, when
the caller ended the listing at an entry the store had already passed. At
the last entry that waited the step's error is still returned, as it is
from a store that hands each entry on as it arrives.

* filer: finish a hard link listing on every return of the listing

The listing hands on the entries that wait from a deferred finish, so a
return path that lists from elsewhere with the same callback hands them on
too. The callback keeps the adjustedEntryFunc shape the prefixed listing
already had.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:47:40 -08:00
Chris LuandClaude Opus 5.5 3d076dfcdf filer: aggregated metadata stream reads the log files of peers with their own store (#13116)
* filer: pass the reader's context to persisted metadata log listings

The day and minute listings behind ReadPersistedLogBuffer used
context.Background(), so nothing scoped to the subscription reached them.
List through one helper that takes the caller's context.

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

* filer: aggregated metadata stream reads the log files of peers with their own store

A filer with its own store never holds another filer's persisted
metadata log: log file writes emit no events and the bootstrap traverse
skips the log directory. The aggregated stream read history from the
local log directory and the in-memory aggregate ring only, and the ring
restarts empty, refilled from each peer's saved offset. A subscriber whose
cursor was older than that missed every event a peer recorded before it,
for example the S3 lifecycle worker replaying expirations.

Aggregated reads now also list the log directories of followed peers not
known to share this filer's store, merged by file name, so the existing
ordered reader and chunk-ref path serve their history. Local streams, which
peers aggregate from, stay local.

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

* filer: bound peer log listings and fail the read when one fails

Each peer listing gets its own deadline, so a peer that stalls mid-listing
cannot hold the read. A failed listing now fails the read instead of
silently hiding that peer's persisted files; peers already retired as
unreachable are left out. Peers are asked from the same start name the
caller uses for its own store instead of the whole directory.

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

* filer: keep a still-unreachable peer out of log listings after its mark expires

A followed peer that keeps refusing connections is marked removed once, and
the mark is dropped with its resume point an hour later. It was then listed
again and its failing listing ended every aggregated persisted-log read.
Leave out any peer refusing connections for peerUnreachableRemovalAfter,
marked or not.

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

* filer: subscribe tests track their peers on the test filer's store

Aggregated reads now list the log files of followed peers with their own
store. The subscribe tests' peers have no server and share the test
filer's store, so record that instead of dialing them.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:46:29 -08:00
12ef22477a filer: read a missing path once when a rename or a delete looks it up (#13114)
* filer: read a missing path once when a rename or a delete looks it up

A rename looks its target up with FindEntryForOverwrite, and
DeleteEntryMetaAndData looks up the path it deletes the same way. Inside a
store transaction an ordinary lookup hides an expired S3 entry and leaves
its row for the commit. A write over the path still owes that row its
chunks and its hard link, so the store was read again whenever the lookup
came back with nothing.

It comes back with nothing far more often because the store holds nothing
at the path, which is what a rename to a new name finds. The second read
then repeats the first. Filer.findEntry already tells whether its answer
is what the store holds at the path, so the store is read again only for
a row the lookup found and kept from its caller.

Around 20 renames of a file to a new name on leveldb2 the store counter
shows 7 finds per rename before and 6 after.

* filer: shorten the overwrite-lookup comments

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:45:49 -08:00
Chris LuandClaude Opus 5.5 bd9e9a37c2 mount: send an open's truncate to the write owner as a conditional update (#13113)
An open with O_TRUNC over an existing file stored the empty entry with an
unconditional UpdateEntry. The filer only routes conditional writes to the
path's write owner, so the truncate landed on the filer the mount talks to,
which deleted the chunks it dropped, while a peer's conditional chmod could
still commit at the owner over the entry it had not yet seen truncated. The
owner's write then brought the deleted chunks back into the entry.

The truncate now goes through saveEntryAttributes: guarded by the entry the
open found, routed to the owner, and replayed on the owner's entry when
refused.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:44:06 -08:00
github-actions[bot] 7d1ad72e74 docs: regenerate star history chart 2026-11-30 01:27:56 +00:00
Martijn HoekstraandClaude Opus 5.5 89dbcb44c7 security: fips.mode follow-ups from the #13029 review (header comments, EMS on verified HTTPS, CA and read checks) (#13110)
* volume: read security.toml section headers that carry a trailing comment

The volume server's own security.toml parser compared each whole trimmed
line with the section headers it knows, so `[fips] # policy`, valid TOML
that Go's viper reads, fell through to an unknown section and its `mode`
was dropped: Go enforced the mode while weed-volume ran with FIPS mode off
and logged nothing. The same held for `[jwt.signing]` and every other
section. Header lines now have a trailing `#` comment removed before they
are matched.

Refs #13029

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

* sw-client: require the Extended Master Secret on verified HTTPS in FIPS mode

In FIPS mode only the `insecure_skip_verify` client configuration, which
sw-client builds itself, set `require_ems`. With certificate checks on,
reqwest built the configuration and left `require_ems` at rustls's
default, which is off for a provider that is not FIPS-validated, so a
trusted TLS 1.2 volume server without EMS was accepted where the insecure
path refused it. Go requires EMS in FIPS mode. Both FIPS-mode paths now go
through one rustls configuration built here: certificates checked against
`https.client.ca` or the system roots (loaded with rustls-native-certs, as
reqwest loads them), or not checked with `insecure_skip_verify`, and EMS
required either way. Off mode keeps reqwest's configuration.

Refs #13029

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

* volume: refuse a FIPS mode from a security.toml parse that did not read the file

resolve_fips_setting reads security.toml once to check that it can, then
parses it. The parse falls back to defaults when its own read fails and
reports that only in `file_read`, which was not checked, so a file that
became unreadable between the two reads resolved to FIPS mode off. A
parse without `file_read` is now the same FipsModeError::File as a failed
first read.

Refs #13029

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

* sw-client: refuse a malformed https.client.ca with insecure_skip_verify in FIPS mode

The FIPS-mode insecure_skip_verify configuration never parsed
`https.client.ca`, so a CA file whose certificate does not parse was
accepted there and refused on every other path, where reqwest or the
verified configuration load it. The CA is now parsed, and refused when
malformed, before it is set aside.

Refs #13029

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

* seaweed-vector: lock sw-client's rustls-native-certs dependency

sw-client depends on rustls-native-certs since the FIPS-mode HTTPS
configuration; seaweed-vector depends on sw-client by path, so a --locked
build there refused to update its lockfile. The crate was already locked
in seaweed-vector; only the edge was missing.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:57:41 -08:00
Chris LuandClaude Opus 5.5 276be51d04 volume(rs): require the Extended Master Secret on outgoing HTTPS in FIPS mode (#13111)
The outgoing client took reqwest's rustls configuration, which leaves
require_ems at rustls's default: off for a provider that is not
FIPS-validated. A TLS 1.2 peer without EMS was accepted where Go's FIPS
mode refuses it. In FIPS mode the configuration is now built with the same
roots, CA and identity, and require_ems set.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:56:59 -08:00
760f88e294 filer: bind scoped POSIX locks to the verified token id (#13047)
* filer/posixlock: key lock owners and leases by principal

A lock's owner becomes (Principal, Sid, Owner). The principal is server-side
state, empty for unscoped callers, so owners with equal client-chosen sid and
owner under different principals conflict and never match on unlock, release,
reassertion or coalescing. The session index and leases key on
(Principal, Sid).

Scoped sessions are leased per key from their first acquisition: the lease
ends at the earlier of TTL after the last acquisition or renewal on that key
and Lease.NotAfter. Expired scoped locks are dropped before any operation on
their key as well as by ReapExpired. Unscoped sessions keep their current
whole-session lease, started by the first keepalive.

The handler passes the unscoped session for now, so behaviour is unchanged.
NewManagerWithClock lets tests drive lease boundaries.

* filer: bind scoped POSIX locks to the verified token id

PosixLock trusted the client-supplied sid. GET_LK reports a conflicting
lock's sid and owner, so a scoped caller with a write grant on the same path
could reuse them to unlock or release another holder's lock, keep it alive,
or replace it through a KEEP_ALIVE reassertion. A tokenless request with the
same identity could do the same.

A request admitted for a scoped token now acts for that token's verified jti,
derived in posixLockAuthority from the interceptor's authority. It controls
only the locks it took, whatever sid or owner it names. Its lease on each key
ends at the earlier of the 15s TTL after its last acquisition or renewal and
the token's expiry plus the clock leeway. Each renewal passes admission for
its key, so a narrower token cannot extend keys outside its grant. Tokenless
and unscoped calls keep the unscoped namespace and behaviour, and can no
longer match a scoped lock. Scoped TRY_LOCK and reassertion ranges must be
well-formed read or write ranges, checked before any state changes.

GET_LK, the protobuf and forwarding are unchanged; the principal is never
returned or logged. A renewed token with a new jti is a new owner: the old
locks expire and are reacquired.

* filer/posixlock: release an expired session once, however many ranges it holds

* posix locks: report a lock lost on re-assertion to the mount

A mount whose lease lapsed, for example when its scoped token expired or
was replaced by one with a new id, kept re-asserting locks that another
session had since taken. The filer logged the loss but returned success,
and the mount discarded the reply, so nothing on the mount side showed it.

KEEP_ALIVE now returns the first conflicting lock in the existing
has_conflict and conflict fields, which older mounts ignore. The mount
warns once per key when it learns of a loss and forgets it once a
re-assertion succeeds or the key is no longer held. Writes are not fenced.

* filer/posixlock: drop every expired session's ranges in one pass

* filer/posixlock: renew a scoped session's same-grant leases together

Scoped leases expire per key and a keepalive renewed only the key it named.
A mount renews its keys one keepalive at a time, so with many keys and slow
keepalives a round could outlast the 15s lease and a healthy mount lost
locks; unscoped sessions never had this problem because any keepalive
renews the whole session.

Each scoped lease now records a fingerprint of the verified grants it was
acquired or re-asserted under: a SHA-256 over the sorted, deduplicated
(access level, path) entries. A keepalive, bare or re-assertion, extends
every live lease of the same session (principal and sid) held under the
same fingerprint, each to the request's lease (the earlier of the TTL and
the token's expiry plus leeway). Leases taken under other grants, such as
a narrower token reusing the jti, are still renewed only by name, and a
lease that already ended is not revived before the sweep drops it. No
extra filer lookups; unscoped sessions are unchanged.

* filer/posixlock: bound same-grant renewal and refuse ended-lease grants

A scoped keepalive scanned every key of its session to renew those held
under the same grant, so a mount renewing N keys one by one did N^2 lease
visits per round under the manager's mutex. The scan now runs at most once
per quarter lease TTL per grant; every key under the grant still ends no
earlier than three quarters of a TTL after the latest renewal, and the named
key is always renewed in full.

TryLock now refuses a scoped grant whose lease has already ended, such as a
request admitted just before its token expired that then waited on the
manager, instead of granting a lock the next operation would drop. The filer
returns Unauthenticated, which the mount reports as EIO.

* filer/posixlock: skip same-grant scans by deadline floor, not by time

The scan throttle remembered when a grant was last renewed, not how long
that renewal made its keys last. A replacement token with the same id and
grants but a later expiry could then renew one key while the others kept
ending at the old token's expiry.

Each session now keeps, per grant, the deadline the last scan gave every
live key under it, lowered whenever a key is leased for less. A renewal
skips the scan only while that floor already reaches the earlier of its
own deadline and three quarters of a TTL from now, so a mount renewing
keys one by one still costs linear work.

A keepalive from a session holding no leases records nothing, and a
session's floors go with its last lease, so lock-less keepalives with
changing session ids no longer accumulate state the sweeper never sees.

* filer/posixlock: never move a scoped lease's deadline earlier

Renew, a re-assertion, a same-grant scan and a re-lock all set the key's
deadline to the request's own bound. A request under the old token of a
principal that already renews under a replacement (same id and grants,
later expiry) can land after the replacement's renewal, for example one
of the 32 concurrent keepalives in flight when the mount switched
credentials. It then cut the key back to the old token's expiry, and the
lock was dropped before the next round although the replacement had
renewed it. Keep the later of the current and the requested deadline:
every deadline still comes from an admitted request of the same
principal, so a lease never outlives the latest of its tokens.

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

* filer/posixlock: keep each session's index and leases in one map

bySession, lastSeen, leases and floors were four maps keyed by Session that
had to be created and pruned together. They become one sessions map whose
sessionState holds the session's keys (with each key's lease), its last
keepalive and its grant floors, so a session's state is dropped in one place.
The release loop shared by ReapExpired and ReleaseSession becomes releaseOn.

ReleaseSession now also forgets an unscoped session's last keepalive, so a
session it released is not reported again by the next sweep.

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-29 12:58:42 -08:00
Chris LuandClaude Opus 5.5 46b10efcce mount: refuse a stale truncate over a peer's chunks and keep later times when merging a flush (#13100)
* mount: refuse a merge whose local truncate cuts chunks a peer wrote

A flush refused by IF_ENTRY_EQUAL replays the handle's truncate onto the
stored entry. The truncate was made over the handle's base, so a chunk a
peer committed after that base was dropped or clipped silently, losing
data the peer had already fsynced. Like a stale whole-file rewrite over a
peer's chunk change, it now fails the merge. A base chunk the peer only
shortened carries no peer data and is still cut.

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

* mount: keep the later mtime and ctime when merging a delayed flush

The merge took every attribute the handle changed from the handle, so a
flush that waited behind a peer's commit moved mtime and ctime back to
the handle's older write. Each time is now merged as one value (seconds
and nanoseconds were merged field by field, so a moved second could take
the peer's nanoseconds): the handle's time stands unless a peer moved it
too and later.

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

* mount: let a truncate merge pass the handle's own committed chunks

A flush whose commit answer was lost finds its own chunks in the stored
entry while its base is still the older one. Those chunks are the
handle's writes, not a peer's, so they do not refuse the merge.

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

* mount: do not keep a stored copy of a chunk the merge re-adds from the handle

A stored chunk the base lacks but the handle holds is the handle's own
commit whose answer was lost. The merge appends the handle's chunks after
the stored ones, so keeping the stored copy referenced the chunk twice.

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

* mount: take the manifests of a failed flush's fold for the handle's own chunks

A flush can commit its folded manifests and lose the answer. The handle
reverts to the member chunks and keeps its old base, so the next merge
found the stored manifest, knew neither its file id nor its key, and
refused it as a peer write across the handle's truncate.

The handle now remembers the folds of flushes that failed over its base,
and a merge unfolds them in the stored entry before comparing, so the
members match the handle's chunks. A peer's manifest is still refused.

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

* mount: take a retried flush's own stored fold for its own chunks

The client retries a request whose connection dropped, and the first try
may have stored the flush's folded manifests. The retry is then refused
over them before the fold is recorded as failed, and the merge took the
manifest for a peer's write across the handle's truncate. The merge now
unfolds the flush's own fold in the stored entry as well; the condition
still names the entry as stored.

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

* mount: keep every fold the filer may hold instead of the last four

Dropping the oldest of four could forget the fold the filer committed,
and the merge then refused that manifest again. A fold is now kept only
when the flush failed without the filer's answer, or when the refusal
lookup shows it stored, so a refused flush no longer adds one, and the
list ends with the base.

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

* mount: keep a flush's fold when its first request may have been stored

A precondition verdict on a retried send does not prove the first send
stored nothing, and a failed refusal lookup then hid that it had. The
create now counts the sends of the request that carries the fold and
keeps the fold whenever the flush fails and that request was sent more
than once or never got the filer's answer. That covers both flush paths,
so revert is back to only restoring the chunks.

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

* mount: drop the failed folds a refused create shows were not stored

A refusal means the stored entry moved off the handle's base, so no
request guarded by that base can store another fold. After the refusal
lookup the handle keeps only the folds whose manifests the stored entry
holds, at most one, which bounds the list over a base.

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

* mount: bound the failed folds a handle keeps over one base

Flushes that keep failing with no filer answer each saved a new fold the
filer may hold, so the list grew for as long as the outage lasted. Once a
handle keeps maxFailedFolds folds over its base, its flushes send their
chunks unfolded for the filer to fold, and no kept fold is dropped.

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

* mount: keep the failed folds a refusal lookup does not show

The refusal comes from the file's write owner, but the lookup after it can
read a filer that lags behind and still shows the base. Pruning the folds
against that read forgot a fold the owner had stored, and once its manifest
showed up a pending truncate took it for a peer's chunk on every flush. The
maxFailedFolds limit bounds the list, so the folds stay until the base moves.

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

* mount: drop the chunks a failed flush sent that the handle has cut since

A flush that commits with its answer lost, then a truncate of the handle,
left the next merge with the handle's own committed chunks in the stored
entry, outside both base and the handle. The truncate check took them for
a peer's writes and refused every later flush over the base. A failed
flush now records the file ids of the chunks it sent that base lacks, and
the merge drops those the handle no longer holds: it cut or replaced them.

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

* mount: copy the failed flush's sent set with a loop

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

* mount: keep folding past maxFailedFolds instead of sending chunks unfolded

The filer folds a flat chunk list itself, into manifests the handle does
not know: a lost answer then left one of them across a pending truncate,
and an acknowledged one gave the handle flat chunks under a folded base.
Flushes fold as before, and the handle stops keeping folds past the limit
while it still records the chunks they sent.

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

* mount: read the stored manifests a refused merge cannot name

A fold changes no content, but a manifest the handle does not know sat in
the stored entry as one chunk: across a pending truncate it refused the
merge, though it can hold the handle's own chunks (a fold it did not keep,
or one the filer made). When the merge is refused, the flush reads those
manifests, replaces them with the chunks they hold and merges again.

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

* mount: hold the chunks the filer stored after a plain acknowledged flush

The filer folds a flat chunk list (the mount's own fold failed), and the
acknowledgement makes the stored entry the base while the handle kept the
flat chunks. A later merge took them for writes of the handle, which can
bring back chunks a peer's truncate removed. As after a merge, the handle
now takes the stored chunks, keeping those attached since the request.

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

* mount: keep a bounded record per failed flush instead of a growing set

The set of chunk ids failed flushes sent grew with every overwrite while
commits failed, and each failure copied it whole. Each failed flush the
filer may have stored (a send got no verdict) now keeps one record, its
fold and the ids it sent, built once and at most maxFailedFlushes over a
base. Past that, a merge refuses the chunks of a flush it did not keep
that the handle has cut since, as a peer's.

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

* mount: register the chunks a rebase or install gives the handle for reads

A handle that takes the stored chunks after a flush (or a peer's, after a
merge) can get manifests the filer made, and resolving them needs the
file's read token. rebaseEntry and installRewrittenChunks now record the
chunks under the file's path before the read view resolves them.

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

* mount: keep every chunk id a failed flush sent, cap only the folds

Past four failed flushes over one base the handle stopped recording what a
later flush sent. If that flush was stored with its answer lost, a truncate
of its chunks was refused as a peer's write and kept failing after the
filer came back. The ids now go into one set shared by the base's marks,
each kept once and never copied, until the base moves. Only the folds stay
capped: a stored manifest past the cap is read when a refused merge cannot
place it.

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

* mount: fail a flush over a peer's chunk change unless -concurrentWriteMerge

A content flush refused because another mount committed first used to
merge the handle's writes onto the stored entry. That merge now runs
only with the new -concurrentWriteMerge mount option (off by default).
By default a stored chunk change that neither the base nor the handle
holds fails the flush with EIO, and a peer's chunk event no longer
rebases a dirty handle. Attribute-only changes and the handle's own
commits (a lost answer, its own truncate) still merge.

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

* mount: recognize the shortened references a failed flush sent

A truncate shrinks a base chunk in place, keeping its file id. A failed
flush that may have stored such a reference recorded only file ids base
lacks, so a later truncate saw its own stored reference as a peer's
change and failed with EIO by default.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:34:30 -08:00
Chris LuandClaude Opus 5.5 a963c1309c worker: purge the filer metadata log from a lifecycle job that keeps it past every TTL (#13101)
* worker: share the one-filer-per-store selection with other filer jobs

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

* worker: add a meta_log_purge job that keeps the log past every TTL

The job deletes whole metadata log days once per filer store, keeping
every day that the longest filer.conf TTL, the longest S3 lifecycle rule,
a registered retention floor or a running replay job's cursor still
needs. A floor input that cannot be read stops the run before anything
is deleted.

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

* worker: register meta_log_purge in the lifecycle lane

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

* maintenance: stop purging the metadata log from the default scripts

The meta_log_purge job now deletes old log days, keeping what TTLs,
lifecycle rules and replay jobs still need. fs.log.purge stays for
manual use.

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

* worker: let an idle filer_ttl rule's read position release the log

filer_ttl no longer needs events up to read_ns, and an idle rule keeps an
old ts_ns while read_ns advances, so the floor follows the later of the
two.

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

* worker: cap min_retention_days so a huge value cannot overflow

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

* worker: show the min_retention_days limit in the admin form

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

* worker: give a registered retention floor the store's filer client

A floor that only gets a context cannot tell which cluster or store it
answers for, so it cannot ask that cluster's master or read the store's
own settings. Pass the filer client the job already holds.

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

* worker: keep the log an unfinished lifecycle walk will replay

A cold-start or recovery walk that resumes across runs rewinds its
shard cursor to the walk's start minus the longest lifecycle TTL once it
completes. Until then only its walk checkpoint records that start, so a
walk running for more than a day let the purge delete the creation
events the rewound replay reads. A checkpoint with buckets done or
partly walked now holds the floor at started_ns minus that TTL.

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

* worker: hold the walk start until the checkpoint goes stale

A walk clears its checkpoint in finish() before each of its shards saves
the rewound cursor, so a purge scan that read the old shard cursor and
then the cleared checkpoint saw neither. A cleared checkpoint keeps
started_ns, so every live checkpoint now holds the floor at its start
minus the longest lifecycle TTL. A finished one stops holding once it
has not been saved for cursorStaleAfter.

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

* worker: read walk checkpoints before the shard cursors they rewind

A purge scan that read a shard cursor, then a checkpoint that a later
walk had already replaced, saw neither the earlier walk's hold nor the
rewind its shards saved. A walk replaces its checkpoint only after the
previous walk's rewind is on disk, so reading the checkpoints first
always sees one of the two.

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

* lifecycle: save a fresh walk's checkpoint at its first progress

A walk that progressed during its first save interval and then stalled
for more than a day had no checkpoint on disk, so the metadata log purge
saw nothing holding the days its completion replays. A fresh walk now
saves on its first finished entry or bucket; a resumed walk already has
its record on disk and keeps the interval.

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

* lifecycle: rewrite an unchanged shard cursor so its mtime stays fresh

A shard stuck on RETRY_LATER saved identical bytes each pass, and
SaveInsideFiler skips identical content, so the file's mtime aged past
the meta log purge's staleness cutoff while the shard still needed it.

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

* worker: keep the log day a reader from the cursor lists first

Log files are named for their flush start, so a file from just before
midnight holds events after a cursor just past it. The reader backs off
one flush interval before choosing its first day; the purge now does too.

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

* worker: stop the meta log purge on an unreadable lifecycle policy

LoadCompileInputs reports a bucket whose lifecycle XML does not parse
separately from its error, so the purge used the shorter floors and
deleted days that bucket's rules may need once the policy is fixed.

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

* worker: read shard cursors with the replay's loader in the meta log purge

A shard cursor the replay refuses, such as an empty object, decoded as
a zero position and released the purge; it now stops the run instead.

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

* worker: saturate the meta log purge's TTL plus a day

A lifecycle TTL near the largest duration wrapped negative once a day
was added, so the purge fell back to the shorter floors; the walk hold
at started_ns minus that TTL likewise dropped below zero and was lost.

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

* worker: leave disabled lifecycle rules out of the meta log purge floor

AllActivePriorStates activates every compiled rule, so a disabled rule
still held the log for its TTL, and disabling it could not release it.

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

* worker: compute the meta log purge floor in SafeKeepFrom

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

* shell: fs.log.purge keeps the logs the meta log purge floor needs unless -force

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

* shell: run the fs.log.purge floor test without a master client

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:33:26 -08:00
3836311f8f filer: end a listing at a short page, and make every store fill its pages (#13105)
* filer: end a listing at a short page from a store that fills its pages

ListEntries read a directory a page at a time and stopped at the first
empty page, so every listing the caller's limit did not cut ended with
one more scan of the store, from the last name on, that returned
nothing: two scans for a directory smaller than a page.

A page that comes back short of its limit now ends the listing when the
store says it fills its pages (the new optional FullPageListingStore).
leveldb, leveldb2, leveldb3 and TiKV do: they iterate the directory's
keys until the limit is handed over or the keys end. A store that cuts a
page of names to the limit and then drops some (the Redis stores, for a
name whose entry is gone or expired) can end a page short with names
behind it; it does not declare the interface and is asked until a page
comes back empty, as before.

TiKV's listing swallowed an iterator error while it skipped the start
name or an expired entry, and ended the page there. It returns the error
now: a page that ends short must mean the keys ended.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: see through the path translator for a store that fills its pages

A path-specific store is wrapped in FilerStorePathTranslator, which does not
implement FullPageListingStore, so its directories kept the extra empty scan.

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

* filer: keep the last listed name when a refill lists nothing

A page that lost entries to expiry is refilled from its last name. A refill
that found nothing returned an empty last name, so the next page of a store
that does not fill its pages started over at the top of the directory and
listed every entry again.

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

* filer: name the stores that fill their pages instead of an interface

A short list of store names in Filer.ListsFullPages replaces the
FullPageListingStore interface, the wrapper method and the per-store
declarations. A path translator reports its backend's name, so it needs
no unwrapping.

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

* foundationdb: read a listing in batches until it fills the page

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

* redis: fill a listing page past orphaned and expired members

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

* redis2: fill a listing page past orphaned and expired members

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

* mongodb: report a cursor error that ends a listing

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

* tarantool: fail a listing on a malformed reply

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

* filer: test the last listed name after a refill that lists nothing

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

* filer: end a listing at a short page from any store

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

* rocksdb: build the tests against the current NewFiler

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

* rocksdb: count only listed entries toward the page limit

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

* rocksdb: return the decode error instead of ending the listing

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-29 12:32:36 -08:00
Martin Lettry 5a9287642f filer: cap list snapshots at the peers' delivery watermark (#13109)
A listing's snapshot only accounted for this filer's in-flight writes. A peer on the same store can have stamped a write below it that is not committed yet; the listing misses it and the client drops its event as already listed, leaving a stale entry (a mount reads a just-closed file as empty) until the next listing.
2026-11-29 11:31:30 -08:00
f9b494c576 filer, s3: give an entry without chunks the ETag of its inline content (#13106)
* filer, s3: give an entry without chunks the ETag of its inline content

A file written through a mount stores no MD5. With no chunks either (an
empty file, or a small one kept inline) S3 answered HEAD, GET and
listings with an empty ETag, and the filer's HTTP API with the chunk
form for zero chunks, "d41d8cd98f00b204e9800998ecf8427e-0". Both now
answer with the MD5 of the inline content, which for an empty file is
what AWS gives an empty object and what the same file gets once it is
written through S3.

An entry whose size reaches past its inline content (a hole that no
chunk covers) keeps the ETag it had.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: match If-Match on an entry without chunks against its inline-content ETag

The gateway now answers the MD5 of the inline bytes for an entry with no
stored MD5 and no chunks; the filer's conditional check still saw an empty
ETag, so a PUT with If-Match set to the ETag HEAD returned failed with 412.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-29 10:32:38 -08:00
db0ec9e9b3 filer: count and time the gRPC requests by method (#13107)
* filer: count and time the gRPC requests by method

The filer's request metrics cover its HTTP API. The mounts and the S3
gateway reach it over gRPC, so on a cluster used through them the filer
reported its store operations and nothing about the requests behind
them: how many lookups, creates, renames or listings arrive, how long
each kind takes, how many end in an error.

Two metrics for the gRPC port, filled by a unary and a stream
interceptor: SeaweedFS_filer_grpc_request_total{method, code} and
SeaweedFS_filer_grpc_request_seconds{method}. A stream is counted when
it ends, and timed unless the client holds it open (a subscription, a
client stream). A lookup that finds nothing returns ErrNotFound without
a status; it is labelled NotFound rather than Unknown.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: label a call ending in its context's error as gRPC reports it

A handler that returns ctx.Err() reaches the client as Canceled or
DeadlineExceeded; status.Code labelled it Unknown.

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

* filer: count a health watch without timing it

grpc.health.v1.Health/Watch stays open until the client leaves, so its
duration is the connection's lifetime, like a subscription's.

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

* metrics: dashboard panels for the filer's gRPC requests

Calls, errors by code, and p99/p50 durations by method, in the Filer row.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-29 10:26:52 -08:00
Chris LuandClaude Opus 5.5 207aa69a9d filer: keep the metadata log in its own collection, with room reserved for it (#13102)
* filer: grow the metadata log collection on its own, fall back when it is full

metaLog.volumeGrowthCount (default 2) is sent with assigns into the
metadata log collection, so it grows by a few volumes instead of the
master's default growth. When that collection cannot take the piece, the
assign falls back to the collection the log uses without the override, so
a full cluster does not stall the log.

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

* filer: keep the metadata log in its own collection by default

metaLog.collection now defaults to filer-meta, so purging old log days
empties whole volumes instead of leaving log chunks scattered across the
default collection's volumes. Setting it to "" keeps the log in the
filer's -collection as before.

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

* volume: default -max to 10 to leave room for the metadata log collection

The default collection still grows by 7 volumes; the extra slots keep
the filer's metadata log collection (2 volumes by default) from taking
them. Go and Rust volume servers share the new default.

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

* filer: bound the meta log collection's share of the assign budget

A meta log collection that cannot grow (for example a replication the
cluster cannot place) keeps answering with retryable errors, so the
first assign used the whole shared budget and the fallback was never
tried. Give it 10s, then fall back, and skip it for a minute after a
failure instead of waiting on it at every flush.

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

* filer: name the default meta log collection so no bucket maps to it

A bucket named filer-meta mapped to the same collection, and deleting
it from the admin page or weed shell drops the collection directly at
the master, taking the metadata log with it. Bucket names cannot
contain "_", and filer group buckets map to "<group>_<bucket>".

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

* filer: clear the meta log overrides after the viper test

Setting the collection back to its default value kept an explicit
override, so the defaults test passed even without the SetDefault.

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

* filer: retry the meta log collection once its fallback also fails

The pause after a failed meta collection assign kept pieces on the shared
collection for a full minute even when that assign failed too, so meta
volumes that finished growing stayed unused while every flush failed.

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

* filer: pick a default meta log collection no grouped bucket maps to

Filer group "_filer" with bucket "meta" maps to "_filer_meta". The
default now keeps its only "_" in front, and the test checks every
group and bucket split of it.

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

* filer: default the meta log collection to _meta

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

* filer: keep the default meta log collection on bucket delete

A filer that logs elsewhere did not treat _meta as reserved, so deleting a
bucket a storage rule maps to _meta dropped the collection other filers
write their logs to.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 10:01:16 -08:00
036d1117d2 fix(s3api): refuse a "dir/" PUT body larger than a directory marker holds (#13104)
* s3api: refuse a "dir/" PUT body larger than a directory marker holds
A key ending in "/" whose body had no Content-Length took the marker
branch, was read whole into memory and stored inline in the directory
entry. One declaring more than 1024 bytes took the regular path, which
wrote it to the object "dir/dir".
Both now get EntityTooLarge: a declared length is checked before the
body is read, an unknown one is read at most 1025 bytes. An aws-chunked
body counts by its decoded length.

* s3api: size an aws-chunked "dir/" body without a decoded length as unknown

Without X-Amz-Decoded-Content-Length the marker check fell back to the
encoded Content-Length, whose chunk framing pushed a marker of up to 1024
bytes past the limit. Such a body is now read through the limit instead.

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

* s3api: keep a "dir/" body past a marker as a version in a versioned bucket

A versioning-enabled bucket stores a trailing-slash key larger than a
marker as a versioned object under its .versions directory, so refusing
it broke that write. Only the unversioned and suspended paths, which
would land on "dir/dir", refuse it now.

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

* s3api: recheck a large "dir/" PUT against the versioning state its write uses

The size check and the write path each read the versioning state, so
versioning suspended in between sent the body to the suspended path,
which writes "dir/dir".

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-29 09:22:35 -08:00
Chris LuandClaude Opus 5.5 7092edfb06 webhook: keep the bearer token on the configured endpoint's host (#13103)
* webhook: send the bearer token only to the configured endpoint's host

A redirect to another host or port, or from https to http, now gets the
request without the Authorization header.

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

* webhook: test the token scope across redirects

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

* webhook: compare effective ports when scoping the token

An omitted default port and an explicit :443 or :80 are the same
endpoint; http on port 80 upgrading to https on 443 keeps the token.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:17:34 -08:00
Chris LuandClaude Opus 5.5 4ff3147ee5 worker: filer_ttl job removes expired rows from stores without native TTL (#13084)
* worker: add a filer_ttl job that walks filer.conf TTL paths

A filer store without native TTL keeps the rows of expired entries until
something looks them up or lists their directory. The job lists every
TTL path subtree once per filer store, so the filer drops the expired
rows it meets.

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

* worker: register the filer_ttl job in the lifecycle lane

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

* filer: re-check an expired entry under its path lock before a listing deletes it

A listing deleted the expired entries it collected by path after the page
was read, so a write that replaced one in between lost its new row. The
delete now re-reads the row under the lock writers take, and in one
conflict-checked transaction on stores that refuse a commit over another
writer's change; anything but a still-expired row is kept.

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

* worker: read each filer store's own filer.conf, chunk-backed included

Filers with separate stores keep separate filer.conf files, so one
filer's rules could hide another store's TTL paths. A config stored in
chunks read as empty. An unreadable config now fails the detection
instead of reading as no rules.

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

* command: count filer_ttl among the mini default job types

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

* worker: resume an unfinished filer_ttl walk from its checkpoint

The walk position is saved in the job's filer store every 30s and at
the first failure, keyed by store signature, and cleared when a pass
completes. The next run skips the prefixes and subtrees already walked,
unless the TTL prefix set changed or the pass is over 7 days old.

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

* worker: save the filer_ttl checkpoint as soon as a walk fails

The first failure froze the checkpoint but only the end of the run saved it,
so a worker killed while walking later prefixes lost it. stop now saves it at
once; the end of the run saves again only if that save failed.

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

* worker: keep a path TTL rule from expiring the filer_ttl checkpoint

A filer.conf TTL rule over /etc/ gave the checkpoint that rule's TTL, so an
interrupted pass could lose its record long before checkpointMaxAge. The
checkpoint is now written with its own TTL of checkpointMaxAge, which the
filer keeps instead of the rule's.

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

* worker: remove a filer_ttl checkpoint the new pass will not resume from

An overwrite keeps the stored entry's Crtime, and the checkpoint's TTL counts
from it, so a pass that replaced a rejected record could lose its own record
before checkpointMaxAge. load now deletes a record it rejects, and the new
pass creates a fresh one.

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

* worker: expire filer_ttl entries from metadata events per TTL rule

Each run replays every filer.conf TTL rule's metadata events from that
rule's cursor up to the run start, and looks up each entry whose TTL has
passed so the filer removes its row. The first entry not yet due holds the
rule's cursor, so a later run replays it. A rule without a cursor, or
whose TTL changed, is listed once to reach rows older than its replay
window. The periodic full walk and its checkpoint are gone.

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

* filer: re-check an S3-expired entry under its path lock before a listing deletes it

A listing deleted an S3-expired object by the row it had read, so an upload
that replaced it after the page was read was removed. The delete now re-reads
the row under the path lock and removes it only if it is still S3-expired.

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

* filer: remove an expired row a lookup meets in a conflict-checked transaction

A lookup that met an expired row deleted it by path, so a replacement written
through another filer between the read and the delete was lost, even on
stores that refuse conflicting commits; a failed delete was hidden behind not
found. The lookup now re-reads and deletes through deleteIfExpired and returns
the delete error.

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

* worker: keep a failed filer_ttl lookup that ties a done event

When the first event at a timestamp was done and the second one's lookup
failed, the cursor already stood at that timestamp, so the retry subscribed
after it and skipped the failed event. A failed lookup now holds the cursor
below a tie, as a waiting entry does.

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

* worker: hold a filer_ttl event whose entry the filer still serves

A lookup that returned the live entry counted as done, so when the worker's
clock ran ahead of the filer's near the deadline the event was skipped and
the row stayed. An entry the filer still serves with the same deadline now
holds the cursor like one not yet due.

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

* worker: keep a path TTL rule from expiring the filer_ttl cursors

The cursors were written without a TTL, so a filer.conf TTL rule covering
/etc/seaweedfs/filer_ttl gave them the rule's TTL and every rule was listed
again once they expired. When a rule covers them they are now written with a
TTL of their own, which the filer keeps.

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

* worker: list a filer_ttl rule again for a live entry its replay cannot reach

A new rule nested under a longer one started its replay one TTL back, so a
live entry the enclosing rule had stamped with its longer TTL, written before
that, was in neither rule's replay: the nested rule now owns it and the
enclosing rule skips it. The listing of a new rule now records the earliest
deadline of such entries, and the rule is listed again then.

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

* worker: hand a removed filer_ttl rule's replay to the rule enclosing it

When a nested rule was removed, its entries became the enclosing rule's, but
that rule's cursor could already be past their events, so they were never
replayed. The enclosing rule now replays from the earlier of both cursors.

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

* worker: list a filer_ttl rule whose unfinished events the filer no longer keeps

When fs.log.purge removed the event of an entry still waiting for its TTL,
the rule's cursor matched, so the rule was never listed and the replay never
met the entry again. A rule whose cursor is older than the oldest kept
metadata log is now listed, and its cursor moves to that log. The cursor also
records how far a replay read with nothing left waiting, so a quiet rule is
not listed just because old logs were purged.

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

* worker: leave S3 lifecycle expiry to the s3_lifecycle job in filer_ttl

An entry whose TTL an S3 lifecycle rule set carries the S3 expiry flag;
s3_lifecycle evaluates and removes it. filer_ttl no longer looks such
entries up, and their deadline no longer holds a TTL rule's cursor.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:20:03 -08:00
github-actions[bot] 0ea67a4438 docs: regenerate star history chart 2026-11-29 00:36:56 +00:00
Chris LuandClaude Opus 5.5 663af6fccb mount: review fixes for the metadata follow shutdown (on top of #13092) (#13097)
* mount: drop the issue number from the shutdown test comment

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

* mount: end the filer walk when the consumer stopped following

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

* pb: end the follow when a retried event reports a stop

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

* mount: check the subscriber is gone before the late event can end it

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

* mount: never retry a filer call whose consumer stopped following

The walk already stopped on pb.ErrStopFollowing, but RetryOnError still
classified the wrapped error by its cause, so a transport-looking cause
reran the whole filer walk.

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

* pb: keep the cursor behind an event whose retry the follow ended

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

* mount: close the meta cache after the follow-cancel test joins it

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:10:26 -08:00
Konstantin Lebedevandwhitefox 63ab6c6190 mount: stop the metadata follow before closing the meta cache (#13092)
* test(mount): reproduce the #5289 mount abort on a late metadata event

A metadata event that arrives after metaCache.Shutdown() reaches
glog.Fatalf through FatalOnError, so the mount dumps every goroutine and
exits 255 instead of unmounting cleanly — the signature reported in
issue #5289, still reachable on current master.

The subscriber has no way to stop: its context is rooted at
context.Background() and util.RetryUntil always retries, while unmount
closes the cache underneath it.

glog.Fatalf cannot be intercepted from another package (glog's
logExitFunc is unexported), so the reproduction runs the mount in a child
process and reads its exit code.

* mount,pb: stop following metadata when the cache closes

The mount follows metadata with FatalOnError, so an event that arrives
after metaCache.Shutdown() — which unmount guarantees, since the
subscriber is never stopped — was logged as a fatal and aborted the
process with a goroutine dump.

Report a closed cache as pb.ErrStopFollowing, a class the follow loop
ends on instead of routing through the per-event error modes. It is not
a failed event but the end of the subscription: no later event can land
either. SubscribeMetaEvents then leaves its retry loop rather than
reconnecting onto a store that no longer exists.

Also export the meta_cache sentinel as ErrClosed so consumers can tell a
closed cache from a storage failure.

* mount: end the metadata follow before closing the meta cache

The subscription goroutine had no owner: its context was rooted at
context.Background() and util.RetryUntil retried forever, while unmount
closed the cache underneath it. Every unmount left a window in which a
filer event landed on a closed store, and the mount survived it only
because the previous commit demoted that error.

Give the follow a context the mount owns, and stop it — cancel, then
join — before metaCache.Shutdown() in both teardown paths. MetadataFollowOption
takes a ParentContext so cancelling the caller ends the stream, which is
the ordering the filer already got in #11363 and #11663; the mount had no
equivalent.

Verified that the new assertion catches the ordering on its own: making
stopMetadataFollow a no-op fails it with the subscriber still running,
even with the fatal path already demoted.

* mount,pb: make a cancelled follow a stop, and cover the new seams

Review findings on the previous commits:

Cancelling the follow context surfaced as a bare gRPC Canceled, which
matched neither terminal condition, so every clean unmount logged an
ERROR, ran the retry callback — which wipes every cached listing on the
assumption that events were missed — and slept a second before the loop
stopped itself. Test the context instead of the error text.

Also assert the two new weed/pb seams where they are defined rather than
only through a mount exit code: ErrStopFollowing ends the stream without
reaching the per-event error modes and leaves the cursor behind the
event, and a cancelled ParentContext ends the stream. Publishing the
cancel handle and bumping the WaitGroup happen under one lock, so a
start racing a stop cannot let the join report success too early.

All four new tests were mutation-checked: dropping the early return,
ignoring ParentContext, removing stopMetadataFollow from ClearCacheDir,
and making stopMetadataFollow a no-op each fail their own test.

---------

Co-authored-by: whitefox <whitefox@mayflower.work>
2026-11-28 16:04:59 -08:00
Chris LuandClaude Opus 5.5 a7cc8fb767 filer, docs: 503 in the upload wait flag help; Yandex restart after a token refresh (#13096)
* filer: flag help names the 503 an upload gets after the wait

The filer answers an upload that found no slot within
-inflightUploadDataTimeout with 503 and Retry-After: 1, not 429.

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

* docs: a restart after a Yandex token refresh may need a new token

The client keeps the refresh token Yandex returns in memory only, and
Yandex does not say whether the stored one survives the rotation, so the
doc no longer promises that a restart keeps working.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:34:59 -08:00
ef0967bead filer: read the entry path once per write (#13090)
* filer: read the entry path once per write

A create looks the path up to decide what it makes of the entry: the inode and
crtime to keep, the chunks the write leaves behind, the old side of the metadata
event. The store wrapper looked the same path up again, in
handleUpdateToHardLinks, to learn the hard link the name carried before. Both
reads happen under the same per-path lock, a moment apart, and for a file written
without a hard link the second one decides nothing at all: its result is
discarded. An overwrite pays for it twice over, because that read decodes the row
being replaced -- gunzip included above CountEntryChunksForGzip -- and it is the
row the create already holds.

Neither read shows up as a second find in the store metrics: the wrapper's goes
to the actual store, and FilerStoreCounter counts only FilerStoreWrapper.FindEntry.

The wrapper now takes the caller's word. InsertEntryReplaces and
UpdateEntryReplaces carry the entry a caller read to handleUpdateToHardLinks,
which keeps to it instead of reading the path again. An insert whose lookup found
the path empty goes the way #13006 opened with InsertEntryKnownAbsent, which
rename alone used.

Which word may be taken is the delicate part, so Filer.findEntry reports whether
its answer is what the store holds at the path:

- a lazy fetch from a remote mount serves an object the store does not have and
  writes nothing to it, so it says nothing about the row there;
- inside a store transaction a lookup hides an expired S3 entry whose row the
  transaction keeps until the commit, and a write replacing it still owes that
  entry its hard link -- which is why FindEntryForOverwrite exists;
- where the expiry check deleted the row, the delete dropped its link already, so
  an answer of "empty" is honest.

The write also reads the path itself whenever there is a link to take off, for
two reasons. A file with a hard link has its record changed again when the store
refused a commit (changeLinkRecord runs its change up to linkRecordAttempts
times), and each run must judge the name as the store holds it by then. And a row
that carries a link is the row whose link this write drops: plain creates are not
routed to the write owner, so another filer may have replaced the same name
already and dropped that link, and dropping it twice deletes the record under the
file's remaining names. What is trusted is the case with nothing to decide --
no link on either side -- which is an ordinary file write, since a mount makes a
link id only when a file is linked or copied.

The HTTP append path read the entry three times: once to merge with it, once to
prove it had not changed while the chunks were uploaded, and once in the create.
The create takes the recheck's entry now.

A 20-chunk entry on leveldb2 goes from 343 to 286 allocs/op and from 44.6 to
38.3 KiB/op per overwrite, the difference being the decode of the replaced row.
Where the store is reached over the network, the read saved is a round trip per
write.

Tests count the reads one write makes at the store, pin that a dropped link is
dropped once against a row another filer has already replaced, and keep the
create using the entry it is handed. #9645's own guard expected the create's
lookup to be what separates passing existing from passing nil; both are one read
now, so it requires one read either way and checks the crtime came from the entry
passed in.

Issue #5067.

Review of the first version caught one more case. The known-absent shortcut must
not take an entry that carries a link: InsertEntryKnownAbsent counts the name as
joining without reading it, so another filer storing that name for the same link
between this lookup and the write would have it counted twice, and the count
would run one above the names. The regular insert reads the name inside the
change of the record. CreateEntry and ReplaceFileForRename keep the write's own
read for a linked entry; TestNewLinkedNameStillReadsThePath pins it.

* filer: drop issue numbers from the write-read test comments

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

* filer: say a plain-over-plain write can miss a link stored after the read

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

---------

Co-authored-by: whitefox <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:33:51 -08:00
Chris LuandClaude Opus 5.5 e7cbfdcc44 s3: blame no filer for a deadline gRPC reports before ctx.Err() (#13098)
The filer walk told the caller's expiry apart from a filer failure by
ctx.Err() alone. A server-side DeadlineExceeded can reach the client
before the context's own timer runs, so the walk recorded a failure
against each filer and moved on with no budget left, the same race
LookupVolumeIds already guards against.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:31:57 -08:00
5b7e2d9e9e fix: retain released lock version watermarks (#13083)
* fix: retain released lock version watermarks

* fix(lock_manager): scope release records to lease identities

Keep a stable acquisition ID in opaque renewal tokens so release history cannot reject a valid lease from a different primary when generation counters overlap. Preserve earlier releases across new acquisitions and ownership eviction.

Carry the maximum lease expiry with releases, prevent renewals from shortening that bound, reject expired inserts, and reclaim release records after expiry. Track replication and handoff before sending copies so local-only leases need no release records.

Add regressions for fresh-primary failover, equal and lower generation counters, reordered releases and renewals, bounded retention, local-only workloads, ownership eviction, legacy release metadata, and gRPC release handling.

* lock_manager: name the release replay tests after the behavior they check

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

* fix(lock_manager): serialize lease handoff with local mutations

Hold per-key mutation admission through a fresh lease snapshot, the transfer RPC, and source demotion or removal. A release that wins first suppresses the transfer; a release arriving during handoff waits and is forwarded to the new primary afterward.

Keep incoming replication outside the gate to avoid callback cycles. Retain source authority on transfer errors and apply transfer completion only to the lease that was sent.

Add real gRPC regressions for releases during both handoff branches and replay after release, plus coverage for fresh snapshots, transfer errors, unrelated keys, and replacement leases.

* fix(lock_manager): retry handoffs without retaining renewal authority

Deliver a source-held lease to the current owner before forwarding renewal or unlock. Freeze local authority before sending a transfer, including when the receiver may have committed despite an RPC error. Retry without requiring a membership change, with backoff and shutdown cancellation.

Recheck ownership after a background handoff and preserve the copy until the latest owner receives it. Replicate the effective installed expiry instead of a shorter transfer input.

Replace timing assumptions with a same-key admission contention hook. Cover pre-handoff releases, lost acknowledgements, retry cleanup, owner changes, and effective expiry. Document why identityless legacy releases cannot safely delete slash-format leases with overlapping generation counters.

* test(filer): set up DLM handoff before the peer lock transfer check

Ring-change transfers now go through Dlm.TransferFn, which
SetupDlmReplication installs; without it the lock stays pending on the
old filer and the peer-auth transfer test cannot see it move.

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

* test(lock_manager): bound the handoff and unlock completion waits

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

* test(filer): give the handoff retry expiry subtest a one-second lease

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

* fix(lock_manager): serve lock and unlock here when a handoff ends with this node as primary

transferToOwnerLocked now returns the primary it observed after the
handoff. LockWithTimeout and Unlock redirected to the primary read before
the transfer, so a ring that moved back during the handoff sent the client
away from the node that holds the lease.

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

* test(lock_manager): bound the admission probes in the handoff tests

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

* fix(filer): keep the holder's renew token while its lock handoff is pending

A failed transfer RPC or a frozen lease answered the lock request with an
error and an empty RenewToken. The client treats that as a rejection and
drops its token, so it can no longer renew the lease once the handoff
completes. Report transfer failures as LockHandoffPending and echo the
caller's token for that error.

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

* refactor(lock_manager): return lease expiry from Lock, Unlock and InsertLock

The DLM was the only production caller of these methods and used private
twins (lockWithExpiry, unlock, insertLock) to get the effective expiry.
Return it from the public methods instead and drop the twins.

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

* refactor(lock_manager): share the copy acceptance checks between InsertLock and InsertBackupLock

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

* refactor(lock_manager): drive handoff tests through TransferLockToOwner

TransferLock and its helpers were only reachable from tests. Remove them
so the tests exercise the production handoff path.

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

* refactor(lock_manager): share the routing and handoff prologue of LockWithTimeout and Unlock

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

---------

Co-authored-by: Master <Master@node0.8m510.lpad-pg0.utah.cloudlab.us>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:31:06 -08:00
Chris LuandClaude Opus 5.5 889af96779 mount: store a truncate through an open handle before answering (#13089)
* mount: store a truncate through an open handle before answering

SetAttr with a new size and an open handle only marked the handle dirty,
so the size reached the filer at the next flush or release. A mount that
died before then brought the old size and data back, and an NFS export
answered SETATTR, which no COMMIT follows, with a size it had not stored.
Flush the handle once the entry locks are released, as a truncate
without a handle saves the entry. The writeback cache still defers it,
except under an NFS export.

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

* mount: test that a truncate through an open handle is stored

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

* mount: refuse a truncate up past the quota before the file grows

The size is now stored before SetAttr answers, so a growth the quota
cannot take was installed and charged, then refused by the flush,
leaving the grown size on the handle. Check the growth first.

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

* mount: compare a truncate's growth with the quota headroom

The used size, the uncommitted writes and the growth were summed in
int64, so a truncate up to near 2^63 wrapped the sum negative and passed
the check. Take the growth as uint64 and compare it with what is left.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:53:42 -08:00
Chris LuandClaude Opus 5.5 6b2ad112a8 volume: check the collection name in handlers that build file paths from it (#13087)
* volume: check the collection name in handlers that build file paths from it

AllocateVolume, VolumeMount, VolumeCopy and the EC rebuild, copy,
delete, mount and to-volume handlers joined the request collection into
volume file paths, so a collection such as "../x" reached files outside
the volume directory. They now apply checkVolumeCollection, as CopyFile
and ReceiveFile already do.

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

* seaweed-volume: check the collection name in handlers that build file paths from it

Mirrors the Go volume server: allocate_volume, volume_mount, volume_copy
and the EC rebuild, copy, delete, mount and to-volume handlers apply
check_volume_collection, as copy_file and receive_file already do.

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

* volume: check the source's collection before VolumeCopy builds paths from it

VolumeCopy names the destination files after the collection the source
reports in ReadVolumeFileStatus, so that value needs the same check as
the request's collection.

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

* seaweed-volume: check the source's collection before volume_copy builds paths from it

Mirrors the Go VolumeCopy: the collection the source reports in
ReadVolumeFileStatus names the destination files, so it gets
check_volume_collection too.

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

* volume: stub the source in the VolumeCopy source collection test

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

* seaweed-volume: keep check_volume_collection's doc comment as on master

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:50:53 -08:00
Chris LuandClaude Opus 5.5 16412c374a test(filer): wait for the fake master's volume location in the manifest reuse tests (#13086)
The master client marks a master current as soon as the stream opens and
applies the first VolumeLocation afterwards, so GetLocations right after
GetMaster can miss volume 1 on a loaded runner.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:49:46 -08:00
Chris LuandClaude Opus 5.5 efcee4a186 test(volume_server): wait out a server's disk I/O before calling its SIGINT exit a hang (#13085)
* test(volume_server): wait out a server's disk I/O before calling its SIGINT exit a hang

stopProcess gave every server 10s to exit after SIGINT. On a CI runner
with a busy disk, the fsync in volume close can take longer than that:
the server is in uninterruptible sleep, not hung. Sample the server's
threads from /proc while waiting. Once one has been in D state, allow
up to a minute. A server that never touched the disk still fails at
10s, and the failure now lists its threads' states and wait channels.

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

* test(volume_server): wait for the sleep child before checking its stop

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

* test(volume_server): reap the SIGINT-ignoring child if it never starts sleeping

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:29:59 -08:00
Chris LuandClaude Opus 5.5 e6aed012f8 filer: pass cutToSpan in the manifest reuse test (#13082)
ResolveChunkManifest gained a cutToSpan argument while this test was in
flight, so master stopped compiling weed/server. The test compares chunk
lists, so it resolves every referenced chunk.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:04:12 -08:00
Chris LuandClaude Opus 5.5 4cf028f683 grafana: show the first EC shard copy failure of each series (#13071)
* grafana: count the failure that creates an EC shard copy failure series

The EC shard copy failure counter exports a collection and reason pair
only once a copy fails, so rate() saw that first value as a baseline and
never showed it. The panel now shows failures per rate interval and adds
the earliest value of a series that did not exist one interval ago.

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

* grafana: count a new EC shard copy failure series from its last value

increase() extrapolates the increments of a series that appears inside
the window, and an instant offset selector loses an old series across a
scrape gap, so the panel could add a whole counter as new failures.
A series with no sample in the day before the window now shows its last
value; every other series shows increase().

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

* grafana: count the first EC shard copy failure after a restart

A restarted volume server exports a failure series again only at its first
failure, so when the same labels had a sample earlier in the day the window
held only the new counter's samples and increase() missed that failure. A
series whose lowest value in the window is below its last value before the
window has been reset since, and now shows its last value; a series back
from a scrape gap keeps its value and still uses increase().

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:58:37 -08:00
a9fda6b50f filer clients: authenticate filer gRPC calls with per-call admin tokens (#13039)
* Add per-call filer authentication sources and pooled client wrappers

* Authenticate gateway filer calls with per-call admin tokens

* Authenticate shell admin and synchronization filer calls

* Authenticate workers MQ and remaining filer client paths

* Cache filer client signing keys and sign subscriptions with the shared key

Re-reading security.toml on every filer RPC cost about 125us against 8us for
signing. Keep the keys for up to a second, re-reading at once when a WEED_
override or the configuration directory changes. When the file exists but
cannot be read, keep the last keys read, else the startup keys, as
FilerAdminKeys does, so a process without a key stays tokenless. Metadata
subscriptions prefer the shared key, as filer peers do, because older filers
verify subscription admin tokens only with it.

* Authenticate admin-script, maintenance and filer.conf shell paths

Plugin worker admin scripts and master maintenance scripts build their own
shell options and carried no filer token source; fs.configure and
s3.bucket.quota.check read filer.conf without it.

* filer.cat: report a failed read; isolate key overrides in the admin-script test

filer.cat ignored the error from its filer call and exited successfully,
leaving a truncated -output file. Report the error and exit with failure.
The admin-script token test now clears the WEED_ signing-key overrides,
which take precedence over security.toml.

* security: refuse gRPC keys too short to sign; query engine uses client TLS

Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The
startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key,
and filer client token sources check the keys they read, so a reloaded or
per-endpoint security file with a short key is refused instead of
panicking when the next RPC signs.

The query engine's broker client dialed every master, filer and broker in
plaintext, so the admin token it now sends could cross the network in the
clear. It dials with the grpc.client TLS settings instead, and weed-sql
loads security.toml as weed-db does.

* security: per-endpoint admin tokens ignore WEED_ key overrides

FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and
WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with
-a.security and -b.security signed both clusters' admin tokens with the
one key, handing each cluster a token valid on the other. A per-endpoint
file now supplies its own keys only.

* weed-sql, weed-db: refuse to start on an unreadable security.toml

Both only warned when security.toml was present but could not be read or
parsed. They then dialed without the grpc.client TLS settings while the
filer token source could still sign admin tokens from WEED_ environment
keys, so the tokens could travel in plaintext. They now exit with an
error that does not quote the file; a missing file is still fine.

* pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients

Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the
existing helpers instead of keeping two names for each. Callers without a
token source pass nil.

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

* util: return the read error from ReadConfiguration

Fold ReadConfigurationWithError into ReadConfiguration. The error is
returned and not logged, since parser errors can quote values; the
existing reload callers already warn when no file was read.

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

* security: keep the test-only filerAdminToken helper in the test

It had no production caller. The test helper now resolves keys through
filerClientKeysFrom, as the token sources do.

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

* util: read security.toml once in LoadSecurityConfigurationOrError

It validated the file, then merged it with a second read whose failure
was ignored and whose parser error was logged. It now merges with one
read and logs nothing from the parser. Viper's search also treats a
directory the process cannot search as holding no file; a candidate
that cannot be checked for lack of permission is now refused too.

* security: verify admin subscription tokens with the gRPC clock leeway

CheckGrpcMetadataSubscription checked admin tokens strictly, while unary
filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second
client admin tokens, a subscriber whose clock trailed the filer's by more
than ten seconds was refused with a matching key. It now takes the leeway,
and the filer passes its configured one. The leeway check moves from the
server package to security.IsFilerAdminTokenWithLeeway so both use it.

* util: start without security.toml only when every candidate is confirmed absent

A candidate whose check fails for any reason other than not existing,
such as a symlink loop, is refused like one the process cannot search.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:59 -08:00
f6b130f61c filer: keep a stored manifest when a commit lists its chunks flat (#13051)
* filer: keep a stored manifest when a commit lists its chunks flat

Since #12462 the filer folds a commit's small chunks into manifests
256 at a time, whichever client sent them. A client that keeps its own
chunk list sends every chunk it wrote on each flush and does not take
the folded list back. The Hadoop client is one: SeaweedOutputStream's
hflush and hsync send CreateEntry with the whole list, which the client
folds itself only past 1000 chunks. Once 256 small chunks have piled
up, each flush makes the filer fold the same chunks again into a new
manifest blob, and the manifest of the entry it replaces is deleted:
up to three manifests written and three deleted per flush.

cleanupChunks now puts back, after compacting the list and before
folding it, each manifest of the replaced entry whose chunks the list
holds flat and unchanged (filer.ReuseStoredManifests). The manifest
must span exactly the chunks it holds. A manifest the commit lists
itself, one that cannot be read, one with a chunk changed or missing,
and a hard-linked file's are left alone. MinusChunks counts the kept
manifests as listed, so the commit does not delete them.

That entry has to be the one the commit replaces and deletes against.
UpdateEntry already prepares its chunks under the path lock from
the entry it read there. CreateEntry folded before taking the lock;
it now prepares the chunks under the lock, after its precondition
checks, and reads the replaced entry there when the request has at
least 256 chunks.  filer.CreateEntry still deletes the chunks of the
replaced entry that the new list drops, which no longer include the
kept manifests.

TestCommitKeepsTheStoredManifestOfChunksListedFlat (create and update):
the second commit of the same list plus one chunk keeps the manifest,
writes no blob and queues nothing for deletion. It fails on master.

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

* filer: take the replaced entry in cleanupChunks instead of a cleanupChunksReplacing twin

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

* filer: reuse a stored manifest only for its chunks listed in its order

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

* filer: keep the stored entry's manifests out of a refused update's cleanup

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

* filer: do not reuse a manifest whose chunk ties with a chunk outside it

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

* filer: drop a pull request number from a reuse test comment

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

* filer: look up same-timestamp chunks by index in the manifest reuse overlap check

The tie check rescanned the whole commit for every candidate manifest,
so a 102,400-chunk commit with 400 matching manifests ran 40M map
lookups under the path lock. Index the commit's positions by
ModifiedTsNs once and check only the positions sharing a held chunk's
timestamp.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-27 18:53:35 -08:00
Chris LuandClaude Opus 5.5 3880e7ee5a volume(rs): keep the needle_not_found doc comment on its function (#13070)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:13 -08:00
c7fc40c76c filer, mount: read a manifest's chunks only within its span (#13048)
* filer, mount: read a manifest's chunks only within its span

Until #13042, a truncate through a manifest only shortened the manifest
chunk; the chunks it holds stayed whole. Reads resolve those chunks at
their own offsets and sizes, so once such a file grows over the cut again
without writing it, by an extending truncate or a write past the end, the
cut bytes come back where zeros belong. #13042 keeps new truncates from
leaving such manifests, but files a mount truncated between #12462 and
#13042 still have them.

Reproduced with weed mount on a local cluster: a mount from before #13042
appends 700 lines with one close() each, so the first 256 fold into a
manifest, and truncates the file to 100 lines; a mount from current master
then extends it past its old end with ftruncate. The extended range read
8,580 bytes of the cut lines instead of zeros, through that mount and
through the filer.

Reads now cut each manifest's chunks to the manifest's span:
ResolveChunkManifestForRead, used by NonOverlappingVisibleIntervals (filer
and S3 streaming, WebDAV, the mount's merge reads), the S3 ranged reads and
the mount's peer reads, and ChunkGroup for the mount's reads. A manifest
made by MaybeManifestize spans its chunks exactly, so only shortened ones
change. ResolveChunkManifest still returns the chunks whole: MinusChunks,
deletions and the other chunk-list comparisons need every chunk a manifest
references, or the chunks past the cut would never be deleted.

* sw-client: read a manifest's chunks only within its span

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

* java client: read a manifest's chunks only within its span

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

* filer: drop PR numbers from the manifest span comments

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

* filer: fold ResolveChunkManifestForRead into ResolveChunkManifest

ResolveChunkManifest takes cutToSpan: the read paths pass true, the
deletion and chunk-list comparison paths pass false.

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

* s3api: cut manifests to their span when flattening an object's chunks

A full-object SSE GET, CopyObject and UploadPartCopy flatten the
source's manifests into a plain chunk list, which drops each manifest's
span, so the chunks a truncate left past a shortened manifest came back
as object data.

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

* shell: purge a volume.fsck path only for chunks within a manifest's span

A chunk past a shortened manifest's span is still referenced but never
read, so a missing volume under it loses nothing. The purge decision now
uses the span-cut chunks while the inventory keeps every reference.

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

* shell: cut manifests to their span in fs.distribute_chunks

The entry is rewritten with the resolved chunks as a flat list or a new
manifest that spans them, so chunks past a shortened manifest's span
became readable again. The filer's update still deletes them, since it
compares against the old entry's uncut chunks.

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

* shell: verify only the chunks within a manifest's span in fs.verify

A chunk past a shortened manifest's span is never read, so a missing
needle under it failed the entry and, with -pruneEntries, deleted a file
whose readable bytes were intact.

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

* shell: mark the chunks past a manifest's span instead of allowing the visible ones

The purge gate now skips only the resolved chunks that the span cut drops,
so chunks that come from outside the manifests keep their purge behavior.

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

* shell: skip the purge for a missing past-span chunk on a listed volume

volume.fsck -findMissingChunksInFiler queued a path for deletion when a
listed volume's index lacked any chunk the uncut inventory recorded,
including a chunk past a shortened manifest's span that no read reaches.
Record those chunks per path during the filer walk and let only a missing
chunk within the span queue the purge. The path is still reported.

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-27 18:51:15 -08:00
c812a37c83 feat(grpc): serve grpc.health.v1 on every server, add health-check-only client certificates (#13049)
* feat(grpc): serve grpc.health.v1 on every server, add health-check-only client certificates

Every gRPC server built by pb.NewGrpcServer now answers the standard
grpc.health.v1.Health service, so blackbox_exporter's grpc prober,
grpc_health_probe and Kubernetes grpc probes can check SeaweedFS ports.
Check("") reports the server; Check(<service>) reports whether that
service is registered on the port.

grpc.health_check_commonNames lists client certificate common names that
pass the mTLS handshake on every component but may call only the health
service; any other RPC gets PermissionDenied. A monitoring probe can then
check the port and its certificate without a credential that opens the
whole gRPC API.

Fixes #5012

* seaweed-volume: serve grpc.health.v1 on the gRPC port

Mirrors pb.NewGrpcServer registering the health service on every Go
server: the whole server, the volume service and the health service
answer SERVING, other names NotFound.

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

* seaweed-volume: confine grpc.health_check_commonNames to the health service

Mirrors the Go healthCheckOnlyTap: a client certificate whose common name
is on [grpc] health_check_commonNames passes the handshake even when
allowed_commonNames is set, and any RPC outside grpc.health.v1.Health is
refused with PermissionDenied. WEED_GRPC_HEALTH_CHECK_COMMONNAMES
overrides the key like the other WEED_GRPC_ settings.

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

* seaweed-volume: end health watches when the gRPC server shuts down

Graceful shutdown waits for open streams, so a client holding a health
Watch kept the volume server from reaching store close. Clearing the
reported statuses ends every Watch stream once the shutdown signal fires.

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

* pb: end health watches before gRPC graceful stop

GracefulStop waits on open streams, and Watch held its stream until the
client left, so a connected probe kept volume and admin worker shutdown
from finishing and made filer and S3 wait out their drain timeout.
StopHealthWatches ends those streams; every GracefulStop path calls it
first.

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

* scaffold: point mTLS health probes at an exec probe

The built-in Kubernetes grpc probe sends no client certificate, so it
cannot pass an mTLS port; grpc_health_probe run as an exec probe can.

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-27 18:50:34 -08:00
Chris LuandClaude Opus 5.5 6c54935723 java client, hdfs3: authenticate to a filer that requires filer JWT or Basic Auth (#13053)
* java client: read security.toml without an [https.client] section

toml.getBoolean returns null for a missing key, so unboxing it threw a
NullPointerException in the static initializer and every FilerClient
failed with ExceptionInInitializerError when security.toml held only
other sections, such as [grpc] or [jwt.filer_signing].

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

* java client: sign filer JWTs and hold [filer.basic_auth] credentials

FilerSecurityContext reads jwt.filer_signing.key, jwt.filer_signing.read.key
(with their expires_after_seconds, defaulting to 10 and 60 like the Go
clients) and [filer.basic_auth] from security.toml, with setters to set
them in code. getFilerAuthorizationHeaderValue returns the credential for a
request to the filer's HTTP port: an HS256 token for the access level,
minted like security.GenJwtForFilerServer, else the filer Basic Auth, else
the existing [basic_auth] value.

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

* java client: send the filer credential on filer-proxied chunk requests

With volume server access through the filer proxy, chunk reads and writes
address the filer's HTTP port, which checks the filer JWT or Basic Auth
before proxying. The write sent the AssignVolume token instead, which the
filer rejects with "wrong jwt", and reads sent no filer token. Send the
filer credential on proxy URLs only; direct and publicUrl volume requests
keep the volume token. With no filer credential configured, the old
headers are sent unchanged.

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

* hdfs3: take filer JWT keys and Basic Auth from the Hadoop configuration

fs.seaweed.filer.jwt.signing.key, fs.seaweed.filer.jwt.signing.read.key
(and their expires.after.seconds) and fs.seaweed.filer.basic.auth.user /
password override security.toml. The secrets are read with
Configuration.getPassword, so a Hadoop credential provider can hold them.

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

* hdfs3: document a filer secured with JWT or Basic Auth

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

* java client: fail a chunk fetch that answers a non-2xx status

doFetchOneFullChunkData returned the response body whatever the status,
so a 401 "wrong jwt" or a 404 JSON error was taken as chunk data and
cached. Throw instead, so the fetch tries the next location and reports
the error.

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

* java client, hdfs3: accept filer Basic Auth with an empty user

The filer turns Basic Auth on whenever the password is set, user empty or
not. The client dropped credentials without a user, so a password-only
filer refused every proxied chunk request.

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

* hdfs3: point the secured filer docs at [https.client]

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

* java client, hdfs3: keep filer credentials on each filer client

The filer JWT keys and [filer.basic_auth] lived in process-wide fields,
so a second filesystem with its own fs.seaweed.filer.* options replaced
the credentials of the first one, and a filesystem without options
inherited the previous overrides. Each FilerClient now copies the
security.toml values into its own FilerCredentials, and chunk reads and
uploads use the credentials of the client that issued them.

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

* hdfs3: let each filer credential option override only its own value

A password-only or token-lifetime-only option in core-site.xml was
ignored or dropped the security.toml user and key. Each option now
replaces just the security.toml value it names.

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

* hdfs3: show [https.client] for a secured filer and per-option overrides

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

* hdfs3: note that [https.client] does not check the filer host name

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

* hdfs3: check filer tokens against the configured key and lifetime

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

* java client: do not follow redirects on filer proxy chunk requests

HttpClient copies the request's Authorization header onto a followed
redirect, even to another origin, so a relayed 3xx would hand the filer
JWT or Basic credential to the redirect target. A 3xx now fails like any
other non-2xx answer and the read moves to the next location.

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

* hdfs3: close the filer client when credential options fail

A credential provider error or a malformed lifetime option threw out of
the store constructor after the client had opened its gRPC channels,
leaving them open on every failed initialization.

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

* hdfs3: say the filer HTTP credentials apply only to filerProxy mode

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

* java client: pick filer credentials by access mode and filer address

The proxy check matched any URL containing proxyChunkId=, so a volume
url or publicUrl carrying that text would receive the filer JWT or Basic
credential. Only filerProxy-mode URLs that start with this client's own
filer proxy prefix count as filer requests now.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:50:04 -08:00
Yip Leo 50ac729a71 filer: fold only runs of small chunks that lie end to end (#13041)
* filer: fold only runs of small chunks that lie end to end

#12462 folds every chunk under 1 MiB into manifests, 256 at a time in
list order. Two things go wrong when those chunks are not plain appends:

- A manifest's chunks are not compacted again. A small chunk that a
  later write covers stays stored and referenced after the write hid it.
- weed mount's bloat check sums chunk sizes and counts a manifest by its
  span. A manifest over chunks that are not next to each other spans
  bytes other chunks hold, so the file looks bloated and the flush reads
  it back and stores it again, whole.

With weed mount on a local cluster, a writer that appends 300-byte
records and rewrites a 4 KiB header at the front after each one (open,
two pwrites, close): after 766 records the mount logged "2.0x chunk
bloat detected ... (2 chunks, 475684 stored vs 233896 content),
merging" and rewrote the file, and did it again at 2.5x (1164184 stored
vs 463396 content); 1,600 records cost two whole-file rewrites. Each
rewrite reads and stores the whole file, and the next one comes a few
hundred flushes later. Random small writes fold their overwritten pages
the same way.

Only small chunks that no other chunk overlaps now fold, and only in
runs that lie end to end, so a manifest spans exactly the bytes it
holds. Appends make such runs and fold as before. Chunks between
full-size ones, chunks that overlap others and chunks with a hole
between them stay flat, as they did before #12462. What is left of a
run stays flat until the run grows.

* filer: size the small-chunk fold's result by its input

CodeQL alert 446 (go/allocation-size-overflow) flagged the capacity
len(inputChunks)-len(folded)+len(manifests). It cannot overflow, but the
input's length bounds the result anyway: each manifest takes the place of
SmallChunkManifestBatch chunks.
2026-11-27 18:49:20 -08:00
Chris LuandClaude Opus 5.5 40a95a8ef5 admin: filter plugin jobs and activities by volume id (#13077)
* admin: keep the volume id on tracked plugin jobs

Volume-scoped jobs carry their volume in the volume_id parameter, but
the in-memory job list drops parameters, so nothing could select a
volume's jobs without reading every job detail file.

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

* admin: filter plugin jobs and activities by volume id

/api/plugin/jobs and /api/plugin/activities accept volume_id, applied
before the limit like the lane filter. Activities follow the tracked
jobs of that volume.

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

* admin: volume id filter on the plugin monitor

A Volume ID box next to the execution state filter narrows the queue,
execution jobs and activities to that volume's jobs, fetched with the
volume_id API filter.

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

* admin: keep detection scans visible under the volume filter

Detection activities belong to no job, so the volume-filtered activity
window had none of them and the Detection Jobs table went empty. That
table now reads its own job-type window.

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

* admin: accept zero-padded volume ids in the monitor filter

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

* admin: drop a monitor refresh that finishes after a newer one

Two refreshes of the same scope can finish out of order; the older one
then replaced the newer rows, with empty lists when its volume-filtered
fetch failed.

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

* admin: keep rows committed for the scope when a plugin monitor refresh fails

A failed request fell back to the rows captured when the refresh started,
so a refresh overlapping one that had already committed the new scope's
rows cleared them. Resolve the fallback when the refresh commits.

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

* admin: validate the monitor volume id before fetching

Out-of-range ids went to the APIs and came back 400. The filter is now
applied only from a valid change event, so the periodic refresh no longer
reads a value still being typed.

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

* admin: volume id filter on the job queue view

The queue renders the volume-scoped rows, but the only filter box sat on
the execution view, so an active filter was invisible and could not be
cleared there. Both views now carry a box kept in sync.

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

* admin: reject unparsable volume id text instead of clearing the filter

A number input holding text like "1e" reports an empty value with
validity.badInput set; treat it as invalid rather than as a cleared box.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:42:11 -08:00
Chris LuandClaude Opus 5.5 ec34160a1a master, admin: report the real last heartbeat time of volume servers (#13074)
* master: report each volume server's last heartbeat time

DataNode.LastSeen only moves when a volume server registers, so nothing
recorded when the master last heard from it. Stamp every processed
heartbeat and carry it in DataNodeInfo.last_heartbeat_ns.

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

* admin: show the master's last heartbeat time for volume servers

The volume server details reported the admin's own clock as the last
heartbeat. Use the time the master reports, and show unknown when the
master does not report one.

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

* admin: carry the last heartbeat time into the volume servers page

GetClusterVolumeServers builds its records from the master's volume list
without the topology conversion, so the details dialog showed unknown.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:02:55 -08:00
Chris LuandClaude Opus 5.5 df98e9df3e admin: wait for the failed record in the worker-restart orphan test (#13079)
handleJobCompleted hands the completion to the dispatcher before it
updates the tracked job, so the test could read the record while it
still said assigned.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:57:38 -08:00
Chris LuandClaude Opus 5.5 2e81c0b7c0 filer: route a rename whose source misses locally to the write owner (#13064)
* filer.proto: mark a forwarded StreamRenameEntry with is_moved

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

* filer: send a rename whose source misses locally to the write owner

Exclusive and conditional creates are stored on the path's write owner. With
separate filer stores, a rename sent to another filer before it has replayed
the create found no source and failed, so a mount that flushed a deferred
create and renamed the file right after got EIO. Such a rename now goes to
the source's write owner, which moves the entry and whose events are relayed
to the caller, unless the owner runs on this filer's store. A forwarded
rename is applied only by the filer its own ring names as the owner.

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

* filer: send an AtomicRenameEntry whose source misses locally to the write owner

The same race reaches the unary rename that S3, WebDAV, SFTP and fs.mv use:
an object or file created through the owner and renamed through another
filer before replication found no source. It is forwarded like the stream
rename, with is_moved bounding it to one hop.

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

* rename: report a missing source as ENOENT

A rename whose source is absent fails with the store's "no entry is found"
error, which neither the filer's errno mapping nor the mount's message
mapping recognized, so the client got EIO instead of ENOENT.

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

* filer.proto: report a forwarded AtomicRenameEntry's last event position

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

* filer: answer a forwarded rename once the owner's events are replayed here

The rename's target is stored on the owner only until this filer replays
it, so an unlink of that name sent here right after the rename would miss
it and report success. The owner now reports the log position of the
rename's last event, and the forwarding filer holds its answer (bounded)
until its stream from the owner has delivered that far.

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

* filer: refuse a forwarded no-replace rename over a target this filer has

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

* filer: wait for an owner this filer no longer follows before answering a forwarded rename

PeersCaughtUpTo counts an untracked peer as caught up. An owner whose
stream was down long enough to be dropped has replayed nothing here, so a
forwarded rename answered then could leave a follow-up unlink through this
filer missing the target. Require the owner to be tracked with a watermark
at or past the rename, still bounded by ownerEventsCatchUpCap.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:54:48 -08:00
Chris LuandClaude Opus 5.5 96fd7fe6e2 volume: report mounted EC shards whose file on disk is gone, replaced or resized (#13069)
* volume: report mounted EC shards whose file on disk is gone, replaced or resized

Each EC heartbeat tick stats every mounted shard file and compares it with the
open descriptor: a missing path or a different file is a ghost, a size other
than the mounted one is stale_size. Mismatches are logged per shard and counted
in SeaweedFS_volumeServer_ec_shard_disk_mismatch{reason}.

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

* volume(rs): report mounted EC shards whose file on disk is gone, replaced or resized

Mirror of the Go check: each EC heartbeat tick compares every mounted shard
with its file (missing or another inode = ghost, other size = stale_size),
warns per shard and sets SeaweedFS_volumeServer_ec_shard_disk_mismatch{reason}.

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

* metrics: chart EC shards that disagree with their file on disk

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

* volume(rs): tell a replaced EC shard file apart on non-unix hosts

Without inode numbers, compare the creation and modification times of the
path and of the open handle.

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

* volume: check mounted EC shards off the heartbeat loop

A stat stuck on a stalled disk no longer holds up heartbeats or shutdown; at
most one check runs at a time.

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

* volume(rs): check mounted EC shards off the heartbeat loop

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

* volume(rs): compare file ids to tell a replaced EC shard file apart on Windows

Timestamps can match on a replacement file. Use the volume serial and
file index from GetFileInformationByHandle there, and dev/inode on
unix, the same identity Go's os.SameFile compares.

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

* volume(rs): copy mounted EC shard state out before checking the disk

The check held the store read guard across its file system calls, so a
stalled disk kept the guard and a waiting writer could then stall the
heartbeat's own read. Copy each shard's path, size and file id under
the guard and check them after it is released. The id is recorded when
the shard opens, so no extra handle is held for the check.

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

* volume(rs): run the EC shard disk check on a detached thread

Dropping the runtime waits for spawn_blocking tasks, so a stat stuck on
a hung disk could hold up shutdown. A plain thread is not waited on.

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

* volume(rs): stat the EC shard path instead of opening it

A replacement the server cannot read failed the open and was never
counted as a ghost. Compare device, inode and length from the path's
metadata, as the Go side does with os.Stat; on Windows open it with no
access rights.

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

* volume(rs): test the EC tick past a stalled disk check

The check thread start takes the check to run, so a test can stall one
after its snapshot and show that a writer still gets the store, the tick
still reports, and no second check starts.

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

* volume: keep VolumeServer int64 counters 8-byte aligned on 32-bit

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:53:58 -08:00
Chris LuandClaude Opus 5.5 8ab78a9a06 s3: return part checksums in ListParts (#13076)
* s3: return part checksums in ListParts

UploadPart stores the part's checksum on the part entry and returns it,
but ListParts built each Part from the SDK type, which has no CRC64NVME
field, and never filled the checksum fields. List each part with its
stored checksum so a client can verify an uploaded part after losing the
UploadPart response.

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

* s3: name the upload's checksum algorithm and type in ListParts

CreateMultipartUpload records the requested checksum algorithm and
type on the upload, but ListParts never reported them. Return both, as
AWS does, when the upload was created with a checksum.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:52:47 -08:00
Chris LuandClaude Opus 5.5 2ce8b75b3f ci: refresh the apt index before installing musl and cross toolchains (#13075)
The runner image's package index can name versions the mirrors have
already dropped, so apt-get install fails with a 404 on the first
security update after the image was built.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:51:52 -08:00
Chris LuandClaude Opus 5.5 b53f6d4b5e admin: warn when more than one scheduler runs the same maintenance work (#13065)
* admin/maintenance: report whether the running manager queues a task type

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

* admin: list the EC balancers that are active at the same time

The plugin ec_balance job, the legacy maintenance manager's ec_balance task
and an admin_script job that runs ec.balance -apply each plan shard moves
from the same topology without knowing about the others.

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

* admin: log a warning while more than one EC balancer is active

The check runs on the maintenance metrics tick and logs again only when the
set of active balancers changes. The legacy maintenance entry names the
admin.toml switch that turns it off.

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

* admin: warn on the plugin pages when more than one EC balancer is active

The scheduler status API returns the active EC balancers, and the scheduler
banner on the plugin and lane pages lists them when there are two or more.

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

* admin/maintenance: count a task type only when a registered worker can run it

Only legacy maintenance workers pull tasks from the legacy queue. With plugin
workers alone, the queued ec_balance tasks never run, so they do not compete
with the plugin ec_balance job.

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

* admin: parse ec.balance apply flags like the flag package

A value counts only when strconv.ParseBool reads it as true, and a # token
ends the arguments, as it does for the shell command's flag parser.

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

* admin/maintenance: skip legacy workers past their heartbeat timeout

A disconnected worker keeps its queue record until the cleanup loop removes
it, so the capability check also requires a heartbeat within the worker
timeout.

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

* admin: count ec.balance only when its flags parse the way the command parses them

An invalid boolean in -apply or -force fails the whole command, the last
value of a flag wins, -force overrides -apply, and parsing stops at the
first non-flag argument.

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

* shell: share ec.balance's flag set and report whether its arguments apply the plan

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

* admin: count an admin_script ec.balance only when ec.balance accepts its flags

Unknown flags and invalid values of any flag fail the command before it
can move shards, so they no longer count as an active balancer.

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

* shell, plugin/worker: move admin_script command tokenizing into the shell package

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

* admin: split admin_script ec.balance arguments with the executor's tokenizer

A quoted value with spaces is one argument to ec.balance, so flags after it
are still seen.

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

* shell: report through one lookup whether a command's arguments change the cluster

ec.balance now also rejects an invalid -volumeIds, as its Do does.

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

* shell: report whether volume.balance arguments apply its plan

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

* shell: report whether ec.encode accepts its arguments

ec.encode has no dry run, so any accepted invocation changes the cluster.

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

* shell: report whether volume.vacuum accepts its arguments

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

* admin: report overlap for every maintenance work that more than one scheduler runs

The plugin scheduler, the legacy maintenance manager, and an admin_script can
each run volume balance, EC balance, EC encoding, and vacuum. Check all four
from one table and report each work with two or more active runners, in the
log and in the scheduler-status API as maintenance_overlaps.

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

* admin: show each maintenance overlap on the plugin pages

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:46:34 -08:00
Chris LuandClaude Opus 5.5 1e4739f97a s3api: count object reads that fail after the status line is sent (#13073)
* s3api: count object reads that fail after the status line is sent

A GET whose body breaks after the 200/206 was committed is recorded by
SeaweedFS_s3_request_total as a success and only shows up in the log.
SeaweedFS_s3_read_aborted_total{bucket,cause} counts these reads on the
volume-server, SSE and remote-mount stream paths, split into
client_canceled, deadline_exceeded and read_error, and is dropped with
the other per-bucket series when a bucket is deleted.

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

* grafana: plot aborted S3 reads by bucket and cause

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

* s3api: count aborted reads of inline objects and directory content

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

* s3api: count gRPC deadline failures as deadline_exceeded aborted reads

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

* s3api: count an aborted read as client_canceled only when its request was canceled

A context.Canceled error under a live request context comes from an
internal cancellation, such as a shared lookup canceled by another
request, so it is recorded as read_error.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:44:12 -08:00
Chris LuandClaude Opus 5.5 ef633dcc4d admin: inspect an S3 object's versions, retention and chunk volume health (#13078)
* admin: inspect an S3 object's versions, retention and chunk volumes

For a bucket and key, collect the base entry and every entry under
<key>.versions, decode version id, delete marker, ETag, client checksum,
Object Lock mode, retain-until, legal hold and the WORM enforcement time,
and map each chunk to its volume. One filtered VolumeList then reports,
per volume, replicas present versus the replica placement, or the EC
shards present and missing against the data shard count.

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

* admin: serve the S3 object inspection at /api/s3/buckets/{bucket}/objects/inspect

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

* admin: add an Inspect Object page for a bucket and key

/object-store/buckets/{bucket}/inspect?key= renders the inspection:
volume health per chunk volume with a link to the volume or EC volume
page, then every version with size, mtime, ETag, client checksum, lock
mode, retain-until, legal hold, WORM time and its chunk file ids.

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

* admin: link each bucket to the object inspector

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

* admin: inspect a key that is also a prefix of other keys

The filer keeps such an object on a directory entry marked as a prefix
object, so the base entry lookup must accept it like a file.

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

* admin: count only S3 version entries as an object's history

A sibling named <key>.versions is history only when it is a directory,
and only children with a version id (attribute or v_ file name, as
VersionIdFromEntry reads them) are versions. Without a base object or
any such version the inspection is not found.

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

* admin: mark the newest version latest when the pointer is missing

When the base object is gone and .versions has no latest pointer (for
example after deleting a current null version), pick the latest with the
S3 gateway's own version ordering, exported as SelectLatestVersionId,
instead of leaving every version noncurrent. A truncated listing marks
none, since it may not hold the newest version.

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

* admin: report the ETag the S3 gateway returns

Use objectETag, exported as ObjectETag, so remote-only entries show
their remote ETag and entries without a stored ETag or MD5 show the
chunk-derived one.

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

* admin: read the buckets path with the inspection's request context

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

* admin: report the filer's logical size for each inspected version

filer.FileSize also covers chunk extents past a stale attribute size and
a newer remote size.

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

* admin: drop EC shard state once a volume also reports a replica

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

* admin: let the latest-version pointer outrank the null-is-latest flag

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

* admin: page the inspector's version scan past non-version entries

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

* admin: judge an inspected EC volume by its newest encode run

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:43:19 -08:00
github-actions[bot] ebe5c8ac91 docs: regenerate star history chart 2026-11-28 01:19:02 +00:00
Chris LuandClaude Opus 5.5 46fe0f10da volume: count failed EC shard copies by reason (#13068)
* volume: count failed EC shard copies by reason

Each failed VolumeEcShardsCopy now increments
SeaweedFS_volumeServer_ec_shard_copy_failures_total{collection,reason} and
logs the volume, shards, source and reason. Reasons: source_not_found,
empty_index, no_space, timeout, io_error, other.

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

* grafana: chart EC shard copy failures by reason

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

* volume(rs): count failed EC shard copies by reason

Mirrors the Go volume server: each failed VolumeEcShardsCopy increments
SeaweedFS_volumeServer_ec_shard_copy_failures_total{collection,reason}
with the same reasons and logs the volume, shards, source and reason.

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

* volume: classify wrapped gRPC NotFound and DeadlineExceeded copy errors

A source status that the destination wraps as text keeps its code only as
"code = NotFound" (Go) or the code's description (Rust), so match those
too.

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

* volume(rs): record EC copy failures inside the copy task

The copy keeps running after the caller cancels, so its failure is
reported from the spawned task; a join error is reported by the handler.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:22:00 -08:00
Chris LuandClaude Opus 5.5 b6237dd8b1 master, admin, shell: warn about volume servers left in the default data center or rack (#13066)
* master: warn when a volume server registers in the default data center or rack

A volume server started without -dataCenter or -rack lands in
DefaultDataCenter/DefaultRack. Next to servers with explicit placement it
becomes its own failure domain for placement and balancing. Log a warning
when such a server registers while other servers name their data center,
or other racks of the same data center are named.

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

* admin: warn about volume servers left in the default data center or rack

The Volume Servers page lists the servers that fell back to
DefaultDataCenter or DefaultRack while other servers name theirs, with
their volume and EC shard counts, so the stray failure domain shows up
before placement and balancing act on it.

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

* shell: cluster.check warns about volume servers in the default data center or rack

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

* shell: cluster.check prints placement warnings before the capacity checks

A disk type with no free slots made cluster.check return before the
default data center/rack warnings were printed.

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

* admin: list each data center's rack once in the default placement check

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:16:25 -08:00
dependabot[bot] 8df718eaf3 build(deps): bump actions/dependency-review-action from 5.0.0 to 5.0.1 (#12929)
Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/actions/dependency-review-action/releases)
- [Commits](https://github.com/actions/dependency-review-action/compare/a1d282b36b6f3519aa1f3fc636f609c47dddb294...bbc44d14a204704ccc493733616cd1e93a0321ec)

---
updated-dependencies:
- dependency-name: actions/dependency-review-action
  dependency-version: 5.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-27 15:04:34 -08:00
76bc731c69 feat: s3: record object path in needle Content-Location pair (#13061)
* feat: operation: pass needle pairs through chunked uploads (#12997)

* feat: s3: build Content-Location needle pair from the object path (#12997)

* feat: s3: record object path in needles written by putToFiler (#12997)

* feat: s3: record destination object path in copied chunks (#12997)

* feat: s3: record destination object path in stream-copied chunks (#12997)

* test: s3: pin Content-Location in putToFiler upload options (#12997)

* s3: record no path on copies of volume-encrypted chunks

A chunk written with -encryptVolumeData is copied as ciphertext through
the plain upload path, so the copy sent the destination path in
plaintext next to encrypted data, while PutObject's cipher upload sends
no pairs at all.

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-27 15:02:15 -08:00
bf0da715fc ci: keep dev builds published and document them (#13059)
* ci: keep dev builds published and document them

The dev release was emptied before every build: the cleanup job deleted
all weed-* assets first, and cancel-in-progress cancelled the build on
the next master push. Build the platforms with one prepare timestamp,
upload first, then prune assets from older builds. Queue runs instead
of cancelling them, and allow manual runs from master only.

Document the dev binaries and the :dev container images in the README
and docker/README.md.

Refs #5009

* ci: key dev build concurrency by ref

A workflow_dispatch from another branch joined the single dev group and
replaced the pending master run before failing its ref guard, so the
newest master commit was never built.

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

* ci: keep newer dev builds when an older run retries

A "Re-run failed jobs" of an older run keeps that run's BUILD_TIME, so
its prune treated a newer complete build as stale and deleted it. Prune
now deletes only assets whose stamp sorts before BUILD_TIME.

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-27 14:59:44 -08:00
Chris LuandClaude Opus 5.5 978ff95327 volume(rs): reload TLS server certificates on SIGHUP (#13067)
The Go volume server re-reads its gRPC and HTTPS cert/key files on
SIGHUP (certreload.ReloadAll). The Rust server built each rustls
ServerConfig with a fixed cert, so a rotated pair only took effect
after a restart. Serve the pair through a resolver that re-reads the
files on SIGHUP and keeps the previous pair when the new files fail to
load.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:57:26 -08:00
Konstantin Lebedevandwhitefox b0df54aa8f security: reload TLS credentials on SIGHUP (#13058)
TLS certs currently refresh only on the periodic WEED_TLS_CERT_REFRESH_INTERVAL poll (5h by default), so after replacing cert/key files an operator has to wait up to one interval for the new material to be used. SIGHUP already reloads configs and JWT keys, but not TLS.

Replace gRPC's pemfile.Provider with a small certprovider.Provider in weed/security/certreload that keeps the current KeyMaterial, refreshes on the same timer, and can be forced to re-read the files via Reload. A process-wide registry plus grace.OnReload(ReloadAll) makes SIGHUP apply rotated certs immediately to every gRPC and HTTPS server/client.

On parse/read errors the previous material is kept, so a broken rotation does not take the listener down.

Fixes #13056

Co-authored-by: whitefox <whitefox@mayflower.work>
2026-11-27 14:57:06 -08:00
7bbb65fa80 master: /col/delete requires an explicit collection name (#13055)
* master: /col/delete requires an explicit collection name

A /col/delete request without a collection parameter, or with an empty
one, read as the empty-named default collection and deleted it. Return
400 instead, and accept collection=_default (the keyword weed shell
uses) to delete the default collection deliberately.

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

* master: keep a collection literally named _default addressable by /col/delete

collection=_default now names the empty-named collection. A collection
created with that literal name would have been unreachable, and a request
meant for it would have deleted the default collection instead. Resolve
the keyword to the literal collection when one exists, and refuse the
request when both exist.

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

* master: /col/delete accepts only the DELETE method

A GET is expected to be safe, yet a bare GET or a link prefetch deleted
the named collection. Any other method now gets 405 with an Allow
header, and the docs, benchmark help and test helpers send DELETE.

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

* master: /col/delete accepts _default_ for the default collection

When a collection literally named _default exists next to the default
collection, collection=_default is refused, which left the default
collection with no way to be named. Accept the _default_ spelling that
weed shell collection.delete already takes; it always means the
default collection.

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

* master: /col/delete keeps a literal _default_ collection addressable

_default_ now resolves like _default: to the literal collection when one
exists, to the default collection otherwise, and refuses the request when
both exist.

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

* REST_API: /col/delete when both keyword names are literal collections

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-27 14:56:18 -08:00
Chris LuandClaude Opus 5.5 96321141cc filer.sync: stop deleting versions on transient lookups and in-flight pointers (#13063)
* filer.sync: retry an update whose destination lookup failed transiently

FilerSink.UpdateEntry reported every lookup error as a missing entry, so
the replicator and filer.sync deleted the destination key and created it
again. For a directory, a canceled or unavailable lookup removed it with
everything under it. Only a real not-found now lets the caller recreate
the key; other lookup errors are returned for retry.

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

* s3: leave a pointer to a recently minted version unrepaired

When a versioned read finds a latest pointer whose version file is
missing, the self-heal rescanned .versions and then either removed the
directory (no version left) or rewrote the pointer to the newest version
found. With filer.sync the directory and its pointer can arrive before
the version file, so the heal acted on a version still in flight: the
local directory removal replicated back and deleted the committed
version on the source cluster, and a pointer repair would roll its
latest pointer back.

While the pointer names a version minted in the last ten minutes, the
read now answers from the rescan without persisting anything, and the
reconciler skips the key. After that window the heal works as before.

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

* filer.sync: retry a failed destination lookup before giving up on an update

Returning a transient lookup error leaves the retry to the caller, and
filer.replicate hands a failed event to the notification input instead
of replaying it. Retry the lookup in place with the shared bounded
backoff; a not-found still returns at once.

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

* filer.sync: count only the not-found sentinel as a missing destination

LookupEntry already maps every miss to filer_pb.ErrNotFound, plain-text
ones included. Matching the sentinel's text in any error also counted an
Unavailable lookup carrying that text as a miss, which let the caller
delete and recreate the key.

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

* s3: requeue an in-flight versions pointer for after the grace window

The reconciler dropped a key whose pointer named a version still in
flight, so nothing revisited it once the window passed. Requeue it for
one grace window without counting the skip as an attempt.

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

* s3: probe the latest version file before deferring an in-flight pointer

A recent pointer whose version file is already present needs no repair;
deferring it kept the key queued for the whole grace window and used
up queue capacity.

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

* s3: retry an in-flight versions pointer when its grace runs out

The reconciler waited a full grace window after the deferral, so a
pointer first seen near the end of its grace stayed unrepaired for
almost twice as long.

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

* s3: run the in-flight pointer grace from its local commit too

The grace was measured from the version id's mint time on the origin
cluster against the local clock, so a peer whose clock ran more than
the grace ahead, or a filer.sync backlog longer than the grace, saw a
just-synced pointer as stale and could remove or roll back the version.
The .versions entry's commit time is stamped by the local filer when
the pointer is stored, so it bounds the wait with the local clock.

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

* s3: repair a pointerless .versions entry despite a recent commit

The in-flight grace protects a pointer whose version file has not arrived
yet. A .versions entry with no pointer names no such file, so a recent
commit of it must not hold back the rebuild of its pointer.

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

* s3: hold a stale-pointer repair while the live entry is still in grace

The heal checked the grace on the snapshot it took before the scan. A
.versions entry stored again with the same pointer during the scan
restarts the grace, so check it on the live entry the CAS is conditioned
on before persisting the repair.

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

* s3: recheck the live grace before removing an empty .versions

The empty-directory cleanup checked the grace on the pre-scan snapshot,
so a pointer stored again during the scan could still have its
.versions removed. Re-read the entry and leave it while its grace lasts.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:51:53 -08:00
Chris LuandClaude Opus 5.5 e01133bfa3 ec_balance: keep node addresses out of the task ID so tasks can be persisted (#13062)
* ec_balance: keep node addresses out of the task ID

The ID embedded both host:port node addresses, and the admin's task
persistence rejects any ID containing ':', so every ec_balance task
failed to save on each state change and lived only in memory. The
volume, shard, timestamp and index already make the ID unique; the
nodes stay in the task's Reason and params.

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

* admin: test that a detected ec_balance task saves and loads

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 12:58:08 -08:00
77333a5578 s3: match copy-source ETag conditions with the shared helper (#13054)
* s3: match copy-source ETags as the read and write paths do

validateSourceConditionalHeaders compared the source ETag to the header
value with strings.Trim, so x-amz-copy-source-if-none-match: W/"<etag>"
did not match and an unchanged source was copied instead of answered
with 412. An If-Match list that contained the source's ETag was
rejected for the same reason. RenameObject shares the helper, so
x-amz-rename-source-if-* behaved the same way.

Use util.ETagListMatches, which the GET and PUT paths already use:
strong comparison for If-Match, weak for If-None-Match, and the quoted
tag lists RFC 9110 allows.

* s3: drop the history comment from the copy-source ETag checks

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

* mount: skip the truncate manifest test on freebsd like its fake filer

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-27 12:48:08 -08:00
397a156104 security: a fips.mode setting that Go checks against GODEBUG and the Rust binaries apply to TLS (#13029)
* util: refuse to start when fips.mode in security.toml disagrees with GODEBUG

security.toml gains [fips] mode = "off" | "on" | "strict", also settable
as WEED_FIPS_MODE: one setting that states the FIPS 140-3 mode of every
process in a deployment, so the Rust binaries, which do not run on the Go
runtime, can follow it. Go processes keep taking their behaviour from
GODEBUG=fips140 and now check it against the setting:
LoadSecurityConfiguration and `weed worker` exit when "off" runs without
fips140=off, "on" without fips140=on, or "strict" without fips140=only,
naming the setting and the GODEBUG value it needs. An unknown value is
refused; unset or empty changes nothing.

Refs #12839

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

* rust: fips.mode with FIPS-mode TLS in weed-volume, weed-worker and weed-vector

seaweed-common gains a fips module: FipsMode resolved from fips.mode in
the security.toml a binary uses, with WEED_FIPS_MODE over it. Each binary
resolves it once at startup, logs it and installs the matching rustls
provider as the process default, refusing to start on an unknown value or
when another provider was installed first.

Under "on" and "strict" the provider is aws-lc-rs filtered to the lists
Go's crypto/tls applies in FIPS mode: TLS 1.3 AES-GCM suites and TLS 1.2
ECDHE AES-GCM suites (no ChaCha20-Poly1305), X25519MLKEM768,
SecP256r1MLKEM768, P-256 and P-384 (no plain X25519), Go's ten signature
schemes (no ML-DSA). Configurations SeaweedFS builds require the Extended
Master Secret in that mode, and the volume server refuses a non-FIPS suite
in tls.cipher_suites instead of falling back. sw-client installs the same
provider instead of ring. Unset or "off" keeps aws-lc-rs's default
provider unchanged.

This is behavioural parity only: the provider still runs on the
non-validated aws-lc-rs build.

Refs #12839

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

* util: refuse a fips.mode that is not a string

viper's GetString turns an array or a table into "", so mode = ["strict"]
under [fips] skipped the GODEBUG check while the Rust binaries refused the
same file. RequireFipsMode now reads the raw value (ViperProxy.Get, under
its lock) and exits when it is not a string, naming its source; an absent
or empty value still means unset, and WEED_FIPS_MODE still wins.

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

* rust: read fips.mode with the parser that reads the JWT keys

seaweed_common::fips::resolve parsed security.toml with the toml crate,
while the volume server reads the rest of the file with its own lenient
loader. A file with [fips] mode = "on" beside an unquoted value the loader
accepts resolved to off and logged "fips.mode unset", although the JWT
keys from the same file were applied. Each binary now reads fips.mode
with the loader it uses for everything else and hands the value to
resolve: the volume server through its line parser, the worker and vector
engine through their parsed Security table, which already refuses a file
that is not TOML. A security.toml the volume server finds but cannot read
stops startup. A missing setting is still off, and WEED_FIPS_MODE still
wins. seaweed-common no longer depends on toml.

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

* sw-client: offer only FIPS signature schemes with insecure_skip_verify

With https.client.insecure_skip_verify, reqwest installs its own verifier,
which advertises a fixed scheme list including SHA-1 and Ed448 whatever
the process provider allows. In FIPS mode the volume transport now builds
its rustls configuration itself on the process provider: the server
certificate and host name are not checked, as the setting asks, but
handshake signatures are verified with the provider's algorithms, only its
schemes are offered, and TLS 1.2 requires the Extended Master Secret.
Outside FIPS mode the reqwest path is unchanged.

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

* seaweed-common: sign only with Go 1.27's FIPS schemes, allow ML-DSA

The FIPS provider kept aws-lc-rs's key provider, so a FIPS-mode listener
signed handshakes with whatever scheme its key and the peer agreed on,
outside the list the provider verifies with. Keys now load through a
provider that limits each key to the FIPS signature schemes and refuses a
key that can sign none of them, such as Ed448; the volume server and the
worker's gRPC TLS name the certificate and key files in that error.

The lists follow Go 1.27.4, which go.mod now requires: its
defaults_fips140.go allows ML-DSA-44, -65 and -87 as signature schemes and
ML-DSA certificate keys (for Go's native module only), so they are allowed
here as well. Go also allows MLKEM1024 but does not enable it by default,
so it stays out of the key exchange list as in Go's defaults. "off" keeps
the default key provider.

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

* mount: skip the truncate manifest test on freebsd like its fake filer

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-27 12:47:44 -08:00
dependabot[bot] 977513cf35 build(deps): bump github/codeql-action from 4.39.3 to 4.39.4 (#12930)
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>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-27 08:55:12 -08:00
Chris Lu 781288cf11 s3api: ignore custom x- query parameters on bucket requests (#13046) 2026-11-27 02:42:37 -08:00
676 changed files with 44688 additions and 4147 deletions

No files matched your search

@@ -16,6 +16,7 @@ runs:
if: inputs.target == 'x86_64-unknown-linux-musl'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y musl-tools
# C deps (aws-lc-sys) must compile against musl headers, not the host
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
@@ -26,6 +27,7 @@ runs:
if: inputs.target == 'aarch64-unknown-linux-musl'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
+1 -1
View File
@@ -15,7 +15,7 @@ runs:
using: composite
steps:
- name: Install cosign
uses: sigstore/cosign-installer@v4.1.3
uses: sigstore/cosign-installer@v4.1.4
- name: Sign
shell: bash
+108 -22
View File
@@ -8,38 +8,44 @@ on:
- 'go.mod'
- 'go.sum'
- '.github/workflows/binaries_dev.yml'
workflow_dispatch:
# Let an in-progress dev build finish. A new push replaces only the pending
# run; cancelling mid-build left the dev release without assets.
concurrency:
group: binaries-dev-${{ github.ref }}
cancel-in-progress: true
cancel-in-progress: false
permissions:
contents: read
jobs:
cleanup:
permissions:
contents: write # for mknejp/delete-release-assets to delete release assets
prepare:
runs-on: ubuntu-latest
outputs:
build_time: ${{ steps.build_time.outputs.value }}
steps:
- name: Ref guard
if: github.ref != 'refs/heads/master'
env:
GH_REF: ${{ github.ref }}
run: |
echo "dev builds only publish from master (got $GH_REF)" >&2
exit 1
- name: Delete old release assets
uses: mknejp/delete-release-assets@v1
continue-on-error: true
with:
token: ${{ github.token }}
tag: dev
fail-if-no-assets: false
assets: |
weed-*
- name: Set BUILD_TIME
id: build_time
run: |
echo "value=$(date -u +%Y%m%d-%H%M)" >> "$GITHUB_OUTPUT"
build_dev_linux_windows:
permissions:
contents: write # for wangyoucao577/go-release-action to upload release assets
needs: cleanup
needs: prepare
runs-on: ubuntu-latest
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
goos: [linux, windows]
@@ -47,12 +53,13 @@ jobs:
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- name: Check out code into the Go module directory
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v2
- name: Set BUILD_TIME env
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> ${GITHUB_ENV}
- name: Go Release Binaries Large Disk
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
@@ -89,8 +96,10 @@ jobs:
build_dev_darwin:
permissions:
contents: write # for wangyoucao577/go-release-action to upload release assets
needs: build_dev_linux_windows
needs: [prepare, build_dev_linux_windows]
runs-on: ubuntu-latest
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
goos: [darwin]
@@ -98,12 +107,13 @@ jobs:
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- name: Check out code into the Go module directory
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v2
- name: Set BUILD_TIME env
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> ${GITHUB_ENV}
- name: Go Release Binaries Large Disk
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
@@ -136,3 +146,79 @@ jobs:
project_path: weed
binary_name: weed-normal-disk
asset_name: "weed-${{ env.BUILD_TIME }}-${{ matrix.goos }}-${{ matrix.goarch }}"
prune:
needs: [prepare, build_dev_linux_windows, build_dev_darwin]
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
RELEASE_TAG: dev
steps:
- name: Delete dev binaries from older builds
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
: "${BUILD_TIME:?BUILD_TIME is empty}"
case "$BUILD_TIME" in
[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]) ;;
*) echo "Invalid BUILD_TIME: $BUILD_TIME" >&2; exit 1 ;;
esac
release_tag="${RELEASE_TAG:-dev}"
if ! release_json=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$release_tag" 2>&1); then
case "$release_json" in
*"Not Found"*) echo "No $release_tag release; nothing to prune"; exit 0 ;;
esac
echo "Release lookup failed: $release_json" >&2
exit 1
fi
release_id=$(jq -r '.id // empty' <<<"$release_json")
if [ -z "$release_id" ]; then
echo "Release lookup returned no id" >&2
exit 1
fi
assets_file=$(mktemp)
trap 'rm -f "$assets_file"' EXIT
if ! gh api "repos/$GITHUB_REPOSITORY/releases/$release_id/assets" --paginate \
--jq '.[] | select((.name | startswith("weed-large-disk-")) or (.name | test("^weed-[0-9]"))) | [.id, .name] | @tsv' \
> "$assets_file"; then
echo "Failed to list release assets" >&2
exit 1
fi
total=$(awk 'END{print NR+0}' "$assets_file")
matching=$(awk -v s="-$BUILD_TIME-" 'index($0,s){n++} END{print n+0}' "$assets_file")
if [ "$matching" -eq 0 ]; then
echo "No assets carry stamp $BUILD_TIME; refusing to prune" >&2
exit 1
fi
build_key=${BUILD_TIME/-/}
kept=0; newer=0; deleted=0; gone=0; failed=0
while IFS=$'\t' read -r id name || [ -n "${name:-}" ]; do
[ -n "${id:-}" ] || continue
case "$name" in
*"-$BUILD_TIME-"*) kept=$((kept+1)); continue ;;
esac
if [[ "$name" =~ -([0-9]{8})-([0-9]{4})- ]] && [ "${BASH_REMATCH[1]}${BASH_REMATCH[2]}" -gt "$build_key" ]; then
newer=$((newer+1)); continue
fi
if out=$(gh api -X DELETE "repos/$GITHUB_REPOSITORY/releases/assets/$id" </dev/null 2>&1); then
deleted=$((deleted+1))
else
case "$out" in
*"Not Found"*) gone=$((gone+1)) ;;
*) failed=$((failed+1)); echo "Failed to delete asset $name ($id): $out" >&2 ;;
esac
fi
done < "$assets_file"
[ "$((kept+newer+deleted+gone+failed))" -eq "$total" ] || { echo "Processed $((kept+newer+deleted+gone+failed)) of $total assets" >&2; exit 1; }
echo "Kept $kept assets from this build and $newer from newer builds; deleted $deleted older assets; $gone already gone; $failed failures"
[ "$failed" -eq 0 ] || { echo "::warning::prune: $failed deletions failed"; exit 1; }
+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.5
# 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.5
# ℹ️ 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.5
+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.5
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.5
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
+1 -1
View File
@@ -15,4 +15,4 @@ jobs:
- name: 'Checkout Repository'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
- name: 'Dependency Review'
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
- name: Run Client Unit Tests
working-directory: other/java/client
run: |
mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest
mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest,FilerJwtTest
- name: Run HDFS3 Configuration Tests
working-directory: other/java/hdfs3
+113 -20
View File
@@ -7,32 +7,43 @@ on:
- 'seaweed-volume/**'
- 'seaweed-common/**'
- '.github/workflows/rust_binaries_dev.yml'
workflow_dispatch:
# Serialize dev builds of the shared "dev" release without cancelling a run.
concurrency:
group: rust-binaries-dev-${{ github.ref }}
cancel-in-progress: false
permissions:
contents: read
jobs:
cleanup:
permissions:
contents: write
prepare:
runs-on: ubuntu-latest
outputs:
build_time: ${{ steps.build_time.outputs.value }}
steps:
- name: Delete old Rust volume dev assets
uses: mknejp/delete-release-assets@v1
continue-on-error: true
with:
token: ${{ github.token }}
tag: dev
fail-if-no-assets: false
assets: |
weed-volume-*
- name: Ref guard
if: github.ref != 'refs/heads/master'
env:
GH_REF: ${{ github.ref }}
run: |
echo "dev builds only publish from master (got $GH_REF)" >&2
exit 1
- name: Set BUILD_TIME
id: build_time
run: |
echo "value=$(date -u +%Y%m%d-%H%M)" >> "$GITHUB_OUTPUT"
build-rust-volume-dev-linux:
permissions:
contents: write
needs: cleanup
needs: prepare
runs-on: ubuntu-24.04
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
include:
@@ -40,6 +51,11 @@ jobs:
asset_suffix: linux-amd64
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- uses: actions/checkout@v7
- name: Install Rust toolchain
@@ -57,9 +73,6 @@ jobs:
restore-keys: |
rust-dev-${{ matrix.target }}-
- name: Set BUILD_TIME
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> "$GITHUB_ENV"
- name: Build Rust volume server (large disk)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -96,8 +109,10 @@ jobs:
build-rust-volume-dev-darwin:
permissions:
contents: write
needs: build-rust-volume-dev-linux
needs: [prepare, build-rust-volume-dev-linux]
runs-on: macos-latest
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
include:
@@ -107,6 +122,11 @@ jobs:
asset_suffix: darwin-amd64
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- uses: actions/checkout@v7
- name: Install Rust toolchain
@@ -126,9 +146,6 @@ jobs:
restore-keys: |
rust-dev-${{ matrix.target }}-
- name: Set BUILD_TIME
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> "$GITHUB_ENV"
- name: Build Rust volume server (large disk)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -161,3 +178,79 @@ jobs:
weed-volume-${{ env.BUILD_TIME }}-${{ matrix.asset_suffix }}.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
prune:
needs: [prepare, build-rust-volume-dev-linux, build-rust-volume-dev-darwin]
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
RELEASE_TAG: dev
steps:
- name: Delete Rust dev binaries from older builds
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
: "${BUILD_TIME:?BUILD_TIME is empty}"
case "$BUILD_TIME" in
[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]) ;;
*) echo "Invalid BUILD_TIME: $BUILD_TIME" >&2; exit 1 ;;
esac
release_tag="${RELEASE_TAG:-dev}"
if ! release_json=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$release_tag" 2>&1); then
case "$release_json" in
*"Not Found"*) echo "No $release_tag release; nothing to prune"; exit 0 ;;
esac
echo "Release lookup failed: $release_json" >&2
exit 1
fi
release_id=$(jq -r '.id // empty' <<<"$release_json")
if [ -z "$release_id" ]; then
echo "Release lookup returned no id" >&2
exit 1
fi
assets_file=$(mktemp)
trap 'rm -f "$assets_file"' EXIT
if ! gh api "repos/$GITHUB_REPOSITORY/releases/$release_id/assets" --paginate \
--jq '.[] | select(.name | startswith("weed-volume-")) | [.id, .name] | @tsv' \
> "$assets_file"; then
echo "Failed to list release assets" >&2
exit 1
fi
total=$(awk 'END{print NR+0}' "$assets_file")
matching=$(awk -v s="-$BUILD_TIME-" 'index($0,s){n++} END{print n+0}' "$assets_file")
if [ "$matching" -eq 0 ]; then
echo "No assets carry stamp $BUILD_TIME; refusing to prune" >&2
exit 1
fi
build_key=${BUILD_TIME/-/}
kept=0; newer=0; deleted=0; gone=0; failed=0
while IFS=$'\t' read -r id name || [ -n "${name:-}" ]; do
[ -n "${id:-}" ] || continue
case "$name" in
*"-$BUILD_TIME-"*) kept=$((kept+1)); continue ;;
esac
if [[ "$name" =~ -([0-9]{8})-([0-9]{4})- ]] && [ "${BASH_REMATCH[1]}${BASH_REMATCH[2]}" -gt "$build_key" ]; then
newer=$((newer+1)); continue
fi
if out=$(gh api -X DELETE "repos/$GITHUB_REPOSITORY/releases/assets/$id" </dev/null 2>&1); then
deleted=$((deleted+1))
else
case "$out" in
*"Not Found"*) gone=$((gone+1)) ;;
*) failed=$((failed+1)); echo "Failed to delete asset $name ($id): $out" >&2 ;;
esac
fi
done < "$assets_file"
[ "$((kept+newer+deleted+gone+failed))" -eq "$total" ] || { echo "Processed $((kept+newer+deleted+gone+failed)) of $total assets" >&2; exit 1; }
echo "Kept $kept assets from this build and $newer from newer builds; deleted $deleted older assets; $gone already gone; $failed failures"
[ "$failed" -eq 0 ] || { echo "::warning::prune: $failed deletions failed"; exit 1; }
+1 -1
View File
@@ -169,7 +169,7 @@ jobs:
sed -i "s/assert prefixes == \['foo%2B1\/', 'foo\/', 'quux%20ab\/'\]/assert prefixes == \['foo\/', 'foo%2B1\/', 'quux%20ab\/'\]/" s3-tests/s3tests/functional/test_s3.py
sed -i "/# request PartNumber out of range/,+4{s/assert status == 400/assert status == 416/; s/assert error_code == 'InvalidPart'/assert error_code == 'InvalidPartNumber'/}" s3-tests/s3tests/functional/test_s3.py
- uses: actions/download-artifact@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
+10
View File
@@ -36,6 +36,7 @@ Table of Contents
* [Docker Compose](#docker-compose)
* [Kubernetes with Helm](#kubernetes-with-helm)
* [Build from source](#build-from-source)
* [Development builds](#development-builds)
* [Scale out](#scale-out)
* [Why SeaweedFS](#why-seaweedfs)
* [Fast](#fast)
@@ -175,6 +176,15 @@ cd seaweedfs/weed && make install
`weed` lands in `$GOPATH/bin`. [Getting Started][GettingStarted] covers running master, volume, filer, and S3 as separate processes.
## Development builds ##
Each dev build workflow publishes its latest successful build of `master`:
- **Binaries**: the [`dev` release](https://github.com/seaweedfs/seaweedfs/releases/tag/dev) has Linux amd64, Windows amd64, and macOS amd64/arm64 archives named `weed-<yyyymmdd-HHMM>-<linux|windows|darwin>-<arch>.tar.gz` (`.zip` on Windows) and `weed-large-disk-<yyyymmdd-HHMM>-<linux|windows|darwin>-<arch>`, each with an `.md5` checksum. The Rust volume server is published there too as `weed-volume-*` for Linux amd64 (glibc) and macOS amd64/arm64. The Go archives contain `weed-normal-disk` or `weed-large-disk` (`.exe` on Windows) rather than `weed`, and the Rust archives contain `weed-volume-normal` or `weed-volume-large-disk` rather than `weed-volume`, so rename or symlink the one you want. The `.md5` files are published for the Go archives only.
- **Containers**: `docker pull chrislusf/seaweedfs:dev` or `ghcr.io/chrislusf/seaweedfs:dev`, built for `linux/amd64` and `linux/arm64`. The [dev compose file](docker/seaweedfs-dev-compose.yml) runs the Docker Hub image as master, volume, filer, S3, WebDAV, and admin.
The timestamp in a binary name is the UTC start time of the run that built it. The Go binaries, the Rust volume server, and the `:dev` image come from three separate path-filtered workflows, so they can carry different timestamps and lag `master` by hours, or much longer when their paths were not touched. The release can list more than one timestamp for a while, for example after a failed or retried run; use the newest one for your platform. The `dev` release is marked pre-release, so it does not appear under [releases/latest](https://github.com/seaweedfs/seaweedfs/releases/latest); these builds come from `master`, can break at any commit, and are not recommended for production.
## Scale out ##
Capacity is a volume server. Start one on any machine with disk and point it at the master:
+15 -2
View File
@@ -278,11 +278,24 @@ automatic vacuum or another request is running does nothing and gets
### Delete a collection
```bash
curl "http://localhost:9333/col/delete?collection=benchmark"
curl -X DELETE "http://localhost:9333/col/delete?collection=benchmark"
```
Deletes all volumes of the collection, including erasure-coded shards.
`204 No Content` on success.
`204 No Content` on success. Only the `DELETE` method is accepted; any other
method gets `405 Method Not Allowed`.
The `collection` parameter is required: a request without it, or with an
empty value, gets `400 Bad Request`. To delete the default (empty-named)
collection, name it explicitly with `collection=_default` or
`collection=_default_`, the keywords `weed shell collection.delete` accepts.
If a collection is literally named a keyword, that name deletes it, and when
it exists next to the default collection the request gets
`400 Bad Request`; use the other keyword for the default collection. If both
keyword names are literal collections next to the default collection, both
keywords get `400 Bad Request`; delete the default collection with
`weed shell` `collection.delete -collection _default -apply`, where the
keywords always mean the default collection.
### Health
+4 -1
View File
@@ -169,7 +169,10 @@ func Run(args []string) int {
}
func runWithOptions(opts *Options) bool {
util.LoadConfiguration("security", false)
if err := util.LoadSecurityConfigurationOrError(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return false
}
// Validate options.
if opts.MasterAddr == "" {
+6
View File
@@ -13,6 +13,7 @@ import (
"github.com/peterh/liner"
"github.com/seaweedfs/seaweedfs/weed/query/engine"
"github.com/seaweedfs/seaweedfs/weed/util"
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
"github.com/seaweedfs/seaweedfs/weed/util/sqlutil"
@@ -106,6 +107,11 @@ func Run(args []string) int {
}
func runWithOptions(opts *Options) bool {
if err := util.LoadSecurityConfigurationOrError(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return false
}
// Initialize SQL engine with master address for service discovery.
sqlEngine := engine.NewSQLEngine(opts.Master)
+3 -1
View File
@@ -21,7 +21,9 @@ docker compose -f seaweedfs-compose.yml -p seaweedfs up
```
## Try latest tip
## Try the latest development image
The compose file below uses `chrislusf/seaweedfs:dev`, built from `master`. It is a development image, not a stable release, and can lag `master` by hours or more; the `org.opencontainers.image.revision` label records the commit it was built from, and pinning by digest keeps that exact build. See [Development builds](../README.md#development-builds) for the `dev` binaries and image details.
```bash
+9 -6
View File
@@ -129,12 +129,15 @@ recursive, and the folder may hold files SeaweedFS never saw.
An access token and its refresh token both live about a year. The client
refreshes the access token when it expires or when the API answers 401, and
uses the rotated refresh token Yandex returns. The refreshed token is kept in
memory only: a client cannot write the configuration back to the filer. A
restart within the token's lifetime keeps working with the stored refresh
token; once Yandex rejects it (`invalid_grant`), issue a new one with
`-yandex.oauth_url` and `-yandex.code` above. Yandex recommends refreshing a
long-lived token every three months.
uses the new refresh token Yandex returns. The refreshed token is kept in
memory only: a client cannot write the configuration back to the filer, so
every restart, and every other process using the same configuration, starts
again from the stored refresh token. Yandex does not document whether that
token stays valid once a newer one has been issued, so after a refresh a
restart can fail with `invalid_grant`. Then, or when the stored token nears
the end of its year, issue a new one with `-yandex.oauth_url` and
`-yandex.code` above. Yandex recommends refreshing a long-lived token every
three months.
## Not covered
+14 -13
View File
@@ -21,12 +21,12 @@ require (
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/aws/aws-sdk-go v1.55.8
github.com/aws/aws-sdk-go-v2 v1.48.0
github.com/aws/aws-sdk-go-v2 v1.48.1
github.com/aws/aws-sdk-go-v2/config v1.33.9
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.9
github.com/aws/smithy-go v1.28.10
github.com/bwmarrin/snowflake v0.3.0
github.com/cenkalti/backoff/v4 v4.3.0
github.com/cespare/xxhash/v2 v2.3.0
@@ -52,13 +52,13 @@ require (
github.com/hashicorp/raft v1.8.0
github.com/hashicorp/raft-boltdb/v2 v2.4.2
github.com/hashicorp/vault/api v1.23.0
github.com/jackc/pgx/v5 v5.10.0
github.com/jhump/protoreflect v1.18.1
github.com/jackc/pgx/v5 v5.13.0
github.com/jhump/protoreflect v1.19.0
github.com/jinzhu/copier v0.4.0
github.com/json-iterator/go v1.1.12
github.com/k0kubun/pp v3.0.1+incompatible
github.com/karlseguin/ccache/v2 v2.0.8
github.com/klauspost/compress v1.20.3
github.com/klauspost/compress v1.20.5
github.com/klauspost/reedsolomon v1.14.2
github.com/kurin/blazer v0.5.3
github.com/linkedin/goavro/v2 v2.15.0
@@ -67,7 +67,7 @@ require (
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
github.com/olivere/elastic/v7 v7.0.32
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.32.0
github.com/parquet-go/parquet-go v0.33.0
github.com/peterh/liner v1.2.3
github.com/pierrec/lz4/v4 v4.1.33
github.com/pkg/sftp v1.13.12
@@ -99,6 +99,7 @@ require (
github.com/tikv/client-go/v2 v2.0.7
github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365
github.com/twmb/avro v1.9.0
github.com/twpayne/go-geom v1.6.1
github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43
github.com/valyala/bytebufferpool v1.0.0
github.com/viant/ptrie v1.0.1
@@ -110,7 +111,7 @@ require (
go.etcd.io/etcd/api/v3 v3.7.3
go.etcd.io/etcd/client/pkg/v3 v3.7.4
go.etcd.io/etcd/client/v3 v3.7.3
go.mongodb.org/mongo-driver v1.17.9
go.mongodb.org/mongo-driver v1.17.10
go.uber.org/atomic v1.12.0
go.yaml.in/yaml/v3 v3.0.6
gocloud.dev v0.49.0
@@ -120,7 +121,7 @@ require (
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
golang.org/x/image v0.46.0
golang.org/x/net v0.62.0
golang.org/x/oauth2 v0.37.0
golang.org/x/oauth2 v0.38.0
golang.org/x/sync v0.25.0
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0
@@ -171,7 +172,7 @@ require (
github.com/abbot/go-http-auth v0.4.0 // indirect
github.com/adrg/xdg v0.5.3 // indirect
github.com/anchore/go-lzo v0.1.1 // indirect
github.com/andybalholm/brotli v1.2.8 // indirect
github.com/andybalholm/brotli v1.3.0 // indirect
github.com/andybalholm/cascadia v1.3.4 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/thrift v0.25.0 // indirect
@@ -308,7 +309,7 @@ require (
github.com/internxt/rclone-adapter v0.0.0-20260708165336-dd6561bacfa2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/jaegertracing/jaeger v1.47.0 // indirect
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
@@ -374,8 +375,8 @@ require (
github.com/openzipkin/zipkin-go v0.4.3 // indirect
github.com/oracle/oci-go-sdk/v65 v65.121.0 // indirect
github.com/panjf2000/ants/v2 v2.12.1 // indirect
github.com/parquet-go/bitpack v1.0.0 // indirect
github.com/parquet-go/jsonlite v1.0.0 // indirect
github.com/parquet-go/bitpack v1.1.1 // indirect
github.com/parquet-go/jsonlite v1.5.7 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
@@ -384,6 +385,7 @@ require (
github.com/pierrre/geohash v1.0.0 // indirect
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
github.com/pingcap/goleveldb v0.0.0-20191226122134-f82aafb29989 // indirect
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
@@ -433,7 +435,6 @@ require (
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/twmb/murmur3 v1.1.8 // indirect
github.com/twpayne/go-geom v1.6.1 // indirect
github.com/twpayne/go-kml/v3 v3.2.1 // indirect
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
+24 -24
View File
@@ -142,8 +142,8 @@ github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktp
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/anchore/go-lzo v0.1.1 h1:IwL/fvkdtlIrYIXck6WxZ3nb8WjjHziYYmGxlooyOnM=
github.com/anchore/go-lzo v0.1.1/go.mod h1:3kLx0bve2oN1iDwgM1U5zGku1Tfbdb0No5qp1eL1fIk=
github.com/andybalholm/brotli v1.2.8 h1:H9F6r7RNwzSRsx/lytpIYkbjNFMt2yNBwsJ2+0gpx78=
github.com/andybalholm/brotli v1.2.8/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
@@ -171,8 +171,8 @@ github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJ
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
github.com/aws/aws-sdk-go-v2 v1.48.1 h1:j6ro6IvbxUe8BCulc/6uWMrhmx6+i5HNIc1GZEJRT9k=
github.com/aws/aws-sdk-go-v2 v1.48.1/go.mod h1:HP8Jzg1FDurJomtx40YM0eiLoJrwjjZ9X+4BNpy4OXc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
@@ -213,8 +213,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEB
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
@@ -722,10 +722,10 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
github.com/jaegertracing/jaeger v1.47.0/go.mod h1:mHU/OHFML51CijQql4+rLfgPOcIb9MhxOMn+RKQwrJc=
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
@@ -740,8 +740,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/jhump/protoreflect v1.18.1 h1:h4odAaLg9wyn7yHxMF7sSkJ7JfLwK1oy37/1Pi212GE=
github.com/jhump/protoreflect v1.18.1/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
github.com/jhump/protoreflect v1.19.0 h1:YhKbE78JrjfngcCZfZTIV7rQQGndyqll6fXfaqiOEg4=
github.com/jhump/protoreflect v1.19.0/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 h1:Dw1rslK/VotaUGYsv53XVWITr+5RCPXfvvlGrM/+B6w=
github.com/jhump/protoreflect/v2 v2.0.0-beta.1/go.mod h1:D9LBEowZyv8/iSu97FU2zmXG3JxVTmNw21mu63niFzU=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
@@ -782,8 +782,8 @@ github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXw
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4=
github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/reedsolomon v1.14.2 h1:SafJYwpBBQBI6amHUygcjxZjXeN2HpiENHQDwuPWCCQ=
@@ -955,12 +955,12 @@ github.com/orcaman/concurrent-map/v2 v2.0.1 h1:jOJ5Pg2w1oeB6PeDurIYf6k9PQ+aTITr/
github.com/orcaman/concurrent-map/v2 v2.0.1/go.mod h1:9Eq3TG2oBe5FirmYWQfYO5iH1q0Jv47PLaNK++uCdOM=
github.com/panjf2000/ants/v2 v2.12.1 h1:BWvU2wHpyXWxhhNXsGB6JXLCNbshyLd1QxvoAmZnu10=
github.com/panjf2000/ants/v2 v2.12.1/go.mod h1:tSQuaNQ6r6NRhPt+IZVUevvDyFMTs+eS4ztZc52uJTY=
github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxPcQA=
github.com/parquet-go/bitpack v1.0.0/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZdd7VU=
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
github.com/parquet-go/parquet-go v0.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
github.com/parquet-go/bitpack v1.1.1 h1:mygqlCBk/rnvtqqP5Oy7IkIPAxZ3bDM7V4yce/ms6pE=
github.com/parquet-go/bitpack v1.1.1/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.5.7 h1:FxIrc2MBZ9QLpljM1+3F3JuCuug+BWOt8Yx+S4o3bl8=
github.com/parquet-go/jsonlite v1.5.7/go.mod h1:ZIyft0+sSdvgTu2m6RpqxWx/F3UBNtF3ammevxDJcoE=
github.com/parquet-go/parquet-go v0.33.0 h1:iDe13lcW6t0mnZWPqKqWccNa5GdP/L9GNNyzlr8JqNY=
github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMPJ6I+/zmNnsOSh4=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
@@ -1355,8 +1355,8 @@ go.etcd.io/etcd/client/pkg/v3 v3.7.4 h1:633yLMDAQHWqLTRMxUNuZfOy6a4REJPcA3juoMRx
go.etcd.io/etcd/client/pkg/v3 v3.7.4/go.mod h1:I1lMmoiq2SF4Wg0Gru7uXMovS1eEo6wwAxcFPFPk/v0=
go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q=
go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE=
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
go.mongodb.org/mongo-driver v1.17.10 h1:kdAgQvu8TROXZpSkJQd5wzfaNCCrMbpZyKFtQ6qkPCE=
go.mongodb.org/mongo-driver v1.17.10/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
@@ -1501,8 +1501,8 @@ golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.55"
appVersion: "4.56"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.55.0
version: 4.56.0
+1060 -1016
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 54 KiB

@@ -42,12 +42,26 @@ public class FileChunkManifest {
// avoid deprecated chunk.getFileId()
resolvedChunks.add(t.toBuilder().setFileId(FilerClient.toFileId(t.getFid())).build());
}
dataChunks.addAll(resolveChunkManifest(filerClient, resolvedChunks));
dataChunks.addAll(resolveChunkManifest(filerClient, cutToManifestSpan(chunk, resolvedChunks)));
}
return dataChunks;
}
// A truncate may have shortened a manifest and left the chunks it holds whole.
static List<FilerProto.FileChunk> cutToManifestSpan(FilerProto.FileChunk manifest, List<FilerProto.FileChunk> held) {
long end = manifest.getOffset() + manifest.getSize();
List<FilerProto.FileChunk> cut = new ArrayList<>(held.size());
for (FilerProto.FileChunk chunk : held) {
if (chunk.getOffset() + chunk.getSize() <= end) {
cut.add(chunk);
} else if (chunk.getOffset() < end) {
cut.add(chunk.toBuilder().setSize(end - chunk.getOffset()).build());
}
}
return cut;
}
private static byte[] fetchChunk(final FilerClient filerClient, FilerProto.FileChunk chunk) throws IOException {
String vid = "" + chunk.getFid().getVolumeId();
@@ -0,0 +1,102 @@
package seaweedfs.client;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
// Credentials for a filer's own HTTP port: [filer.basic_auth], [jwt.filer_signing] and
// [jwt.filer_signing.read]. Each FilerClient starts from its own copy of the security.toml values.
public final class FilerCredentials {
private static final long DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS = 10;
private static final long DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS = 60;
private volatile String basicAuthUser = "";
private volatile String basicAuthPassword = "";
private volatile String basicAuthHeaderValue;
private volatile String signingKey = "";
private volatile long signingExpiresAfterSeconds = DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS;
private volatile String readSigningKey = "";
private volatile long readSigningExpiresAfterSeconds = DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS;
public FilerCredentials() {
}
public FilerCredentials(FilerCredentials other) {
synchronized (other) {
basicAuthUser = other.basicAuthUser;
basicAuthPassword = other.basicAuthPassword;
basicAuthHeaderValue = other.basicAuthHeaderValue;
signingKey = other.signingKey;
signingExpiresAfterSeconds = other.signingExpiresAfterSeconds;
readSigningKey = other.readSigningKey;
readSigningExpiresAfterSeconds = other.readSigningExpiresAfterSeconds;
}
}
// A null argument keeps the current value. Like the filer, an empty password turns
// Basic Auth off and an empty user is allowed.
public synchronized void setBasicAuth(String user, String password) {
if (user != null) {
basicAuthUser = user;
}
if (password != null) {
basicAuthPassword = password;
}
basicAuthHeaderValue = basicAuthPassword.isEmpty() ? null
: FilerSecurityContext.encodeBasicAuth(basicAuthUser, basicAuthPassword);
}
// A null key or expiresAfterSeconds <= 0 keeps the current value; an empty key turns signing off.
public synchronized void setJwtSigningKey(String key, long expiresAfterSeconds) {
if (key != null) {
signingKey = key;
}
if (expiresAfterSeconds > 0) {
signingExpiresAfterSeconds = expiresAfterSeconds;
}
}
// Same as setJwtSigningKey, for the read key.
public synchronized void setJwtReadSigningKey(String key, long expiresAfterSeconds) {
if (key != null) {
readSigningKey = key;
}
if (expiresAfterSeconds > 0) {
readSigningExpiresAfterSeconds = expiresAfterSeconds;
}
}
// Returns the Authorization header value for an HTTP request addressed to the filer:
// a filer JWT for the access level when its key is set, else [filer.basic_auth], else
// [basic_auth]; null when none is configured. The filer reads GET and HEAD with the read key.
public String getAuthorizationHeaderValue(boolean isWrite) {
String key = isWrite ? signingKey : readSigningKey;
if (!key.isEmpty()) {
return "BEARER " + genJwtForFilerServer(key.getBytes(StandardCharsets.UTF_8),
isWrite ? signingExpiresAfterSeconds : readSigningExpiresAfterSeconds);
}
String basicAuth = basicAuthHeaderValue;
if (basicAuth != null) {
return basicAuth;
}
return FilerSecurityContext.getBasicAuthHeaderValue();
}
// Mints an HS256 token with only an "exp" claim, like security.GenJwtForFilerServer.
static String genJwtForFilerServer(byte[] signingKey, long expiresAfterSeconds) {
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
long exp = System.currentTimeMillis() / 1000 + expiresAfterSeconds;
String signingInput = encoder.encodeToString("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8))
+ "." + encoder.encodeToString(("{\"exp\":" + exp + "}").getBytes(StandardCharsets.UTF_8));
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
return signingInput + "." + encoder.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("cannot sign filer jwt", e);
}
}
}
@@ -50,6 +50,7 @@ public class FilerGrpcClient {
private String replication = "";
private int volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT;
private String filerAddress;
private final FilerCredentials filerCredentials = new FilerCredentials(FilerSecurityContext.getFilerCredentials());
public FilerGrpcClient(String host, int port, int grpcPort, String cn) {
this(host, port, grpcPort, cn, sslContext);
@@ -154,6 +155,11 @@ public class FilerGrpcClient {
return SeaweedFilerGrpc.newFutureStub(getChannel());
}
// Credentials for this client's requests to the filer's HTTP port; changes affect only this client.
public FilerCredentials getFilerCredentials() {
return filerCredentials;
}
public void setAccessVolumeServerDirectly() {
this.volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT;
}
@@ -183,9 +189,18 @@ public class FilerGrpcClient {
case VOLUME_SERVER_ACCESS_PUBLIC_URL:
return String.format("%s://%s/%s", protocol, publicUrl, chunkId);
case VOLUME_SERVER_ACCESS_FILER_PROXY:
return String.format("%s://%s/?proxyChunkId=%s", protocol, this.filerAddress, chunkId);
return proxyChunkUrlPrefix() + chunkId;
default:
return String.format("%s://%s/%s", protocol, url, chunkId);
}
}
// Reports whether a chunk URL addresses this client's filer chunk proxy rather than a volume server.
public boolean isProxyChunkUrl(String url) {
return isAccessVolumeServerByFilerProxy() && url != null && url.startsWith(proxyChunkUrlPrefix());
}
private String proxyChunkUrlPrefix() {
return String.format("%s://%s/?proxyChunkId=", protocol, this.filerAddress);
}
}
@@ -43,6 +43,8 @@ public abstract class FilerSecurityContext extends SslContext {
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
private static volatile String basicAuthHeaderValue;
private static final FilerCredentials filerCredentials = new FilerCredentials();
static {
String securityFileName = "security.toml";
@@ -64,6 +66,11 @@ public abstract class FilerSecurityContext extends SslContext {
basicAuthHeaderValue = computeBasicAuthHeaderValue(
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
filerCredentials.setBasicAuth(toml.getString("filer.basic_auth.user"), toml.getString("filer.basic_auth.password"));
filerCredentials.setJwtSigningKey(toml.getString("jwt.filer_signing.key"),
toml.getLong("jwt.filer_signing.expires_after_seconds", 0L));
filerCredentials.setJwtReadSigningKey(toml.getString("jwt.filer_signing.read.key"),
toml.getLong("jwt.filer_signing.read.expires_after_seconds", 0L));
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
@@ -86,7 +93,7 @@ public abstract class FilerSecurityContext extends SslContext {
}
}
if (toml.getBoolean("https.client.enabled")) {
if (toml.getBoolean("https.client.enabled", false)) {
httpTrustCertCollectionFilePath = toml.getString("https.client.ca");
logger.debug("loading HTTP ca from {}", httpTrustCertCollectionFilePath);
httpClientCertChainFilePath = toml.getString("https.client.cert");
@@ -146,11 +153,20 @@ public abstract class FilerSecurityContext extends SslContext {
return basicAuthHeaderValue;
}
// The filer credentials read from security.toml; each FilerClient copies them.
static FilerCredentials getFilerCredentials() {
return filerCredentials;
}
private static String computeBasicAuthHeaderValue(String username, String password) {
if (Strings.isNullOrEmpty(username)) {
return null;
}
String credentials = username + ":" + (password == null ? "" : password);
return encodeBasicAuth(username, password == null ? "" : password);
}
static String encodeBasicAuth(String username, String password) {
String credentials = username + ":" + password;
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
}
@@ -136,7 +136,7 @@ public class SeaweedRead {
for (FilerProto.Location location : locations.getLocationsList()) {
String url = filerClient.getChunkUrl(chunkView.fileId, location.getUrl(), location.getPublicUrl());
try {
byte[] fetched = doFetchOneFullChunkData(chunkView, url);
byte[] fetched = doFetchOneFullChunkData(filerClient, chunkView, url);
// An empty (or null) body for a chunk we are reading from is never
// valid; treat it as a transient failure so the retry loop tries
// another location and backs off, rather than caching an empty chunk.
@@ -171,15 +171,19 @@ public class SeaweedRead {
}
private static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException {
private static byte[] doFetchOneFullChunkData(FilerClient filerClient, ChunkView chunkView, String url) throws IOException {
HttpGet request = new HttpGet(url);
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
String authHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (filerClient.isProxyChunkUrl(url)) {
authHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(false);
request.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG);
}
if (authHeader != null) {
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
byte[] data = null;
@@ -187,6 +191,11 @@ public class SeaweedRead {
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
try {
int status = response.getStatusLine().getStatusCode();
if (status / 100 != 2) {
throw new IOException("fetch " + url + ": " + response.getStatusLine());
}
HttpEntity entity = response.getEntity();
Header contentEncodingHeader = entity.getContentEncoding();
@@ -1,5 +1,6 @@
package seaweedfs.client;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
@@ -90,4 +91,7 @@ public class SeaweedUtil {
}
return host + ":" + port;
}
// Redirects would carry the filer credential to the redirect target.
static final RequestConfig PROXY_CHUNK_REQUEST_CONFIG = RequestConfig.custom().setRedirectsEnabled(false).build();
}
@@ -135,7 +135,7 @@ public class SeaweedWrite {
cipherKeyString = ByteString.copyFrom(cipherKey);
}
String etag = multipartUpload(targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey);
String etag = multipartUpload(filerClient, targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey);
return FilerProto.FileChunk.newBuilder()
.setFileId(fileId)
@@ -167,7 +167,8 @@ public class SeaweedWrite {
}
}
private static String multipartUpload(String targetUrl,
private static String multipartUpload(FilerClient filerClient,
String targetUrl,
String auth,
final byte[] bytes,
final long bytesOffset, final long bytesLength,
@@ -193,7 +194,14 @@ public class SeaweedWrite {
}
HttpPost post = new HttpPost(targetUrl);
if (auth != null && auth.length() != 0) {
String filerAuthHeader = null;
if (filerClient.isProxyChunkUrl(targetUrl)) {
filerAuthHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(true);
post.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG);
}
if (filerAuthHeader != null) {
post.addHeader("Authorization", filerAuthHeader);
} else if (auth != null && auth.length() != 0) {
// Volume JWT and Basic Auth both use the Authorization header; the JWT wins
// when present. Front the volume with a JWT-free path to use Basic Auth here.
post.addHeader("Authorization", "BEARER " + auth);
@@ -556,9 +556,15 @@ message AtomicRenameEntryRequest {
// already exists. Lets a caller that authorized the rename without delete
// access on an absent target stay safe if one is created concurrently.
bool fail_if_target_exists = 6;
// Set on a rename forwarded to the source's write owner, so it is not
// forwarded again.
bool is_moved = 7;
}
message AtomicRenameEntryResponse {
// Set for a forwarded rename: the owner's metadata log position of
// the rename's last event.
int64 ts_ns = 1;
}
message StreamRenameEntryRequest {
@@ -567,6 +573,9 @@ message StreamRenameEntryRequest {
string new_directory = 3;
string new_name = 4;
repeated int32 signatures = 5;
// Set on a rename forwarded to the source's write owner, so it is not
// forwarded again.
bool is_moved = 6;
}
message StreamRenameEntryResponse {
string directory = 1;
@@ -0,0 +1,43 @@
package seaweedfs.client;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FileChunkManifestTest {
private static FilerProto.FileChunk chunk(int volumeId, long key, long offset, long size) {
return FilerProto.FileChunk.newBuilder()
.setFid(FilerProto.FileId.newBuilder().setVolumeId(volumeId).setFileKey(key).setCookie(1))
.setOffset(offset)
.setSize(size)
.setModifiedTsNs(1)
.build();
}
@Test
public void testCutToManifestSpanCutsAShortenedManifest() throws IOException {
List<FilerProto.FileChunk> held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100), chunk(9, 3, 200, 100));
FilerProto.FileChunk manifest = chunk(9, 4, 0, 150).toBuilder().setIsChunkManifest(true).build();
List<FilerProto.FileChunk> cut = FileChunkManifest.cutToManifestSpan(manifest, held);
Assert.assertEquals(2, cut.size());
Assert.assertEquals(held.get(0), cut.get(0));
Assert.assertEquals(100, cut.get(1).getOffset());
Assert.assertEquals(50, cut.get(1).getSize());
Assert.assertEquals(100, held.get(1).getSize());
List<SeaweedRead.VisibleInterval> visibles = ReadChunks.readResolvedChunks(cut);
Assert.assertEquals(150, visibles.get(visibles.size() - 1).stop);
}
@Test
public void testCutToManifestSpanLeavesAWholeManifestAlone() {
List<FilerProto.FileChunk> held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100));
FilerProto.FileChunk manifest = chunk(9, 4, 0, 200).toBuilder().setIsChunkManifest(true).build();
Assert.assertEquals(held, FileChunkManifest.cutToManifestSpan(manifest, held));
}
}
@@ -0,0 +1,244 @@
package seaweedfs.client;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class FilerJwtTest {
private FilerCredentials credentials;
@Before
public void clearCredentials() {
FilerSecurityContext.setBasicAuth(null, null);
credentials = new FilerCredentials();
}
@After
public void clearProxyBasicAuth() {
FilerSecurityContext.setBasicAuth(null, null);
}
@Test
public void filerJwtIsSignedHs256WithExp() throws Exception {
long before = System.currentTimeMillis() / 1000;
String token = FilerCredentials.genJwtForFilerServer("write-key".getBytes(StandardCharsets.UTF_8), 10);
long after = System.currentTimeMillis() / 1000;
String[] parts = token.split("\\.");
assertEquals(3, parts.length);
assertEquals("{\"alg\":\"HS256\",\"typ\":\"JWT\"}", decode(parts[0]));
long exp = exp(decode(parts[1]));
assertTrue(exp >= before + 10 && exp <= after + 10);
assertEquals(sign("write-key", parts[0] + "." + parts[1]), parts[2]);
assertFalse(token.contains("="));
}
@Test
public void noCredentialsMeansNoFilerHeader() {
assertNull(credentials.getAuthorizationHeaderValue(true));
assertNull(credentials.getAuthorizationHeaderValue(false));
}
@Test
public void accessLevelPicksItsSigningKey() throws Exception {
credentials.setJwtSigningKey("write-key", 0);
credentials.setJwtReadSigningKey("read-key", 0);
long now = System.currentTimeMillis() / 1000;
String[] write = bearer(credentials.getAuthorizationHeaderValue(true));
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
assertTrue(exp(decode(write[1])) - now <= 11);
String[] read = bearer(credentials.getAuthorizationHeaderValue(false));
assertEquals(sign("read-key", read[0] + "." + read[1]), read[2]);
assertTrue(exp(decode(read[1])) - now >= 60);
}
@Test
public void basicAuthCoversAccessLevelsWithoutKey() {
FilerSecurityContext.setBasicAuth("proxy", "proxy-pass");
assertEquals(FilerSecurityContext.getBasicAuthHeaderValue(),
credentials.getAuthorizationHeaderValue(false));
credentials.setBasicAuth("filer", "filer-pass");
String filerBasic = "Basic " + Base64.getEncoder()
.encodeToString("filer:filer-pass".getBytes(StandardCharsets.UTF_8));
assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false));
credentials.setJwtSigningKey("write-key", 5);
assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("BEARER "));
assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false));
}
@Test
public void filerBasicAuthFollowsThePassword() {
credentials.setBasicAuth("filer", "");
assertNull(credentials.getAuthorizationHeaderValue(false));
credentials.setBasicAuth("", "only-pass");
assertEquals("Basic " + Base64.getEncoder().encodeToString(":only-pass".getBytes(StandardCharsets.UTF_8)),
credentials.getAuthorizationHeaderValue(false));
}
@Test
public void nullKeepsTheCurrentValue() throws Exception {
credentials.setBasicAuth("filer", "old-pass");
credentials.setBasicAuth(null, "new-pass");
assertEquals("Basic " + Base64.getEncoder().encodeToString("filer:new-pass".getBytes(StandardCharsets.UTF_8)),
credentials.getAuthorizationHeaderValue(false));
credentials.setJwtSigningKey("write-key", 0);
credentials.setJwtSigningKey(null, 300);
long now = System.currentTimeMillis() / 1000;
String[] write = bearer(credentials.getAuthorizationHeaderValue(true));
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
assertTrue(exp(decode(write[1])) - now >= 300);
credentials.setJwtSigningKey("", 0);
assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("Basic "));
}
@Test
public void copiesSignIndependently() throws Exception {
credentials.setJwtSigningKey("shared-key", 0);
FilerCredentials a = new FilerCredentials(credentials);
FilerCredentials b = new FilerCredentials(credentials);
b.setJwtSigningKey("b-key", 0);
String[] fromA = bearer(a.getAuthorizationHeaderValue(true));
String[] fromB = bearer(b.getAuthorizationHeaderValue(true));
assertEquals(sign("shared-key", fromA[0] + "." + fromA[1]), fromA[2]);
assertEquals(sign("b-key", fromB[0] + "." + fromB[1]), fromB[2]);
String[] fromDefaults = bearer(credentials.getAuthorizationHeaderValue(true));
assertEquals(sign("shared-key", fromDefaults[0] + "." + fromDefaults[1]), fromDefaults[2]);
}
@Test
public void onlyFilerProxyUrlsAreFilerRequests() throws Exception {
Server filerGrpc = startFilerGrpc();
FilerClient filerClient = new FilerClient("127.0.0.1", 8888, filerGrpc.getPort(), "");
try {
String proxyUrl = "http://127.0.0.1:8888/?proxyChunkId=3,01637037d6";
assertFalse(filerClient.isProxyChunkUrl(proxyUrl));
filerClient.setAccessVolumeServerByFilerProxy();
assertEquals(proxyUrl, filerClient.getChunkUrl("3,01637037d6", "volume:8080", "volume:8080"));
assertTrue(filerClient.isProxyChunkUrl(proxyUrl));
assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/3,01637037d6"));
assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/?proxyChunkId=/3,01637037d6"));
assertFalse(filerClient.isProxyChunkUrl("http://127.0.0.1:8888.example/?proxyChunkId=3,01637037d6"));
assertFalse(filerClient.isProxyChunkUrl(null));
} finally {
filerClient.shutdown();
filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}
@Test
public void proxyChunkReadDoesNotFollowRedirects() throws Exception {
AtomicInteger targetHits = new AtomicInteger();
HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
target.createContext("/", exchange -> {
targetHits.incrementAndGet();
respond(exchange, 200, "leaked");
});
List<String> filerAuth = new CopyOnWriteArrayList<>();
HttpServer filer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
filer.createContext("/", exchange -> {
filerAuth.add(exchange.getRequestHeaders().getFirst("Authorization"));
if (filerAuth.size() == 1) {
exchange.getResponseHeaders().set("Location", "http://127.0.0.1:" + target.getAddress().getPort() + "/");
respond(exchange, 302, "");
} else {
respond(exchange, 200, "chunk");
}
});
Server filerGrpc = startFilerGrpc();
target.start();
filer.start();
FilerClient filerClient = new FilerClient("127.0.0.1", filer.getAddress().getPort(), filerGrpc.getPort(), "");
try {
filerClient.setAccessVolumeServerByFilerProxy();
filerClient.getFilerCredentials().setJwtReadSigningKey("read-key", 0);
FilerProto.Locations locations = FilerProto.Locations.newBuilder()
.addLocations(FilerProto.Location.newBuilder().setUrl("volume:8080")).build();
byte[] data = SeaweedRead.doFetchFullChunkData(filerClient,
new SeaweedRead.ChunkView("3,01637037d6", 0, 5, 0, true, null, false), locations);
assertEquals("chunk", new String(data, StandardCharsets.UTF_8));
assertEquals(0, targetHits.get());
assertEquals(2, filerAuth.size());
assertTrue(filerAuth.get(0).startsWith("BEARER "));
} finally {
filerClient.shutdown();
filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
filer.stop(0);
target.stop(0);
}
}
private static Server startFilerGrpc() throws IOException {
return ServerBuilder.forPort(0).addService(new SeaweedFilerGrpc.SeaweedFilerImplBase() {
@Override
public void getFilerConfiguration(FilerProto.GetFilerConfigurationRequest request,
StreamObserver<FilerProto.GetFilerConfigurationResponse> observer) {
observer.onNext(FilerProto.GetFilerConfigurationResponse.getDefaultInstance());
observer.onCompleted();
}
}).build().start();
}
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
}
private static String[] bearer(String header) {
assertTrue(header.startsWith("BEARER "));
return header.substring("BEARER ".length()).split("\\.");
}
private static String decode(String part) {
return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8);
}
private static long exp(String payload) {
Matcher m = Pattern.compile("^\\{\"exp\":(\\d+)\\}$").matcher(payload);
assertTrue(payload, m.matches());
return Long.parseLong(m.group(1));
}
private static String sign(String key, String signingInput) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
}
}
+69
View File
@@ -149,6 +149,75 @@ The test suite covers:
hadoop fs -put local.txt seaweedfs://localhost:8888/test/
```
### Secured filer
With `fs.seaweed.volume.server.access` set to `filerProxy`, chunk reads and writes go to the
filer's HTTP port, so they need the filer's HTTP credentials. The client signs a filer JWT
when it has the filer's `jwt.filer_signing` key (writes) or
`jwt.filer_signing.read` key (reads), and otherwise sends the `[filer.basic_auth]`
credentials. These credentials are sent only to the filer, never to volume servers. In `direct`
and `publicUrl` modes chunk requests go straight to volume servers, so the filer's HTTP
credentials are not used; writes carry the volume token from the volume assignment as before.
gRPC mTLS comes from the `[grpc]` section as before, but it does not cover these HTTP chunk requests:
to keep the credentials off plain HTTP, serve the filer HTTP port over HTTPS (`[https.filer]`
on the filer) and enable `[https.client]` here. The client checks the certificate chain but
not the host name, so set `https.client.ca` to a CA that issues certificates only for your
SeaweedFS servers.
`security.toml` (read from `./`, `~/.seaweedfs/` or `/etc/seaweedfs/`), using the filer's
own values:
```toml
[jwt.filer_signing]
key = "<filer write key>"
[jwt.filer_signing.read]
key = "<filer read key>"
# or, for a filer with Basic Auth
[filer.basic_auth]
user = "<user>"
password = "<password>"
[grpc]
ca = "/etc/seaweedfs/ca.crt"
[grpc.client]
cert = "/etc/seaweedfs/client.crt"
key = "/etc/seaweedfs/client.key"
[https.client]
enabled = true
ca = "/etc/seaweedfs/ca.crt"
cert = "/etc/seaweedfs/client.crt"
key = "/etc/seaweedfs/client.key"
```
The same values can be set in `core-site.xml`. Each option overrides only its own
`security.toml` value (for example, a password alone keeps the `security.toml` user), and
applies only to that filesystem. The secrets can also come from a Hadoop credential provider:
```xml
<property>
<name>fs.seaweed.volume.server.access</name>
<value>filerProxy</value>
</property>
<property>
<name>fs.seaweed.filer.jwt.signing.key</name>
<value>filer write key</value>
</property>
<property>
<name>fs.seaweed.filer.jwt.signing.read.key</name>
<value>filer read key</value>
</property>
<!-- token lifetimes, defaults 10 and 60 seconds:
fs.seaweed.filer.jwt.signing.expires.after.seconds
fs.seaweed.filer.jwt.signing.read.expires.after.seconds -->
<!-- or Basic Auth:
fs.seaweed.filer.basic.auth.user
fs.seaweed.filer.basic.auth.password -->
```
## Continuous Integration
For CI environments, tests can be run in two modes:
@@ -10,6 +10,7 @@ import org.apache.hadoop.util.Progressable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import seaweedfs.client.FilerProto;
import seaweedfs.client.FilerCredentials;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -30,6 +31,12 @@ public class SeaweedFileSystem extends FileSystem {
public static final String FS_SEAWEED_VOLUME_SERVER_ACCESS = "fs.seaweed.volume.server.access";
public static final int FS_SEAWEED_DEFAULT_BUFFER_SIZE = 4 * 1024 * 1024;
public static final String FS_SEAWEED_FILER_CN = "fs.seaweed.filer.cn";
public static final String FS_SEAWEED_FILER_BASIC_AUTH_USER = "fs.seaweed.filer.basic.auth.user";
public static final String FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD = "fs.seaweed.filer.basic.auth.password";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_KEY = "fs.seaweed.filer.jwt.signing.key";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES = "fs.seaweed.filer.jwt.signing.expires.after.seconds";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY = "fs.seaweed.filer.jwt.signing.read.key";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES = "fs.seaweed.filer.jwt.signing.read.expires.after.seconds";
private static final Logger LOG = LoggerFactory.getLogger(SeaweedFileSystem.class);
@@ -69,6 +76,21 @@ public class SeaweedFileSystem extends FileSystem {
seaweedFileSystemStore = new SeaweedFileSystemStore(host, port, grpcPort, cn, conf);
}
// Each option set here overrides only its own [filer.basic_auth] or [jwt.filer_signing] value of security.toml.
static void applyFilerCredentials(Configuration conf, FilerCredentials credentials) throws IOException {
credentials.setBasicAuth(conf.get(FS_SEAWEED_FILER_BASIC_AUTH_USER),
secret(conf, FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD));
credentials.setJwtSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_KEY),
conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 0));
credentials.setJwtReadSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY),
conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 0));
}
private static String secret(Configuration conf, String name) throws IOException {
char[] value = conf.getPassword(name);
return value == null ? null : new String(value);
}
@Override
public void close() throws IOException {
super.close();
@@ -27,9 +27,15 @@ public class SeaweedFileSystemStore {
private FilerClient filerClient;
private Configuration conf;
public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) {
public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) throws IOException {
filerClient = new FilerClient(host, port, grpcPort, cn);
this.conf = conf;
try {
SeaweedFileSystem.applyFilerCredentials(conf, filerClient.getFilerCredentials());
} catch (IOException | RuntimeException e) {
close();
throw e;
}
String volumeServerAccessMode = this.conf.get(FS_SEAWEED_VOLUME_SERVER_ACCESS, "direct");
if (volumeServerAccessMode.equals("publicUrl")) {
filerClient.setAccessVolumeServerByPublicUrl();
@@ -4,6 +4,12 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Test;
import seaweedfs.client.FilerCredentials;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.Assert.*;
@@ -87,4 +93,57 @@ public class SeaweedFileSystemConfigTest {
// Test default port constant
assertEquals(8888, SeaweedFileSystem.FS_SEAWEED_DEFAULT_PORT);
}
@Test
public void testFilerCredentialsFromConfiguration() throws Exception {
FilerCredentials credentials = new FilerCredentials();
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_USER, "alice");
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "s3cret");
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
String basic = "Basic " + Base64.getEncoder().encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8));
assertEquals(basic, credentials.getAuthorizationHeaderValue(true));
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_KEY, "write-key");
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 120);
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
long now = System.currentTimeMillis() / 1000;
assertTrue(signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now >= 119);
assertEquals(basic, credentials.getAuthorizationHeaderValue(false));
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY, "read-key");
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 240);
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
long readExp = signedExp(credentials.getAuthorizationHeaderValue(false), "read-key") - now;
assertTrue(readExp >= 239 && readExp <= 245);
long writeExp = signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now;
assertTrue(writeExp >= 119 && writeExp <= 125);
}
@Test
public void testFilerCredentialOptionsOverrideOneValueEach() throws Exception {
FilerCredentials credentials = new FilerCredentials();
credentials.setBasicAuth("toml-user", "toml-pass");
credentials.setJwtReadSigningKey("toml-read-key", 0);
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "new-pass");
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 300);
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
assertEquals("Basic " + Base64.getEncoder().encodeToString("toml-user:new-pass".getBytes(StandardCharsets.UTF_8)),
credentials.getAuthorizationHeaderValue(true));
long exp = signedExp(credentials.getAuthorizationHeaderValue(false), "toml-read-key");
assertTrue(exp - System.currentTimeMillis() / 1000 >= 299);
}
// Asserts the header is a filer JWT signed with key and returns its exp claim.
private static long signedExp(String header, String key) throws Exception {
assertTrue(header, header.startsWith("BEARER "));
String[] parts = header.substring("BEARER ".length()).split("\\.");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString(
mac.doFinal((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8))), parts[2]);
String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
return Long.parseLong(payload.replaceAll("[^0-9]", ""));
}
}
+672
View File
@@ -5451,6 +5451,198 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "EC Shard Copy Failures by reason",
"description": "Failed EC shard copies into each volume server per rate interval, by collection and reason (source_not_found, empty_index, no_space, timeout, io_error, other). The volume server log names the volume, shards and source of each failure.",
"type": "timeseries",
"id": 269,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 142
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, collection, reason) ((last_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) and (min_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) < last_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[1d] offset $__rate_interval))) or (increase(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) and count_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[1d] offset $__rate_interval)) or (last_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) unless count_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[1d] offset $__rate_interval)))",
"range": true,
"refId": "A",
"legendFormat": "{{instance}} {{collection}} {{reason}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "EC Shards Disagreeing With Disk",
"description": "Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size since the mount (stale_size).",
"type": "timeseries",
"id": 270,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 150
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, reason) (SeaweedFS_volumeServer_ec_shard_disk_mismatch{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{instance}} {{reason}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
@@ -7634,6 +7826,390 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Filer gRPC QPS by method",
"description": "gRPC calls to the filer (mounts, S3 gateways, peers, shell), by method.",
"type": "timeseries",
"id": 271,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 103
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "reqps",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (method) (rate(SeaweedFS_filer_grpc_request_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{method}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Filer gRPC Errors by method and code",
"description": "gRPC calls to the filer that did not end OK. NotFound is mostly lookups of names that do not exist.",
"type": "timeseries",
"id": 272,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 103
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "reqps",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (method, code) (rate(SeaweedFS_filer_grpc_request_total{code!=\"OK\", cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{method}} {{code}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Filer gRPC Duration p99 by method",
"description": "Subscriptions, health watches and client streams are counted but not timed.",
"type": "timeseries",
"id": 273,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 111
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))",
"range": true,
"refId": "A",
"legendFormat": "{{method}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Filer gRPC Duration p50 by method",
"description": "Subscriptions, health watches and client streams are counted but not timed.",
"type": "timeseries",
"id": 274,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 111
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.50, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))",
"range": true,
"refId": "A",
"legendFormat": "{{method}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
@@ -10260,6 +10836,102 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "S3 Aborted Reads by Bucket",
"description": "Object reads that failed after the status line was sent: the request counter records them as successes, so they only show here.",
"type": "timeseries",
"id": 270,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 66
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "reqps",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (bucket, cause) (rate(SeaweedFS_s3_read_aborted_total{cluster=~\"$cluster\", bucket=~\"$bucket\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{bucket}} {{cause}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
+290
View File
@@ -0,0 +1,290 @@
//! The FIPS 140-3 mode a SeaweedFS process runs in.
//!
//! One setting states it for a whole deployment: `[fips] mode` in
//! security.toml, or `WEED_FIPS_MODE`, which wins over the file as viper's
//! `AutomaticEnv` does for the Go processes. Go processes take their mode from
//! `GODEBUG=fips140` and refuse to start when it differs from the setting; the
//! Rust binaries take it from the setting alone, and under [`FipsMode::On`]
//! and [`FipsMode::Strict`] restrict TLS to what Go's `crypto/tls` allows in
//! FIPS mode (see [`crate::tls`]). This restricts behaviour only: the
//! cryptography underneath is still the non-validated aws-lc-rs build.
//!
//! Each binary reads `fips.mode` with the parser it uses for the rest of
//! security.toml and hands the value to [`resolve`], so the mode and the JWT
//! keys are either both read from a file or both missed.
use std::ffi::OsString;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
/// The security.toml setting, as `section.key`.
pub const SETTING: &str = "fips.mode";
/// The environment variable that overrides [`SETTING`].
pub const ENV: &str = "WEED_FIPS_MODE";
/// The modes `fips.mode` names. Unset reads as [`FipsMode::Off`], which is
/// how every Rust binary behaved before the setting existed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FipsMode {
/// No FIPS restrictions; Go processes need `fips140=off`.
#[default]
Off,
/// FIPS-mode TLS; Go processes need `GODEBUG=fips140=on`.
On,
/// FIPS-mode TLS; Go processes need `GODEBUG=fips140=only`, which also
/// refuses non-approved algorithms outside TLS.
Strict,
}
impl FipsMode {
/// Parses a value of `fips.mode`: `off`, `on` or `strict`, or `None` for
/// an empty value, which leaves the setting unset.
pub fn parse(value: &str) -> Result<Option<Self>, FipsModeError> {
match value {
"" => Ok(None),
"off" => Ok(Some(Self::Off)),
"on" => Ok(Some(Self::On)),
"strict" => Ok(Some(Self::Strict)),
other => Err(FipsModeError::Unknown {
source: SETTING.to_string(),
value: other.to_string(),
}),
}
}
/// Whether TLS is restricted to the FIPS 140-3 lists.
pub fn is_fips(self) -> bool {
self != Self::Off
}
pub fn as_str(self) -> &'static str {
match self {
Self::Off => "off",
Self::On => "on",
Self::Strict => "strict",
}
}
}
impl fmt::Display for FipsMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Why the mode could not be resolved or recorded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FipsModeError {
/// `source` holds a value that is not `off`, `on` or `strict`.
Unknown { source: String, value: String },
/// The process mode was already set to a different mode.
AlreadySet { set: FipsMode, wanted: FipsMode },
/// The security.toml at `path` exists but could not be read or parsed, so
/// whether it sets `fips.mode` is unknown.
File { path: PathBuf, reason: String },
}
impl fmt::Display for FipsModeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unknown { source, value } => {
write!(f, "{source} is {value:?}; want off, on or strict")
}
Self::AlreadySet { set, wanted } => {
write!(f, "FIPS mode is already {set}, cannot switch to {wanted}")
}
Self::File { path, reason } => write!(
f,
"{}: {reason}; cannot tell whether it sets {SETTING}",
path.display()
),
}
}
}
impl std::error::Error for FipsModeError {}
/// A resolved `fips.mode`: the mode, and where it was set (`None` when
/// nothing set it and the mode is [`FipsMode::Off`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Setting {
pub mode: FipsMode,
pub source: Option<String>,
}
impl fmt::Display for Setting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.source {
Some(source) => write!(f, "FIPS mode {} ({source})", self.mode),
None => write!(f, "FIPS mode {} ({SETTING} unset)", self.mode),
}
}
}
/// Resolves the mode of a process whose own security.toml loader read
/// `file_value` for `fips.mode` from `file` (`None` when there is no file or
/// it does not set the key): `WEED_FIPS_MODE` when set and non-empty, else
/// `file_value`, else [`FipsMode::Off`]. An unknown value is an error naming
/// where it came from.
pub fn resolve(
file: Option<&Path>,
file_value: Option<&str>,
env: &dyn Fn(&str) -> Option<OsString>,
) -> Result<Setting, FipsModeError> {
let from_env = env(ENV)
.map(|v| v.to_string_lossy().into_owned())
.filter(|v| !v.is_empty());
let from_file = || {
let source = match file {
Some(path) => format!("{}: {SETTING}", path.display()),
None => SETTING.to_string(),
};
file_value.map(|value| (source, value.to_string()))
};
let Some((source, value)) = from_env.map(|v| (ENV.to_string(), v)).or_else(from_file) else {
return Ok(Setting {
mode: FipsMode::Off,
source: None,
});
};
match FipsMode::parse(&value) {
Ok(Some(mode)) => Ok(Setting {
mode,
source: Some(source),
}),
Ok(None) => Ok(Setting {
mode: FipsMode::Off,
source: None,
}),
Err(_) => Err(FipsModeError::Unknown { source, value }),
}
}
static PROCESS_MODE: OnceLock<FipsMode> = OnceLock::new();
/// Records the mode this process runs in. A second call with the same mode is
/// a no-op; one with another mode is an error, since providers and
/// configurations built under the first would not change.
pub fn set_process_mode(mode: FipsMode) -> Result<(), FipsModeError> {
let set = *PROCESS_MODE.get_or_init(|| mode);
if set != mode {
return Err(FipsModeError::AlreadySet { set, wanted: mode });
}
Ok(())
}
/// The mode recorded by [`set_process_mode`], [`FipsMode::Off`] before.
pub fn process_mode() -> FipsMode {
PROCESS_MODE.get().copied().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn env_of(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<OsString> {
move |key| {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| OsString::from(v))
}
}
const FILE_PATH: &str = "/etc/seaweedfs/security.toml";
#[test]
fn parse_knows_three_modes_and_empty() {
assert_eq!(FipsMode::parse(""), Ok(None));
assert_eq!(FipsMode::parse("off"), Ok(Some(FipsMode::Off)));
assert_eq!(FipsMode::parse("on"), Ok(Some(FipsMode::On)));
assert_eq!(FipsMode::parse("strict"), Ok(Some(FipsMode::Strict)));
assert!(FipsMode::parse("only").is_err());
assert!(FipsMode::parse("On").is_err());
}
#[test]
fn unset_everywhere_is_off() {
let off = Setting {
mode: FipsMode::Off,
source: None,
};
assert_eq!(resolve(None, None, &env_of(&[])), Ok(off.clone()));
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), None, &env_of(&[])),
Ok(off.clone())
);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some(""), &env_of(&[])),
Ok(off.clone())
);
assert_eq!(off.to_string(), "FIPS mode off (fips.mode unset)");
}
#[test]
fn the_file_sets_the_mode() {
let setting = resolve(Some(Path::new(FILE_PATH)), Some("strict"), &env_of(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
assert_eq!(
setting.to_string(),
"FIPS mode strict (/etc/seaweedfs/security.toml: fips.mode)"
);
}
#[test]
fn the_environment_wins_over_the_file() {
let env = env_of(&[("WEED_FIPS_MODE", "on")]);
let setting = resolve(Some(Path::new(FILE_PATH)), Some("off"), &env).unwrap();
assert_eq!(setting.mode, FipsMode::On);
assert_eq!(setting.to_string(), "FIPS mode on (WEED_FIPS_MODE)");
assert_eq!(resolve(None, None, &env).unwrap().mode, FipsMode::On);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some("[\"strict\"]"), &env)
.unwrap()
.mode,
FipsMode::On
);
}
#[test]
fn an_empty_environment_variable_counts_as_unset() {
let env = env_of(&[("WEED_FIPS_MODE", "")]);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some("on"), &env)
.unwrap()
.mode,
FipsMode::On
);
}
#[test]
fn an_unknown_value_is_refused_naming_its_source() {
let err = resolve(None, None, &env_of(&[("WEED_FIPS_MODE", "yes")])).unwrap_err();
assert_eq!(
err.to_string(),
"WEED_FIPS_MODE is \"yes\"; want off, on or strict"
);
let err = resolve(
Some(Path::new(FILE_PATH)),
Some("[\"strict\"]"),
&env_of(&[]),
)
.unwrap_err();
assert_eq!(
err.to_string(),
"/etc/seaweedfs/security.toml: fips.mode is \"[\\\"strict\\\"]\"; want off, on or strict"
);
}
#[test]
fn the_process_mode_is_set_once() {
assert_eq!(set_process_mode(process_mode()), Ok(()));
let other = if process_mode() == FipsMode::On {
FipsMode::Off
} else {
FipsMode::On
};
assert!(set_process_mode(other).is_err());
}
}
+2
View File
@@ -8,7 +8,9 @@
//! rustls provider, which only works if every binary installs the same one.
//! The security.toml search path joined them for the same reason: an operator
//! mounts the file once and every binary has to look where `weed` looks.
//! The FIPS mode joined them because it decides that provider.
pub mod address;
pub mod fips;
pub mod security_config;
pub mod tls;
+3
View File
@@ -0,0 +1,3 @@
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIKcJM4ur78AjGRa92XbPxkXK+Dx4z7eObSdEzyhV/iiI
-----END PRIVATE KEY-----
+4
View File
@@ -0,0 +1,4 @@
-----BEGIN PRIVATE KEY-----
MEcCAQAwBQYDK2VxBDsEOSsBSiCeTY1tto3PFVZFeK55DoEaqWlcSREnSTQ4nfkr
Lvw0O5dru34QfckKqoFuEoyMvMh1RIz95g==
-----END PRIVATE KEY-----
+57
View File
@@ -0,0 +1,57 @@
-----BEGIN PRIVATE KEY-----
MIIKPgIBADALBglghkgBZQMEAxEEggoqMIIKJgQgQQrP8unrSpS7t1GeYGJIpRto
SmG4mJa33bu2HdaeZFsEggoA/gIsLnCAYuY4UDW5CpPcovPbtEmtHbOEZPWYYbiY
sGpD93b/wCjXPD+7jcDHohVQJ75aO4Adsj5sq/5zMixfzIPslMUdkX310RVIpi43
D6bfBrAxkO0U1Nkn6iDOqw+UWc9YvRM5WkujREA8qng79JZ1gbDEHUw4JahfIs79
F4fjQkGAuCxauC0bBCQihk1YpEkLQYUkGDCIBmJMQAUAhUUBIS0LIUyJpGnURilb
iBAMRQLEuEEJBHGJJlEhSTHRSA0QESYhRQgjGIEkiCjMkEDJIFBTwnCcomBUBlBb
uBFMSGHJxmjZgpAhsyhglkxiBo7BRoDUJEARgojRAiVYEg4AxklcFmCBQGUZiQRR
ok2bgI1CpA2USIwjgYnYNIpcICXKMi3RomijokghCSaaokyTwlFaFnEiBCqilkwR
iSwLGQEUIFHBsm1kBGVYRmniRnICsRCTJirDoogKSBHcSHHiqBGRGCkDMlJCCDFD
tGQAR0rYMATkRnGYAikixkjMhGUSyHAKSWgMkkAZGBLbJGBkIAQDhjCgEkEDR4zA
Jg0CQDJSlBEkQCUUGCEjyU1iIClRMBETgSQbR2WRqEWcRoBDIiLjoo1SpCVIuA1j
CDAJRYwYEGwEmDBRODFLFnAjwowjAkzbtm3QFE0ZsmVEGGwDRQwKyTBTIgkSxoAc
g03SoGRBRm0RSIQihQ0cqSDYSCYMOAqYIgoiFHLghixcRiQhhHEKBwHKOAACKWkR
I4pCFI2JyCUSOCkZNwmBxCAcQ3IhJVKEpkUgJgySGHLcJkRRlmHRlk0TgDCauCDg
JGURtmgbFWpBOHKKmCUag03BgnAhsohgFAGQuGHDRlEkBTGRFAkhEI7ThoBbyJDC
IGSkJkwgs0VjpgWIsE0Ctk0CyQFSBk4SowlDoCRZEmYKGSqiRIACpJGDQgUYRGDI
CIyJBCUaKA7EIijcJACEqC0DEgABOE2TyCwTSGAJlyhbgADZkGkDpgVaMFASGGlR
RgIBJ4bQQmEjQAlkkFEAGW0JQYIDFm0DNpDIgIQYQ4WTwiwgBAKJMi0ZliCUMEWa
GIkaJ5IKwJFjCI0iiGDjEExBtpCcKGVcMm4CsXAIImWEwhDYOI4hgUgCQYoUBZCC
soTbtBALEEIcJpAQF1EZlnDEqCgbNyCLBIISMVCLQgwJkmDJGCGCRiIYMYrKkiCa
xGTbZXtrCGKSFu3craDAVG1GAKYgmimIF4ktgY7/C4ammULwJmqnjNfOSlCt598v
9ofuxnVZlDEtlTjgKQPPfXOp3lEzl9Die1QeZNqcg3IuTVRnUolGKTI62HNqKXfm
PrSQ9sPnOdGa4XyXYncraf1UuZ//hknLrM88D+kNoGqP65ni+OQ5MU0nsy52Y6ns
G88lSAFypwo+welJJAWxek5PsLbhnYyZfTpKvPC52ZfRCQBCG4n4RK0qtiaFBgly
JrBUVnzLvMtxZPr7rK47UipXcQAAnd6m1Ul8wE7/FCBQ6xWQQQUH8lmW8a6ZSuod
lW2Evbut2p8B9HadMBRP6+2oPrYfrpTSkDawNPiNIWZvk4F6klljAWmrDJB0v/ou
kIzuYiMWkZhbhJO6bVVpW8/h2HQarETnCERtqBjXRDiJgg0gzHQZiNACMV3LiEaS
muZIxqzzsOhn/i6RA9qnBqvl3mk/2GFXudiLFVk0cYMBLqn3tIt2k/+S0DsbKvSE
0dPSqzXx62oLgqxK8DJmrJ5YHTHSTsJfHO64VX3f1MnFLhV/6TPOteJmE/8CEmZK
gtrDpN9wYvmFe3vWUCAsYOzfnzDolq+SsqXAbZhkYNoomAwBK36pU0aE/e8SiCdP
I7EM17AyPW5f9mLs0S3g9zVX3NK9zgaW9EtQ8zLXm7sOeazzEp6xxobOvJCBwoav
tPzT+vab5u8nNDIcLIAj/mYAjkjS7cog135qOE56WiTOW7gCB75C6WkiAQTOqZ7J
+AFUgwN9j61cdTeJW/NbPgndlpjK+HiTYeENdnBQ898/JmUblhzcR/QpMEih3QO/
Q7+AfejRpVPpOLDDJwRfc19b6ymZ27nJVQ4GChI6oKX4Po4JNo54UO09bRsCf9Eq
sq9EvCBsS6H0xw6Y7EmNab0BpW6iFUmac9Bj4cWh9trZ/bZwExW4YvwX+bDIM/A8
mqmpsZSbkE/RoEiKSS7NHc3XgVsGJ2czkftcGbnUBZmIaPVu6XVJyyBwM7GogESv
yuQGFbuSlOhrwphtNfpm0T+/vU/elaIPJS0Os2sgmPgGqHE+o5BndkZ/hD8c5Ec0
Zs64BZugQoLKLTJtn+JqVWd6PotXBgEazdechsQQfCqOwRUO8VP9Q7A/sPQpgAk8
UyMvQliHdF2FFE9BHYMMw2B8a05+MUogYAS+V4RB1mMl35Lv1W3nOvIszSkFGact
T4uh7/mQwekpR0AXRcYdF72YDuC7WvMG7cBvZe5oi1c1/vu0R+NgUw1yMiZp3f/C
xqM/h1QzQTxSaro4oJm6/nJr3hSj6yx83cPbQzusLAb0CkkGlqw977rxWC56rPUt
d7cMOG9L7dMPIzuQ6PkQY6ttgDpH176d2vZphfFqjyUb05ryA+vJw/+xh73le837
TaNeTemy+p2UlYdW2LkTrgz0v/t2CsiT6LL9uGyz0rGrs/bGJg3XPMxsukHanThd
KKm8leIE02ogDiSfy2Ozf+rdJUGDArr4Jb5IYGE8bQUdfdBvvb1eKDhgKvYHM5XE
ExnFQSa8pftsXjS2F7MQr397tBL6WNC+KPnbgXmLhJbmGvnuS7XaHkErrRQwD75M
tP6b2fZiKWz9gx+0nkOxM1PX+cPVWrgbrrvpJUZewe1LW+Mctuei8sXTkHQ9stq7
23xqQTUe9soXWy277wlPr1eXY2gnKkH7hc7flu5gGSoaG29g4okvu6hrTUJ4tJgd
0YaLF0uNt2LvgBNOVxHBFX09GzGsvxfhY9+dRl0CDq3oHvaWCLs52WYx0u6s0Oyq
mCKG9lTdKL57pyPAPR1iCZzTDLbjhdxMQUFQ7zHHfQksu5ui3MHnaA+BAijZgmi2
0rs/QEh7Wv1AJS2XkNoFN7CxBQueBmXb2OtsqNHPv4lbE17UrHUbi9GHoMhfaGMB
9YzcPP/3Qentc3az4T4HsZUdePakJguI3qLBKGLdXtn2JHNoJ/poCxtVEEQ474us
YZQvYXbBmeJ+kwczfabNqRdGDnN4e1bfSxnSiVCJJDK5EQGNatqCso5S+5jyAd6z
FBbOe72dJxacVdU0esOrRK0cafJpeeCNgtUiRCZeWiFi3d+daLgqcqEiaV2Obk99
SiG57HJDpMrQgyzVuucms3bRWlb8H38DBFjclt4ONFx5dymNR/C2QCm+FCXvuFEv
UHB9qJcdZuhjkRNszOrvkokJdWWt9GxRWQ6eR+raum0q+Q==
-----END PRIVATE KEY-----
+5
View File
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKQGVRsbYNwfFeCQU
4c2Nkjnme5k8eDQ1loKC5/qKNeGhRANCAAQtjdBx4U07ZO68fAkYnGbhCoeVTC9o
BejPCRmx9mOOhD3dKK5j9hsgVBd0RagUsgVwkq5xLKrvMB8ZoQe2jKRF
-----END PRIVATE KEY-----
+419 -6
View File
@@ -5,19 +5,285 @@
//! backend and reqwest — so rustls cannot auto-select a provider and tonic's
//! client TLS panics on first use. Each binary has to pin one, and it has to be
//! the same one, which is why the choice lives here rather than in either tree.
//!
//! Under [`FipsMode::On`] and [`FipsMode::Strict`] the provider is aws-lc-rs
//! filtered to what Go's `crypto/tls` allows when `GODEBUG=fips140` is `on` or
//! `only` (`crypto/tls/defaults_fips140.go`, Go 1.27.4, the version go.mod
//! requires). TLS 1.2 and 1.3 are all rustls implements, which is Go's FIPS
//! version list.
use rustls::crypto::aws_lc_rs;
use std::sync::{Arc, OnceLock};
/// Pin rustls's process-wide default provider to aws-lc-rs, matching the
/// volume server's TLS config. Idempotent: the first call wins and every
/// later one is a no-op, so callers do not have to coordinate.
use rustls::crypto::{
CryptoProvider, KeyProvider, SupportedKxGroup, WebPkiSupportedAlgorithms, aws_lc_rs,
};
use rustls::pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer, alg_id};
use rustls::sign::{Signer, SigningKey};
use rustls::{CipherSuite, NamedGroup, SignatureAlgorithm, SignatureScheme};
use crate::fips::{self, FipsMode, FipsModeError};
/// Go's `allowedCipherSuitesTLS13FIPS` and the AES-GCM part of
/// `allowedCipherSuitesFIPS`. Go also allows
/// `TLS_ECDHE_{ECDSA,RSA}_WITH_AES_128_CBC_SHA256`, which rustls does not
/// implement.
pub const FIPS_CIPHER_SUITES: &[CipherSuite] = &[
CipherSuite::TLS13_AES_128_GCM_SHA256,
CipherSuite::TLS13_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
];
/// Go's `allowedCurvePreferencesFIPS` as rustls 0.23 has them and Go enables
/// by default, in Go's preference order. rustls has no SecP384r1MLKEM1024 and
/// no P-521; it has MLKEM1024, which Go allows but enables only when
/// configured, so it is left out as Go leaves it out of its defaults.
fn fips_kx_groups() -> Vec<&'static dyn SupportedKxGroup> {
vec![
aws_lc_rs::kx_group::X25519MLKEM768,
aws_lc_rs::kx_group::SECP256R1MLKEM768,
aws_lc_rs::kx_group::SECP256R1,
aws_lc_rs::kx_group::SECP384R1,
]
}
/// Go's `allowedSignatureAlgorithmsFIPS`.
pub const FIPS_SIGNATURE_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::ECDSA_NISTP256_SHA256,
SignatureScheme::ED25519,
SignatureScheme::ML_DSA_44,
SignatureScheme::ML_DSA_65,
SignatureScheme::ML_DSA_87,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::RSA_PKCS1_SHA256,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::ECDSA_NISTP384_SHA384,
SignatureScheme::ECDSA_NISTP521_SHA512,
];
/// The certificate key types Go's `isCertificateAllowedFIPS` accepts: RSA,
/// ECDSA on P-256, P-384 or P-521, Ed25519, and ML-DSA (Go allows ML-DSA for
/// its native module only). The RSA algorithms rustls verifies with take keys
/// of 2048 to 8192 bits, so Go's 2048-bit floor holds.
const FIPS_CERTIFICATE_KEYS: &[rustls::pki_types::AlgorithmIdentifier] = &[
alg_id::RSA_ENCRYPTION,
alg_id::ECDSA_P256,
alg_id::ECDSA_P384,
alg_id::ECDSA_P521,
alg_id::ED25519,
alg_id::ML_DSA_44,
alg_id::ML_DSA_65,
alg_id::ML_DSA_87,
];
/// The aws-lc-rs verification algorithms limited to Go's FIPS signature
/// schemes and certificate keys. With aws-lc-rs's current set that removes
/// nothing; the filter keeps an algorithm a later rustls adds out of FIPS
/// mode until Go allows it. Built once, since rustls needs `'static` slices.
fn fips_signature_verification_algorithms() -> WebPkiSupportedAlgorithms {
static ALGORITHMS: OnceLock<WebPkiSupportedAlgorithms> = OnceLock::new();
*ALGORITHMS.get_or_init(|| {
let default = aws_lc_rs::default_provider().signature_verification_algorithms;
let all = default
.all
.iter()
.filter(|alg| FIPS_CERTIFICATE_KEYS.contains(&alg.public_key_alg_id()))
.copied()
.collect::<Vec<_>>();
let mapping = default
.mapping
.iter()
.filter(|(scheme, _)| FIPS_SIGNATURE_SCHEMES.contains(scheme))
.copied()
.collect::<Vec<_>>();
WebPkiSupportedAlgorithms {
all: all.leak(),
mapping: mapping.leak(),
}
})
}
/// Loads private keys through aws-lc-rs and passes them through
/// [`restrict_to_fips`], so a FIPS-mode listener or client signs handshakes
/// only with Go's FIPS signature schemes.
#[derive(Debug)]
struct FipsKeyProvider;
static FIPS_KEY_PROVIDER: FipsKeyProvider = FipsKeyProvider;
impl KeyProvider for FipsKeyProvider {
fn load_private_key(
&self,
key_der: PrivateKeyDer<'static>,
) -> Result<Arc<dyn SigningKey>, rustls::Error> {
let key = aws_lc_rs::default_provider()
.key_provider
.load_private_key(key_der)?;
restrict_to_fips(key)
}
fn fips(&self) -> bool {
aws_lc_rs::default_provider().key_provider.fips()
}
}
/// Wraps `key` so it offers only [`FIPS_SIGNATURE_SCHEMES`], refusing a key
/// that can sign none of them, such as Ed448, with an error naming its type.
fn restrict_to_fips(key: Arc<dyn SigningKey>) -> Result<Arc<dyn SigningKey>, rustls::Error> {
if key.choose_scheme(FIPS_SIGNATURE_SCHEMES).is_none() {
return Err(rustls::Error::General(format!(
"{} private key is not allowed in FIPS mode, which accepts RSA, ECDSA P-256/P-384/P-521, Ed25519 and ML-DSA keys",
key_kind(key.algorithm())
)));
}
Ok(Arc::new(FipsSigningKey(key)))
}
/// How a refused key is named.
fn key_kind(algorithm: SignatureAlgorithm) -> String {
match algorithm {
SignatureAlgorithm::ED448 => "an Ed448".to_string(),
other => format!("a {other:?}"),
}
}
/// A signing key that offers only [`FIPS_SIGNATURE_SCHEMES`].
#[derive(Debug)]
struct FipsSigningKey(Arc<dyn SigningKey>);
impl SigningKey for FipsSigningKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
let allowed = offered
.iter()
.copied()
.filter(|scheme| FIPS_SIGNATURE_SCHEMES.contains(scheme))
.collect::<Vec<_>>();
self.0.choose_scheme(&allowed)
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
self.0.public_key()
}
fn algorithm(&self) -> SignatureAlgorithm {
self.0.algorithm()
}
}
/// The aws-lc-rs provider with Go's FIPS-mode TLS lists applied. It still
/// runs on the non-validated aws-lc-rs build, so `CryptoProvider::fips()` is
/// false.
pub fn fips_provider() -> CryptoProvider {
let default = aws_lc_rs::default_provider();
CryptoProvider {
cipher_suites: default
.cipher_suites
.into_iter()
.filter(|suite| FIPS_CIPHER_SUITES.contains(&suite.suite()))
.collect(),
kx_groups: fips_kx_groups(),
signature_verification_algorithms: fips_signature_verification_algorithms(),
key_provider: &FIPS_KEY_PROVIDER,
..default
}
}
/// The provider for `mode`: aws-lc-rs's default under [`FipsMode::Off`],
/// [`fips_provider`] otherwise.
pub fn provider_for(mode: FipsMode) -> CryptoProvider {
if mode.is_fips() {
fips_provider()
} else {
aws_lc_rs::default_provider()
}
}
/// The provider for this process's mode ([`fips::process_mode`]).
pub fn crypto_provider() -> CryptoProvider {
provider_for(fips::process_mode())
}
/// Pin rustls's process-wide default provider to [`crypto_provider`]:
/// aws-lc-rs, filtered to the FIPS lists when the process mode asks for it.
/// Idempotent: the first call wins and every later one is a no-op, so callers
/// do not have to coordinate.
pub fn install_default_crypto_provider() {
let _ = aws_lc_rs::default_provider().install_default();
let _ = crypto_provider().install_default();
}
/// Whether TLS 1.2 connections must use the Extended Master Secret, as Go
/// requires in FIPS mode. rustls requires it only of a validated provider,
/// so configurations SeaweedFS builds itself set `require_ems` from this.
pub fn require_ems() -> bool {
fips::process_mode().is_fips()
}
/// Why [`install_process_provider`] failed.
#[derive(Debug)]
pub enum InstallError {
Mode(FipsModeError),
/// A provider other than this mode's was installed first.
OtherProvider(FipsMode),
}
impl std::fmt::Display for InstallError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Mode(e) => e.fmt(f),
Self::OtherProvider(mode) => write!(
f,
"a rustls crypto provider other than the one for FIPS mode {mode} is already installed"
),
}
}
}
impl std::error::Error for InstallError {}
/// Records `mode` as this process's FIPS mode and installs its provider as the
/// rustls process default. Call it once at startup, before anything builds a
/// TLS configuration; it fails if a different provider got there first, so a
/// FIPS-mode process never runs on the unfiltered one.
pub fn install_process_provider(mode: FipsMode) -> Result<(), InstallError> {
fips::set_process_mode(mode).map_err(InstallError::Mode)?;
install_default_crypto_provider();
let installed = CryptoProvider::get_default().ok_or(InstallError::OtherProvider(mode))?;
if !same_lists(installed, &provider_for(mode)) {
return Err(InstallError::OtherProvider(mode));
}
Ok(())
}
/// Whether two providers offer the same suites, groups and signature schemes.
fn same_lists(a: &CryptoProvider, b: &CryptoProvider) -> bool {
let suites = |p: &CryptoProvider| {
p.cipher_suites
.iter()
.map(|s| s.suite())
.collect::<Vec<_>>()
};
let groups = |p: &CryptoProvider| {
p.kx_groups
.iter()
.map(|g| g.name())
.collect::<Vec<NamedGroup>>()
};
suites(a) == suites(b)
&& groups(a) == groups(b)
&& a.signature_verification_algorithms.supported_schemes()
== b.signature_verification_algorithms.supported_schemes()
&& a.signature_verification_algorithms.all.len()
== b.signature_verification_algorithms.all.len()
}
#[cfg(test)]
mod tests {
use super::install_default_crypto_provider;
use super::*;
#[test]
fn installing_is_idempotent_and_leaves_a_default_behind() {
@@ -25,4 +291,151 @@ mod tests {
install_default_crypto_provider();
assert!(rustls::crypto::CryptoProvider::get_default().is_some());
}
#[test]
fn off_is_the_unfiltered_default() {
assert!(same_lists(
&provider_for(FipsMode::Off),
&aws_lc_rs::default_provider()
));
}
#[test]
fn fips_mode_drops_chacha20_and_plain_x25519() {
for mode in [FipsMode::On, FipsMode::Strict] {
let provider = provider_for(mode);
let suites = provider
.cipher_suites
.iter()
.map(|s| s.suite())
.collect::<Vec<_>>();
assert_eq!(
suites,
vec![
CipherSuite::TLS13_AES_256_GCM_SHA384,
CipherSuite::TLS13_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
]
);
let groups = provider
.kx_groups
.iter()
.map(|g| g.name())
.collect::<Vec<_>>();
assert_eq!(
groups,
vec![
NamedGroup::X25519MLKEM768,
NamedGroup::secp256r1MLKEM768,
NamedGroup::secp256r1,
NamedGroup::secp384r1,
]
);
}
}
fn load(provider: &CryptoProvider, pem: &str) -> Result<Arc<dyn SigningKey>, rustls::Error> {
use rustls::pki_types::pem::PemObject;
provider
.key_provider
.load_private_key(PrivateKeyDer::from_pem_slice(pem.as_bytes()).unwrap())
}
const ML_DSA_44_KEY: &str = include_str!("testdata/mldsa44.pem");
const ED448_KEY: &str = include_str!("testdata/ed448.pem");
const P256_KEY: &str = include_str!("testdata/p256.pem");
const ED25519_KEY: &str = include_str!("testdata/ed25519.pem");
/// A key that signs only Ed448, which aws-lc-rs cannot load, to drive the
/// refusal.
#[derive(Debug)]
struct Ed448Only;
impl SigningKey for Ed448Only {
fn choose_scheme(&self, _offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
None
}
fn algorithm(&self) -> SignatureAlgorithm {
SignatureAlgorithm::ED448
}
}
#[test]
fn fips_mode_refuses_keys_outside_go_s_list() {
let err = restrict_to_fips(Arc::new(Ed448Only)).unwrap_err();
assert!(err.to_string().contains("an Ed448 private key"), "{err}");
assert!(
err.to_string().contains("not allowed in FIPS mode"),
"{err}"
);
assert!(load(&provider_for(FipsMode::On), ED448_KEY).is_err());
}
#[test]
fn fips_mode_allows_ml_dsa_as_go_1_27_does() {
let fips = provider_for(FipsMode::On);
let ml_dsa = load(&fips, ML_DSA_44_KEY).unwrap();
assert!(
ml_dsa
.choose_scheme(&[SignatureScheme::ML_DSA_44])
.is_some()
);
}
#[test]
fn fips_mode_keys_sign_with_fips_schemes_only() {
let fips = provider_for(FipsMode::Strict);
let p256 = load(&fips, P256_KEY).unwrap();
let signer = p256
.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.unwrap();
assert_eq!(signer.scheme(), SignatureScheme::ECDSA_NISTP256_SHA256);
assert!(
p256.choose_scheme(&[SignatureScheme::ECDSA_SHA1_Legacy])
.is_none()
);
assert!(p256.public_key().is_some());
let ed25519 = load(&fips, ED25519_KEY).unwrap();
assert!(ed25519.choose_scheme(&[SignatureScheme::ED25519]).is_some());
}
#[test]
fn off_keeps_the_default_key_provider() {
let off = provider_for(FipsMode::Off);
let ml_dsa = load(&off, ML_DSA_44_KEY).unwrap();
assert!(
ml_dsa
.choose_scheme(&[SignatureScheme::ML_DSA_44])
.is_some()
);
}
#[test]
fn fips_mode_verifies_go_s_signature_schemes_only() {
let provider = fips_provider();
let mut schemes = provider
.signature_verification_algorithms
.supported_schemes();
let mut want = FIPS_SIGNATURE_SCHEMES.to_vec();
schemes.sort_by_key(|s| u16::from(*s));
want.sort_by_key(|s| u16::from(*s));
assert_eq!(schemes, want);
assert!(
provider
.signature_verification_algorithms
.all
.iter()
.all(|alg| FIPS_CERTIFICATE_KEYS.contains(&alg.public_key_alg_id()))
);
let default = aws_lc_rs::default_provider();
assert_eq!(
default.signature_verification_algorithms.all.len(),
provider.signature_verification_algorithms.all.len(),
"Go 1.27 allows every key type aws-lc-rs verifies"
);
}
}
+2
View File
@@ -6338,6 +6338,8 @@ dependencies = [
"protoc-bin-vendored",
"reqwest 0.12.28",
"rustls",
"rustls-native-certs",
"seaweed-common",
"thiserror 2.0.21",
"tokio",
"tonic",
+1 -1
View File
@@ -180,7 +180,6 @@ impl Tables {
#[tokio::main]
async fn main() -> Result<()> {
weed_lance_worker::tls::install_default_crypto_provider();
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(
@@ -191,6 +190,7 @@ async fn main() -> Result<()> {
let args = Args::parse();
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
weed_lance_worker::tls::install_for_fips_mode(&security)?;
let signing_key = SigningKey::new(
args.filer_signing_key
.or_else(|| security.get("jwt.filer_signing.key")),
+1 -1
View File
@@ -129,8 +129,8 @@ fn advertised_addr(listen: &str, masters: &[String], advertise: Option<&str>) ->
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse_from(normalize_args(std::env::args().collect()));
weed_lance_worker::tls::install_default_crypto_provider();
let security = Security::load(args.security_toml.as_deref())?;
weed_lance_worker::tls::install_for_fips_mode(&security)?;
if let Some(path) = security.path() {
tracing::info!("security settings from {}", path.display());
}
+16
View File
@@ -4067,6 +4067,7 @@ dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
"tokio-util",
]
[[package]]
@@ -4165,6 +4166,19 @@ dependencies = [
"syn",
]
[[package]]
name = "tonic-health"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcfab99db777fba2802f0dfa861d1628d1ae916fb199d29819941f139ae85082"
dependencies = [
"prost 0.14.4",
"tokio",
"tokio-stream",
"tonic",
"tonic-prost",
]
[[package]]
name = "tonic-prost"
version = "0.14.6"
@@ -4639,6 +4653,7 @@ dependencies = [
"tokio-stream",
"toml",
"tonic",
"tonic-health",
"tonic-prost",
"tonic-prost-build",
"tonic-reflection",
@@ -4647,6 +4662,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"uuid",
"webpki-roots",
"windows-sys 0.61.2",
"x509-parser",
"xxhash-rust",
+2
View File
@@ -42,6 +42,7 @@ tokio-io-timeout = "1"
tonic = { version = "0.14", features = ["tls-aws-lc"] }
tonic-prost = "0.14"
tonic-reflection = "0.14"
tonic-health = "0.14"
prost = "0.14"
prost-types = "0.14"
@@ -67,6 +68,7 @@ jsonwebtoken = { version = "10", features = ["rust_crypto"] }
rustls = "0.23"
tokio-rustls = "0.26"
rustls-pemfile = "2"
webpki-roots = "1"
# LevelDB (via RocksDB for better Rust support)
# Using rusty-leveldb for pure Rust LevelDB
+1
View File
@@ -436,6 +436,7 @@ message DataNodeInfo {
string id = 1;
map<string, DiskInfo> diskInfos = 2;
uint32 grpc_port = 3;
int64 last_heartbeat_ns = 5;
string address = 4; // ip:port for connecting to the volume server
}
message RackInfo {
+199 -39
View File
@@ -22,6 +22,15 @@ fn process_env(key: &str) -> Option<OsString> {
/// `std::env::var`'s view of an [`EnvLookup`]: unset and non-UTF-8 both read
/// as absent, exactly as `std::env::var(key).ok()` does.
fn parse_common_names(value: &str) -> Vec<String> {
value
.split(',')
.map(str::trim)
.filter(|name| !name.is_empty())
.map(String::from)
.collect()
}
fn env_string(env: EnvLookup<'_>, key: &str) -> Option<String> {
env(key).and_then(|value| value.into_string().ok())
}
@@ -166,7 +175,7 @@ pub struct Cli {
/// Maximum numbers of volumes, count[,count]...
/// If set to zero, the limit will be auto configured as free disk space divided by volume size.
#[arg(long = "max", default_value = "8")]
#[arg(long = "max", default_value = "10")]
pub max: String,
/// Comma separated IP addresses having write permission. No limit if empty.
@@ -324,6 +333,7 @@ pub struct VolumeServerConfig {
pub grpc_ca_file: String,
pub grpc_allowed_wildcard_domain: String,
pub grpc_volume_allowed_common_names: Vec<String>,
pub grpc_health_check_common_names: Vec<String>,
pub tls_policy: TlsPolicy,
/// Path to security.toml — stored for SIGHUP reload.
pub security_file: String,
@@ -1019,6 +1029,7 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
grpc_ca_file: sec.grpc_ca_file,
grpc_allowed_wildcard_domain: sec.grpc_allowed_wildcard_domain,
grpc_volume_allowed_common_names: sec.grpc_volume_allowed_common_names,
grpc_health_check_common_names: sec.grpc_health_check_common_names,
tls_policy: sec.tls_policy,
security_file: cli.security_file,
allow_untrusted_remote_endpoints: cli.allow_untrusted_remote_endpoints,
@@ -1052,12 +1063,16 @@ pub struct SecurityConfig {
pub grpc_ca_file: String,
pub grpc_allowed_wildcard_domain: String,
pub grpc_volume_allowed_common_names: Vec<String>,
pub grpc_health_check_common_names: Vec<String>,
pub tls_policy: TlsPolicy,
pub access_ui: bool,
/// The file was read; otherwise only defaults and WEED_ overrides are set.
pub file_read: bool,
/// IPs from [guard] white_list in security.toml
pub guard_white_list: Vec<String>,
/// `[fips] mode` as the file sets it, read like every other key here;
/// `WEED_FIPS_MODE` is applied by `seaweed_common::fips::resolve`.
pub fips_mode: Option<String>,
}
/// Parse a security.toml file to extract JWT signing keys and TLS configuration.
@@ -1132,6 +1147,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
Tls,
Guard,
Access,
Fips,
}
let mut section = Section::None;
@@ -1141,44 +1157,20 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if trimmed == "[jwt.signing.read]" {
section = Section::JwtSigningRead;
continue;
}
if trimmed == "[jwt.signing]" {
section = Section::JwtSigning;
continue;
}
if trimmed == "[https.client]" {
section = Section::HttpsClient;
continue;
}
if trimmed == "[grpc]" {
section = Section::Grpc;
continue;
}
if trimmed == "[https.volume]" {
section = Section::HttpsVolume;
continue;
}
if trimmed == "[grpc.volume]" {
section = Section::GrpcVolume;
continue;
}
if trimmed == "[tls]" {
section = Section::Tls;
continue;
}
if trimmed == "[guard]" {
section = Section::Guard;
continue;
}
if trimmed == "[access]" {
section = Section::Access;
continue;
}
if trimmed.starts_with('[') {
section = Section::None;
if let Some(header) = section_header(trimmed) {
section = match header {
"[jwt.signing.read]" => Section::JwtSigningRead,
"[jwt.signing]" => Section::JwtSigning,
"[https.client]" => Section::HttpsClient,
"[grpc]" => Section::Grpc,
"[https.volume]" => Section::HttpsVolume,
"[grpc.volume]" => Section::GrpcVolume,
"[tls]" => Section::Tls,
"[guard]" => Section::Guard,
"[access]" => Section::Access,
"[fips]" => Section::Fips,
_ => Section::None,
};
continue;
}
@@ -1214,6 +1206,9 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
"allowed_wildcard_domain" => {
cfg.grpc_allowed_wildcard_domain = value.to_string()
}
"health_check_commonNames" => {
cfg.grpc_health_check_common_names = parse_common_names(value)
}
_ => {}
},
Section::HttpsVolume => match key {
@@ -1254,6 +1249,11 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
cfg.access_ui = value.parse().unwrap_or(false)
}
}
Section::Fips => {
if key == "mode" {
cfg.fips_mode = Some(value.to_string())
}
}
Section::None => {}
}
}
@@ -1277,6 +1277,20 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
cfg
}
/// The table header on a trimmed security.toml line, without the trailing
/// comment TOML allows after it (`[fips] # policy` is `[fips]`), or `None`
/// when the line is not a header. None of the sections read here has a `#`
/// in its name.
fn section_header(trimmed: &str) -> Option<&str> {
if !trimmed.starts_with('[') {
return None;
}
let header = trimmed
.split_once('#')
.map_or(trimmed, |(header, _)| header);
Some(header.trim_end())
}
/// Reads the right-hand side of `key = value` the way TOML (and so Go) does:
/// escapes decoded, literal strings kept as written, a trailing comment
/// dropped. Text TOML rejects keeps the plain quote trimming.
@@ -1291,6 +1305,52 @@ fn toml_value_text(raw: &str) -> String {
}
}
/// The FIPS mode this volume server runs in: `WEED_FIPS_MODE`, else
/// `fips.mode` in the security.toml `--securityFile` names or the search
/// finds, read by the same loader as the JWT keys, else off. A file that
/// exists but cannot be read is an error, since it may set the mode.
pub fn resolve_fips_setting(
security_file: &str,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(security_file, &process_env)
}
fn resolve_fips_setting_with_env(
security_file: &str,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
let path = resolve_security_config_path(security_file, env).filter(|p| p.exists());
let Some(path) = path else {
return seaweed_common::fips::resolve(None, None, env);
};
if let Err(e) = std::fs::read_to_string(&path) {
return Err(seaweed_common::fips::FipsModeError::File {
path,
reason: e.to_string(),
});
}
let parsed = parse_security_config_with_env(&path.to_string_lossy(), env);
fips_setting_from_parsed(path, &parsed, env)
}
/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env`
/// applied. A parse that could not read the file is an error like the first
/// read, so a file that stops being readable between the two reads cannot
/// leave the mode off.
fn fips_setting_from_parsed(
path: PathBuf,
parsed: &SecurityConfig,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
if !parsed.file_read {
return Err(seaweed_common::fips::FipsModeError::File {
path,
reason: "could not be read".to_string(),
});
}
seaweed_common::fips::resolve(Some(&path), parsed.fips_mode.as_deref(), env)
}
fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBuf> {
if !path.is_empty() {
return Some(PathBuf::from(path));
@@ -1367,6 +1427,9 @@ fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
if let Some(v) = env_string(env, "WEED_GRPC_VOLUME_ALLOWED_COMMONNAMES") {
cfg.grpc_volume_allowed_common_names = v.split(',').map(|name| name.to_string()).collect();
}
if let Some(v) = env_string(env, "WEED_GRPC_HEALTH_CHECK_COMMONNAMES") {
cfg.grpc_health_check_common_names = parse_common_names(&v);
}
if let Some(v) = env_string(env, "WEED_TLS_MIN_VERSION") {
cfg.tls_policy.min_version = v;
}
@@ -2026,6 +2089,7 @@ client_key = "/etc/seaweedfs/volume-client-key.pem"
r#"
[grpc]
allowed_wildcard_domain = ".example.com"
health_check_commonNames = "blackbox, ,probe"
[grpc.volume]
allowed_commonNames = "volume-a.internal,volume-b.internal"
@@ -2042,6 +2106,10 @@ allowed_commonNames = "volume-a.internal,volume-b.internal"
String::from("volume-b.internal")
]
);
assert_eq!(
cfg.grpc_health_check_common_names,
vec![String::from("blackbox"), String::from("probe")]
);
}
#[test]
@@ -2238,6 +2306,98 @@ previous_key = "read-old"
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_fips_mode_from_the_security_file_and_env() {
use seaweed_common::fips::FipsMode;
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "[fips]\nmode = \"on\"\n").unwrap();
let path = tmp.path().to_str().unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
let env = fake_env(&[("WEED_FIPS_MODE", "strict")]);
let setting = resolve_fips_setting_with_env(path, &env).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
let env = fake_env(&[("WEED_FIPS_MODE", "only")]);
assert!(resolve_fips_setting_with_env(path, &env).is_err());
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Off);
}
#[test]
fn test_fips_mode_is_read_with_the_jwt_keys_from_a_lenient_file() {
use seaweed_common::fips::FipsMode;
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[fips]\nmode = \"on\"\n[jwt.signing]\nkey = unquoted-secret\n";
std::fs::write(tmp.path(), text).unwrap();
let path = tmp.path().to_str().unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"unquoted-secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
std::fs::write(tmp.path(), "[fips]\nmode = [\"strict\"]\n").unwrap();
assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err());
}
#[test]
fn test_section_headers_with_a_trailing_comment() {
use seaweed_common::fips::FipsMode;
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[fips] # deployment policy\nmode = \"on\"\n\
[jwt.signing] # comment\nkey = \"secret\"\n\
[other] # not read\nkey = \"ignored\"\n";
std::fs::write(tmp.path(), text).unwrap();
let path = tmp.path().to_str().unwrap();
assert!(text.parse::<toml::Table>().is_ok(), "TOML, as Go reads it");
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
assert_eq!(cfg.jwt_signing_key, b"secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
}
#[test]
fn test_fips_mode_refuses_a_security_file_it_cannot_read() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"[fips]\nmode = \"on\"\n\xff\xfe\n").unwrap();
let path = tmp.path().to_str().unwrap();
let err = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap_err();
assert!(
err.to_string()
.contains("cannot tell whether it sets fips.mode"),
"{err}"
);
let missing = format!("{path}.missing");
let setting = resolve_fips_setting_with_env(&missing, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off);
}
#[test]
fn test_fips_mode_refuses_a_parse_that_did_not_read_the_file() {
use seaweed_common::fips::FipsMode;
let path = PathBuf::from("/etc/seaweedfs/security.toml");
let unread = SecurityConfig::default();
let err = fips_setting_from_parsed(path.clone(), &unread, &fake_env(&[])).unwrap_err();
assert!(
err.to_string()
.contains("could not be read; cannot tell whether it sets fips.mode"),
"{err}"
);
let read = SecurityConfig {
file_read: true,
fips_mode: Some("on".to_string()),
..SecurityConfig::default()
};
let setting = fips_setting_from_parsed(path, &read, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
}
#[test]
fn test_env_override_takes_precedence_over_file() {
let tmp = tempfile::NamedTempFile::new().unwrap();
+294 -27
View File
@@ -5,9 +5,10 @@ use tracing::{error, info, warn};
use seaweed_volume::config::{self, VolumeServerConfig};
use seaweed_volume::metrics;
use seaweed_volume::pb::volume_server_pb::volume_server_server::VolumeServerServer;
use seaweed_volume::security::health_check_access::HealthCheckOnlyLayer;
use seaweed_volume::security::tls::{
GrpcClientAuthPolicy, TlsPolicy, build_rustls_server_config,
build_rustls_server_config_with_grpc_client_auth, install_default_crypto_provider,
build_rustls_server_config_with_grpc_client_auth,
};
use seaweed_volume::security::{Guard, SigningKey};
#[cfg(unix)]
@@ -47,8 +48,6 @@ fn main() {
// returns. See seaweed_volume::malloc_tuning for the measurements.
let malloc_tuning = seaweed_volume::malloc_tuning::pin_mmap_threshold();
install_default_crypto_provider();
// Initialize tracing
tracing_subscriber::fmt()
.with_env_filter(
@@ -58,6 +57,7 @@ fn main() {
.init();
let config = config::parse_cli();
install_crypto_provider_for_fips_mode(&config.security_file);
seaweed_volume::server::server_stats::init_process_start();
#[cfg(unix)]
let cpu_profile = match CpuProfileSession::start(&config) {
@@ -102,6 +102,30 @@ fn main() {
}
}
/// Resolves the FIPS mode from `fips.mode` or `WEED_FIPS_MODE`, logs it and
/// installs the matching rustls provider before anything builds TLS; exits
/// when the value is unknown.
fn install_crypto_provider_for_fips_mode(security_file: &str) {
let installed = config::resolve_fips_setting(security_file)
.map_err(|e| e.to_string())
.and_then(|setting| {
seaweed_common::tls::install_process_provider(setting.mode)
.map(|()| setting)
.map_err(|e| e.to_string())
});
match installed {
Ok(setting) if setting.mode.is_fips() => info!(
"{}: TLS limited to the FIPS 140-3 versions, suites, groups and signature schemes Go allows; the cryptographic module is not validated",
setting
),
Ok(setting) => info!("{}", setting),
Err(e) => {
error!("{}", e);
std::process::exit(1);
}
}
}
/// Mirrors Go's rejectHttpsDowngrade: a redirect must not downgrade a request
/// carrying data and auth headers from https to plaintext.
fn redirect_is_https_downgrade(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
@@ -145,28 +169,22 @@ fn build_outgoing_http_client(
));
}
let mut builder = outgoing_client_builder(redirect_policy);
if !config.https_client_ca_file.is_empty() {
let ca_pem = std::fs::read(&config.https_client_ca_file).map_err(|e| {
let ca_pem = if config.https_client_ca_file.is_empty() {
None
} else {
Some(std::fs::read(&config.https_client_ca_file).map_err(|e| {
format!(
"Failed to read HTTPS client CA file '{}': {}",
config.https_client_ca_file, e
)
})?;
let cert = reqwest::Certificate::from_pem(&ca_pem).map_err(|e| {
format!(
"Failed to parse HTTPS client CA PEM '{}': {}",
config.https_client_ca_file, e
)
})?;
builder = builder.add_root_certificate(cert);
}
})?)
};
match (
let identity = match (
config.https_client_cert_file.is_empty(),
config.https_client_key_file.is_empty(),
) {
(true, true) => {}
(true, true) => None,
(false, false) => {
let cert_pem = std::fs::read(&config.https_client_cert_file).map_err(|e| {
format!(
@@ -180,6 +198,45 @@ fn build_outgoing_http_client(
config.https_client_key_file, e
)
})?;
Some((cert_pem, key_pem))
}
_ => {
return Err(format!(
"HTTPS client requires both cert and key, got cert='{}' key='{}'",
config.https_client_cert_file, config.https_client_key_file
)
.into());
}
};
let mut builder = outgoing_client_builder(redirect_policy);
if seaweed_common::fips::process_mode().is_fips() {
let tls = fips_outgoing_tls_config(
ca_pem.as_deref(),
identity.as_ref().map(|(cert, key)| (cert.as_slice(), key.as_slice())),
Arc::new(seaweed_common::tls::crypto_provider()),
)
.map_err(|e| {
format!(
"Failed to build the HTTPS client TLS configuration (ca '{}', cert '{}', key '{}'): {}",
config.https_client_ca_file,
config.https_client_cert_file,
config.https_client_key_file,
e
)
})?;
builder = builder.use_preconfigured_tls(tls);
} else {
if let Some(ca_pem) = &ca_pem {
let cert = reqwest::Certificate::from_pem(ca_pem).map_err(|e| {
format!(
"Failed to parse HTTPS client CA PEM '{}': {}",
config.https_client_ca_file, e
)
})?;
builder = builder.add_root_certificate(cert);
}
if let Some((cert_pem, key_pem)) = identity {
let mut identity_pem = cert_pem;
if !identity_pem.ends_with(b"\n") {
identity_pem.push(b'\n');
@@ -193,18 +250,45 @@ fn build_outgoing_http_client(
})?;
builder = builder.identity(identity);
}
_ => {
return Err(format!(
"HTTPS client requires both cert and key, got cert='{}' key='{}'",
config.https_client_cert_file, config.https_client_key_file
)
.into());
}
}
Ok((builder.build()?, scheme.to_string()))
}
/// The outgoing HTTPS client configuration in FIPS mode: the roots, CA and
/// identity reqwest would use, with the Extended Master Secret required on
/// TLS 1.2 as Go requires it. reqwest leaves `require_ems` at rustls's
/// default, which is off for a provider that is not FIPS-validated.
fn fips_outgoing_tls_config(
ca_pem: Option<&[u8]>,
identity: Option<(&[u8], &[u8])>,
provider: Arc<rustls::crypto::CryptoProvider>,
) -> Result<rustls::ClientConfig, Box<dyn std::error::Error>> {
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
let mut roots = rustls::RootCertStore::empty();
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
if let Some(ca) = ca_pem {
for cert in CertificateDer::pem_slice_iter(ca) {
roots.add(cert?)?;
}
}
let builder = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.with_root_certificates(roots);
let mut tls = match identity {
Some((cert, key)) => {
let chain = CertificateDer::pem_slice_iter(cert).collect::<Result<Vec<_>, _>>()?;
builder.with_client_auth_cert(chain, PrivateKeyDer::from_pem_slice(key)?)?
}
None => builder.with_no_client_auth(),
};
tls.alpn_protocols = vec![b"http/1.1".to_vec()];
tls.require_ems = true;
Ok(tls)
}
fn tls_policy_is_configured(policy: &TlsPolicy) -> bool {
!policy.min_version.is_empty()
|| !policy.max_version.is_empty()
@@ -226,6 +310,7 @@ fn build_grpc_server_tls_acceptor(
tls_policy: &TlsPolicy,
allowed_wildcard_domain: &str,
allowed_common_names: &[String],
health_check_common_names: &[String],
) -> Result<Option<TlsAcceptor>, Box<dyn std::error::Error>> {
if cert_path.is_empty() && key_path.is_empty() {
return Ok(None);
@@ -239,6 +324,7 @@ fn build_grpc_server_tls_acceptor(
let client_auth_policy = GrpcClientAuthPolicy {
allowed_common_names: allowed_common_names.to_vec(),
allowed_wildcard_domain: allowed_wildcard_domain.to_string(),
health_check_common_names: health_check_common_names.to_vec(),
};
let mut server_config = build_rustls_server_config_with_grpc_client_auth(
cert_path,
@@ -267,7 +353,9 @@ fn build_http_server_tls_acceptor(
) {
Ok(tls_config) => tls_config,
Err(e)
if !config.https_ca_file.is_empty() && tls_policy_is_configured(&config.tls_policy) =>
if !config.https_ca_file.is_empty()
&& tls_policy_is_configured(&config.tls_policy)
&& !seaweed_common::fips::process_mode().is_fips() =>
{
warn!(
"Failed to apply HTTP TLS policy '{}', falling back to default rustls policy",
@@ -304,6 +392,32 @@ fn build_volume_grpc_service(
.max_encoding_message_size(GRPC_MAX_MESSAGE_SIZE)
}
const GRPC_HEALTH_SERVICES: [&str; 3] = [
"",
<VolumeServerServer<VolumeGrpcService> as tonic::server::NamedService>::NAME,
<tonic_health::pb::health_server::HealthServer<tonic_health::server::HealthService> as tonic::server::NamedService>::NAME,
];
async fn build_grpc_health_service() -> (
tonic_health::server::HealthReporter,
tonic_health::pb::health_server::HealthServer<impl tonic_health::pb::health_server::Health>,
) {
let (reporter, service) = tonic_health::server::health_reporter();
for name in GRPC_HEALTH_SERVICES {
reporter
.set_service_status(name, tonic_health::ServingStatus::Serving)
.await;
}
(reporter, service)
}
/// Ends open Watch streams, which graceful shutdown would otherwise wait on.
async fn end_grpc_health_watches(mut reporter: tonic_health::server::HealthReporter) {
for name in GRPC_HEALTH_SERVICES {
reporter.clear_service_status(name).await;
}
}
fn apply_idle_timeout<S>(
stream: S,
idle_timeout: std::time::Duration,
@@ -553,6 +667,7 @@ async fn run(
&config.tls_policy,
&config.grpc_allowed_wildcard_domain,
&config.grpc_volume_allowed_common_names,
&config.grpc_health_check_common_names,
)?;
info!("Starting HTTP server on {}", admin_addr);
@@ -613,6 +728,9 @@ async fn run(
sighup.recv().await;
info!("Received SIGHUP, reloading...");
// 0. Re-read TLS server certificates (Go's certreload.ReloadAll)
seaweed_volume::security::tls::reload_all();
// 1. Load new volumes from disk (Go's LoadNewVolumes)
{
info!("Loading new volume ids...");
@@ -712,6 +830,7 @@ async fn run(
let grpc_handle = {
let grpc_state = state.clone();
let grpc_tls_acceptor = grpc_tls_acceptor.clone();
let health_check_only = HealthCheckOnlyLayer::new(&config.grpc_health_check_common_names);
let mut shutdown_rx = shutdown_tx.subscribe();
let shutdown_tx_grpc = shutdown_tx.clone();
tokio::spawn(async move {
@@ -726,17 +845,21 @@ async fn run(
.register_encoded_file_descriptor_set(seaweed_volume::pb::FILE_DESCRIPTOR_SET)
.build_v1alpha()
.expect("Failed to build gRPC reflection v1alpha service");
let (health_reporter, health_service) = build_grpc_health_service().await;
let result = if let Some(tls_acceptor) = grpc_tls_acceptor {
let incoming =
grpc_tls_incoming(grpc_listener, tls_acceptor, GRPC_TLS_HANDSHAKE_TIMEOUT);
info!("gRPC server listening on {} (TLS enabled)", grpc_local_addr);
build_grpc_server_builder()
.layer(health_check_only)
.layer(GrpcRequestIdLayer)
.add_service(reflection_v1)
.add_service(reflection_v1alpha)
.add_service(health_service)
.add_service(build_volume_grpc_service(grpc_service))
.serve_with_incoming_shutdown(incoming, async move {
let _ = shutdown_rx.recv().await;
end_grpc_health_watches(health_reporter).await;
})
.await
} else {
@@ -746,9 +869,11 @@ async fn run(
.layer(GrpcRequestIdLayer)
.add_service(reflection_v1)
.add_service(reflection_v1alpha)
.add_service(health_service)
.add_service(build_volume_grpc_service(grpc_service))
.serve_with_incoming_shutdown(incoming, async move {
let _ = shutdown_rx.recv().await;
end_grpc_health_watches(health_reporter).await;
})
.await
};
@@ -1137,6 +1262,61 @@ mod tests {
/// A connect that never finishes fails at the 5 s bound. It stalls in the
/// resolver, which the connect bound also covers, because that needs no
/// routing: a real unanswered SYN depends on the host's network.
#[tokio::test]
async fn grpc_health_answers_for_the_volume_server() {
use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (health_reporter, health_service) = super::build_grpc_health_service().await;
tokio::spawn(
tonic::transport::Server::builder()
.add_service(health_service)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),
);
let channel = tonic::transport::Endpoint::from_shared(format!("http://{}", addr))
.unwrap()
.connect()
.await
.unwrap();
let mut client = HealthClient::new(channel);
for service in ["", "volume_server_pb.VolumeServer", "grpc.health.v1.Health"] {
let response = client
.check(HealthCheckRequest {
service: service.to_string(),
})
.await
.unwrap_or_else(|e| panic!("Check({:?}): {}", service, e));
assert_eq!(
response.into_inner().status,
tonic_health::pb::health_check_response::ServingStatus::Serving as i32,
"Check({:?})",
service
);
}
let err = client
.check(HealthCheckRequest {
service: "master_pb.Seaweed".to_string(),
})
.await
.unwrap_err();
assert_eq!(err.code(), tonic::Code::NotFound);
let mut watch = client
.watch(HealthCheckRequest {
service: String::new(),
})
.await
.unwrap()
.into_inner();
assert!(watch.message().await.unwrap().is_some());
super::end_grpc_health_watches(health_reporter).await;
let ended = tokio::time::timeout(std::time::Duration::from_secs(5), watch.message())
.await
.expect("Watch still open after end_grpc_health_watches");
assert!(matches!(ended, Ok(None)), "{:?}", ended);
}
#[tokio::test(start_paused = true)]
async fn outgoing_client_bounds_a_stalled_connect() {
struct Stalled;
@@ -1161,6 +1341,24 @@ mod tests {
assert_eq!(started.elapsed(), super::OUTGOING_CONNECT_TIMEOUT);
}
#[test]
fn fips_outgoing_tls_requires_ems() {
let provider = std::sync::Arc::new(seaweed_common::tls::provider_for(
seaweed_common::fips::FipsMode::On,
));
let tls = super::fips_outgoing_tls_config(
Some(TEST_CA_PEM.as_bytes()),
Some((TEST_LEAF_PEM.as_bytes(), TEST_LEAF_KEY_PEM.as_bytes())),
provider.clone(),
)
.unwrap();
assert!(tls.require_ems);
assert_eq!(tls.alpn_protocols, vec![b"http/1.1".to_vec()]);
let malformed_ca = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
assert!(super::fips_outgoing_tls_config(Some(malformed_ca), None, provider).is_err());
}
fn write_pem(dir: &tempfile::TempDir, name: &str, body: &str) -> String {
let path = dir.path().join(name);
std::fs::write(&path, body).unwrap();
@@ -1177,7 +1375,7 @@ mod tests {
let ca = write_pem(dir, "ca.pem", TEST_CA_PEM);
let cert = write_pem(dir, "leaf.pem", TEST_LEAF_PEM);
let key = write_pem(dir, "leaf.key", TEST_LEAF_KEY_PEM);
build_grpc_server_tls_acceptor(&cert, &key, &ca, &TlsPolicy::default(), "", &[])
build_grpc_server_tls_acceptor(&cert, &key, &ca, &TlsPolicy::default(), "", &[], &[])
.unwrap()
.unwrap()
}
@@ -1259,11 +1457,78 @@ mod tests {
);
assert!(
build_grpc_server_tls_acceptor(&cert, &key, "", &TlsPolicy::default(), "", &[])
build_grpc_server_tls_acceptor(&cert, &key, "", &TlsPolicy::default(), "", &[], &[])
.is_err()
);
}
/// A certificate on grpc.health_check_commonNames passes the handshake even
/// with allowed_commonNames set, and reaches only the health service.
#[tokio::test]
async fn test_grpc_health_check_common_name_reaches_only_health() {
use seaweed_volume::pb::volume_server_pb::{
VolumeServerStatusRequest, volume_server_client::VolumeServerClient,
};
use seaweed_volume::security::health_check_access::HealthCheckOnlyLayer;
use tonic::transport::{Certificate, ClientTlsConfig, Endpoint, Identity};
use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient};
seaweed_volume::security::tls::install_default_crypto_provider();
let dir = tempfile::tempdir().unwrap();
let cert = write_pem(&dir, "leaf.pem", TEST_LEAF_PEM);
let key = write_pem(&dir, "leaf.key", TEST_LEAF_KEY_PEM);
let ca = write_pem(&dir, "ca.pem", TEST_CA_PEM);
let health_names = vec!["localhost".to_string()];
let acceptor = build_grpc_server_tls_acceptor(
&cert,
&key,
&ca,
&TlsPolicy::default(),
"",
&["volume".to_string()],
&health_names,
)
.unwrap()
.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let incoming = grpc_tls_incoming(listener, acceptor, GRPC_TLS_HANDSHAKE_TIMEOUT);
let (_health_reporter, health_service) = super::build_grpc_health_service().await;
tokio::spawn(
tonic::transport::Server::builder()
.layer(HealthCheckOnlyLayer::new(&health_names))
.add_service(health_service)
.serve_with_incoming(incoming),
);
let tls = ClientTlsConfig::new()
.ca_certificate(Certificate::from_pem(TEST_CA_PEM))
.identity(Identity::from_pem(TEST_LEAF_PEM, TEST_LEAF_KEY_PEM))
.domain_name("localhost");
let channel = Endpoint::from_shared(format!("https://{}", addr))
.unwrap()
.tls_config(tls)
.unwrap()
.connect()
.await
.unwrap();
let response = HealthClient::new(channel.clone())
.check(HealthCheckRequest {
service: String::new(),
})
.await
.unwrap();
assert_eq!(
response.into_inner().status,
tonic_health::pb::health_check_response::ServingStatus::Serving as i32
);
let err = VolumeServerClient::new(channel)
.volume_server_status(VolumeServerStatusRequest {})
.await
.unwrap_err();
assert_eq!(err.code(), tonic::Code::PermissionDenied, "{}", err);
}
#[test]
fn test_grpc_server_tls_errors_when_files_are_missing() {
assert!(
@@ -1274,6 +1539,7 @@ mod tests {
&TlsPolicy::default(),
"",
&[],
&[],
)
.is_err()
);
@@ -1310,6 +1576,7 @@ mod tests {
},
"",
&[],
&[],
)
.is_err()
);
+35
View File
@@ -122,6 +122,18 @@ pub static VOLUME_GAUGE: LazyLock<GaugeVec> = LazyLock::new(|| {
.expect("metric can be created")
});
/// Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size (stale_size).
pub static EC_SHARD_DISK_MISMATCH_GAUGE: LazyLock<GaugeVec> = LazyLock::new(|| {
GaugeVec::new(
Opts::new(
"SeaweedFS_volumeServer_ec_shard_disk_mismatch",
"Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size (stale_size).",
),
&["reason"],
)
.expect("metric can be created")
});
/// Read-only volumes per collection and type.
pub static READ_ONLY_VOLUME_GAUGE: LazyLock<GaugeVec> = LazyLock::new(|| {
GaugeVec::new(
@@ -280,6 +292,19 @@ pub static EC_RECONSTRUCTED_INTERVAL_COUNTER: LazyLock<IntCounterVec> = LazyLock
.expect("metric can be created")
});
/// Failed EC shard copies into this server, with labels `collection` and
/// `reason`. Mirrors Go's VolumeServerEcShardCopyFailures.
pub static EC_SHARD_COPY_FAILURES: LazyLock<IntCounterVec> = LazyLock::new(|| {
IntCounterVec::new(
Opts::new(
"SeaweedFS_volumeServer_ec_shard_copy_failures_total",
"Counter of failed EC shard copies into this server by collection and reason.",
),
&["collection", "reason"],
)
.expect("metric can be created")
});
/// Counter of storage read/write EIO errors on volumes and EC shards.
/// Mirrors Go's VolumeServerStorageIoErrorCounter.
pub static STORAGE_IO_ERROR_COUNTER: LazyLock<IntCounter> = LazyLock::new(|| {
@@ -392,6 +417,14 @@ pub const ERROR_WRITE_TO_LOCAL_DISK: &str = "errorWriteToLocalDisk";
pub const ERROR_UNMARSHAL_PAIRS: &str = "errorUnmarshalPairs";
pub const ERROR_WRITE_TO_REPLICAS: &str = "errorWriteToReplicas";
// EC shard copy failure reasons (Go: stats.EcShardCopy*).
pub const EC_SHARD_COPY_SOURCE_NOT_FOUND: &str = "source_not_found";
pub const EC_SHARD_COPY_EMPTY_INDEX: &str = "empty_index";
pub const EC_SHARD_COPY_NO_SPACE: &str = "no_space";
pub const EC_SHARD_COPY_TIMEOUT: &str = "timeout";
pub const EC_SHARD_COPY_IO_ERROR: &str = "io_error";
pub const EC_SHARD_COPY_OTHER: &str = "other";
// Go volume heartbeat metric label values.
pub const READ_ONLY_LABEL_IS_READ_ONLY: &str = "IsReadOnly";
pub const READ_ONLY_LABEL_NO_WRITE_OR_DELETE: &str = "noWriteOrDelete";
@@ -418,6 +451,7 @@ pub fn register_metrics() {
Box::new(VACUUMING_DROPPED_NEEDLES_COUNTER.clone()),
Box::new(VOLUME_GAUGE.clone()),
Box::new(READ_ONLY_VOLUME_GAUGE.clone()),
Box::new(EC_SHARD_DISK_MISMATCH_GAUGE.clone()),
Box::new(MAX_VOLUMES.clone()),
Box::new(DISK_SIZE_GAUGE.clone()),
Box::new(RESOURCE_GAUGE.clone()),
@@ -432,6 +466,7 @@ pub fn register_metrics() {
Box::new(SCRUB_SHARD_FAILURES.clone()),
Box::new(STORAGE_IO_ERROR_COUNTER.clone()),
Box::new(EC_RECONSTRUCTED_INTERVAL_COUNTER.clone()),
Box::new(EC_SHARD_COPY_FAILURES.clone()),
Box::new(IO_QUARANTINE_GAUGE.clone()),
// Legacy metrics
Box::new(VOLUMES_TOTAL.clone()),
+1
View File
@@ -4,6 +4,7 @@
//! - Guard: combines whitelist IP checking with JWT token validation
//! - JWT: HS256 HMAC signing with file-id claims
pub mod health_check_access;
pub mod tls;
use std::collections::HashSet;
@@ -0,0 +1,93 @@
use std::collections::HashSet;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use hyper::http;
use rustls::pki_types::CertificateDer;
use tonic::transport::server::{TcpConnectInfo, TlsConnectInfo};
use tower::{Layer, Service};
use super::tls::parse_common_name;
const GRPC_HEALTH_SERVICE_PREFIX: &str = "/grpc.health.v1.Health/";
/// Confines clients whose certificate common name is in
/// grpc.health_check_commonNames to the gRPC health service, like the Go
/// servers' healthCheckOnlyTap. A name on allowed_commonNames too stays
/// confined.
#[derive(Clone, Debug, Default)]
pub struct HealthCheckOnlyLayer {
names: Arc<HashSet<String>>,
}
impl HealthCheckOnlyLayer {
pub fn new(names: &[String]) -> Self {
Self {
names: Arc::new(names.iter().cloned().collect()),
}
}
}
impl<S> Layer<S> for HealthCheckOnlyLayer {
type Service = HealthCheckOnlyService<S>;
fn layer(&self, inner: S) -> Self::Service {
HealthCheckOnlyService {
inner,
names: self.names.clone(),
}
}
}
#[derive(Clone, Debug)]
pub struct HealthCheckOnlyService<S> {
inner: S,
names: Arc<HashSet<String>>,
}
impl<S, B> Service<http::Request<B>> for HealthCheckOnlyService<S>
where
S: Service<http::Request<B>, Response = http::Response<tonic::body::Body>>,
S::Future: Send + 'static,
{
type Response = http::Response<tonic::body::Body>;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: http::Request<B>) -> Self::Future {
let peer_certs = request
.extensions()
.get::<TlsConnectInfo<TcpConnectInfo>>()
.and_then(|info| info.peer_certs());
if let Some(common_name) = health_check_confined(
&self.names,
request.uri().path(),
peer_certs.as_deref().map(Vec::as_slice),
) {
let status = tonic::Status::permission_denied(format!(
"certificate {:?} may only call the gRPC health service",
common_name
));
return Box::pin(async move { Ok(status.into_http()) });
}
Box::pin(self.inner.call(request))
}
}
fn health_check_confined(
names: &HashSet<String>,
path: &str,
peer_certs: Option<&[CertificateDer<'static>]>,
) -> Option<String> {
if names.is_empty() || path.starts_with(GRPC_HEALTH_SERVICE_PREFIX) {
return None;
}
let common_name = parse_common_name(peer_certs?.first()?).ok()?;
names.contains(&common_name).then_some(common_name)
}
+265 -16
View File
@@ -1,14 +1,14 @@
use std::collections::HashSet;
use std::fmt;
use std::sync::Arc;
use std::sync::{Arc, Mutex, RwLock, Weak};
use rustls::client::danger::HandshakeSignatureValid;
use rustls::crypto::CryptoProvider;
use rustls::crypto::aws_lc_rs;
use rustls::pki_types::UnixTime;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::server::{ClientHello, ResolvesServerCert, WebPkiClientVerifier};
use rustls::sign::CertifiedKey;
use rustls::{
CipherSuite, DigitallySignedStruct, DistinguishedName, RootCertStore, ServerConfig,
SignatureScheme, SupportedCipherSuite, SupportedProtocolVersion,
@@ -26,6 +26,9 @@ pub struct TlsPolicy {
pub struct GrpcClientAuthPolicy {
pub allowed_common_names: Vec<String>,
pub allowed_wildcard_domain: String,
/// Pass the handshake like allowed_common_names, but HealthCheckOnlyLayer
/// lets them call only the gRPC health service.
pub health_check_common_names: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -53,6 +56,7 @@ struct CommonNameVerifier {
inner: Arc<dyn ClientCertVerifier>,
allowed_common_names: HashSet<String>,
allowed_wildcard_domain: String,
health_check_common_names: HashSet<String>,
}
impl ClientCertVerifier for CommonNameVerifier {
@@ -86,7 +90,8 @@ impl ClientCertVerifier for CommonNameVerifier {
&common_name,
&self.allowed_common_names,
&self.allowed_wildcard_domain,
) {
) || self.health_check_common_names.contains(&common_name)
{
return Ok(ClientCertVerified::assertion());
}
Err(rustls::Error::General(format!(
@@ -120,10 +125,10 @@ impl ClientCertVerifier for CommonNameVerifier {
// aws-lc-rs and ring both get linked transitively, so rustls can't auto-select
// a provider and tonic's client TLS panics on first use. Pin the default to
// aws-lc-rs, matching the server config. Idempotent. The body lives in
// seaweed-common so this binary and the Rust plugin workers cannot end up
// installing different providers; re-exported here so callers keep their
// import path.
// aws-lc-rs, matching the server config (filtered to the FIPS lists in FIPS
// mode). Idempotent. The body lives in seaweed-common so this binary and the
// Rust plugin workers cannot end up installing different providers;
// re-exported here so callers keep their import path.
pub use seaweed_common::tls::install_default_crypto_provider;
pub fn build_rustls_server_config(
@@ -158,8 +163,6 @@ fn build_rustls_server_config_with_client_auth(
policy: &TlsPolicy,
client_auth_policy: Option<&GrpcClientAuthPolicy>,
) -> Result<ServerConfig, TlsPolicyError> {
let cert_chain = read_cert_chain(cert_path)?;
let private_key = read_private_key(key_path)?;
let provider = build_crypto_provider(policy)?;
let versions = build_supported_versions(policy)?;
@@ -188,6 +191,11 @@ fn build_rustls_server_config_with_client_auth(
.cloned()
.collect(),
allowed_wildcard_domain: client_auth_policy.allowed_wildcard_domain.clone(),
health_check_common_names: client_auth_policy
.health_check_common_names
.iter()
.cloned()
.collect(),
})
} else {
verifier
@@ -195,9 +203,85 @@ fn build_rustls_server_config_with_client_auth(
builder.with_client_cert_verifier(verifier)
};
builder
.with_single_cert(cert_chain, private_key)
.map_err(|e| TlsPolicyError(format!("build rustls server config failed: {}", e)))
let cert = ReloadableCert::new(cert_path, key_path, provider)?;
let mut config = builder.with_cert_resolver(cert);
config.require_ems = config.require_ems || seaweed_common::tls::require_ems();
Ok(config)
}
/// Serves the cert/key pair read from disk and re-reads it on `reload_all`
/// (SIGHUP), mirroring Go's certreload provider.
#[derive(Debug)]
struct ReloadableCert {
cert_path: String,
key_path: String,
provider: Arc<CryptoProvider>,
current: RwLock<Arc<CertifiedKey>>,
}
static RELOADABLE_CERTS: Mutex<Vec<Weak<ReloadableCert>>> = Mutex::new(Vec::new());
impl ReloadableCert {
fn new(
cert_path: &str,
key_path: &str,
provider: Arc<CryptoProvider>,
) -> Result<Arc<Self>, TlsPolicyError> {
let current = load_certified_key(cert_path, key_path, &provider)?;
let cert = Arc::new(Self {
cert_path: cert_path.to_string(),
key_path: key_path.to_string(),
provider,
current: RwLock::new(Arc::new(current)),
});
let mut certs = RELOADABLE_CERTS.lock().unwrap();
certs.retain(|c| c.strong_count() > 0);
certs.push(Arc::downgrade(&cert));
Ok(cert)
}
fn reload(&self) -> Result<(), TlsPolicyError> {
let next = load_certified_key(&self.cert_path, &self.key_path, &self.provider)?;
*self.current.write().unwrap() = Arc::new(next);
Ok(())
}
}
impl ResolvesServerCert for ReloadableCert {
fn resolve(&self, _client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
Some(self.current.read().unwrap().clone())
}
}
fn load_certified_key(
cert_path: &str,
key_path: &str,
provider: &CryptoProvider,
) -> Result<CertifiedKey, TlsPolicyError> {
let cert_chain = read_cert_chain(cert_path)?;
let private_key = read_private_key(key_path)?;
CertifiedKey::from_der(cert_chain, private_key, provider).map_err(|e| {
TlsPolicyError(format!(
"build rustls server config from '{}' and '{}' failed: {}",
cert_path, key_path, e
))
})
}
/// Re-reads the cert/key files of every live TLS server config. A pair that
/// fails to load keeps serving the previous one.
pub fn reload_all() {
let certs: Vec<Arc<ReloadableCert>> = {
let mut certs = RELOADABLE_CERTS.lock().unwrap();
certs.retain(|c| c.strong_count() > 0);
certs.iter().filter_map(Weak::upgrade).collect()
};
for cert in certs {
match cert.reload() {
Ok(()) => tracing::info!("reloaded TLS cert {}", cert.cert_path),
Err(e) => tracing::warn!("keeping TLS cert {}: {}", cert.cert_path, e),
}
}
}
fn read_cert_chain(cert_path: &str) -> Result<Vec<CertificateDer<'static>>, TlsPolicyError> {
@@ -241,8 +325,21 @@ fn read_root_store(ca_path: &str) -> Result<RootCertStore, TlsPolicyError> {
Ok(roots)
}
/// The process's provider (see `seaweed_common::tls::crypto_provider`) with
/// `tls.cipher_suites` applied. In FIPS mode a configured suite outside the
/// FIPS list is an error, so the setting cannot widen what the mode allows.
fn build_crypto_provider(policy: &TlsPolicy) -> Result<Arc<CryptoProvider>, TlsPolicyError> {
let mut provider = aws_lc_rs::default_provider();
build_crypto_provider_for(seaweed_common::fips::process_mode(), policy)
}
fn build_crypto_provider_for(
mode: seaweed_common::fips::FipsMode,
policy: &TlsPolicy,
) -> Result<Arc<CryptoProvider>, TlsPolicyError> {
let mut provider = seaweed_common::tls::provider_for(mode);
if mode.is_fips() {
refuse_non_fips_cipher_suites(mode, &policy.cipher_suites)?;
}
let cipher_suites = parse_cipher_suites(&provider.cipher_suites, &policy.cipher_suites)?;
if !cipher_suites.is_empty() {
provider.cipher_suites = cipher_suites;
@@ -250,6 +347,25 @@ fn build_crypto_provider(policy: &TlsPolicy) -> Result<Arc<CryptoProvider>, TlsP
Ok(Arc::new(provider))
}
/// Errors naming the first suite in `value` (`tls.cipher_suites`) that rustls
/// implements but FIPS mode does not allow, such as ChaCha20-Poly1305.
fn refuse_non_fips_cipher_suites(
mode: seaweed_common::fips::FipsMode,
value: &str,
) -> Result<(), TlsPolicyError> {
for name in value.split(',').map(str::trim).filter(|n| !n.is_empty()) {
if let Ok(suite) = parse_cipher_suite_name(name)
&& !seaweed_common::tls::FIPS_CIPHER_SUITES.contains(&suite)
{
return Err(TlsPolicyError(format!(
"tls.cipher_suites names '{}', which FIPS mode {} does not allow",
name, mode
)));
}
}
Ok(())
}
pub fn build_supported_versions(
policy: &TlsPolicy,
) -> Result<Vec<&'static SupportedProtocolVersion>, TlsPolicyError> {
@@ -343,7 +459,7 @@ fn parse_cipher_suite_name(value: &str) -> Result<CipherSuite, TlsPolicyError> {
}
}
fn parse_common_name(cert: &CertificateDer<'_>) -> Result<String, TlsPolicyError> {
pub(crate) fn parse_common_name(cert: &CertificateDer<'_>) -> Result<String, TlsPolicyError> {
let (_, certificate) = X509Certificate::from_der(cert.as_ref())
.map_err(|e| TlsPolicyError(format!("parse X.509 certificate failed: {}", e)))?;
let common_name = certificate
@@ -420,9 +536,14 @@ fn go_tls_version_for_supported(version: &SupportedProtocolVersion) -> GoTlsVers
#[cfg(test)]
mod tests {
use super::{TlsPolicy, build_supported_versions, common_name_is_allowed, parse_cipher_suites};
use super::{
ReloadableCert, TlsPolicy, build_crypto_provider_for, build_rustls_server_config,
build_supported_versions, common_name_is_allowed, parse_cipher_suites, reload_all,
};
use rustls::crypto::aws_lc_rs;
use seaweed_common::fips::FipsMode;
use std::collections::HashSet;
use std::sync::Arc;
#[test]
fn test_build_supported_versions_defaults_to_tls12_and_tls13() {
@@ -465,6 +586,55 @@ mod tests {
assert_eq!(cipher_suites.len(), 2);
}
#[test]
fn test_fips_mode_refuses_a_configured_chacha20_suite() {
let policy = |suites: &str| TlsPolicy {
cipher_suites: suites.to_string(),
..TlsPolicy::default()
};
let err = build_crypto_provider_for(
FipsMode::On,
&policy("TLS_AES_128_GCM_SHA256,TLS_CHACHA20_POLY1305_SHA256"),
)
.unwrap_err();
assert_eq!(
err.to_string(),
"tls.cipher_suites names 'TLS_CHACHA20_POLY1305_SHA256', which FIPS mode on does not allow"
);
let provider = build_crypto_provider_for(
FipsMode::Strict,
&policy("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_AES_128_GCM_SHA256"),
)
.unwrap();
assert_eq!(provider.cipher_suites.len(), 2);
let provider =
build_crypto_provider_for(FipsMode::Off, &policy("TLS_CHACHA20_POLY1305_SHA256"))
.unwrap();
assert_eq!(provider.cipher_suites.len(), 1);
}
#[test]
fn test_fips_mode_provider_drops_chacha20_and_x25519() {
let provider = build_crypto_provider_for(FipsMode::On, &TlsPolicy::default()).unwrap();
assert!(
provider
.cipher_suites
.iter()
.all(|s| s.suite() != rustls::CipherSuite::TLS13_CHACHA20_POLY1305_SHA256)
);
assert!(
provider
.kx_groups
.iter()
.all(|g| g.name() != rustls::NamedGroup::X25519)
);
let default = build_crypto_provider_for(FipsMode::Off, &TlsPolicy::default()).unwrap();
assert_eq!(
default.cipher_suites.len(),
aws_lc_rs::default_provider().cipher_suites.len()
);
}
#[test]
fn test_common_name_is_allowed_matches_exact_and_wildcard() {
let allowed_common_names =
@@ -525,4 +695,83 @@ mod tests {
".example.com",
));
}
// Two unrelated self-signed localhost pairs used to rotate the files.
const FIRST_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBizCCATGgAwIBAgIUauDdiWDFpHLXr8Xtf8s4d4f394kwCgYIKoZIzj0EAwIw\nEDEOMAwGA1UEAwwFZmlyc3QwHhcNMjYxMTI3MjEzMDExWhcNMzYxMTI0MjEzMDEx\nWjAQMQ4wDAYDVQQDDAVmaXJzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNH8\nYX6HlRaup0oiSFzhG2Vei3ffH8gX3JLYsa7GkwebmplCYvTEQIE/2lRyBy2t10k4\n9LCQl/5UXqPSGtxClsWjaTBnMB0GA1UdDgQWBBQka2xHibxVJIsJUgcjCzX08XB/\nsDAfBgNVHSMEGDAWgBQka2xHibxVJIsJUgcjCzX08XB/sDAPBgNVHRMBAf8EBTAD\nAQH/MBQGA1UdEQQNMAuCCWxvY2FsaG9zdDAKBggqhkjOPQQDAgNIADBFAiEAo5fC\nW8S7MfBHy+pa0T6eWzx3bkJx/p8EazaH2QL0bPoCIHmCoQocMMjGHWC4VvvxazeJ\nQjV6OINpIcehqJIeHEk7\n-----END CERTIFICATE-----\n";
const FIRST_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgBKOApzLisI0tXK5d\nYxiPB4BJhegPo67l3teNjLzJKIShRANCAATR/GF+h5UWrqdKIkhc4RtlXot33x/I\nF9yS2LGuxpMHm5qZQmL0xECBP9pUcgctrddJOPSwkJf+VF6j0hrcQpbF\n-----END PRIVATE KEY-----\n";
const SECOND_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBjjCCATOgAwIBAgIUKaOd+9Eypm1Iomu9vkP70b/92bswCgYIKoZIzj0EAwIw\nETEPMA0GA1UEAwwGc2Vjb25kMB4XDTI2MTEyNzIxMzAxMVoXDTM2MTEyNDIxMzAx\nMVowETEPMA0GA1UEAwwGc2Vjb25kMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE\nqbQV86SqTM3nyKlr5jFjhZ0hjZuMemeXomV7OPcZSVovXCfHlZsuaQAXzaOZNtrd\nU2FbpFxcGXVYw+K2f1NoDaNpMGcwHQYDVR0OBBYEFDMw3Xj86fk1HYTSk4VQBQ3N\nhwkkMB8GA1UdIwQYMBaAFDMw3Xj86fk1HYTSk4VQBQ3NhwkkMA8GA1UdEwEB/wQF\nMAMBAf8wFAYDVR0RBA0wC4IJbG9jYWxob3N0MAoGCCqGSM49BAMCA0kAMEYCIQCO\nucyTGgXImXfmbDF404yiBExWDoiLdgecAeN65DtZwgIhANqJtBqN5KL/FAfdKtit\nPaDLh5HHPhJNbXinIz/7a6Nf\n-----END CERTIFICATE-----\n";
const SECOND_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgTqvWMTK2wl1pB63u\nnJoiarARgNRRoTcULqrG8OkrvTahRANCAASptBXzpKpMzefIqWvmMWOFnSGNm4x6\nZ5eiZXs49xlJWi9cJ8eVmy5pABfNo5k22t1TYVukXFwZdVjD4rZ/U2gN\n-----END PRIVATE KEY-----\n";
fn write_pair(dir: &tempfile::TempDir, cert: &str, key: &str) -> (String, String) {
let cert_path = dir.path().join("tls.crt");
let key_path = dir.path().join("tls.key");
std::fs::write(&cert_path, cert).unwrap();
std::fs::write(&key_path, key).unwrap();
(
cert_path.to_string_lossy().into_owned(),
key_path.to_string_lossy().into_owned(),
)
}
fn leaf_der(pem: &str) -> Vec<u8> {
rustls_pemfile::certs(&mut pem.as_bytes())
.next()
.unwrap()
.unwrap()
.to_vec()
}
fn served_leaf(cert: &ReloadableCert) -> Vec<u8> {
cert.current.read().unwrap().cert[0].to_vec()
}
#[test]
fn test_reload_all_serves_the_rotated_pair() {
let dir = tempfile::tempdir().unwrap();
let (cert_path, key_path) = write_pair(&dir, FIRST_CERT_PEM, FIRST_KEY_PEM);
let cert = ReloadableCert::new(
&cert_path,
&key_path,
Arc::new(aws_lc_rs::default_provider()),
)
.unwrap();
assert_eq!(served_leaf(&cert), leaf_der(FIRST_CERT_PEM));
write_pair(&dir, SECOND_CERT_PEM, SECOND_KEY_PEM);
reload_all();
assert_eq!(served_leaf(&cert), leaf_der(SECOND_CERT_PEM));
}
#[test]
fn test_reload_keeps_the_previous_pair_when_the_files_are_bad() {
let dir = tempfile::tempdir().unwrap();
let (cert_path, key_path) = write_pair(&dir, FIRST_CERT_PEM, FIRST_KEY_PEM);
let cert = ReloadableCert::new(
&cert_path,
&key_path,
Arc::new(aws_lc_rs::default_provider()),
)
.unwrap();
write_pair(&dir, SECOND_CERT_PEM, FIRST_KEY_PEM);
assert!(cert.reload().is_err(), "a key that does not match the cert");
assert_eq!(served_leaf(&cert), leaf_der(FIRST_CERT_PEM));
write_pair(&dir, "not a certificate", FIRST_KEY_PEM);
assert!(cert.reload().is_err(), "a cert file without a certificate");
assert_eq!(served_leaf(&cert), leaf_der(FIRST_CERT_PEM));
}
#[test]
fn test_build_rustls_server_config_rejects_a_mismatched_pair() {
let dir = tempfile::tempdir().unwrap();
let (cert_path, key_path) = write_pair(&dir, SECOND_CERT_PEM, FIRST_KEY_PEM);
assert!(
build_rustls_server_config(&cert_path, &key_path, "", &TlsPolicy::default()).is_err()
);
write_pair(&dir, SECOND_CERT_PEM, SECOND_KEY_PEM);
assert!(
build_rustls_server_config(&cert_path, &key_path, "", &TlsPolicy::default()).is_ok()
);
}
}
+1
View File
@@ -454,6 +454,7 @@ mod tests {
grpc_ca_file: String::new(),
grpc_allowed_wildcard_domain: String::new(),
grpc_volume_allowed_common_names: vec![],
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
}
+282 -2
View File
@@ -51,6 +51,36 @@ fn scrub_mode_label(mode: i32) -> &'static str {
}
}
/// Maps a failed EC shard copy to a bounded reason label. Errors from the
/// source arrive as gRPC text, so it matches messages. Mirrors Go's
/// ecShardCopyFailureReason.
fn ec_shard_copy_failure_reason(status: &Status) -> &'static str {
use crate::metrics as m;
let code = status.code();
let msg = status.message().to_lowercase();
if msg.contains(".ecx is 0 bytes") {
m::EC_SHARD_COPY_EMPTY_INDEX
} else if code == tonic::Code::ResourceExhausted || msg.contains("no space left") {
m::EC_SHARD_COPY_NO_SPACE
} else if code == tonic::Code::DeadlineExceeded
|| msg.contains("deadline exceeded")
|| msg.contains("deadlineexceeded")
|| msg.contains("deadline expired")
|| msg.contains("deadline has elapsed")
|| msg.contains("timeout")
|| msg.contains("timed out")
{
m::EC_SHARD_COPY_TIMEOUT
} else if code == tonic::Code::NotFound || msg.contains("not found") || msg.contains("notfound")
{
m::EC_SHARD_COPY_SOURCE_NOT_FOUND
} else if msg.contains("input/output error") {
m::EC_SHARD_COPY_IO_ERROR
} else {
m::EC_SHARD_COPY_OTHER
}
}
/// Go formats the id in decimal; fs.verify matches the "needle not found " prefix.
fn needle_not_found(needle_id: NeedleId) -> Status {
Status::not_found(format!("needle not found {}", needle_id.0))
@@ -1574,6 +1604,7 @@ impl VolumeServer for VolumeGrpcService {
self.check_grpc_admin_auth(&request)?;
self.state.check_maintenance()?;
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
let rp = crate::storage::super_block::ReplicaPlacement::from_string(&req.replication)
.map_err(|e| Status::invalid_argument(e.to_string()))?;
@@ -1977,6 +2008,8 @@ impl VolumeServer for VolumeGrpcService {
) -> Result<Response<volume_server_pb::VolumeMountResponse>, Status> {
self.check_grpc_admin_auth(&request)?;
let req = request.into_inner();
check_volume_collection(req.collection.as_deref().unwrap_or_default())
.map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
// A decode in flight may be mid-compaction on this volume's
@@ -2337,6 +2370,7 @@ impl VolumeServer for VolumeGrpcService {
self.check_grpc_admin_auth(&request)?;
self.state.check_maintenance()?;
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
if !self.state.allow_untrusted_remote_endpoints {
@@ -3427,6 +3461,7 @@ impl VolumeServer for VolumeGrpcService {
self.check_grpc_admin_auth(&request)?;
self.state.check_maintenance()?;
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
let collection = &req.collection;
@@ -3897,6 +3932,7 @@ impl VolumeServer for VolumeGrpcService {
self.check_grpc_admin_auth(&request)?;
self.state.check_maintenance()?;
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
if !self.state.allow_untrusted_remote_endpoints {
@@ -3931,16 +3967,42 @@ impl VolumeServer for VolumeGrpcService {
state: self.state.clone(),
};
let request_id = crate::server::request_id::current_request_id();
let collection = req.collection.clone();
let source = req.source_data_node.clone();
let wire_shard_ids = req.shard_ids.clone();
let report = move |status: &Status| {
let reason = ec_shard_copy_failure_reason(status);
crate::metrics::EC_SHARD_COPY_FAILURES
.with_label_values(&[collection.as_str(), reason])
.inc();
tracing::warn!(
"VolumeEcShardsCopy volume {} shards {:?} from {} failed ({}): {}",
vid,
wire_shard_ids,
source,
reason,
status.message()
);
};
let task_report = report.clone();
tokio::spawn(async move {
let _lifecycle = lifecycle;
let copy = svc.volume_ec_shards_copy_locked(req, vid, shard_ids);
match request_id {
let result = match request_id {
Some(id) => crate::server::request_id::scope_request_id(id, copy).await,
None => copy.await,
};
if let Err(status) = &result {
task_report(status);
}
result
})
.await
.map_err(|e| Status::internal(format!("VolumeEcShardsCopy volume {}: {}", vid, e)))?
.map_err(|e| {
let status = Status::internal(format!("VolumeEcShardsCopy volume {}: {}", vid, e));
report(&status);
status
})?
}
/// Allowed in maintenance mode: like `volume_delete` it only removes data, and
@@ -3951,6 +4013,7 @@ impl VolumeServer for VolumeGrpcService {
) -> Result<Response<volume_server_pb::VolumeEcShardsDeleteResponse>, Status> {
self.check_grpc_admin_auth(&request)?;
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
if req.full_teardown {
@@ -4094,6 +4157,7 @@ impl VolumeServer for VolumeGrpcService {
request: Request<volume_server_pb::VolumeEcShardsMountRequest>,
) -> Result<Response<volume_server_pb::VolumeEcShardsMountResponse>, Status> {
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
// Pre-validate the ENTIRE batch before any mutation: validating inside
@@ -4425,6 +4489,7 @@ impl VolumeServer for VolumeGrpcService {
self.check_grpc_admin_auth(&request)?;
self.state.check_maintenance()?;
let req = request.into_inner();
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
let vid = VolumeId(req.volume_id);
// Staged mode: the caller decoded off-box and streamed the normal volume
@@ -5967,6 +6032,8 @@ mod copy_source {
.await
.map_err(|e| Status::internal(format!("read volume file status failed, {}", e)))?
.into_inner();
super::check_volume_collection(&vol_info.collection)
.map_err(|e| Status::internal(format!("source volume {}: {}", volume_id, e)))?;
Ok(Self(vol_info))
}
}
@@ -8435,6 +8502,75 @@ mod tests {
use tempfile::TempDir;
use tokio_stream::StreamExt;
#[test]
fn test_ec_shard_copy_failure_reason() {
use crate::metrics as m;
let cases = [
(
Status::internal(format!(
"VolumeEcShardsCopy volume 7 copy .ec01: {}",
Status::not_found("No such file or directory (os error 2)")
)),
m::EC_SHARD_COPY_SOURCE_NOT_FOUND,
),
(
Status::internal(
"failed to copy /d/7.ec01 file: rpc error: code = NotFound desc = gone",
),
m::EC_SHARD_COPY_SOURCE_NOT_FOUND,
),
(
Status::internal(format!(
"VolumeEcShardsCopy volume 7 copy .ec01: {}",
Status::deadline_exceeded("stream")
)),
m::EC_SHARD_COPY_TIMEOUT,
),
(
Status::internal(
"VolumeEcShardsCopy volume 7: failed to copy /d/7.ec01 file: CopyFile not found ec volume id 7",
),
m::EC_SHARD_COPY_SOURCE_NOT_FOUND,
),
(
Status::not_found("volume 7"),
m::EC_SHARD_COPY_SOURCE_NOT_FOUND,
),
(
Status::failed_precondition("VolumeEcShardsCopy volume 7: source .ecx is 0 bytes"),
m::EC_SHARD_COPY_EMPTY_INDEX,
),
(Status::internal("no space left"), m::EC_SHARD_COPY_NO_SPACE),
(
Status::internal("write 7.ec01.copying: No space left on device (os error 28)"),
m::EC_SHARD_COPY_NO_SPACE,
),
(
Status::deadline_exceeded("stream"),
m::EC_SHARD_COPY_TIMEOUT,
),
(
Status::internal("copy 7.ec01: deadline has elapsed"),
m::EC_SHARD_COPY_TIMEOUT,
),
(
Status::unknown("context deadline exceeded"),
m::EC_SHARD_COPY_TIMEOUT,
),
(
Status::internal("write 7.ec01.copying: Input/output error (os error 5)"),
m::EC_SHARD_COPY_IO_ERROR,
),
(
Status::failed_precondition("copied shards are encode run 1 but /d mounts run 2"),
m::EC_SHARD_COPY_OTHER,
),
];
for (status, want) in cases {
assert_eq!(ec_shard_copy_failure_reason(&status), want, "{status:?}");
}
}
fn loc(dir: &str, idx_dir: &str, shard_count: usize, has_ecx: bool) -> LocInfo {
LocInfo {
dir: dir.to_string(),
@@ -13250,6 +13386,150 @@ mod tests {
assert!(err.message().contains("is being copied"), "{}", err.message());
}
#[tokio::test]
async fn test_handlers_reject_a_collection_that_leaves_the_volume_dir() {
use volume_server_pb::*;
let (service, _tmp) = make_local_service_with_volume("collection_check", None);
for collection in ["..", "../outside", "a/b", "a\\b"] {
let c = || collection.to_string();
let errs = [
(
"allocate_volume",
service
.allocate_volume(Request::new(AllocateVolumeRequest {
volume_id: 7,
collection: c(),
..Default::default()
}))
.await
.err(),
),
(
"volume_mount",
service
.volume_mount(Request::new(VolumeMountRequest {
volume_id: 7,
collection: Some(c()),
..Default::default()
}))
.await
.err(),
),
(
"volume_copy",
service
.volume_copy(Request::new(VolumeCopyRequest {
volume_id: 7,
collection: c(),
..Default::default()
}))
.await
.err(),
),
(
"volume_ec_shards_rebuild",
service
.volume_ec_shards_rebuild(Request::new(VolumeEcShardsRebuildRequest {
volume_id: 7,
collection: c(),
..Default::default()
}))
.await
.err(),
),
(
"volume_ec_shards_copy",
service
.volume_ec_shards_copy(Request::new(VolumeEcShardsCopyRequest {
volume_id: 7,
collection: c(),
..Default::default()
}))
.await
.err(),
),
(
"volume_ec_shards_delete",
service
.volume_ec_shards_delete(Request::new(VolumeEcShardsDeleteRequest {
volume_id: 7,
collection: c(),
full_teardown: true,
..Default::default()
}))
.await
.err(),
),
(
"volume_ec_shards_mount",
service
.volume_ec_shards_mount(Request::new(VolumeEcShardsMountRequest {
volume_id: 7,
collection: c(),
shard_ids: vec![0],
..Default::default()
}))
.await
.err(),
),
(
"volume_ec_shards_to_volume",
service
.volume_ec_shards_to_volume(Request::new(VolumeEcShardsToVolumeRequest {
volume_id: 7,
collection: c(),
from_staged: true,
..Default::default()
}))
.await
.err(),
),
];
for (name, err) in errs {
let err = err.unwrap_or_else(|| panic!("{name}({collection:?}) succeeded"));
assert_eq!(
err.code(),
tonic::Code::InvalidArgument,
"{name}({collection:?})"
);
assert!(
err.message().contains("invalid collection"),
"{name}({collection:?}): {}",
err.message()
);
}
}
}
#[tokio::test]
async fn test_volume_copy_rejects_a_source_collection_that_leaves_the_volume_dir() {
let (source_service, _source_tmp) = make_local_service_with_volume("a\\b", None);
let (port, _shutdown) = serve_source(source_service).await;
let (dest_service, _dest_tmp) = make_local_service_with_volume("", None);
dest_service
.state
.store
.write()
.unwrap()
.delete_volume(VolumeId(1), false, false, false)
.unwrap();
let err = dest_service
.volume_copy(Request::new(volume_server_pb::VolumeCopyRequest {
volume_id: 1,
source_data_node: format!("127.0.0.1:1.{}", port),
..Default::default()
}))
.await
.err()
.expect("copy from a source reporting a path collection succeeded");
assert!(
err.message().contains("invalid collection"),
"{}",
err.message()
);
}
/// The staged adoption renames .copying files into place and mounts, so
/// it holds the copy claim for the whole span — Go's adoptStagedVolume.
#[tokio::test]
+97 -1
View File
@@ -6,7 +6,7 @@
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::broadcast;
@@ -17,6 +17,7 @@ use super::volume_server::{VolumeServerState, to_http_address};
use crate::pb::master_pb;
use crate::pb::volume_server_pb;
use crate::remote_storage::s3_tier::{S3TierBackend, S3TierConfig};
use crate::storage::erasure_coding::ec_shard::EcShardDiskCheck;
use crate::storage::store::Store;
use crate::storage::types::{NeedleId, VolumeId};
use crate::storage::volume_report::VolumeReportKey;
@@ -1038,6 +1039,31 @@ async fn maybe_adjust_volume_max(
.await
}
static EC_SHARD_CHECK_RUNNING: AtomicBool = AtomicBool::new(false);
/// Runs `check` over the mounted EC shards on its own thread, unless the
/// last one is still running; whether it started.
fn start_ec_shard_check(state: &Arc<VolumeServerState>, check: fn(&[EcShardDiskCheck])) -> bool {
if EC_SHARD_CHECK_RUNNING.swap(true, Ordering::AcqRel) {
return false;
}
let state = state.clone();
// A plain thread, not spawn_blocking: runtime shutdown waits for
// blocking tasks, and a stat on a hung disk may never return.
let spawned = std::thread::Builder::new()
.name("ec-shard-check".into())
.spawn(move || {
let shards = state.store.read().unwrap().ec_shard_disk_checks();
check(&shards);
EC_SHARD_CHECK_RUNNING.store(false, Ordering::Release);
});
if spawned.is_err() {
EC_SHARD_CHECK_RUNNING.store(false, Ordering::Release);
return false;
}
true
}
/// The EC heartbeat and the shard list later deltas are diffed against,
/// under one guard so no mount lands between them unreported.
async fn ec_tick_pass(
@@ -1050,6 +1076,9 @@ async fn ec_tick_pass(
),
tokio::task::JoinError,
> {
start_ec_shard_check(state, |shards| {
Store::check_mounted_ec_shards(shards);
});
off_runtime(config, state, |config, state| {
let store = state.store.read().unwrap();
(
@@ -2694,6 +2723,73 @@ mod tests {
assert_eq!(shards.len(), 1);
}
static STALLED_CHECK_STARTED: AtomicBool = AtomicBool::new(false);
static STALLED_CHECK_RELEASED: AtomicBool = AtomicBool::new(false);
fn stalled_ec_shard_check(_: &[EcShardDiskCheck]) {
STALLED_CHECK_STARTED.store(true, Ordering::SeqCst);
while !STALLED_CHECK_RELEASED.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(5));
}
}
// A disk check stuck on a hung disk holds no store guard: a writer gets
// the store, the tick still reports, and no second check starts.
#[tokio::test]
async fn test_ec_tick_pass_runs_past_a_stalled_disk_check() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let mut store = reporting_store(dir, 0);
std::fs::write(format!("{}/ec_tick_stalled_check_43.ec00", dir), b"shard").unwrap();
std::fs::write(format!("{}/ec_tick_stalled_check_43.ecx", dir), [0u8; 16]).unwrap();
store.locations[0]
.mount_ec_shards(VolumeId(43), "ec_tick_stalled_check", &[0], "")
.unwrap();
let state = test_state_with_store(store);
while !start_ec_shard_check(&state, stalled_ec_shard_check) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
while !STALLED_CHECK_STARTED.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let (wrote_tx, wrote_rx) = std::sync::mpsc::channel();
{
let state = state.clone();
std::thread::spawn(move || {
drop(state.store.write().unwrap());
let _ = wrote_tx.send(());
});
}
wrote_rx
.recv_timeout(Duration::from_secs(10))
.expect("the stalled disk check kept the store guard");
let (heartbeat, shards) = tokio::time::timeout(
Duration::from_secs(10),
ec_tick_pass(&test_config(), &state),
)
.await
.expect("the EC tick waited for the stalled disk check")
.unwrap();
let still_one_check = EC_SHARD_CHECK_RUNNING.load(Ordering::SeqCst);
STALLED_CHECK_RELEASED.store(true, Ordering::SeqCst);
assert_eq!(heartbeat.ec_shards.len(), 1);
assert_eq!(shards.len(), 1);
assert!(
still_one_check,
"a second disk check ran beside the stalled one"
);
tokio::time::timeout(Duration::from_secs(10), async {
while EC_SHARD_CHECK_RUNNING.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the released check did not finish");
}
#[tokio::test]
async fn test_volume_max_adjustment_waits_for_the_store_off_the_runtime() {
let temp_dir = tempfile::tempdir().unwrap();
+1
View File
@@ -174,6 +174,7 @@ mod tests {
grpc_ca_file: String::new(),
grpc_allowed_wildcard_domain: String::new(),
grpc_volume_allowed_common_names: vec![],
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
}
@@ -30,6 +30,53 @@ pub fn shard_id_try_from(v: u32) -> Result<ShardId, String> {
}
}
pub const EC_SHARD_GHOST: &str = "ghost";
pub const EC_SHARD_STALE_SIZE: &str = "stale_size";
/// What tells two files apart: (device, inode) on unix, (volume serial,
/// file index) on Windows.
#[cfg(unix)]
fn file_id(f: &File) -> io::Result<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
let m = f.metadata()?;
Ok((m.dev(), m.ino()))
}
#[cfg(windows)]
fn file_id(f: &File) -> io::Result<(u64, u64)> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
};
// SAFETY: the handle stays open for the call and `info` is a valid out-param.
unsafe {
let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed();
if GetFileInformationByHandle(f.as_raw_handle() as _, &mut info) == 0 {
return Err(io::Error::last_os_error());
}
Ok((
info.dwVolumeSerialNumber as u64,
(info.nFileIndexHigh as u64) << 32 | info.nFileIndexLow as u64,
))
}
}
/// The file id and length of `path`, read without read access to the file.
#[cfg(unix)]
fn path_file_id(path: &str) -> io::Result<((u64, u64), u64)> {
use std::os::unix::fs::MetadataExt;
let m = std::fs::metadata(path)?;
Ok(((m.dev(), m.ino()), m.len()))
}
#[cfg(windows)]
fn path_file_id(path: &str) -> io::Result<((u64, u64), u64)> {
use std::os::windows::fs::OpenOptionsExt;
// No access rights, as std::fs::metadata opens it.
let f = OpenOptions::new().access_mode(0).open(path)?;
Ok((file_id(&f)?, f.metadata()?.len()))
}
/// A single erasure-coded shard file.
pub struct EcVolumeShard {
pub volume_id: VolumeId,
@@ -39,6 +86,7 @@ pub struct EcVolumeShard {
pub disk_type: DiskType,
ecd_file: Option<File>,
ecd_file_size: i64,
ecd_file_id: Option<(u64, u64)>,
}
impl EcVolumeShard {
@@ -52,6 +100,7 @@ impl EcVolumeShard {
disk_type: DiskType::default(),
ecd_file: None,
ecd_file_size: 0,
ecd_file_id: None,
}
}
@@ -67,6 +116,7 @@ impl EcVolumeShard {
let path = self.file_name();
let file = open_volume_file(OpenOptions::new().read(true), &path)?;
self.ecd_file_size = file.metadata()?.len() as i64;
self.ecd_file_id = file_id(&file).ok();
self.ecd_file = Some(file);
Ok(())
}
@@ -84,6 +134,7 @@ impl EcVolumeShard {
)?;
self.ecd_file = Some(file);
self.ecd_file_size = 0;
self.ecd_file_id = None;
Ok(())
}
@@ -112,6 +163,17 @@ impl EcVolumeShard {
self.ecd_file_size
}
pub fn disk_check(&self) -> EcShardDiskCheck {
EcShardDiskCheck {
volume_id: self.volume_id,
shard_id: self.shard_id,
dir: self.dir.clone(),
path: self.file_name(),
mounted_size: self.ecd_file_size,
mounted_id: self.ecd_file_id,
}
}
/// A duplicate of the mounted shard handle, for a reader that has to
/// outlive the store guard.
///
@@ -144,6 +206,7 @@ impl EcVolumeShard {
let _ = file.sync_all();
}
self.ecd_file = None;
self.ecd_file_id = None;
}
/// Delete the shard file from disk.
@@ -153,6 +216,34 @@ impl EcVolumeShard {
}
}
/// What the disk check needs from a mounted shard, copied out under the
/// store guard so the file system calls run after it is released.
pub struct EcShardDiskCheck {
pub volume_id: VolumeId,
pub shard_id: ShardId,
pub dir: String,
pub mounted_size: i64,
path: String,
mounted_id: Option<(u64, u64)>,
}
impl EcShardDiskCheck {
/// How the shard file on disk disagrees with the mount: `EC_SHARD_GHOST`
/// when the path is gone or names another file than the open one,
/// `EC_SHARD_STALE_SIZE` when its size changed since the mount.
pub fn disk_mismatch(&self) -> Option<&'static str> {
let (id, len) = match path_file_id(&self.path) {
Ok(v) => v,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Some(EC_SHARD_GHOST),
Err(_) => return None,
};
if self.mounted_id.is_some_and(|mounted| mounted != id) {
return Some(EC_SHARD_GHOST);
}
(len as i64 != self.mounted_size).then_some(EC_SHARD_STALE_SIZE)
}
}
/// ShardBits: bitmap tracking which shards are present.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ShardBits(pub u32);
+121
View File
@@ -1113,6 +1113,47 @@ impl Store {
.sum()
}
/// Every mounted EC shard, for `check_mounted_ec_shards`.
pub fn ec_shard_disk_checks(
&self,
) -> Vec<crate::storage::erasure_coding::ec_shard::EcShardDiskCheck> {
self.locations
.iter()
.flat_map(|loc| loc.ec_volumes())
.flat_map(|(_, ecv)| ecv.shards.iter().flatten())
.map(|shard| shard.disk_check())
.collect()
}
/// Compares mounted EC shards with their files on disk, logs each
/// mismatch and returns the counts per reason.
pub fn check_mounted_ec_shards(
shards: &[crate::storage::erasure_coding::ec_shard::EcShardDiskCheck],
) -> std::collections::HashMap<&'static str, usize> {
use crate::storage::erasure_coding::ec_shard::{EC_SHARD_GHOST, EC_SHARD_STALE_SIZE};
let mut counts =
std::collections::HashMap::from([(EC_SHARD_GHOST, 0), (EC_SHARD_STALE_SIZE, 0)]);
for shard in shards {
if let Some(reason) = shard.disk_mismatch() {
*counts.entry(reason).or_default() += 1;
tracing::warn!(
volume_id = shard.volume_id.0,
shard_id = shard.shard_id,
dir = %shard.dir,
mounted_size = shard.mounted_size,
reason,
"mounted ec shard disagrees with its file on disk"
);
}
}
for (reason, n) in &counts {
crate::metrics::EC_SHARD_DISK_MISMATCH_GAUGE
.with_label_values(&[reason])
.set(*n as f64);
}
counts
}
/// Total EC shard count across all locations.
pub fn ec_shard_count(&self) -> usize {
self.locations.iter().map(|loc| loc.ec_shard_count()).sum()
@@ -3463,6 +3504,86 @@ mod tests {
assert!(!std::path::Path::new(&format!("{}/expired_ec_case_9.ec00", dir)).exists());
}
#[test]
fn test_check_mounted_ec_shards_finds_ghost_and_stale_size() {
use crate::storage::erasure_coding::ec_shard::{EC_SHARD_GHOST, EC_SHARD_STALE_SIZE};
use std::collections::HashMap;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut store = make_test_store(&[dir]);
std::fs::write(format!("{}/col_42.ecx", dir), [0u8; 16]).unwrap();
let shard_path = format!("{}/col_42.ec00", dir);
std::fs::write(&shard_path, b"shard bytes").unwrap();
store.mount_ec_shards(VolumeId(42), "col", &[0]).unwrap();
let counts = |ghost: usize, stale: usize| {
HashMap::from([(EC_SHARD_GHOST, ghost), (EC_SHARD_STALE_SIZE, stale)])
};
let check = |store: &Store| Store::check_mounted_ec_shards(&store.ec_shard_disk_checks());
assert_eq!(check(&store), counts(0, 0));
let mut f = std::fs::OpenOptions::new()
.append(true)
.open(&shard_path)
.unwrap();
std::io::Write::write_all(&mut f, b"grown").unwrap();
drop(f);
assert_eq!(check(&store), counts(0, 1));
let replacement = format!("{}.new", shard_path);
std::fs::write(&replacement, b"shard bytes").unwrap();
std::fs::rename(&replacement, &shard_path).unwrap();
assert_eq!(check(&store), counts(1, 0));
assert!(store.locations[0].reopen_ec_shard(VolumeId(42), 0).unwrap());
assert_eq!(check(&store), counts(0, 0));
std::fs::remove_file(&shard_path).unwrap();
assert_eq!(check(&store), counts(1, 0));
}
#[cfg(unix)]
#[test]
fn test_check_mounted_ec_shards_finds_an_unreadable_replacement() {
use crate::storage::erasure_coding::ec_shard::EC_SHARD_GHOST;
use std::os::unix::fs::PermissionsExt;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut store = make_test_store(&[dir]);
std::fs::write(format!("{}/col_42.ecx", dir), [0u8; 16]).unwrap();
let shard_path = format!("{}/col_42.ec00", dir);
std::fs::write(&shard_path, b"shard bytes").unwrap();
store.mount_ec_shards(VolumeId(42), "col", &[0]).unwrap();
let replacement = format!("{}.new", shard_path);
std::fs::write(&replacement, b"shard bytes").unwrap();
std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o000)).unwrap();
std::fs::rename(&replacement, &shard_path).unwrap();
let counts = Store::check_mounted_ec_shards(&store.ec_shard_disk_checks());
assert_eq!(counts[EC_SHARD_GHOST], 1);
}
#[test]
fn test_check_mounted_ec_shards_runs_while_a_writer_holds_the_store() {
use crate::storage::erasure_coding::ec_shard::EC_SHARD_GHOST;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut store = make_test_store(&[dir]);
std::fs::write(format!("{}/col_42.ecx", dir), [0u8; 16]).unwrap();
let shard_path = format!("{}/col_42.ec00", dir);
std::fs::write(&shard_path, b"shard bytes").unwrap();
store.mount_ec_shards(VolumeId(42), "col", &[0]).unwrap();
let store = std::sync::RwLock::new(store);
let shards = store.read().unwrap().ec_shard_disk_checks();
let writer = store.write().unwrap();
std::fs::remove_file(&shard_path).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(Store::check_mounted_ec_shards(&shards)).unwrap());
let counts = rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
assert_eq!(counts[EC_SHARD_GHOST], 1);
drop(writer);
}
#[test]
fn test_store_volume_not_found() {
let tmp = TempDir::new().unwrap();
+2
View File
@@ -6363,7 +6363,9 @@ dependencies = [
"protoc-bin-vendored",
"reqwest 0.12.28",
"rustls",
"rustls-native-certs",
"rustls-pemfile",
"seaweed-common",
"thiserror 2.0.20",
"tokio",
"tokio-rustls",
+17 -5
View File
@@ -21,7 +21,7 @@ use http::Uri;
use hyper_util::rt::TokioIo;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::verify_server_cert_signed_by_trust_anchor;
use rustls::crypto::{CryptoProvider, aws_lc_rs};
use rustls::crypto::CryptoProvider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
@@ -213,8 +213,14 @@ fn build_config(files: &GrpcServerTls) -> Result<ServerConfig> {
let mut config = ServerConfig::builder()
.with_client_cert_verifier(verifier)
.with_single_cert(cert_chain, key)
.context("server certificate")?;
.with_context(|| {
format!(
"server certificate {} and key {}",
files.cert_path, files.key_path
)
})?;
config.alpn_protocols = vec![b"h2".to_vec()];
config.require_ems = config.require_ems || crate::tls::require_ems();
Ok(config)
}
@@ -403,7 +409,7 @@ fn client_config(
crate::tls::install_default_crypto_provider();
let verifier = ServerIdentityVerifier {
roots: Arc::new(root_store(&files.ca_path, &ca)?),
provider: Arc::new(aws_lc_rs::default_provider()),
provider: Arc::new(crate::tls::crypto_provider()),
allowed_names: files.allowed_server_names.iter().cloned().collect(),
allowed_wildcard_domain: files.allowed_server_wildcard_domain.clone(),
};
@@ -414,8 +420,14 @@ fn client_config(
cert_chain("cert", &files.cert_path, &cert)?,
private_key("key", &files.key_path, &key)?,
)
.context("client certificate")?;
.with_context(|| {
format!(
"client certificate {} and key {}",
files.cert_path, files.key_path
)
})?;
config.alpn_protocols = vec![b"h2".to_vec()];
config.require_ems = config.require_ems || crate::tls::require_ems();
Ok(config)
}
@@ -762,7 +774,7 @@ mod tests {
roots: Arc::new(
root_store("ca.pem", &std::fs::read(fixture("ca.pem")).unwrap()).unwrap(),
),
provider: Arc::new(aws_lc_rs::default_provider()),
provider: Arc::new(crate::tls::crypto_provider()),
allowed_names: allowed.iter().map(|s| s.to_string()).collect(),
allowed_wildcard_domain: wildcard.into(),
};
+1 -2
View File
@@ -118,8 +118,6 @@ fn metrics_address(ip: &str, port: u16) -> Result<SocketAddr> {
#[tokio::main]
async fn main() -> Result<()> {
weed_lance_worker::tls::install_default_crypto_provider();
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
@@ -132,6 +130,7 @@ async fn main() -> Result<()> {
// 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())?;
weed_lance_worker::tls::install_for_fips_mode(&security)?;
let filer_signing = match args.filer_signing_key.filter(|key| !key.is_empty()) {
Some(key) => Some((key, 0)),
None => security
@@ -168,6 +168,21 @@ impl Security {
}
}
/// A dotted key such as `fips.mode` as the file alone sets it, without
/// the environment: a string as written, any other value as its TOML
/// text, so a caller can refuse it; empty counts as unset.
pub fn file_setting(&self, key: &str) -> Option<String> {
let mut parts = key.split('.');
let mut value = entry(&self.table, parts.next()?)?;
for part in parts {
value = entry(value.as_table()?, part)?;
}
match value {
toml::Value::String(s) => Some(s.clone()).filter(|s| !s.is_empty()),
other => Some(other.to_string()),
}
}
/// A dotted key such as `grpc.ca`, from `WEED_GRPC_CA` when set, else
/// the file; empty counts as unset.
pub fn get(&self, key: &str) -> Option<String> {
@@ -350,6 +365,18 @@ mod tests {
(dir, ca, cert, key, client)
}
#[test]
fn fips_mode_is_read_from_the_file_alone_and_kept_when_not_a_string() {
let env = [("WEED_FIPS_MODE", "on")];
let s = security("[FIPS]\nMode = \"strict\"\n", &env);
assert_eq!(s.file_setting("fips.mode").as_deref(), Some("strict"));
let s = security("[fips]\nmode = [\"strict\"]\n", &[]);
assert_eq!(s.file_setting("fips.mode").as_deref(), Some("[\"strict\"]"));
let s = security("[fips]\nmode = \"\"\n", &[]);
assert_eq!(s.file_setting("fips.mode"), None);
assert_eq!(security("", &[]).file_setting("fips.mode"), None);
}
#[test]
fn the_environment_wins_over_the_file() {
let s = security(
+31 -4
View File
@@ -1,10 +1,37 @@
// aws-lc-rs and ring both get linked transitively (lance's aws backend pulls
// aws-lc-rs, reqwest's rustls-tls pulls ring), so rustls can't auto-select a
// provider and tonic's client TLS panics on first use. Pin the default to
// aws-lc-rs. The body lives in seaweed-common so this binary and the Rust
// volume server cannot end up installing different providers; re-exported here
// so callers keep their import path.
pub use seaweed_common::tls::install_default_crypto_provider;
// aws-lc-rs (filtered to the FIPS lists in FIPS mode). The body lives in
// seaweed-common so this binary and the Rust volume server cannot end up
// installing different providers; re-exported here so callers keep their
// import path.
pub use seaweed_common::tls::{crypto_provider, install_default_crypto_provider, require_ems};
/// Resolves the FIPS mode of a process that reads `security`
/// (`WEED_FIPS_MODE`, else its `fips.mode`, read from the same parsed file
/// as the JWT keys), installs the matching rustls provider as the process
/// default and logs the mode. Call it once at startup, before anything
/// configures TLS.
pub fn install_for_fips_mode(
security: &crate::security::Security,
) -> anyhow::Result<seaweed_common::fips::FipsMode> {
let setting = seaweed_common::fips::resolve(
security.path(),
security
.file_setting(seaweed_common::fips::SETTING)
.as_deref(),
&|key| std::env::var_os(key),
)?;
seaweed_common::tls::install_process_provider(setting.mode)?;
if setting.mode.is_fips() {
tracing::info!(
"{setting}: TLS limited to the FIPS 140-3 versions, suites, groups and signature schemes Go allows; the cryptographic module is not validated"
);
} else {
tracing::info!("{setting}");
}
Ok(setting.mode)
}
#[cfg(test)]
mod tests {
@@ -17,6 +17,11 @@ prost.workspace = true
# System roots for volume servers behind public CAs, as Go's http client.
reqwest = { version = "0.12", default-features = false, features = ["multipart", "rustls-tls-native-roots"] }
rustls = { version = "0.23", default-features = false, features = ["ring"] }
# The system roots for the FIPS-mode client configuration sw-client builds
# itself; the version reqwest's rustls-tls-native-roots uses.
rustls-native-certs = "0.8"
# The process-wide rustls provider every SeaweedFS Rust binary installs.
seaweed-common = { path = "../../../seaweed-common" }
thiserror = "2"
tokio.workspace = true
tonic.workspace = true
+56 -1
View File
@@ -486,12 +486,31 @@ async fn expand_chunks(
};
let manifest = FileChunkManifest::decode(raw.as_slice())
.with_context(|| format!("decode manifest {fid}"))?;
let sub = Box::pin(expand_chunks(client, volumes, &manifest.chunks, decoder)).await?;
let held = cut_to_manifest_span(chunk, manifest.chunks);
let sub = Box::pin(expand_chunks(client, volumes, &held, decoder)).await?;
data.extend(sub);
}
Ok(data)
}
/// The chunks a manifest holds, cut to the manifest's span: a truncate may
/// have shortened the manifest and left its chunks whole.
fn cut_to_manifest_span(manifest: &FileChunk, held: Vec<FileChunk>) -> Vec<FileChunk> {
let end = manifest.offset + manifest.size as i64;
held.into_iter()
.filter_map(|mut c| {
if c.offset + c.size as i64 <= end {
return Some(c);
}
if c.offset >= end {
return None;
}
c.size = (end - c.offset) as u64;
Some(c)
})
.collect()
}
/// Resolve data chunks into non-overlapping visible intervals (latest write wins).
fn resolve_visibles(chunks: &[FileChunk]) -> Vec<Visible> {
if let Some(visibles) = resolve_visibles_ordered_non_overlapping(chunks) {
@@ -1454,6 +1473,42 @@ mod tests {
assert_eq!(tail, &plain[19..], "a size past u64::MAX reads to EOF");
}
#[tokio::test]
async fn a_shortened_manifest_reads_only_its_span() {
let plain: Vec<u8> = (0..16u8).map(|i| i + 1).collect();
let inner = FileChunkManifest {
chunks: vec![chunk("1,aa", 0, 8, 1), chunk("1,bb", 8, 8, 1)],
};
let needles = HashMap::from([
("1,mm".to_string(), inner.encode_to_vec()),
("1,aa".to_string(), plain[..8].to_vec()),
("1,bb".to_string(), plain[8..].to_vec()),
]);
let volumes = VolumeReader::with_transport(Arc::new(BytesTransport {
needles,
reads: AtomicUsize::new(0),
whole_reads: AtomicUsize::new(0),
}));
volumes.location_cache.learn(1, vec!["h:1".into()]);
let mut manifest = chunk("1,mm", 0, 12, 1);
manifest.is_chunk_manifest = true;
let entry = Entry {
attributes: Some(crate::filer_pb::FuseAttributes {
file_size: 20,
..Default::default()
}),
chunks: vec![manifest],
..Default::default()
};
let mut client = FilerClient::connect_lazy("127.0.0.1:1").unwrap();
let got = read_file(&mut client, &volumes, &entry, 0, 20)
.await
.unwrap();
let mut want = plain[..12].to_vec();
want.resize(20, 0);
assert_eq!(got, want);
}
#[tokio::test]
async fn encrypted_chunks_need_a_decoder() {
let (entry, plain, _, volumes) = encrypted_file();
+358 -25
View File
@@ -14,6 +14,12 @@ use anyhow::{Context, Result, anyhow, bail};
use async_trait::async_trait;
use bytes::Bytes;
use reqwest::header::{AUTHORIZATION, RANGE};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::CryptoProvider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -188,9 +194,12 @@ impl std::fmt::Debug for HttpsTls {
}
/// Both tonic and reqwest link rustls; with more than one crypto provider
/// compiled in, rustls needs one picked before TLS is configured.
/// compiled in, rustls needs one picked before TLS is configured. It is the
/// one every SeaweedFS Rust binary installs (`seaweed_common::tls`): aws-lc-rs,
/// filtered to the FIPS lists in FIPS mode. A binary's own earlier install
/// wins, so a library caller cannot replace it.
pub fn install_crypto_provider() {
let _ = rustls::crypto::ring::default_provider().install_default();
seaweed_common::tls::install_default_crypto_provider();
}
/// Default transport: the SeaweedFS volume HTTP API — `GET /<fileId>` with an
@@ -228,29 +237,15 @@ impl HttpTransport {
/// A transport dialing volume servers over HTTPS.
pub fn with_tls(tls: &HttpsTls) -> Result<Self> {
install_crypto_provider();
let mut builder = reqwest::Client::builder()
.connect_timeout(VOLUME_CONNECT_TIMEOUT)
.use_rustls_tls()
.danger_accept_invalid_certs(tls.insecure_skip_verify);
if let Some(ca) = &tls.ca_pem {
builder = builder.tls_built_in_root_certs(false).add_root_certificate(
reqwest::Certificate::from_pem(ca).context("https.client.ca")?,
);
}
match (&tls.cert_pem, &tls.key_pem) {
(Some(cert), Some(key)) => {
let mut pem = cert.clone();
if !pem.ends_with(b"\n") {
pem.push(b'\n');
}
pem.extend_from_slice(key);
builder = builder.identity(
reqwest::Identity::from_pem(&pem).context("https.client cert and key")?,
);
}
(None, None) => {}
_ => bail!("https.client needs both cert and key, or neither"),
}
let builder = reqwest::Client::builder().connect_timeout(VOLUME_CONNECT_TIMEOUT);
let builder = if seaweed_common::fips::process_mode().is_fips() {
builder.use_preconfigured_tls(fips_tls_config(
tls,
Arc::new(seaweed_common::tls::crypto_provider()),
)?)
} else {
reqwest_tls(builder, tls)?
};
Ok(Self {
http: builder.build().context("volume HTTPS client")?,
scheme: "https",
@@ -260,6 +255,168 @@ impl HttpTransport {
}
}
/// reqwest's own rustls configuration for `tls`: the CA, the client identity,
/// and with `insecure_skip_verify` reqwest's verifier that accepts any server.
fn reqwest_tls(builder: reqwest::ClientBuilder, tls: &HttpsTls) -> Result<reqwest::ClientBuilder> {
let mut builder = builder
.use_rustls_tls()
.danger_accept_invalid_certs(tls.insecure_skip_verify);
if let Some(ca) = &tls.ca_pem {
builder = builder
.tls_built_in_root_certs(false)
.add_root_certificate(reqwest::Certificate::from_pem(ca).context("https.client.ca")?);
}
match (&tls.cert_pem, &tls.key_pem) {
(Some(cert), Some(key)) => {
let mut pem = cert.clone();
if !pem.ends_with(b"\n") {
pem.push(b'\n');
}
pem.extend_from_slice(key);
builder = builder
.identity(reqwest::Identity::from_pem(&pem).context("https.client cert and key")?);
}
(None, None) => {}
_ => bail!("https.client needs both cert and key, or neither"),
}
Ok(builder)
}
/// The client configuration for `tls` in FIPS mode, on `provider`. It is
/// built here rather than by reqwest for two reasons: reqwest leaves
/// `require_ems` at rustls's default, which is off for a provider that is not
/// FIPS-validated, while Go requires the Extended Master Secret for TLS 1.2
/// in FIPS mode; and reqwest's verifier for `insecure_skip_verify` advertises
/// its own signature schemes (SHA-1, Ed448) whatever the provider allows.
/// Server certificates are checked against `ca` (the system roots without
/// one); with `insecure_skip_verify` they are not, but handshake signatures
/// still are, with the provider's algorithms, and only its schemes are
/// offered, and a malformed `ca` is still refused, as reqwest refuses it on
/// every path. HTTP/1.1 only, as the volume servers speak it.
fn fips_tls_config(tls: &HttpsTls, provider: Arc<CryptoProvider>) -> Result<rustls::ClientConfig> {
let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.context("TLS versions")?;
let builder = if tls.insecure_skip_verify {
if let Some(ca) = &tls.ca_pem {
ca_roots(ca)?;
}
builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(UnverifiedServer { provider }))
} else {
builder.with_root_certificates(root_certificates(tls)?)
};
let mut config = match (&tls.cert_pem, &tls.key_pem) {
(Some(cert), Some(key)) => {
let chain = CertificateDer::pem_slice_iter(cert)
.collect::<std::result::Result<Vec<_>, _>>()
.context("https.client cert")?;
let key = PrivateKeyDer::from_pem_slice(key).context("https.client key")?;
builder
.with_client_auth_cert(chain, key)
.context("https.client cert and key")?
}
(None, None) => builder.with_no_client_auth(),
_ => bail!("https.client needs both cert and key, or neither"),
};
config.alpn_protocols = vec![b"http/1.1".to_vec()];
config.require_ems = true;
Ok(config)
}
/// The roots server certificates are checked against: the certificates in
/// `https.client.ca`, else the system's.
fn root_certificates(tls: &HttpsTls) -> Result<rustls::RootCertStore> {
match &tls.ca_pem {
Some(ca) => ca_roots(ca),
None => native_roots(),
}
}
/// The certificates in an `https.client.ca` PEM, refused when one does not
/// parse, as reqwest refuses them.
fn ca_roots(ca: &[u8]) -> Result<rustls::RootCertStore> {
let mut roots = rustls::RootCertStore::empty();
for cert in CertificateDer::pem_slice_iter(ca) {
roots
.add(cert.context("https.client.ca")?)
.context("https.client.ca")?;
}
Ok(roots)
}
/// The system's root certificates as reqwest loads them: ones rustls cannot
/// parse are skipped, and it is an error only when none parses and some did
/// not.
fn native_roots() -> Result<rustls::RootCertStore> {
let loaded = rustls_native_certs::load_native_certs();
let mut roots = rustls::RootCertStore::empty();
let (added, ignored) = roots.add_parsable_certificates(loaded.certs);
if added == 0 && ignored > 0 {
bail!(
"no valid certificate in the system root store: {:?}",
loaded.errors
);
}
Ok(roots)
}
/// Accepts any server certificate and host name, as `insecure_skip_verify`
/// asks, while verifying the handshake signatures with the provider's
/// algorithms and offering only their schemes.
#[derive(Debug)]
struct UnverifiedServer {
provider: Arc<CryptoProvider>,
}
impl ServerCertVerifier for UnverifiedServer {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> std::result::Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.provider
.signature_verification_algorithms
.supported_schemes()
}
}
#[async_trait]
impl VolumeTransport for HttpTransport {
async fn read(
@@ -427,6 +584,182 @@ mod tests {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// The signature schemes a client with `config` offers in its ClientHello,
/// as a server sees them: one flight through in-memory connections.
fn offered_schemes(config: rustls::ClientConfig) -> Vec<SignatureScheme> {
#[derive(Debug, Default)]
struct Recorder(std::sync::Mutex<Vec<SignatureScheme>>);
impl rustls::server::ResolvesServerCert for Recorder {
fn resolve(
&self,
hello: rustls::server::ClientHello<'_>,
) -> Option<Arc<rustls::sign::CertifiedKey>> {
*self.0.lock().unwrap() = hello.signature_schemes().to_vec();
None
}
}
let recorder = Arc::new(Recorder::default());
let server_config = rustls::ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_cert_resolver(recorder.clone());
let name = ServerName::try_from("volume.example").unwrap();
let mut client = rustls::ClientConnection::new(Arc::new(config), name).unwrap();
let mut server = rustls::ServerConnection::new(Arc::new(server_config)).unwrap();
let mut flight = Vec::new();
client.write_tls(&mut flight).unwrap();
server.read_tls(&mut flight.as_slice()).unwrap();
let _ = server.process_new_packets();
recorder.0.lock().unwrap().clone()
}
/// The provider FIPS mode installs.
fn fips_provider() -> Arc<CryptoProvider> {
Arc::new(seaweed_common::tls::provider_for(
seaweed_common::fips::FipsMode::On,
))
}
/// `https.client` with certificate checks off, as FIPS mode builds it.
fn unverified() -> HttpsTls {
HttpsTls {
insecure_skip_verify: true,
..HttpsTls::default()
}
}
/// `https.client` with `ca` set to the lance test CA.
fn with_test_ca() -> HttpsTls {
HttpsTls {
ca_pem: Some(TEST_CA.to_vec()),
..HttpsTls::default()
}
}
const TEST_CA: &[u8] = include_bytes!("../../lance/tests/tls/ca.pem");
const TEST_LEAF: &[u8] = include_bytes!("../../lance/tests/tls/a.pem");
const TEST_LEAF_KEY: &[u8] = include_bytes!("../../lance/tests/tls/a.key");
/// Runs a full handshake between `config` and a server presenting the
/// lance test leaf for `localhost`, in memory.
fn handshake(config: rustls::ClientConfig) -> std::result::Result<(), rustls::Error> {
let chain = CertificateDer::pem_slice_iter(TEST_LEAF)
.collect::<std::result::Result<Vec<_>, _>>()
.unwrap();
let key = PrivateKeyDer::from_pem_slice(TEST_LEAF_KEY).unwrap();
let server_config = rustls::ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_single_cert(chain, key)
.unwrap();
let name = ServerName::try_from("localhost").unwrap();
let mut client = rustls::ClientConnection::new(Arc::new(config), name).unwrap();
let mut server = rustls::ServerConnection::new(Arc::new(server_config)).unwrap();
while client.is_handshaking() || server.is_handshaking() {
let mut flight = Vec::new();
client.write_tls(&mut flight).unwrap();
if !flight.is_empty() {
server.read_tls(&mut flight.as_slice()).unwrap();
server.process_new_packets()?;
}
let mut flight = Vec::new();
server.write_tls(&mut flight).unwrap();
if !flight.is_empty() {
client.read_tls(&mut flight.as_slice()).unwrap();
client.process_new_packets()?;
}
}
Ok(())
}
/// `offered` and the FIPS signature schemes, each sorted.
fn sorted_against_fips(
mut offered: Vec<SignatureScheme>,
) -> (Vec<SignatureScheme>, Vec<SignatureScheme>) {
let mut want = seaweed_common::tls::FIPS_SIGNATURE_SCHEMES.to_vec();
offered.sort_by_key(|s| u16::from(*s));
want.sort_by_key(|s| u16::from(*s));
(offered, want)
}
#[test]
fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() {
let config = fips_tls_config(&unverified(), fips_provider()).unwrap();
assert!(config.require_ems);
let (offered, want) = sorted_against_fips(offered_schemes(config));
assert_eq!(offered, want);
assert!(!offered.contains(&SignatureScheme::ED448));
assert!(!offered.contains(&SignatureScheme::RSA_PKCS1_SHA1));
}
#[test]
fn verified_tls_in_fips_mode_requires_ems_and_checks_the_server() {
let config = fips_tls_config(&with_test_ca(), fips_provider()).unwrap();
assert!(config.require_ems);
let (offered, want) = sorted_against_fips(offered_schemes(config.clone()));
assert_eq!(offered, want);
handshake(config).unwrap();
let wrong_ca = HttpsTls {
ca_pem: Some(TEST_LEAF.to_vec()),
..HttpsTls::default()
};
let config = fips_tls_config(&wrong_ca, fips_provider()).unwrap();
let err = handshake(config).unwrap_err();
assert!(
matches!(err, rustls::Error::InvalidCertificate(_)),
"{err:?}"
);
}
/// A PEM certificate block whose DER is not a certificate.
const MALFORMED_CA: &[u8] = b"-----BEGIN CERTIFICATE-----
AAAA
-----END CERTIFICATE-----
";
#[test]
fn a_malformed_ca_is_refused_with_and_without_certificate_checks() {
for insecure_skip_verify in [false, true] {
let tls = HttpsTls {
ca_pem: Some(MALFORMED_CA.to_vec()),
insecure_skip_verify,
..HttpsTls::default()
};
let err = fips_tls_config(&tls, fips_provider()).unwrap_err();
assert!(format!("{err:#}").contains("https.client.ca"), "{err:#}");
assert!(
HttpTransport::with_tls(&tls).is_err(),
"off mode, insecure_skip_verify = {insecure_skip_verify}"
);
}
let tls = HttpsTls {
ca_pem: Some(TEST_CA.to_vec()),
..unverified()
};
assert!(fips_tls_config(&tls, fips_provider()).is_ok());
}
#[test]
fn fips_tls_needs_both_halves_of_the_identity() {
let half = HttpsTls {
cert_pem: Some(b"x".to_vec()),
..unverified()
};
assert!(fips_tls_config(&half, fips_provider()).is_err());
let half = HttpsTls {
cert_pem: Some(b"x".to_vec()),
..with_test_ca()
};
assert!(fips_tls_config(&half, fips_provider()).is_err());
}
#[test]
fn not_written_is_found_under_later_contexts_and_only_there() {
use anyhow::Context;
@@ -187,6 +187,10 @@ func (store *MockFoundationDBStore) KvGet(ctx context.Context, key []byte) ([]by
return value, nil
}
func (store *MockFoundationDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *MockFoundationDBStore) KvDelete(ctx context.Context, key []byte) error {
delete(store.kvStore, string(key))
return nil
+1 -1
View File
@@ -186,7 +186,7 @@ func forceDeleteCollection(t *testing.T, bucketName string) {
return
}
endpoint := strings.TrimRight(defaultConfig.MasterEndpoint, "/") + "/col/delete?collection=" + url.QueryEscape(bucketName)
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
t.Logf("Note: building collection delete request for %s failed: %v", bucketName, err)
return
+1 -1
View File
@@ -166,7 +166,7 @@ func forceDeleteCollection(t *testing.T, bucketName string) {
return
}
endpoint := strings.TrimRight(masterEndpoint, "/") + "/col/delete?collection=" + url.QueryEscape(bucketName)
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
t.Logf("Note: building collection delete request for %s failed: %v", bucketName, err)
return
+1 -1
View File
@@ -156,7 +156,7 @@ func forceDeleteCollection(t *testing.T, bucketName string) {
return
}
endpoint := strings.TrimRight(defaultConfig.MasterEndpoint, "/") + "/col/delete?collection=" + url.QueryEscape(bucketName)
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
t.Logf("Note: building collection delete request for %s failed: %v", bucketName, err)
return
+1
View File
@@ -254,6 +254,7 @@ spark = (SparkSession.builder
.config("spark.hadoop.hive.metastore.schema.verification.record.version", "false")
.config("spark.jars.ivy", ivy_dir)
.config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:3.3.2,com.amazonaws:aws-java-sdk-bundle:1.12.262")
.config("spark.jars.repositories", "https://maven-central.storage-download.googleapis.com/maven2/")
.config("spark.hadoop.fs.s3a.access.key", "test")
.config("spark.hadoop.fs.s3a.secret.key", "test")
.config("spark.hadoop.fs.s3a.endpoint", "host.docker.internal:%d")
+1 -1
View File
@@ -193,7 +193,7 @@ func forceDeleteCollection(t *testing.T, bucketName string) {
return
}
endpoint := strings.TrimRight(masterEndpoint, "/") + "/col/delete?collection=" + url.QueryEscape(bucketName)
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
t.Logf("Note: building collection delete request for %s failed: %v", bucketName, err)
return
+1 -1
View File
@@ -180,7 +180,7 @@ func forceDeleteCollection(t *testing.T, bucketName string) {
return
}
endpoint := strings.TrimRight(defaultConfig.MasterEndpoint, "/") + "/col/delete?collection=" + url.QueryEscape(bucketName)
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
t.Logf("Note: building collection delete request for %s failed: %v", bucketName, err)
return
@@ -145,6 +145,104 @@ func TestMasterHTTPSCertRotation(t *testing.T) {
waitForCert(t, addr, caPool, leafSerial2, 15*time.Second, "rotated cert")
}
// TestMasterHTTPSCertRotationOnSIGHUP is the same rotation flow as
// TestMasterHTTPSCertRotation, but with a one-hour refresh window and a
// SIGHUP instead of waiting for the periodic tick. It verifies the
// grace.OnReload hook forces certreload providers to re-read cert/key
// immediately.
func TestMasterHTTPSCertRotationOnSIGHUP(t *testing.T) {
if testing.Short() {
t.Skip("skipping HTTPS rotation integration test in -short mode")
}
weedBin := findWeedBinary(t)
dir := t.TempDir()
tlsDir := filepath.Join(dir, "tls")
if err := os.MkdirAll(tlsDir, 0o755); err != nil {
t.Fatalf("mkdir tls: %v", err)
}
certPath := filepath.Join(tlsDir, "server.crt")
keyPath := filepath.Join(tlsDir, "server.key")
ca, caKey := generateCA(t)
leafSerial1 := big.NewInt(20001)
leafSerial2 := big.NewInt(20002)
writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial1)
masterDir := filepath.Join(dir, "master")
if err := os.MkdirAll(masterDir, 0o755); err != nil {
t.Fatalf("mkdir master: %v", err)
}
if err := os.WriteFile(filepath.Join(masterDir, "security.toml"), []byte("# test\n"), 0o644); err != nil {
t.Fatalf("write security.toml: %v", err)
}
port, grpcPort := getFreeTCPPort(t), getFreeTCPPort(t)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, weedBin, "master",
"-ip", "127.0.0.1",
"-port", strconv.Itoa(port),
"-port.grpc", strconv.Itoa(grpcPort),
"-mdir", masterDir,
)
cmd.Dir = masterDir
cmd.Env = append(os.Environ(),
"HOME="+dir,
"WEED_HTTPS_MASTER_CERT="+certPath,
"WEED_HTTPS_MASTER_KEY="+keyPath,
// Keep the periodic refresh out of the way: the new cert must
// appear because of SIGHUP, not because of a tick.
"WEED_TLS_CERT_REFRESH_INTERVAL=1h",
)
logPath := filepath.Join(masterDir, "master.log")
logOut, err := os.Create(logPath)
if err != nil {
t.Fatalf("create master log: %v", err)
}
cmd.Stdout = logOut
cmd.Stderr = logOut
if err := cmd.Start(); err != nil {
t.Fatalf("start master: %v", err)
}
t.Cleanup(func() {
if cmd.Process != nil {
_ = cmd.Process.Signal(syscall.SIGTERM)
done := make(chan struct{})
go func() { _ = cmd.Wait(); close(done) }()
select {
case <-done:
case <-time.After(10 * time.Second):
_ = cmd.Process.Kill()
<-done
}
}
_ = logOut.Close()
if t.Failed() {
if b, readErr := os.ReadFile(logPath); readErr == nil {
t.Logf("master.log:\n%s", string(b))
}
}
})
caPool := x509.NewCertPool()
caPool.AddCert(ca)
addr := fmt.Sprintf("127.0.0.1:%d", port)
waitForCert(t, addr, caPool, leafSerial1, 30*time.Second, "initial cert")
writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial2)
if err := cmd.Process.Signal(syscall.SIGHUP); err != nil {
t.Fatalf("send SIGHUP: %v", err)
}
waitForCert(t, addr, caPool, leafSerial2, 10*time.Second, "rotated cert after SIGHUP")
}
// waitForCert polls until a TLS handshake against addr yields a peer
// cert with the expected serial, or fails the test at the deadline.
// The last handshake error is surfaced in the fatal message so that a
+72 -10
View File
@@ -326,9 +326,17 @@ func (c *Cluster) waitForTCP(addr string) error {
return fmt.Errorf("timed out waiting for tcp %s", addr)
}
// stopProcess interrupts cmd and waits for it to exit, killing it after 10s.
// A server that does not exit cleanly on SIGINT fails the test: a panic or a
// hang on shutdown is a bug the tests would otherwise never see.
// stopTimeout bounds a server's exit after SIGINT; stopDiskTimeout replaces it
// once a thread of the server has been seen in an uninterruptible wait, such
// as the close fsync on a slow CI disk.
var (
stopTimeout = 10 * time.Second
stopDiskTimeout = time.Minute
)
// stopProcess interrupts cmd and waits for it to exit, killing it after
// stopTimeout. A server that does not exit cleanly on SIGINT fails the test: a
// panic or a hang on shutdown is a bug the tests would otherwise never see.
func stopProcess(tb testing.TB, name string, cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
@@ -340,18 +348,72 @@ func stopProcess(tb testing.TB, name string, cmd *exec.Cmd) {
done <- cmd.Wait()
}()
select {
case <-time.After(10 * time.Second):
start := time.Now()
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
diskWait := false
for {
select {
case err := <-done:
if err != nil {
tb.Errorf("%s did not exit cleanly on SIGINT: %v", name, err)
}
return
case <-tick.C:
}
threads, inDiskWait := processThreads(cmd.Process.Pid)
diskWait = diskWait || inDiskWait
limit := stopTimeout
if diskWait {
limit = stopDiskTimeout
}
if time.Since(start) < limit {
continue
}
_ = cmd.Process.Kill()
<-done
tb.Errorf("%s did not exit within 10s of SIGINT", name)
case err := <-done:
if err != nil {
tb.Errorf("%s did not exit cleanly on SIGINT: %v", name, err)
}
tb.Errorf("%s did not exit within %v of SIGINT, threads: %s", name, limit, threads)
return
}
}
// processThreads summarizes pid's threads from /proc as "name state wchan"
// with counts, and reports whether any is in uninterruptible sleep (D).
func processThreads(pid int) (string, bool) {
dir := fmt.Sprintf("/proc/%d/task", pid)
tasks, err := os.ReadDir(dir)
if err != nil {
return "unavailable", false
}
counts := map[string]int{}
var order []string
inDiskWait := false
for _, task := range tasks {
stat, err := os.ReadFile(filepath.Join(dir, task.Name(), "stat"))
if err != nil {
continue
}
s := string(stat)
open, end := strings.IndexByte(s, '('), strings.LastIndexByte(s, ')')
if open < 0 || end < open || end+2 >= len(s) {
continue
}
state := s[end+2]
inDiskWait = inDiskWait || state == 'D'
wchan, _ := os.ReadFile(filepath.Join(dir, task.Name(), "wchan"))
key := fmt.Sprintf("%s %c %s", s[open+1:end], state, wchan)
if counts[key] == 0 {
order = append(order, key)
}
counts[key]++
}
parts := make([]string, 0, len(order))
for _, key := range order {
parts = append(parts, fmt.Sprintf("%dx[%s]", counts[key], key))
}
return strings.Join(parts, " "), inDiskWait
}
func newWorkDir() (dir string, keepLogs bool, err error) {
keepLogs = os.Getenv("VOLUME_SERVER_IT_KEEP_LOGS") == "1"
dir, err = os.MkdirTemp("", "seaweedfs_volume_server_it_")
@@ -0,0 +1,80 @@
package framework
import (
"fmt"
"os/exec"
"runtime"
"strings"
"testing"
"time"
)
type errorRecorder struct {
testing.TB
errs []string
}
func (r *errorRecorder) Errorf(format string, args ...any) {
r.errs = append(r.errs, fmt.Sprintf(format, args...))
}
func TestStopProcessReportsTheThreadsOfAServerIgnoringSIGINT(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("thread states come from /proc")
}
defer func(d time.Duration) { stopTimeout = d }(stopTimeout)
stopTimeout = 200 * time.Millisecond
cmd := exec.Command("sh", "-c", `trap "" INT; exec sleep 30`)
if err := cmd.Start(); err != nil {
t.Fatalf("start: %v", err)
}
defer func() {
_ = cmd.Process.Kill()
_ = cmd.Wait()
}()
waitForSleepThread(t, cmd.Process.Pid)
rec := &errorRecorder{TB: t}
stopProcess(rec, "server", cmd)
if len(rec.errs) != 1 || !strings.Contains(rec.errs[0], "server did not exit within") || !strings.Contains(rec.errs[0], "1x[sleep S ") {
t.Fatalf("errors = %q", rec.errs)
}
}
func TestProcessThreadsFindsNoDiskWaitInAnIdleProcess(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("thread states come from /proc")
}
cmd := exec.Command("sleep", "30")
if err := cmd.Start(); err != nil {
t.Fatalf("start: %v", err)
}
defer func() {
_ = cmd.Process.Kill()
_ = cmd.Wait()
}()
waitForSleepThread(t, cmd.Process.Pid)
threads, inDiskWait := processThreads(cmd.Process.Pid)
if inDiskWait || !strings.HasPrefix(threads, "1x[sleep S ") {
t.Fatalf("threads = %q, inDiskWait = %v", threads, inDiskWait)
}
}
// waitForSleepThread waits until pid has exec'd sleep and is sleeping, so
// a SIGINT trap set before the exec is in place.
func waitForSleepThread(t *testing.T, pid int) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for {
threads, _ := processThreads(pid)
if strings.HasPrefix(threads, "1x[sleep S ") {
return
}
if time.Now().After(deadline) {
t.Fatalf("pid %d never reached sleep: %q", pid, threads)
}
time.Sleep(10 * time.Millisecond)
}
}
+12 -8
View File
@@ -113,14 +113,15 @@ func getCollectionName(filerGroup, bucketName string) string {
}
type AdminServer struct {
masterClient *wdclient.MasterClient
templateFS http.FileSystem
dataDir string
filerGroup string
grpcDialOption grpc.DialOption
cacheExpiration time.Duration
lastCacheUpdate time.Time
cachedTopology *ClusterTopology
masterClient *wdclient.MasterClient
templateFS http.FileSystem
dataDir string
filerGroup string
grpcDialOption grpc.DialOption
filerTokenSource security.FilerTokenSource
cacheExpiration time.Duration
lastCacheUpdate time.Time
cachedTopology *ClusterTopology
// dashSamples is a bounded in-memory ring of recent cluster snapshots that
// powers the dashboard's at-a-glance sparklines (see dashboard_metrics.go),
@@ -215,6 +216,7 @@ func NewAdminServer(masters string, filerGroup string, templateFS http.FileSyste
dataDir: dataDir,
filerGroup: filerGroup,
grpcDialOption: grpcDialOption,
filerTokenSource: security.FilerAdminToken,
cacheExpiration: defaultCacheTimeout,
filerCacheExpiration: defaultFilerCacheTimeout,
configPersistence: NewConfigPersistence(dataDir),
@@ -443,6 +445,7 @@ func (s *AdminServer) publishMaintenanceMetrics(ctx context.Context) {
// Seed one sample so the dashboard has something to draw before the first tick.
s.recordDashboardSample()
var maintenanceOverlap string
for {
select {
case <-ctx.Done():
@@ -450,6 +453,7 @@ func (s *AdminServer) publishMaintenanceMetrics(ctx context.Context) {
case <-ticker.C:
s.collectMaintenanceMetrics()
s.recordDashboardSample()
maintenanceOverlap = s.warnOnMaintenanceOverlap(maintenanceOverlap)
}
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ func (s *AdminServer) WithFilerClient(f func(client filer_pb.SeaweedFilerClient)
return fmt.Errorf("no filer available")
}
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, s.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
return f(client)
})
}
+8 -1
View File
@@ -225,7 +225,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
MaxVolumes: int(totalMaxVolumes),
DiskUsage: diskUsage,
DiskCapacity: diskCapacity,
LastHeartbeat: time.Now(),
LastHeartbeat: dataNodeLastHeartbeat(node),
RemoteSize: remoteSize,
}
@@ -268,3 +268,10 @@ func (s *AdminServer) InvalidateCache() {
s.lastCollectionStatsUpdate = time.Now().Add(-s.collectionStatsCacheThreshold)
s.collectionStatsCache = nil
}
func dataNodeLastHeartbeat(node *master_pb.DataNodeInfo) time.Time {
if node.LastHeartbeatNs <= 0 {
return time.Time{}
}
return time.Unix(0, node.LastHeartbeatNs)
}
+31
View File
@@ -0,0 +1,31 @@
package dash
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
func TestDefaultPlacementServers(t *testing.T) {
servers := []VolumeServer{
{Address: "a:8080", DataCenter: "dc1", Rack: "r1", Volumes: 3},
{Address: "b:8080", DataCenter: "dc1", Rack: "r2"},
{Address: "c:8080", DataCenter: topology.DefaultDataCenter, Rack: topology.DefaultRack, EcShards: 2030},
{Address: "d:8080", DataCenter: "dc1", Rack: topology.DefaultRack},
}
got := defaultPlacementServers(servers)
if len(got) != 2 || got[0].Address != "c:8080" || got[1].Address != "d:8080" {
t.Fatalf("defaultPlacementServers = %+v, want c:8080 and d:8080", got)
}
if got[0].EcShards != 2030 {
t.Fatalf("EC shard count not carried: %d", got[0].EcShards)
}
allDefault := []VolumeServer{
{Address: "a:8080", DataCenter: topology.DefaultDataCenter, Rack: topology.DefaultRack},
{Address: "b:8080", DataCenter: topology.DefaultDataCenter, Rack: topology.DefaultRack},
}
if got := defaultPlacementServers(allDefault); len(got) != 0 {
t.Fatalf("all-default cluster flagged: %+v", got)
}
}
@@ -0,0 +1,58 @@
package dash
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
// Volume servers are identified by host:port, and the detected task must
// still be saved under its ID.
func TestECBalanceTaskStateIsSaved(t *testing.T) {
disk := func(shards ...*master_pb.VolumeEcShardInformationMessage) map[string]*master_pb.DiskInfo {
return map[string]*master_pb.DiskInfo{"": {MaxVolumeCount: 100, EcShardInfos: shards}}
}
topoInfo := &master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: []*master_pb.DataNodeInfo{
{Id: "10.0.0.1:8080", DiskInfos: disk(&master_pb.VolumeEcShardInformationMessage{Id: 100, FileCount: 1, Collection: "col1", EcIndexBits: 0x3FFF})},
{Id: "10.0.0.2:8080", DiskInfos: disk()},
{Id: "10.0.0.3:8080", DiskInfos: disk()},
}}},
}},
}
at := topology.NewActiveTopology(0)
if err := at.UpdateTopology(topoInfo); err != nil {
t.Fatalf("UpdateTopology: %v", err)
}
results, _, err := ec_balance.Detection(context.Background(), nil, &types.ClusterInfo{ActiveTopology: at}, ec_balance.NewDefaultConfig(), 0)
if err != nil {
t.Fatalf("Detection: %v", err)
}
if len(results) == 0 {
t.Fatal("fixture planned no moves")
}
cp := NewConfigPersistence(t.TempDir())
for _, r := range results {
task := &maintenance.MaintenanceTask{
ID: r.TaskID,
Type: maintenance.MaintenanceTaskType(r.TaskType),
VolumeID: r.VolumeID,
Server: r.Server,
Status: maintenance.TaskStatusPending,
}
if err := cp.SaveTaskState(task); err != nil {
t.Fatalf("SaveTaskState(%q): %v", r.TaskID, err)
}
if _, err := cp.LoadTaskState(r.TaskID); err != nil {
t.Fatalf("LoadTaskState(%q): %v", r.TaskID, err)
}
}
}
+170
View File
@@ -0,0 +1,170 @@
package dash
import (
"context"
"crypto/rand"
"encoding/hex"
"net"
"strconv"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"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/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type dashAuthFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
}
func (dashAuthFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets", FilerGroup: "test"}, nil
}
func (dashAuthFiler) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{}}, nil
}
func dashAuthCheck(ctx context.Context, key security.SigningKey, require bool) error {
md, _ := metadata.FromIncomingContext(ctx)
values := md.Get("authorization")
if len(key) == 0 {
if require && len(values) == 0 {
return status.Error(codes.Unauthenticated, "authentication required")
}
if len(values) == 0 {
return nil
}
}
if len(values) != 1 {
return status.Error(codes.Unauthenticated, "authentication required")
}
const prefix = "Bearer "
if len(values[0]) <= len(prefix) || values[0][:len(prefix)] != prefix || !security.IsFilerAdminToken(key, security.EncodedJwt(values[0][len(prefix):])) {
return status.Error(codes.Unauthenticated, "invalid authentication")
}
return nil
}
func dashAuthAddress(address string) pb.ServerAddress {
_, portText, err := net.SplitHostPort(address)
if err != nil {
return pb.ServerAddress(address)
}
port, err := strconv.Atoi(portText)
if err != nil {
return pb.ServerAddress(address)
}
return pb.NewServerAddressWithGrpcPort(address, port)
}
func startDashAuthFiler(t *testing.T, key security.SigningKey, require bool) pb.ServerAddress {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal("listen")
}
server := grpc.NewServer(
grpc.UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if err := dashAuthCheck(ctx, key, require); err != nil {
return nil, err
}
return handler(ctx, req)
}),
grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := dashAuthCheck(stream.Context(), key, require); err != nil {
return err
}
return handler(srv, stream)
}),
)
filer_pb.RegisterSeaweedFilerServer(server, dashAuthFiler{})
go func() { _ = server.Serve(listener) }()
address := dashAuthAddress(listener.Addr().String())
t.Cleanup(func() {
server.Stop()
_ = listener.Close()
pb.InvalidateGrpcConnection(address.ToGrpcAddress())
})
return address
}
func dashTestKey(t *testing.T) security.SigningKey {
t.Helper()
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
t.Fatal("generate disposable signing key")
}
return security.SigningKey(hex.EncodeToString(bytes))
}
func TestAdminFilerReadsUsePerCallAdminToken(t *testing.T) {
key := dashTestKey(t)
otherKey := dashTestKey(t)
for _, tc := range []struct {
name string
require bool
source security.FilerTokenSource
want codes.Code
}{
{
name: "valid token",
require: true,
source: func(context.Context) (security.EncodedJwt, error) {
return security.GenJwtForFilerAdmin(key, 10), nil
},
want: codes.OK,
},
{
name: "wrong key",
require: true,
source: func(context.Context) (security.EncodedJwt, error) {
return security.GenJwtForFilerAdmin(otherKey, 10), nil
},
want: codes.Unauthenticated,
},
{
name: "missing token",
require: true,
want: codes.Unauthenticated,
},
{
name: "optional no key",
require: false,
want: codes.OK,
},
} {
t.Run(tc.name, func(t *testing.T) {
serverKey := key
if tc.name == "optional no key" {
serverKey = nil
}
address := startDashAuthFiler(t, serverKey, tc.require)
server := &AdminServer{
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
filerTokenSource: tc.source,
cachedFilers: []string{string(address)},
lastFilerUpdate: time.Now(),
filerCacheExpiration: time.Hour,
}
config, err := server.getFilerConfig()
if status.Code(err) != tc.want {
t.Fatalf("admin filer configuration read code=%v, want %v", status.Code(err), tc.want)
}
if tc.want == codes.OK {
if config.BucketsPath != "/buckets" || config.FilerGroup != "test" {
t.Fatal("admin filer configuration response was not preserved")
}
if _, err := server.getFilerConf(); err != nil {
t.Fatal("admin filer.conf read was refused")
}
}
})
}
}
+137
View File
@@ -0,0 +1,137 @@
package dash
import (
"fmt"
"strings"
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/shell"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
const pluginAdminScriptJobType = "admin_script"
type maintenanceWork struct {
name string
pluginJobType string
legacyTaskType types.TaskType
shellCommand string
}
// duplicableMaintenanceWork lists work that the plugin scheduler, the legacy
// maintenance manager, and an admin_script can each run on their own.
var duplicableMaintenanceWork = []maintenanceWork{
{"volume balance", "volume_balance", types.TaskTypeBalance, "volume.balance"},
{"EC balance", "ec_balance", types.TaskTypeECBalance, "ec.balance"},
{"EC encoding", "erasure_coding", types.TaskTypeErasureCoding, "ec.encode"},
{"vacuum", "vacuum", types.TaskTypeVacuum, "volume.vacuum"},
}
// MaintenanceOverlap names work that more than one scheduler runs.
type MaintenanceOverlap struct {
Work string `json:"work"`
Runners []string `json:"runners"`
}
type maintenanceRunnerState struct {
PluginEnabled map[string]bool
LegacyEnabled map[types.TaskType]bool
AdminScriptEnabled bool
AdminScript string
}
func maintenanceOverlaps(state maintenanceRunnerState) []MaintenanceOverlap {
var scriptCommands map[string]bool
if state.AdminScriptEnabled {
scriptCommands = scriptAppliedCommands(state.AdminScript)
}
var overlaps []MaintenanceOverlap
for _, work := range duplicableMaintenanceWork {
var runners []string
if state.PluginEnabled[work.pluginJobType] {
runners = append(runners, fmt.Sprintf("plugin %s job", work.pluginJobType))
}
if state.LegacyEnabled[work.legacyTaskType] {
runners = append(runners, fmt.Sprintf("legacy maintenance %s task (turn off with enabled = false under [maintenance] in admin.toml)", work.legacyTaskType))
}
if scriptCommands[work.shellCommand] {
runners = append(runners, fmt.Sprintf("%s job running %s", pluginAdminScriptJobType, work.shellCommand))
}
if len(runners) > 1 {
overlaps = append(overlaps, MaintenanceOverlap{Work: work.name, Runners: runners})
}
}
return overlaps
}
func scriptAppliedCommands(script string) map[string]bool {
applied := make(map[string]bool)
for _, line := range strings.Split(strings.ReplaceAll(script, "\r\n", "\n"), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
for _, chunk := range strings.Split(line, ";") {
name, args, ok := shell.SplitScriptCommand(strings.TrimSpace(chunk))
if ok && shell.CommandArgsApply(name, args) {
applied[name] = true
}
}
}
return applied
}
func (s *AdminServer) collectMaintenanceRunnerState() maintenanceRunnerState {
state := maintenanceRunnerState{
PluginEnabled: make(map[string]bool),
LegacyEnabled: make(map[types.TaskType]bool),
}
if s.maintenanceManager != nil {
for _, work := range duplicableMaintenanceWork {
state.LegacyEnabled[work.legacyTaskType] = s.maintenanceManager.IsTaskTypeEnabled(maintenance.MaintenanceTaskType(work.legacyTaskType))
}
}
pluginSvc := s.GetPlugin()
if pluginSvc == nil {
return state
}
states, err := pluginSvc.ListSchedulerStates()
if err != nil {
glog.V(1).Infof("maintenance overlap check: list scheduler states: %v", err)
return state
}
for _, jobState := range states {
state.PluginEnabled[jobState.JobType] = jobState.Enabled
}
state.AdminScriptEnabled = state.PluginEnabled[pluginAdminScriptJobType]
if state.AdminScriptEnabled {
cfg, err := pluginSvc.LoadJobTypeConfig(pluginAdminScriptJobType)
if err != nil {
glog.V(1).Infof("maintenance overlap check: load %s config: %v", pluginAdminScriptJobType, err)
} else if cfg != nil {
state.AdminScript = cfg.GetAdminConfigValues()["script"].GetStringValue()
}
}
return state
}
// MaintenanceOverlaps lists the work that more than one scheduler runs on its own.
// Each runner plans from the same topology without knowing about the others.
func (s *AdminServer) MaintenanceOverlaps() []MaintenanceOverlap {
return maintenanceOverlaps(s.collectMaintenanceRunnerState())
}
func (s *AdminServer) warnOnMaintenanceOverlap(previous string) string {
var lines []string
for _, overlap := range s.MaintenanceOverlaps() {
lines = append(lines, fmt.Sprintf("%s has %d independent runners: %s", overlap.Work, len(overlap.Runners), strings.Join(overlap.Runners, ", ")))
}
current := strings.Join(lines, "; ")
if current != previous {
for _, line := range lines {
glog.Warningf("%s. Keep only one enabled.", line)
}
}
return current
}
+108
View File
@@ -0,0 +1,108 @@
package dash
import (
"reflect"
"testing"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
func TestScriptAppliedCommands(t *testing.T) {
cases := []struct {
script string
want bool
}{
{"", false},
{"fs.log.purge -daysAgo=7\nvolume.fix.replication -apply", false},
{"ec.balance", false},
{"ec.balance -collection=x", false},
{"ec.balance -apply", true},
{"ec.balance -force", true},
{"ec.balance --apply", true},
{"ec.balance -apply=true", true},
{"ec.balance -apply=false", false},
{"ec.balance -apply=FALSE", false},
{"ec.balance -apply=T", true},
{"ec.balance -apply=maybe", false},
{"ec.balance -collection=a # add -apply later", false},
{"ec.balance -apply=false # use -apply for writes", false},
{"# ec.balance -apply", false},
{"volume.list; ec.balance -collection=a -apply", true},
{"ec.rebuild -apply\r\nec.balance -apply\r\n", true},
{"ec.balancer -apply", false},
{"ec.balance -apply=maybe -force", false},
{"ec.balance -apply -force=maybe", false},
{"ec.balance -apply -force=false", false},
{"ec.balance -force=false -apply", false},
{"ec.balance -apply -apply=false", false},
{"ec.balance -collection x -apply", true},
{"ec.balance -collection -apply", false},
{"ec.balance x -apply", false},
{"ec.balance -collection \"a b\" -apply", true},
{"ec.balance -collection 'a b' -force", true},
{"ec.balance -collection #x -apply", true},
{"ec.balance -bogus -apply", false},
{"ec.balance -maxParallelization=x -apply", false},
{"ec.balance -maxParallelization 4 -apply", true},
{"ec.balance -volumeIds=x -apply", false},
}
for _, c := range cases {
if got := scriptAppliedCommands(c.script)["ec.balance"]; got != c.want {
t.Errorf("scriptAppliedCommands(%q) has ec.balance = %v, want %v", c.script, got, c.want)
}
}
}
func TestScriptAppliedCommandsAcrossWork(t *testing.T) {
got := scriptAppliedCommands("volume.balance -apply\nec.encode -collection=a\nvolume.vacuum -garbageThreshold=0.2\nvolume.fix.replication -apply\nvolume.list")
want := map[string]bool{"volume.balance": true, "ec.encode": true, "volume.vacuum": true}
if !reflect.DeepEqual(got, want) {
t.Errorf("scriptAppliedCommands = %v, want %v", got, want)
}
if got := scriptAppliedCommands("volume.balance\nec.encode -quietFor=soon"); len(got) != 0 {
t.Errorf("dry-run and rejected commands counted: %v", got)
}
}
func TestMaintenanceOverlaps(t *testing.T) {
legacyEC := "legacy maintenance ec_balance task (turn off with enabled = false under [maintenance] in admin.toml)"
cases := []struct {
name string
state maintenanceRunnerState
want []MaintenanceOverlap
}{
{"none", maintenanceRunnerState{}, nil},
{"plugin only", maintenanceRunnerState{PluginEnabled: map[string]bool{"ec_balance": true, "vacuum": true}}, nil},
{"disabled script ignored", maintenanceRunnerState{
PluginEnabled: map[string]bool{"ec_balance": true},
AdminScript: "ec.balance -apply",
}, nil},
{"plugin and legacy on different work", maintenanceRunnerState{
PluginEnabled: map[string]bool{"vacuum": true},
LegacyEnabled: map[types.TaskType]bool{types.TaskTypeECBalance: true},
}, nil},
{"all three on EC balance", maintenanceRunnerState{
PluginEnabled: map[string]bool{"ec_balance": true, "admin_script": true},
LegacyEnabled: map[types.TaskType]bool{types.TaskTypeECBalance: true},
AdminScriptEnabled: true,
AdminScript: "ec.balance -apply",
}, []MaintenanceOverlap{{Work: "EC balance", Runners: []string{"plugin ec_balance job", legacyEC, "admin_script job running ec.balance"}}}},
{"script overlaps two plugin jobs", maintenanceRunnerState{
PluginEnabled: map[string]bool{"volume_balance": true, "vacuum": true, "erasure_coding": true, "admin_script": true},
AdminScriptEnabled: true,
AdminScript: "volume.balance -force\nvolume.vacuum",
}, []MaintenanceOverlap{
{Work: "volume balance", Runners: []string{"plugin volume_balance job", "admin_script job running volume.balance"}},
{Work: "vacuum", Runners: []string{"plugin vacuum job", "admin_script job running volume.vacuum"}},
}},
{"legacy and plugin encoding", maintenanceRunnerState{
PluginEnabled: map[string]bool{"erasure_coding": true},
LegacyEnabled: map[types.TaskType]bool{types.TaskTypeErasureCoding: true},
}, []MaintenanceOverlap{{Work: "EC encoding", Runners: []string{"plugin erasure_coding job", "legacy maintenance erasure_coding task (turn off with enabled = false under [maintenance] in admin.toml)"}}}},
}
for _, c := range cases {
if got := maintenanceOverlaps(c.state); !reflect.DeepEqual(got, c.want) {
t.Errorf("%s: maintenanceOverlaps = %v, want %v", c.name, got, c.want)
}
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ func (s *AdminServer) GetMountClients() (*MountClientsData, error) {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), mountClientsFilerTimeout)
defer cancel()
err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, s.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.ListMetadataSubscribers(ctx, &filer_pb.ListMetadataSubscribersRequest{
ClientTypes: mountClientTypes,
})
+64 -7
View File
@@ -70,6 +70,47 @@ func filterActivitiesByLane(activities []plugin.JobActivity, laneFilter string)
return filtered
}
func parseVolumeIDFilter(raw string) (uint32, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return 0, nil
}
value, err := strconv.ParseUint(raw, 10, 32)
if err != nil || value == 0 {
return 0, fmt.Errorf("invalid volume_id %q", raw)
}
return uint32(value), nil
}
func filterTrackedJobsByVolume(jobs []plugin.TrackedJob, volumeID uint32) []plugin.TrackedJob {
if volumeID == 0 {
return jobs
}
filtered := make([]plugin.TrackedJob, 0, len(jobs))
for _, job := range jobs {
if job.VolumeID == volumeID {
filtered = append(filtered, job)
}
}
return filtered
}
func filterActivitiesByJobs(activities []plugin.JobActivity, jobs []plugin.TrackedJob) []plugin.JobActivity {
jobIDs := make(map[string]struct{}, len(jobs))
for _, job := range jobs {
jobIDs[job.JobID] = struct{}{}
}
filtered := make([]plugin.JobActivity, 0, len(activities))
for _, activity := range activities {
if _, ok := jobIDs[activity.JobID]; ok {
filtered = append(filtered, activity)
}
}
return filtered
}
// GetPluginStatusAPI returns plugin status.
func (s *AdminServer) GetPluginStatusAPI(w http.ResponseWriter, r *http.Request) {
plugin := s.GetPlugin()
@@ -153,10 +194,15 @@ func (s *AdminServer) GetPluginJobsAPI(w http.ResponseWriter, r *http.Request) {
jobType := strings.TrimSpace(query.Get("job_type"))
state := strings.TrimSpace(query.Get("state"))
laneFilter := strings.TrimSpace(query.Get("lane"))
volumeID, err := parseVolumeIDFilter(query.Get("volume_id"))
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
limit := parsePositiveInt(query.Get("limit"), 200)
// Apply the lane before the limit, or a busy lane's newest rows crowd out a quiet lane.
// Apply the filters before the limit, or a busy lane's newest rows crowd out a quiet lane.
listLimit := limit
if laneFilter != "" {
if laneFilter != "" || volumeID != 0 {
listLimit = 0
}
jobs := s.ListPluginJobs(jobType, state, listLimit)
@@ -165,6 +211,7 @@ func (s *AdminServer) GetPluginJobsAPI(w http.ResponseWriter, r *http.Request) {
return
}
jobs = filterTrackedJobsByLane(jobs, laneFilter)
jobs = filterTrackedJobsByVolume(jobs, volumeID)
if len(jobs) > limit {
jobs = jobs[:limit]
}
@@ -261,9 +308,14 @@ func (s *AdminServer) GetPluginActivitiesAPI(w http.ResponseWriter, r *http.Requ
query := r.URL.Query()
jobType := strings.TrimSpace(query.Get("job_type"))
laneFilter := strings.TrimSpace(query.Get("lane"))
volumeID, err := parseVolumeIDFilter(query.Get("volume_id"))
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
limit := parsePositiveInt(query.Get("limit"), 500)
listLimit := limit
if laneFilter != "" {
if laneFilter != "" || volumeID != 0 {
listLimit = 0
}
activities := s.ListPluginActivities(jobType, listLimit)
@@ -272,6 +324,9 @@ func (s *AdminServer) GetPluginActivitiesAPI(w http.ResponseWriter, r *http.Requ
return
}
activities = filterActivitiesByLane(activities, laneFilter)
if volumeID != 0 {
activities = filterActivitiesByJobs(activities, filterTrackedJobsByVolume(s.ListPluginJobs(jobType, "", 0), volumeID))
}
if len(activities) > limit {
activities = activities[:limit]
}
@@ -349,8 +404,9 @@ func (s *AdminServer) GetPluginSchedulerStatusAPI(w http.ResponseWriter, r *http
if laneFilter != "" {
lane := plugin.SchedulerLane(laneFilter)
response := map[string]interface{}{
"enabled": true,
"scheduler": pluginSvc.GetLaneSchedulerStatus(lane),
"enabled": true,
"scheduler": pluginSvc.GetLaneSchedulerStatus(lane),
"maintenance_overlaps": s.MaintenanceOverlaps(),
}
if s.pluginLock != nil {
response["lock"] = lockStatus
@@ -360,8 +416,9 @@ func (s *AdminServer) GetPluginSchedulerStatusAPI(w http.ResponseWriter, r *http
}
response := map[string]interface{}{
"enabled": true,
"scheduler": pluginSvc.GetSchedulerStatus(),
"enabled": true,
"scheduler": pluginSvc.GetSchedulerStatus(),
"maintenance_overlaps": s.MaintenanceOverlaps(),
}
if s.pluginLock != nil {
response["lock"] = lockStatus
+72
View File
@@ -290,3 +290,75 @@ func TestPluginJobsAndActivitiesAPILimitAfterLaneFilter(t *testing.T) {
t.Fatalf("default lane activities: got %d rows, want the limit of 2", len(rows))
}
}
func TestPluginJobsAndActivitiesAPIVolumeIDFilter(t *testing.T) {
dataDir := t.TempDir()
store, err := plugin.NewConfigStore(dataDir)
if err != nil {
t.Fatalf("NewConfigStore: %v", err)
}
now := time.Now()
var jobs []plugin.TrackedJob
var activities []plugin.JobActivity
for i := 0; i < 6; i++ {
jobType, jobID, volumeID := "erasure_coding", fmt.Sprintf("ec-%d", i), uint32(7)
if i%2 == 1 {
jobType, jobID, volumeID = "vacuum", fmt.Sprintf("vacuum-%d", i), uint32(8)
}
at := now.Add(-time.Duration(i) * time.Minute)
jobs = append(jobs, plugin.TrackedJob{JobID: jobID, JobType: jobType, VolumeID: volumeID, State: plugin.StateSucceeded, UpdatedAt: &at})
activities = append(activities, plugin.JobActivity{JobID: jobID, JobType: jobType, Message: "done", OccurredAt: &at})
}
if err := store.SaveTrackedJobs(jobs); err != nil {
t.Fatalf("SaveTrackedJobs: %v", err)
}
if err := store.SaveActivities(activities); err != nil {
t.Fatalf("SaveActivities: %v", err)
}
p, err := plugin.New(plugin.Options{DataDir: dataDir})
if err != nil {
t.Fatalf("plugin.New: %v", err)
}
defer p.Shutdown()
s := &AdminServer{plugin: p}
get := func(handler http.HandlerFunc, url string, wantStatus int) []map[string]any {
recorder := httptest.NewRecorder()
handler(recorder, httptest.NewRequest(http.MethodGet, url, nil))
if recorder.Code != wantStatus {
t.Fatalf("%s: status %d, want %d", url, recorder.Code, wantStatus)
}
if wantStatus != http.StatusOK {
return nil
}
var rows []map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &rows); err != nil {
t.Fatalf("%s: %v", url, err)
}
return rows
}
idsOf := func(rows []map[string]any) []string {
ids := make([]string, 0, len(rows))
for _, row := range rows {
ids = append(ids, fmt.Sprint(row["job_id"]))
}
return ids
}
if ids := idsOf(get(s.GetPluginJobsAPI, "/api/plugin/jobs?limit=2&volume_id=8", http.StatusOK)); fmt.Sprint(ids) != "[vacuum-1 vacuum-3]" {
t.Fatalf("volume 8 jobs: got %v", ids)
}
if ids := idsOf(get(s.GetPluginJobsAPI, "/api/plugin/jobs?volume_id=7&job_type=vacuum", http.StatusOK)); len(ids) != 0 {
t.Fatalf("volume 7 vacuum jobs: got %v, want none", ids)
}
if ids := idsOf(get(s.GetPluginActivitiesAPI, "/api/plugin/activities?limit=2&volume_id=7", http.StatusOK)); fmt.Sprint(ids) != "[ec-0 ec-2]" {
t.Fatalf("volume 7 activities: got %v", ids)
}
if ids := idsOf(get(s.GetPluginActivitiesAPI, "/api/plugin/activities?volume_id=9", http.StatusOK)); len(ids) != 0 {
t.Fatalf("volume 9 activities: got %v, want none", ids)
}
for _, bad := range []string{"0", "-1", "abc", "4294967296"} {
get(s.GetPluginJobsAPI, "/api/plugin/jobs?volume_id="+bad, http.StatusBadRequest)
get(s.GetPluginActivitiesAPI, "/api/plugin/activities?volume_id="+bad, http.StatusBadRequest)
}
}
+451
View File
@@ -0,0 +1,451 @@
package dash
import (
"context"
"errors"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
)
const (
maxInspectedS3ObjectVersions = 10000
inspectedS3ObjectVersionsPageSize = 1024
)
type S3ObjectInspection struct {
Bucket string `json:"bucket"`
Key string `json:"key"`
Versioned bool `json:"versioned"`
Truncated bool `json:"truncated,omitempty"`
Versions []S3ObjectVersionInspection `json:"versions"`
Volumes []S3ObjectVolumeHealth `json:"volumes"`
}
type S3ObjectVersionInspection struct {
VersionId string `json:"versionId"`
Path string `json:"path"`
IsLatest bool `json:"isLatest"`
IsDeleteMarker bool `json:"isDeleteMarker"`
Size uint64 `json:"size"`
ModifiedAt time.Time `json:"modifiedAt"`
ETag string `json:"etag,omitempty"`
ChecksumAlgorithm string `json:"checksumAlgorithm,omitempty"`
ChecksumValue string `json:"checksumValue,omitempty"`
ChecksumType string `json:"checksumType,omitempty"`
ObjectLockMode string `json:"objectLockMode,omitempty"`
RetainUntil *time.Time `json:"retainUntil,omitempty"`
LegalHold string `json:"legalHold,omitempty"`
WormEnforcedAt *time.Time `json:"wormEnforcedAt,omitempty"`
InlineBytes int `json:"inlineBytes,omitempty"`
RemoteStorage string `json:"remoteStorage,omitempty"`
Chunks []S3ObjectChunkInspection `json:"chunks"`
}
type S3ObjectChunkInspection struct {
FileId string `json:"fileId"`
VolumeId uint32 `json:"volumeId"`
Offset int64 `json:"offset"`
Size uint64 `json:"size"`
IsManifest bool `json:"isManifest,omitempty"`
}
type S3ObjectVolumeHealth struct {
VolumeId uint32 `json:"volumeId"`
Collection string `json:"collection,omitempty"`
Kind string `json:"kind"`
Servers []string `json:"servers,omitempty"`
CopiesPresent int `json:"copiesPresent,omitempty"`
CopiesExpected int `json:"copiesExpected,omitempty"`
ReadOnly bool `json:"readOnly,omitempty"`
EcShardsPresent int `json:"ecShardsPresent,omitempty"`
EcDataShards int `json:"ecDataShards,omitempty"`
EcTotalShards int `json:"ecTotalShards,omitempty"`
EcMissingShards []uint32 `json:"ecMissingShards,omitempty"`
Healthy bool `json:"healthy"`
}
const (
s3ObjectVolumeReplicated = "replicated"
s3ObjectVolumeEc = "ec"
s3ObjectVolumeMissing = "missing"
)
func (s *AdminServer) InspectS3ObjectAPI(w http.ResponseWriter, r *http.Request) {
bucket := mux.Vars(r)["bucket"]
key := r.URL.Query().Get("key")
if err := validateInspectedS3Object(bucket, key); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
inspection, err := s.InspectS3Object(r.Context(), bucket, strings.TrimPrefix(key, "/"))
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
writeJSONError(w, http.StatusNotFound, err.Error())
return
}
writeJSONError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, inspection)
}
func validateInspectedS3Object(bucket, key string) error {
if bucket == "" || strings.ContainsAny(bucket, "/\\") || bucket == "." || bucket == ".." {
return fmt.Errorf("invalid bucket name %q", bucket)
}
key = strings.TrimPrefix(key, "/")
if key == "" || strings.HasSuffix(key, "/") {
return fmt.Errorf("object key is required")
}
for _, segment := range strings.Split(key, "/") {
if segment == "" || segment == "." || segment == ".." {
return fmt.Errorf("invalid object key %q", key)
}
}
return nil
}
func (s *AdminServer) InspectS3Object(ctx context.Context, bucket, key string) (*S3ObjectInspection, error) {
inspection := &S3ObjectInspection{Bucket: bucket, Key: key}
var objectDir, objectName string
var baseEntry, versionsEntry *filer_pb.Entry
var versionEntries []*filer_pb.Entry
err := s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
config, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer configuration: %w", err)
}
bucketsPath := s3_constants.DefaultBucketsPath
if config.DirBuckets != "" {
bucketsPath = config.DirBuckets
}
objectDir, objectName = splitInspectedS3ObjectKey(bucketsPath+"/"+bucket, key)
versionsName := objectName + s3_constants.VersionsFolder
versionsDir := objectDir + "/" + versionsName
if _, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: bucketsPath, Name: bucket}); err != nil {
return fmt.Errorf("bucket %s: %w", bucket, err)
}
if resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: objectDir, Name: objectName}); err == nil {
if !resp.Entry.IsDirectory || resp.Entry.IsPrefixObject() {
baseEntry = resp.Entry
}
} else if !errors.Is(err, filer_pb.ErrNotFound) {
return fmt.Errorf("lookup %s/%s: %w", objectDir, objectName, err)
}
if resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: objectDir, Name: versionsName}); err == nil {
if resp.Entry.IsDirectory {
versionsEntry = resp.Entry
}
} else if !errors.Is(err, filer_pb.ErrNotFound) {
return fmt.Errorf("lookup %s: %w", versionsDir, err)
}
if versionsEntry == nil {
return nil
}
versionEntries, inspection.Truncated, err = listInspectedS3ObjectVersions(ctx, client, versionsDir)
return err
})
if err != nil {
return nil, err
}
if baseEntry == nil && len(versionEntries) == 0 {
return nil, fmt.Errorf("object %s/%s: %w", bucket, key, filer_pb.ErrNotFound)
}
inspection.Versioned = versionsEntry != nil
inspection.Versions = assembleS3ObjectVersions(objectDir, objectName, baseEntry, versionsEntry, versionEntries, inspection.Truncated)
volumeIds := s3ObjectVolumeIds(inspection.Versions)
if len(volumeIds) == 0 {
return inspection, nil
}
var topology *master_pb.TopologyInfo
err = s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := pb.CollectVolumeList(ctx, client, &master_pb.VolumeListRequest{VolumeIds: volumeIds})
if err != nil {
return err
}
topology = resp.TopologyInfo
return nil
})
if err != nil {
return nil, fmt.Errorf("volume list: %w", err)
}
inspection.Volumes = summarizeS3ObjectVolumes(volumeIds, topology)
return inspection, nil
}
// listInspectedS3ObjectVersions pages through versionsDir, skipping entries
// without a version id, until it holds maxInspectedS3ObjectVersions versions.
func listInspectedS3ObjectVersions(ctx context.Context, client filer_pb.SeaweedFilerClient, versionsDir string) (versions []*filer_pb.Entry, truncated bool, err error) {
startFrom := ""
for {
listed, last := 0, false
err = filer_pb.SeaweedList(ctx, client, versionsDir, "", func(entry *filer_pb.Entry, isLast bool) error {
listed++
last = isLast
startFrom = entry.Name
if s3api.VersionIdFromEntry(entry) == "" {
return nil
}
if len(versions) >= maxInspectedS3ObjectVersions {
truncated = true
return nil
}
versions = append(versions, entry)
return nil
}, startFrom, false, inspectedS3ObjectVersionsPageSize)
if err != nil || truncated || last || listed == 0 {
return versions, truncated, err
}
}
}
func splitInspectedS3ObjectKey(bucketDir, key string) (dir, name string) {
if i := strings.LastIndex(key, "/"); i >= 0 {
return bucketDir + "/" + key[:i], key[i+1:]
}
return bucketDir, key
}
func assembleS3ObjectVersions(objectDir, objectName string, baseEntry, versionsEntry *filer_pb.Entry, versionEntries []*filer_pb.Entry, truncated bool) []S3ObjectVersionInspection {
var latestVersionId string
nullIsLatest := versionsEntry == nil
if versionsEntry != nil {
latestVersionId = string(versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey])
nullIsLatest = latestVersionId == ""
}
if baseEntry == nil && latestVersionId == "" {
nullIsLatest = false
if !truncated {
latestVersionId = s3api.SelectLatestVersionId(versionEntries)
}
}
var versions []S3ObjectVersionInspection
if baseEntry != nil {
version := inspectS3ObjectVersion(objectDir+"/"+objectName, baseEntry)
if version.VersionId == "" {
version.VersionId = "null"
}
version.IsLatest = nullIsLatest || version.VersionId == latestVersionId
versions = append(versions, version)
}
versionsDir := objectDir + "/" + objectName + s3_constants.VersionsFolder
for _, entry := range versionEntries {
version := inspectS3ObjectVersion(versionsDir+"/"+entry.Name, entry)
version.VersionId = s3api.VersionIdFromEntry(entry)
version.IsLatest = !nullIsLatest && version.VersionId == latestVersionId
versions = append(versions, version)
}
sort.SliceStable(versions, func(i, j int) bool {
if versions[i].IsLatest != versions[j].IsLatest {
return versions[i].IsLatest
}
return versions[i].ModifiedAt.After(versions[j].ModifiedAt)
})
return versions
}
func inspectS3ObjectVersion(path string, entry *filer_pb.Entry) S3ObjectVersionInspection {
ext := entry.Extended
version := S3ObjectVersionInspection{
VersionId: string(ext[s3_constants.ExtVersionIdKey]),
Path: path,
IsDeleteMarker: string(ext[s3_constants.ExtDeleteMarkerKey]) == "true",
ETag: strings.Trim(s3api.ObjectETag(entry), `"`),
ChecksumAlgorithm: string(ext[s3_constants.ExtChecksumAlgorithm]),
ChecksumValue: string(ext[s3_constants.ExtChecksumValue]),
ChecksumType: string(ext[s3_constants.ExtChecksumType]),
ObjectLockMode: string(ext[s3_constants.ExtObjectLockModeKey]),
LegalHold: string(ext[s3_constants.ExtLegalHoldKey]),
InlineBytes: len(entry.Content),
Size: filer.FileSize(entry),
}
if attr := entry.Attributes; attr != nil {
version.ModifiedAt = time.Unix(attr.Mtime, int64(attr.MtimeNs)).UTC()
}
if entry.WormEnforcedAtTsNs > 0 {
t := time.Unix(0, entry.WormEnforcedAtTsNs).UTC()
version.WormEnforcedAt = &t
}
if raw := string(ext[s3_constants.ExtRetentionUntilDateKey]); raw != "" {
if seconds, err := strconv.ParseInt(raw, 10, 64); err == nil {
t := time.Unix(seconds, 0).UTC()
version.RetainUntil = &t
}
}
if entry.RemoteEntry != nil {
version.RemoteStorage = entry.RemoteEntry.StorageName
}
for _, chunk := range entry.Chunks {
c := S3ObjectChunkInspection{
FileId: chunk.GetFileIdString(),
Offset: chunk.Offset,
Size: chunk.Size,
IsManifest: chunk.IsChunkManifest,
}
if chunk.Fid != nil {
c.VolumeId = chunk.Fid.VolumeId
} else if fid, err := filer_pb.ToFileIdObject(chunk.FileId); err == nil {
c.VolumeId = fid.VolumeId
}
version.Chunks = append(version.Chunks, c)
}
return version
}
func s3ObjectVolumeIds(versions []S3ObjectVersionInspection) []uint32 {
seen := make(map[uint32]bool)
var ids []uint32
for _, version := range versions {
for _, chunk := range version.Chunks {
if chunk.VolumeId == 0 || seen[chunk.VolumeId] {
continue
}
seen[chunk.VolumeId] = true
ids = append(ids, chunk.VolumeId)
}
}
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
return ids
}
func summarizeS3ObjectVolumes(volumeIds []uint32, topology *master_pb.TopologyInfo) []S3ObjectVolumeHealth {
health := make(map[uint32]*S3ObjectVolumeHealth, len(volumeIds))
for _, id := range volumeIds {
health[id] = &S3ObjectVolumeHealth{VolumeId: id, Kind: s3ObjectVolumeMissing}
}
ecRuns := make(map[uint32]map[int64]*s3ObjectEcRun)
if topology != nil {
for _, dc := range topology.DataCenterInfos {
for _, rack := range dc.RackInfos {
for _, node := range rack.DataNodeInfos {
for _, disk := range node.DiskInfos {
for _, v := range disk.VolumeInfos {
h := health[v.Id]
if h == nil {
continue
}
h.Kind = s3ObjectVolumeReplicated
h.Collection = v.Collection
h.Servers = append(h.Servers, node.Id)
h.CopiesPresent++
h.ReadOnly = h.ReadOnly || v.ReadOnly
if rp, err := super_block.NewReplicaPlacementFromByte(byte(v.ReplicaPlacement)); err == nil {
h.CopiesExpected = rp.GetCopyCount()
}
}
for _, ec := range disk.EcShardInfos {
h := health[ec.Id]
if h == nil || h.Kind == s3ObjectVolumeReplicated {
continue
}
h.Kind = s3ObjectVolumeEc
h.Collection = ec.Collection
if ecRuns[ec.Id] == nil {
ecRuns[ec.Id] = make(map[int64]*s3ObjectEcRun)
}
run := ecRuns[ec.Id][ec.EncodeTsNs]
if run == nil {
run = &s3ObjectEcRun{}
ecRuns[ec.Id][ec.EncodeTsNs] = run
}
run.servers = append(run.servers, node.Id)
run.dataShards = erasure_coding.EcShardsVolumeDataShards(ec)
run.totalShards = run.dataShards + erasure_coding.EcShardsVolumeParityShards(ec)
run.bits |= erasure_coding.ShardBits(ec.EcIndexBits)
}
}
}
}
}
}
result := make([]S3ObjectVolumeHealth, 0, len(volumeIds))
for _, id := range volumeIds {
h := health[id]
switch h.Kind {
case s3ObjectVolumeReplicated:
h.Healthy = h.CopiesPresent >= h.CopiesExpected
case s3ObjectVolumeEc:
run := currentS3ObjectEcRun(ecRuns[id])
h.Servers = run.servers
h.EcDataShards = run.dataShards
h.EcTotalShards = run.totalShards
bits := run.bits
for shardId := 0; shardId < h.EcTotalShards; shardId++ {
if bits.Has(erasure_coding.ShardId(shardId)) {
h.EcShardsPresent++
} else {
h.EcMissingShards = append(h.EcMissingShards, uint32(shardId))
}
}
h.Healthy = h.EcShardsPresent >= h.EcDataShards
}
sort.Strings(h.Servers)
result = append(result, *h)
}
return result
}
type s3ObjectEcRun struct {
bits erasure_coding.ShardBits
dataShards int
totalShards int
servers []string
}
// currentS3ObjectEcRun returns the newest encode run of a volume's EC shards,
// joined by shards whose server reports no encode run.
func currentS3ObjectEcRun(runs map[int64]*s3ObjectEcRun) s3ObjectEcRun {
var newest int64
for encodeTsNs := range runs {
newest = max(newest, encodeTsNs)
}
current := *runs[newest]
if unknown := runs[0]; newest != 0 && unknown != nil {
current.bits |= unknown.bits
current.servers = append(append([]string(nil), current.servers...), unknown.servers...)
}
return current
}
type S3ObjectInspectorData struct {
Username string `json:"username"`
Bucket string `json:"bucket"`
Key string `json:"key"`
Inspection *S3ObjectInspection `json:"inspection,omitempty"`
Error string `json:"error,omitempty"`
}
func (s *AdminServer) GetS3ObjectInspectorData(ctx context.Context, bucket, key string) S3ObjectInspectorData {
data := S3ObjectInspectorData{Bucket: bucket, Key: key}
if key == "" {
return data
}
if err := validateInspectedS3Object(bucket, key); err != nil {
data.Error = err.Error()
return data
}
inspection, err := s.InspectS3Object(ctx, bucket, strings.TrimPrefix(key, "/"))
if err != nil {
data.Error = err.Error()
return data
}
data.Inspection = inspection
return data
}
+295
View File
@@ -0,0 +1,295 @@
package dash
import (
"context"
"fmt"
"io"
"reflect"
"sort"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func TestValidateInspectedS3Object(t *testing.T) {
valid := [][2]string{{"b", "k"}, {"b", "/a/b.txt"}, {"b", "a/b c/d"}}
for _, c := range valid {
if err := validateInspectedS3Object(c[0], c[1]); err != nil {
t.Errorf("validateInspectedS3Object(%q, %q) = %v", c[0], c[1], err)
}
}
invalid := [][2]string{{"", "k"}, {"a/b", "k"}, {"..", "k"}, {"b", ""}, {"b", "dir/"}, {"b", "a/../k"}, {"b", "a//k"}, {"b", "./k"}}
for _, c := range invalid {
if err := validateInspectedS3Object(c[0], c[1]); err == nil {
t.Errorf("validateInspectedS3Object(%q, %q) accepted", c[0], c[1])
}
}
}
func TestSplitInspectedS3ObjectKey(t *testing.T) {
dir, name := splitInspectedS3ObjectKey("/buckets/b", "a/b/c.txt")
if dir != "/buckets/b/a/b" || name != "c.txt" {
t.Fatalf("got %q %q", dir, name)
}
dir, name = splitInspectedS3ObjectKey("/buckets/b", "c.txt")
if dir != "/buckets/b" || name != "c.txt" {
t.Fatalf("got %q %q", dir, name)
}
}
func inspectorTestEntry(name string, mtime int64, ext map[string]string, chunks ...*filer_pb.FileChunk) *filer_pb.Entry {
extended := make(map[string][]byte, len(ext))
for k, v := range ext {
extended[k] = []byte(v)
}
return &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileSize: 10, Mtime: mtime},
Extended: extended,
Chunks: chunks,
}
}
func TestAssembleS3ObjectVersions(t *testing.T) {
versionsEntry := inspectorTestEntry("k.versions", 0, map[string]string{s3_constants.ExtLatestVersionIdKey: "v2"})
locked := inspectorTestEntry("v_v1", 100, map[string]string{
s3_constants.ExtVersionIdKey: "v1",
s3_constants.ExtETagKey: `"abc"`,
s3_constants.ExtChecksumAlgorithm: "SHA256",
s3_constants.ExtChecksumValue: "c2hh",
s3_constants.ExtObjectLockModeKey: s3_constants.RetentionModeCompliance,
s3_constants.ExtRetentionUntilDateKey: "1893456000",
s3_constants.ExtLegalHoldKey: s3_constants.LegalHoldOn,
}, &filer_pb.FileChunk{FileId: "7,01637037d6", Size: 10}, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 9, FileKey: 1, Cookie: 2}, Offset: 10, Size: 5, IsChunkManifest: true})
locked.WormEnforcedAtTsNs = time.Unix(200, 0).UnixNano()
marker := inspectorTestEntry("v_v2", 300, map[string]string{
s3_constants.ExtVersionIdKey: "v2",
s3_constants.ExtDeleteMarkerKey: "true",
})
base := inspectorTestEntry("k", 50, nil, &filer_pb.FileChunk{FileId: "3,02637037d6", Size: 10})
versions := assembleS3ObjectVersions("/buckets/b/d", "k", base, versionsEntry, []*filer_pb.Entry{locked, marker}, false)
if len(versions) != 3 {
t.Fatalf("got %d versions", len(versions))
}
if v := versions[0]; v.VersionId != "v2" || !v.IsLatest || !v.IsDeleteMarker || v.Path != "/buckets/b/d/k.versions/v_v2" {
t.Fatalf("latest = %+v", v)
}
v1 := versions[1]
if v1.VersionId != "v1" || v1.IsLatest || v1.ETag != "abc" || v1.ChecksumAlgorithm != "SHA256" || v1.ChecksumValue != "c2hh" {
t.Fatalf("v1 = %+v", v1)
}
if v1.ObjectLockMode != s3_constants.RetentionModeCompliance || v1.LegalHold != s3_constants.LegalHoldOn {
t.Fatalf("v1 lock = %+v", v1)
}
if v1.RetainUntil == nil || !v1.RetainUntil.Equal(time.Unix(1893456000, 0)) {
t.Fatalf("v1 retain until = %v", v1.RetainUntil)
}
if v1.WormEnforcedAt == nil || !v1.WormEnforcedAt.Equal(time.Unix(200, 0)) {
t.Fatalf("v1 worm = %v", v1.WormEnforcedAt)
}
if len(v1.Chunks) != 2 || v1.Chunks[0].VolumeId != 7 || v1.Chunks[1].VolumeId != 9 || !v1.Chunks[1].IsManifest || v1.Chunks[1].FileId == "" {
t.Fatalf("v1 chunks = %+v", v1.Chunks)
}
if v := versions[2]; v.VersionId != "null" || v.IsLatest || v.Path != "/buckets/b/d/k" {
t.Fatalf("null = %+v", v)
}
if ids := s3ObjectVolumeIds(versions); !reflect.DeepEqual(ids, []uint32{3, 7, 9}) {
t.Fatalf("volume ids = %v", ids)
}
}
func TestAssembleS3ObjectVersionsNullLatest(t *testing.T) {
base := inspectorTestEntry("k", 50, nil)
if versions := assembleS3ObjectVersions("/buckets/b", "k", base, nil, nil, false); len(versions) != 1 || !versions[0].IsLatest || versions[0].VersionId != "null" {
t.Fatalf("unversioned = %+v", versions)
}
versionsEntry := inspectorTestEntry("k.versions", 0, map[string]string{
s3_constants.ExtLatestVersionIdKey: "v1",
s3_constants.ExtNullVersionIsLatestKey: "true",
})
v1 := inspectorTestEntry("v_v1", 100, map[string]string{s3_constants.ExtVersionIdKey: "v1"})
versions := assembleS3ObjectVersions("/buckets/b", "k", base, versionsEntry, []*filer_pb.Entry{v1}, false)
if len(versions) != 2 || versions[0].VersionId != "v1" || !versions[0].IsLatest || versions[1].IsLatest {
t.Fatalf("pointer with stale null flag = %+v", versions)
}
suspended := inspectorTestEntry("k.versions", 0, map[string]string{s3_constants.ExtNullVersionIsLatestKey: "true"})
versions = assembleS3ObjectVersions("/buckets/b", "k", base, suspended, []*filer_pb.Entry{v1}, false)
if len(versions) != 2 || versions[0].VersionId != "null" || !versions[0].IsLatest || versions[1].IsLatest {
t.Fatalf("suspended = %+v", versions)
}
}
func TestAssembleS3ObjectVersionsWithoutPointer(t *testing.T) {
older := inspectorTestEntry("v_6713f0ad56f535bcb4717d38b89d2800", 200, map[string]string{s3_constants.ExtVersionIdKey: "6713f0ad56f535bcb4717d38b89d2800"})
newer := inspectorTestEntry("v_6713f0ad569d387d178b2ca8fab47783", 100, map[string]string{s3_constants.ExtVersionIdKey: "6713f0ad569d387d178b2ca8fab47783"})
versionsEntry := inspectorTestEntry("k.versions", 0, map[string]string{s3_constants.ExtNullVersionIsLatestKey: "true"})
versions := assembleS3ObjectVersions("/buckets/b", "k", nil, versionsEntry, []*filer_pb.Entry{older, newer}, false)
if len(versions) != 2 || versions[0].VersionId != newer.Name[2:] || !versions[0].IsLatest || versions[1].IsLatest {
t.Fatalf("recovered = %+v", versions)
}
for _, v := range assembleS3ObjectVersions("/buckets/b", "k", nil, versionsEntry, []*filer_pb.Entry{older, newer}, true) {
if v.IsLatest {
t.Fatalf("truncated scan marked %s latest", v.VersionId)
}
}
}
func TestInspectS3ObjectVersionRemoteETag(t *testing.T) {
entry := inspectorTestEntry("k", 1, nil)
entry.RemoteEntry = &filer_pb.RemoteEntry{StorageName: "s3remote", RemoteETag: "abc", RemoteSize: 10}
if v := inspectS3ObjectVersion("/buckets/b/k", entry); v.ETag != "abc" || v.RemoteStorage != "s3remote" {
t.Fatalf("remote = %+v", v)
}
}
func TestInspectS3ObjectVersionSizeFromChunks(t *testing.T) {
entry := inspectorTestEntry("k", 1, nil, &filer_pb.FileChunk{FileId: "3,02637037d6", Offset: 0, Size: 64})
entry.Attributes.FileSize = 0
if v := inspectS3ObjectVersion("/buckets/b/k", entry); v.Size != 64 {
t.Fatalf("size = %d", v.Size)
}
}
func TestSummarizeS3ObjectVolumes(t *testing.T) {
node := func(id string, disks ...*master_pb.DiskInfo) *master_pb.DataNodeInfo {
m := make(map[string]*master_pb.DiskInfo)
for i, d := range disks {
m[string(rune('a'+i))] = d
}
return &master_pb.DataNodeInfo{Id: id, DiskInfos: m}
}
topology := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{
Id: "r1",
DataNodeInfos: []*master_pb.DataNodeInfo{
node("s1:8080", &master_pb.DiskInfo{
VolumeInfos: []*master_pb.VolumeInformationMessage{{Id: 1, Collection: "b", ReplicaPlacement: 1}, {Id: 2, ReplicaPlacement: 0}, {Id: 99}},
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{Id: 3, Collection: "b", EcIndexBits: 0x3ff}},
}),
node("s2:8080", &master_pb.DiskInfo{
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{Id: 3, Collection: "b", EcIndexBits: 0x400}, {Id: 4, EcIndexBits: 0x1ff}},
}),
},
}},
}}}
got := summarizeS3ObjectVolumes([]uint32{1, 2, 3, 4, 5}, topology)
if len(got) != 5 {
t.Fatalf("got %d volumes", len(got))
}
if v := got[0]; v.Kind != s3ObjectVolumeReplicated || v.CopiesPresent != 1 || v.CopiesExpected != 2 || v.Healthy {
t.Errorf("volume 1 = %+v", v)
}
if v := got[1]; v.Kind != s3ObjectVolumeReplicated || v.CopiesPresent != 1 || v.CopiesExpected != 1 || !v.Healthy {
t.Errorf("volume 2 = %+v", v)
}
if v := got[2]; v.Kind != s3ObjectVolumeEc || v.EcShardsPresent != 11 || !v.Healthy || !reflect.DeepEqual(v.EcMissingShards, []uint32{11, 12, 13}) || !reflect.DeepEqual(v.Servers, []string{"s1:8080", "s2:8080"}) {
t.Errorf("volume 3 = %+v", v)
}
if v := got[3]; v.Kind != s3ObjectVolumeEc || v.EcShardsPresent != 9 || v.Healthy {
t.Errorf("volume 4 = %+v", v)
}
if v := got[4]; v.Kind != s3ObjectVolumeMissing || v.Healthy {
t.Errorf("volume 5 = %+v", v)
}
}
func TestSummarizeS3ObjectVolumesPrefersReplicaOverEcShards(t *testing.T) {
topology := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{{
RackInfos: []*master_pb.RackInfo{{
DataNodeInfos: []*master_pb.DataNodeInfo{
{Id: "a-ec:8080", DiskInfos: map[string]*master_pb.DiskInfo{"": {EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{Id: 6, EcIndexBits: 0x3fff}}}}},
{Id: "b-vol:8080", DiskInfos: map[string]*master_pb.DiskInfo{"": {VolumeInfos: []*master_pb.VolumeInformationMessage{{Id: 6}}}}},
},
}},
}}}
got := summarizeS3ObjectVolumes([]uint32{6}, topology)
if v := got[0]; v.Kind != s3ObjectVolumeReplicated || !reflect.DeepEqual(v.Servers, []string{"b-vol:8080"}) || v.EcTotalShards != 0 || v.EcShardsPresent != 0 || !v.Healthy {
t.Fatalf("volume 6 = %+v", v)
}
}
type inspectorListStream struct {
grpc.ServerStreamingClient[filer_pb.ListEntriesResponse]
entries []*filer_pb.Entry
}
func (s *inspectorListStream) Recv() (*filer_pb.ListEntriesResponse, error) {
if len(s.entries) == 0 {
return nil, io.EOF
}
e := s.entries[0]
s.entries = s.entries[1:]
return &filer_pb.ListEntriesResponse{Entry: e}, nil
}
func (s *inspectorListStream) Trailer() metadata.MD { return nil }
type inspectorListClient struct {
filer_pb.SeaweedFilerClient
entries []*filer_pb.Entry
}
func (c *inspectorListClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
i := sort.Search(len(c.entries), func(i int) bool { return c.entries[i].Name > in.StartFromFileName })
end := min(len(c.entries), i+int(in.Limit))
return &inspectorListStream{entries: c.entries[i:end]}, nil
}
func TestListInspectedS3ObjectVersionsSkipsNonVersionEntries(t *testing.T) {
versions := func(n int) []*filer_pb.Entry {
entries := []*filer_pb.Entry{{Name: "a-not-a-version"}}
for i := 0; i < n; i++ {
id := fmt.Sprintf("%032x", i)
entries = append(entries, inspectorTestEntry("v_"+id, 1, map[string]string{s3_constants.ExtVersionIdKey: id}))
}
return entries
}
ctx := context.Background()
for _, c := range []struct {
versions int
want int
truncated bool
}{
{0, 0, false},
{maxInspectedS3ObjectVersions, maxInspectedS3ObjectVersions, false},
{maxInspectedS3ObjectVersions + 1, maxInspectedS3ObjectVersions, true},
{inspectedS3ObjectVersionsPageSize - 1, inspectedS3ObjectVersionsPageSize - 1, false},
} {
got, truncated, err := listInspectedS3ObjectVersions(ctx, &inspectorListClient{entries: versions(c.versions)}, "/buckets/b/k.versions")
if err != nil || len(got) != c.want || truncated != c.truncated {
t.Errorf("%d versions: got %d truncated=%v err=%v", c.versions, len(got), truncated, err)
}
}
got, truncated, err := listInspectedS3ObjectVersions(ctx, &inspectorListClient{}, "/buckets/b/k.versions")
if err != nil || len(got) != 0 || truncated {
t.Errorf("empty: got %d truncated=%v err=%v", len(got), truncated, err)
}
}
func TestSummarizeS3ObjectVolumesCountsOneEncodeRun(t *testing.T) {
holder := func(id string, shards ...*master_pb.VolumeEcShardInformationMessage) *master_pb.DataNodeInfo {
return &master_pb.DataNodeInfo{Id: id, DiskInfos: map[string]*master_pb.DiskInfo{"": {EcShardInfos: shards}}}
}
topology := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{{
RackInfos: []*master_pb.RackInfo{{
DataNodeInfos: []*master_pb.DataNodeInfo{
holder("old:8080", &master_pb.VolumeEcShardInformationMessage{Id: 7, EcIndexBits: 0x01f, EncodeTsNs: 100}),
holder("new:8080", &master_pb.VolumeEcShardInformationMessage{Id: 7, EcIndexBits: 0x3e0, EncodeTsNs: 200}),
holder("legacy:8080", &master_pb.VolumeEcShardInformationMessage{Id: 7, EcIndexBits: 0x400}),
},
}},
}}}
got := summarizeS3ObjectVolumes([]uint32{7}, topology)
if v := got[0]; v.Kind != s3ObjectVolumeEc || v.EcShardsPresent != 6 || v.Healthy || !reflect.DeepEqual(v.Servers, []string{"legacy:8080", "new:8080"}) {
t.Fatalf("volume 7 = %+v", v)
}
}
+3
View File
@@ -512,6 +512,9 @@ type ClusterVolumeServersData struct {
TotalVolumes int `json:"total_volumes"`
TotalCapacity int64 `json:"total_capacity"`
LastUpdated time.Time `json:"last_updated"`
// DefaultPlacementServers sit in DefaultDataCenter or DefaultRack while
// other servers name theirs.
DefaultPlacementServers []VolumeServer `json:"default_placement_servers,omitempty"`
}
// Type aliases for maintenance package types to support existing code
+26 -5
View File
@@ -11,6 +11,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
// GetClusterVolumes retrieves cluster volumes data with pagination, sorting, and filtering
@@ -521,6 +522,7 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
EcVolumes: 0,
EcShards: 0,
EcShardDetails: []VolumeServerEcInfo{},
LastHeartbeat: dataNodeLastHeartbeat(node),
}
}
vs := volumeServerMap[node.Id]
@@ -644,10 +646,29 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
}
return &ClusterVolumeServersData{
VolumeServers: volumeServers,
TotalVolumeServers: len(volumeServers),
TotalVolumes: totalVolumes,
TotalCapacity: totalCapacity,
LastUpdated: time.Now(),
VolumeServers: volumeServers,
TotalVolumeServers: len(volumeServers),
TotalVolumes: totalVolumes,
TotalCapacity: totalCapacity,
LastUpdated: time.Now(),
DefaultPlacementServers: defaultPlacementServers(volumeServers),
}, nil
}
func defaultPlacementServers(servers []VolumeServer) []VolumeServer {
dcRacks := make(map[string][]string)
seen := make(map[[2]string]bool)
for _, vs := range servers {
if key := [2]string{vs.DataCenter, vs.Rack}; !seen[key] {
seen[key] = true
dcRacks[vs.DataCenter] = append(dcRacks[vs.DataCenter], vs.Rack)
}
}
var stray []VolumeServer
for _, vs := range servers {
if topology.DefaultPlacementStandsOut(vs.DataCenter, vs.Rack, dcRacks) {
stray = append(stray, vs)
}
}
return stray
}
+23
View File
@@ -314,3 +314,26 @@ func TestClusterTopologyDiskTotals(t *testing.T) {
require.Equal(t, int64(1_000_000_000_000+10*30000*1024*1024), topology.DiskCapacity)
require.Equal(t, int64(590_000_000_000+30_000_000_000+5_000_000_000), topology.TotalSize)
}
func TestVolumeServerLastHeartbeat(t *testing.T) {
reported := time.Date(2026, 11, 27, 12, 0, 5, 0, time.UTC)
topology := volumeAccessTestTopology(
&master_pb.DataNodeInfo{Id: "node-a", LastHeartbeatNs: reported.UnixNano()},
&master_pb.DataNodeInfo{Id: "node-b"},
)
want := map[string]time.Time{"node-a": reported, "node-b": {}}
servers, err := newVolumeServersTestAdmin(t, topology).GetClusterVolumeServers()
require.NoError(t, err)
require.Len(t, servers.VolumeServers, 2)
for _, vs := range servers.VolumeServers {
require.True(t, want[vs.Address].Equal(vs.LastHeartbeat), "volume servers page %s: %v", vs.Address, vs.LastHeartbeat)
}
clusterTopology, err := newVolumeServersTestAdmin(t, topology).GetClusterTopology()
require.NoError(t, err)
require.Len(t, clusterTopology.VolumeServers, 2)
for _, vs := range clusterTopology.VolumeServers {
require.True(t, want[vs.Address].Equal(vs.LastHeartbeat), "topology %s: %v", vs.Address, vs.LastHeartbeat)
}
}
+3 -2
View File
@@ -100,9 +100,9 @@ func (s *WorkerGrpcServer) StartWithTLS(bindIp string, port int, listener net.Li
}
// Create gRPC server with optional TLS
tlsOption, _ := security.LoadServerTLS(util.GetViper(), "grpc.admin")
tlsOption, healthCheckOption := security.LoadServerTLS(util.GetViper(), "grpc.admin")
s.mtlsEnabled = tlsOption != nil
grpcServer := pb.NewGrpcServer(tlsOption)
grpcServer := pb.NewGrpcServer(tlsOption, healthCheckOption)
worker_pb.RegisterWorkerServiceServer(grpcServer, s)
if plugin := s.adminServer.GetPlugin(); plugin != nil {
@@ -182,6 +182,7 @@ func (s *WorkerGrpcServer) Stop() error {
// Stop gRPC server
if s.grpcServer != nil {
pb.StopHealthWatches(s.grpcServer)
s.grpcServer.GracefulStop()
}
+14
View File
@@ -108,6 +108,7 @@ func (h *AdminHandlers) registerUIRoutes(r *mux.Router) {
// Object Store management routes
r.HandleFunc("/object-store/buckets", h.ShowS3Buckets).Methods(http.MethodGet)
r.HandleFunc("/object-store/buckets/{bucket}", h.ShowBucketDetails).Methods(http.MethodGet)
r.HandleFunc("/object-store/buckets/{bucket}/inspect", h.ShowS3ObjectInspector).Methods(http.MethodGet)
r.HandleFunc("/object-store/users", h.userHandlers.ShowObjectStoreUsers).Methods(http.MethodGet)
r.HandleFunc("/object-store/policies", h.policyHandlers.ShowPolicies).Methods(http.MethodGet)
r.HandleFunc("/object-store/groups", h.groupHandlers.ShowGroups).Methods(http.MethodGet)
@@ -189,6 +190,7 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
s3Api.Handle("/buckets/{bucket}/lifecycle", wrapWrite(h.adminServer.DeleteBucketLifecycle)).Methods(http.MethodDelete)
s3Api.Handle("/buckets/{bucket}/quota", wrapWrite(h.adminServer.UpdateBucketQuota)).Methods(http.MethodPut)
s3Api.Handle("/buckets/{bucket}/owner", wrapWrite(h.adminServer.UpdateBucketOwner)).Methods(http.MethodPut)
s3Api.HandleFunc("/buckets/{bucket}/objects/inspect", h.adminServer.InspectS3ObjectAPI).Methods(http.MethodGet)
s3Api.HandleFunc("/buckets/{bucket}/policy", h.adminServer.ShowBucketPolicy).Methods(http.MethodGet)
s3Api.Handle("/buckets/{bucket}/policy", wrapWrite(h.adminServer.UpdateBucketPolicy)).Methods(http.MethodPut)
s3Api.Handle("/buckets/{bucket}/policy", wrapWrite(h.adminServer.RemoveBucketPolicy)).Methods(http.MethodDelete)
@@ -616,6 +618,18 @@ func (h *AdminHandlers) ShowBucketDetails(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, details)
}
func (h *AdminHandlers) ShowS3ObjectInspector(w http.ResponseWriter, r *http.Request) {
username := h.getUsername(r)
data := h.adminServer.GetS3ObjectInspectorData(r.Context(), mux.Vars(r)["bucket"], r.URL.Query().Get("key"))
data.Username = username
w.Header().Set("Content-Type", "text/html")
viewCtx := layout.NewViewContext(r, username, dash.CSRFTokenFromContext(r.Context()))
if err := layout.Layout(viewCtx, app.S3ObjectInspector(data)).Render(r.Context(), w); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to render template: "+err.Error())
}
}
// getS3BucketsData retrieves Object Store buckets data from the server with pagination
func (h *AdminHandlers) getS3BucketsData(r *http.Request, page, pageSize int, sortBy, sortOrder string) dash.S3BucketsData {
username := dash.UsernameFromContext(r.Context())
@@ -176,6 +176,12 @@ func (mm *MaintenanceManager) IsRunning() bool {
return mm.running
}
// IsTaskTypeEnabled reports whether the running manager queues tasks of taskType
// and a registered worker can run them.
func (mm *MaintenanceManager) IsTaskTypeEnabled(taskType MaintenanceTaskType) bool {
return mm.IsRunning() && IsTaskEnabled(mm.scanner.policy, taskType) && mm.queue.hasWorkerFor(taskType, time.Duration(mm.config.WorkerTimeoutSeconds)*time.Second)
}
// Stop terminates the maintenance manager. It is a no-op when the manager is not
// running, so a second call cannot close the already closed stop channel.
func (mm *MaintenanceManager) Stop() {
@@ -138,3 +138,37 @@ func TestMaintenanceManager_LogThrottling(t *testing.T) {
t.Errorf("Expected error count to be 25, got %d", manager.errorCount)
}
}
func TestMaintenanceManager_IsTaskTypeEnabled(t *testing.T) {
config := DefaultMaintenanceConfig()
config.Policy = &MaintenancePolicy{TaskPolicies: map[string]*TaskPolicy{
"ec_balance": {Enabled: true},
"vacuum": {Enabled: false},
}}
manager := NewMaintenanceManager(nil, config, nil)
if manager.IsTaskTypeEnabled("ec_balance") {
t.Fatal("a stopped manager queues nothing")
}
manager.mutex.Lock()
manager.running = true
manager.mutex.Unlock()
if manager.IsTaskTypeEnabled("ec_balance") {
t.Fatal("no registered worker can run ec_balance")
}
manager.queue.workers["w1"] = &MaintenanceWorker{ID: "w1", Status: "active", LastHeartbeat: time.Now(), Capabilities: []MaintenanceTaskType{"vacuum"}}
if manager.IsTaskTypeEnabled("ec_balance") {
t.Fatal("the only worker cannot run ec_balance")
}
manager.queue.workers["w2"] = &MaintenanceWorker{ID: "w2", Status: "active", LastHeartbeat: time.Now().Add(-time.Hour), Capabilities: []MaintenanceTaskType{"ec_balance"}}
if manager.IsTaskTypeEnabled("ec_balance") {
t.Fatal("a worker past its heartbeat timeout cannot run ec_balance")
}
manager.queue.workers["w3"] = &MaintenanceWorker{ID: "w3", Status: "busy", LastHeartbeat: time.Now(), Capabilities: []MaintenanceTaskType{"ec_balance"}}
if !manager.IsTaskTypeEnabled("ec_balance") {
t.Fatal("ec_balance is enabled and a worker can run it")
}
if manager.IsTaskTypeEnabled("vacuum") || manager.IsTaskTypeEnabled("balance") {
t.Fatal("disabled and missing task types are not enabled")
}
}
@@ -925,6 +925,26 @@ func (mq *MaintenanceQueue) GetWorkers() []*MaintenanceWorker {
return workers
}
func (mq *MaintenanceQueue) hasWorkerFor(taskType MaintenanceTaskType, workerTimeout time.Duration) bool {
cutoff := time.Now().Add(-workerTimeout)
mq.mutex.RLock()
defer mq.mutex.RUnlock()
for _, worker := range mq.workers {
if worker.Status != "active" && worker.Status != "busy" {
continue
}
if workerTimeout > 0 && worker.LastHeartbeat.Before(cutoff) {
continue
}
for _, capability := range worker.Capabilities {
if capability == taskType {
return true
}
}
}
return false
}
// GetWorkerSlots returns used/max task slots per worker ID, snapshotted under
// the lock so callers don't read live worker fields that task updates mutate.
// Keyed by ID so callers can merge this registry with the plugin worker
+3 -6
View File
@@ -110,12 +110,9 @@ func TestExecutionFailsWhenWorkerRestartsWithoutJob(t *testing.T) {
t.Fatal("dispatch was not failed after its worker restarted without the job")
}
tracked, ok := p.GetTrackedJob(jobID)
if !ok || tracked == nil {
t.Fatalf("job %s is not tracked", jobID)
}
if tracked.State != StateFailed || tracked.RequestID != requestID {
t.Fatalf("expected request %s failed, got state=%s request=%s", requestID, tracked.State, tracked.RequestID)
// the dispatcher gets the completion before the record is updated
if tracked := waitTrackedState(t, p, jobID, StateFailed); tracked.RequestID != requestID {
t.Fatalf("expected request %s failed, got request %s", requestID, tracked.RequestID)
}
}
Loaded 100 of 676 files, more files were not shown because too many files have changed in this diff. Show more