Compare commits

...
Author SHA1 Message Date
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
332 changed files with 21065 additions and 2358 deletions

No files matched your search

+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
+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)
+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
+1
View File
@@ -384,6 +384,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
+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 -1031
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);
@@ -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]", ""));
}
}
+387 -3
View File
@@ -5458,7 +5458,7 @@
"uid": "${DS_PROMETHEUS}"
},
"title": "EC Shard Copy Failures by reason",
"description": "Rate of failed EC shard copies into each volume server 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.",
"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": {
@@ -5505,7 +5505,7 @@
}
},
"mappings": [],
"unit": "ops",
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
@@ -5540,7 +5540,7 @@
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, collection, reason) (rate(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"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}}"
@@ -7826,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"
}
]
},
+1
View File
@@ -6338,6 +6338,7 @@ dependencies = [
"protoc-bin-vendored",
"reqwest 0.12.28",
"rustls",
"rustls-native-certs",
"seaweed-common",
"thiserror 2.0.21",
"tokio",
+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
+111 -45
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,6 +1063,7 @@ 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.
@@ -1145,48 +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 == "[fips]" {
section = Section::Fips;
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;
}
@@ -1222,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 {
@@ -1290,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.
@@ -1328,8 +1329,26 @@ fn resolve_fips_setting_with_env(
reason: e.to_string(),
});
}
let file_value = parse_security_config_with_env(&path.to_string_lossy(), env).fips_mode;
seaweed_common::fips::resolve(Some(&path), file_value.as_deref(), env)
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> {
@@ -1408,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;
}
@@ -2067,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"
@@ -2083,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]
@@ -2316,6 +2343,24 @@ previous_key = "read-old"
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();
@@ -2332,6 +2377,27 @@ previous_key = "read-old"
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();
+262 -23
View File
@@ -5,6 +5,7 @@ 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,
@@ -168,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!(
@@ -203,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');
@@ -216,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()
@@ -249,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);
@@ -262,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,
@@ -329,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,
@@ -578,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);
@@ -740,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 {
@@ -754,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 {
@@ -774,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
};
@@ -1165,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;
@@ -1189,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();
@@ -1205,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()
}
@@ -1287,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!(
@@ -1302,6 +1539,7 @@ mod tests {
&TlsPolicy::default(),
"",
&[],
&[],
)
.is_err()
);
@@ -1338,6 +1576,7 @@ mod tests {
},
"",
&[],
&[],
)
.is_err()
);
+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)
}
+12 -2
View File
@@ -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!(
@@ -186,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
@@ -449,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
+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(),
}
+156 -1
View File
@@ -51,7 +51,6 @@ fn scrub_mode_label(mode: i32) -> &'static str {
}
}
/// Go formats the id in decimal; fs.verify matches the "needle not found " prefix.
/// 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.
@@ -82,6 +81,7 @@ fn ec_shard_copy_failure_reason(status: &Status) -> &'static str {
}
}
/// 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))
}
@@ -1604,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()))?;
@@ -2007,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
@@ -2367,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 {
@@ -3457,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;
@@ -3927,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 {
@@ -4007,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 {
@@ -4150,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
@@ -4481,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
@@ -6023,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))
}
}
@@ -13375,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]
+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(),
}
+1
View File
@@ -6363,6 +6363,7 @@ dependencies = [
"protoc-bin-vendored",
"reqwest 0.12.28",
"rustls",
"rustls-native-certs",
"rustls-pemfile",
"seaweed-common",
"thiserror 2.0.20",
@@ -17,6 +17,9 @@ 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"
+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();
+194 -34
View File
@@ -238,9 +238,8 @@ impl HttpTransport {
pub fn with_tls(tls: &HttpsTls) -> Result<Self> {
install_crypto_provider();
let builder = reqwest::Client::builder().connect_timeout(VOLUME_CONNECT_TIMEOUT);
let builder = if tls.insecure_skip_verify && seaweed_common::fips::process_mode().is_fips()
{
builder.use_preconfigured_tls(unverified_tls_config(
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()),
)?)
@@ -283,24 +282,31 @@ fn reqwest_tls(builder: reqwest::ClientBuilder, tls: &HttpsTls) -> Result<reqwes
Ok(builder)
}
/// The client configuration for `https.client.insecure_skip_verify` in FIPS
/// mode, on `provider`. reqwest's verifier for that setting advertises its own
/// signature schemes (SHA-1, Ed448) whatever the provider allows, so this one
/// is built here: the server certificate is not checked, but handshake
/// signatures are, with the provider's algorithms, and only its schemes are
/// offered. HTTP/1.1 only, as the volume servers speak it.
fn unverified_tls_config(
tls: &HttpsTls,
provider: Arc<CryptoProvider>,
) -> Result<rustls::ClientConfig> {
let verifier = Arc::new(UnverifiedServer {
provider: provider.clone(),
});
let builder = rustls::ClientConfig::builder_with_provider(provider)
/// 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")?
.dangerous()
.with_custom_certificate_verifier(verifier);
.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)
@@ -315,10 +321,47 @@ fn unverified_tls_config(
_ => bail!("https.client needs both cert and key, or neither"),
};
config.alpn_protocols = vec![b"http/1.1".to_vec()];
config.require_ems = config.require_ems || seaweed_common::tls::require_ems();
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.
@@ -573,31 +616,148 @@ mod tests {
recorder.0.lock().unwrap().clone()
}
#[test]
fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() {
let provider = Arc::new(seaweed_common::tls::provider_for(
/// The provider FIPS mode installs.
fn fips_provider() -> Arc<CryptoProvider> {
Arc::new(seaweed_common::tls::provider_for(
seaweed_common::fips::FipsMode::On,
));
let config = unverified_tls_config(&HttpsTls::default(), provider).unwrap();
let mut offered = offered_schemes(config);
))
}
/// `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 unverified_tls_needs_both_halves_of_the_identity() {
let provider = Arc::new(seaweed_common::tls::provider_for(
seaweed_common::fips::FipsMode::On,
));
let half = HttpsTls {
cert_pem: Some(b"x".to_vec()),
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()
};
assert!(unverified_tls_config(&half, provider).is_err());
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]
+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")
+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)
}
}
+10 -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),
+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)
})
}
+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")
}
}
})
}
}
+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,
})
+58 -3
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]
}
+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)
}
}
+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()
}
+8
View File
@@ -10,6 +10,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -805,6 +806,9 @@ func mergeTrackedStatusIntoDetail(detail *TrackedJob, tracked *TrackedJob) {
if detail.DedupeKey == "" {
detail.DedupeKey = tracked.DedupeKey
}
if detail.VolumeID == 0 {
detail.VolumeID = tracked.VolumeID
}
if detail.Summary == "" {
detail.Summary = tracked.Summary
}
@@ -942,6 +946,7 @@ func (r *Plugin) trackExecutionStart(requestID, workerID string, job *plugin_pb.
tracked.RequestID = requestID
tracked.WorkerID = workerID
tracked.DedupeKey = job.DedupeKey
tracked.VolumeID = pluginworker.ReadUint32Config(job.Parameters, "volume_id", 0)
tracked.Summary = job.Summary
tracked.State = strings.ToLower(plugin_pb.JobState_JOB_STATE_ASSIGNED.String())
tracked.Progress = 0
@@ -962,6 +967,7 @@ func (r *Plugin) trackExecutionStart(requestID, workerID string, job *plugin_pb.
detail.RequestID = requestID
detail.WorkerID = workerID
detail.DedupeKey = job.DedupeKey
detail.VolumeID = trackedSnapshot.VolumeID
detail.Summary = job.Summary
detail.Detail = job.Detail
detail.Parameters = enrichTrackedJobParameters(job.JobType, configValueMapToPlain(job.Parameters))
@@ -1017,6 +1023,7 @@ func (r *Plugin) trackExecutionQueued(job *plugin_pb.JobSpec) {
tracked.JobType = job.JobType
tracked.DedupeKey = job.DedupeKey
tracked.VolumeID = pluginworker.ReadUint32Config(job.Parameters, "volume_id", 0)
tracked.Summary = job.Summary
tracked.State = strings.ToLower(plugin_pb.JobState_JOB_STATE_PENDING.String())
tracked.Progress = 0
@@ -1034,6 +1041,7 @@ func (r *Plugin) trackExecutionQueued(job *plugin_pb.JobSpec) {
detail.JobID = job.JobId
detail.JobType = job.JobType
detail.DedupeKey = job.DedupeKey
detail.VolumeID = trackedSnapshot.VolumeID
detail.Summary = job.Summary
detail.Detail = job.Detail
detail.Parameters = enrichTrackedJobParameters(job.JobType, configValueMapToPlain(job.Parameters))
+45
View File
@@ -170,6 +170,51 @@ func TestTrackExecutionQueuedMarksPendingState(t *testing.T) {
}
}
func TestTrackedJobsKeepVolumeID(t *testing.T) {
t.Parallel()
pluginSvc, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
defer pluginSvc.Shutdown()
pluginSvc.trackExecutionQueued(&plugin_pb.JobSpec{
JobId: "job-ec-17",
JobType: "erasure_coding",
Parameters: map[string]*plugin_pb.ConfigValue{
"volume_id": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 17}},
},
})
pluginSvc.trackExecutionStart("req-1", "worker-a", &plugin_pb.JobSpec{
JobId: "job-vacuum-23",
JobType: "vacuum",
Parameters: map[string]*plugin_pb.ConfigValue{
"volume_id": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: "23"}},
},
}, 1)
pluginSvc.trackExecutionQueued(&plugin_pb.JobSpec{JobId: "job-no-volume", JobType: "iceberg"})
want := map[string]uint32{"job-ec-17": 17, "job-vacuum-23": 23, "job-no-volume": 0}
jobs := pluginSvc.ListTrackedJobs("", "", 0)
if len(jobs) != len(want) {
t.Fatalf("expected %d tracked jobs, got %d", len(want), len(jobs))
}
for _, job := range jobs {
if job.VolumeID != want[job.JobID] {
t.Fatalf("job %s: volume id %d, want %d", job.JobID, job.VolumeID, want[job.JobID])
}
}
detail, found, err := pluginSvc.BuildJobDetail("job-ec-17", 10, 0)
if err != nil || !found || detail.Job == nil {
t.Fatalf("BuildJobDetail: found=%v err=%v", found, err)
}
if detail.Job.VolumeID != 17 {
t.Fatalf("detail volume id %d, want 17", detail.Job.VolumeID)
}
}
func TestHandleJobProgressUpdateCarriesWorkerIDInActivities(t *testing.T) {
t.Parallel()
+3 -1
View File
@@ -90,7 +90,9 @@ var jobTypeLaneMap = map[string]SchedulerLane{
"iceberg_maintenance": LaneIceberg,
// S3 lifecycle management
"s3_lifecycle": LaneLifecycle,
"s3_lifecycle": LaneLifecycle,
"filer_ttl": LaneLifecycle,
"meta_log_purge": LaneLifecycle,
// Lance table maintenance. Without these the job types fall back to the
// default lane, which serialises everything under the cluster admin lock
+1
View File
@@ -44,6 +44,7 @@ type TrackedJob struct {
RequestID string `json:"request_id"`
WorkerID string `json:"worker_id"`
DedupeKey string `json:"dedupe_key,omitempty"`
VolumeID uint32 `json:"volume_id,omitempty"`
Summary string `json:"summary,omitempty"`
Detail string `json:"detail,omitempty"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
+86 -14
View File
@@ -383,6 +383,7 @@ templ Plugin(page string, initialJob string, lane string) {
<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
<h5 class="mb-0"><i class="bi bi-list me-2"></i>Job Queue</h5>
<div class="d-flex gap-2 align-items-center flex-wrap">
<input type="number" min="1" max="4294967295" step="1" autocomplete="off" class="form-control form-control-sm plugin-monitor-volume-filter" placeholder="Volume ID" title="Show only jobs of this volume" style="width: 130px;"/>
<small class="text-muted">States: pending/assigned/running</small>
</div>
</div>
@@ -451,6 +452,7 @@ templ Plugin(page string, initialJob string, lane string) {
<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
<h5 class="mb-0"><i class="bi bi-list-check me-2"></i>Execution Jobs</h5>
<div class="d-flex gap-2 align-items-center flex-wrap">
<input type="number" min="1" max="4294967295" step="1" autocomplete="off" class="form-control form-control-sm plugin-monitor-volume-filter" placeholder="Volume ID" title="Show only jobs and activities of this volume" style="width: 130px;"/>
<select class="form-select form-select-sm" id="plugin-monitor-job-state-filter" style="min-width: 180px;">
<option value="">All States</option>
<option value="assigned">Assigned</option>
@@ -612,6 +614,7 @@ templ Plugin(page string, initialJob string, lane string) {
activeSubTab: 'configuration',
initialNavigationApplied: false,
monitorExecutionJobState: '',
monitorVolumeID: '',
workers: [],
jobs: [],
activities: [],
@@ -622,6 +625,10 @@ templ Plugin(page string, initialJob string, lane string) {
allJobs: [],
allActivities: [],
monitorRowsScope: null,
detectionActivities: [],
detectionRowsScope: null,
monitorRefreshSeq: 0,
monitorCommittedRefreshID: 0,
refreshError: '',
loadedJobType: '',
descriptor: null,
@@ -643,6 +650,24 @@ templ Plugin(page string, initialJob string, lane string) {
return url + sep + 'job_type=' + encodeURIComponent(jobType);
}
function appendVolumeParam(url) {
if (!state.monitorVolumeID) return url;
var sep = url.indexOf('?') === -1 ? '?' : '&';
return url + sep + 'volume_id=' + encodeURIComponent(state.monitorVolumeID);
}
function readMonitorVolumeFilter(input) {
if (input.validity && input.validity.badInput) {
return null;
}
var value = String(input.value || '').trim();
if (!value) {
return '';
}
var volumeID = /^[0-9]+$/.test(value) ? Number(value) : 0;
return volumeID >= 1 && volumeID <= 4294967295 ? String(volumeID) : null;
}
function getCSRFToken() {
var meta = document.querySelector('meta[name="csrf-token"]');
if (!meta) {
@@ -1877,7 +1902,7 @@ templ Plugin(page string, initialJob string, lane string) {
}
var filteredActivities = [];
var activities = Array.isArray(state.activities) ? state.activities : [];
var activities = Array.isArray(state.detectionActivities) ? state.detectionActivities : [];
for (var i = 0; i < activities.length; i++) {
var activity = activities[i] || {};
var jobType = String(activity.job_type || '').trim();
@@ -3102,28 +3127,42 @@ templ Plugin(page string, initialJob string, lane string) {
// The newest 500 rows cluster-wide may hold none of the selected job type on a busy
// cluster, so the job-type sub-tabs fetch their own server-side filtered window.
var scopedJobType = monitorJobTypeScope();
var sameScope = state.monitorRowsScope === scopedJobType;
var scopedVolume = state.monitorVolumeID;
var rowsScope = scopedJobType + '|' + scopedVolume;
var scopedRows = scopedJobType || scopedVolume;
var refreshID = ++state.monitorRefreshSeq;
// A failed request keeps its last rows; the rest still land and the failure is rethrown.
// A failed request keeps the rows committed when this refresh lands; the rest still
// land and the failure is rethrown.
var failure = null;
function keepOnFailure(promise, previous) {
var failed = {};
function keepOnFailure(promise) {
return promise.catch(function(e) {
failure = failure || e;
return previous;
return failed;
});
}
function kept(value, previous) {
return value === failed ? previous : value;
}
var allJobsPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/jobs?limit=500')), state.allJobs);
var allActivitiesPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/activities?limit=500')), state.allActivities);
var jobsPromise = scopedJobType ? keepOnFailure(pluginRequest('GET', appendJobTypeParam(appendLaneParam('/api/plugin/jobs?limit=500'), scopedJobType)), sameScope ? state.jobs : null) : allJobsPromise;
var activitiesPromise = scopedJobType ? keepOnFailure(pluginRequest('GET', appendJobTypeParam(appendLaneParam('/api/plugin/activities?limit=500'), scopedJobType)), sameScope ? state.activities : null) : allActivitiesPromise;
var schedulerPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/scheduler-states')), state.schedulerStates);
var allJobsPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/jobs?limit=500')));
var allActivitiesPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/activities?limit=500')));
var jobsPromise = scopedRows ? keepOnFailure(pluginRequest('GET', appendVolumeParam(appendJobTypeParam(appendLaneParam('/api/plugin/jobs?limit=500'), scopedJobType)))) : allJobsPromise;
var activitiesPromise = scopedRows ? keepOnFailure(pluginRequest('GET', appendVolumeParam(appendJobTypeParam(appendLaneParam('/api/plugin/activities?limit=500'), scopedJobType)))) : allActivitiesPromise;
// Detection scans belong to no job, so the volume filter would hide every one of them.
var detectionActivitiesPromise = activitiesPromise;
if (scopedVolume) {
detectionActivitiesPromise = scopedJobType ? keepOnFailure(pluginRequest('GET', appendJobTypeParam(appendLaneParam('/api/plugin/activities?limit=500'), scopedJobType))) : allActivitiesPromise;
}
var schedulerPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/scheduler-states')));
var schedulerStatusPromise = pluginRequest('GET', appendLaneParam('/api/plugin/scheduler-status'));
var allJobs = await allJobsPromise;
var allActivities = await allActivitiesPromise;
var jobs = await jobsPromise;
var activities = await activitiesPromise;
var detectionActivities = await detectionActivitiesPromise;
var schedulerStates = await schedulerPromise;
var schedulerStatus = null;
try {
@@ -3131,15 +3170,26 @@ templ Plugin(page string, initialJob string, lane string) {
} catch (e) {
schedulerStatus = null;
}
if (monitorJobTypeScope() !== scopedJobType) {
if (monitorJobTypeScope() !== scopedJobType || state.monitorVolumeID !== scopedVolume || refreshID < state.monitorCommittedRefreshID) {
return;
}
state.monitorCommittedRefreshID = refreshID;
var sameScope = state.monitorRowsScope === rowsScope;
allJobs = kept(allJobs, state.allJobs);
allActivities = kept(allActivities, state.allActivities);
jobs = kept(jobs, sameScope ? state.jobs : null);
activities = kept(activities, sameScope ? state.activities : null);
detectionActivities = kept(detectionActivities, state.detectionRowsScope === scopedJobType ? state.detectionActivities : null);
schedulerStates = kept(schedulerStates, state.schedulerStates);
state.allJobs = Array.isArray(allJobs) ? allJobs : [];
state.allActivities = Array.isArray(allActivities) ? allActivities : [];
state.jobs = Array.isArray(jobs) ? jobs : state.allJobs;
state.activities = Array.isArray(activities) ? activities : state.allActivities;
state.monitorRowsScope = scopedJobType;
state.jobs = Array.isArray(jobs) ? jobs : (scopedVolume ? [] : state.allJobs);
state.activities = Array.isArray(activities) ? activities : (scopedVolume ? [] : state.allActivities);
state.monitorRowsScope = rowsScope;
state.detectionActivities = Array.isArray(detectionActivities) ? detectionActivities : state.allActivities;
state.detectionRowsScope = scopedJobType;
state.schedulerStates = Array.isArray(schedulerStates) ? schedulerStates : [];
state.schedulerStatus = schedulerStatus && schedulerStatus.scheduler ? schedulerStatus.scheduler : null;
state.schedulerLock = schedulerStatus && schedulerStatus.lock ? schedulerStatus.lock : null;
@@ -3202,6 +3252,28 @@ templ Plugin(page string, initialJob string, lane string) {
});
}
var monitorVolumeFilters = document.querySelectorAll('.plugin-monitor-volume-filter');
for (var v = 0; v < monitorVolumeFilters.length; v++) {
monitorVolumeFilters[v].addEventListener('change', async function(event) {
var volumeID = readMonitorVolumeFilter(event.target);
if (volumeID !== null) {
state.monitorVolumeID = volumeID;
}
for (var k = 0; k < monitorVolumeFilters.length; k++) {
monitorVolumeFilters[k].value = state.monitorVolumeID;
}
if (volumeID === null) {
notify('Volume ID must be a whole number from 1 to 4294967295', 'warning');
return;
}
try {
await refreshJobsAndActivities();
} catch (refreshErr) {
notify('Monitoring refresh failed: ' + refreshErr.message, 'error');
}
});
}
var expireBtn = document.getElementById('plugin-expire-job-btn');
if (expireBtn) {
expireBtn.addEventListener('click', function() {
+1 -1
View File
@@ -109,7 +109,7 @@ func Plugin(page string, initialJob string, lane string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next scheduled check</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"small text-muted\">Selected Job Type</div><div class=\"fw-semibold\" id=\"plugin-selected-job-type\">-</div></div><div class=\"mb-3\"><div class=\"d-flex justify-content-between align-items-center mb-2\"><h6 class=\"mb-0\">Descriptor</h6><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"plugin-refresh-schema-btn\"><i class=\"bi bi-cloud-download me-1\"></i>Refresh Schema</button></div><div class=\"alert alert-light border\" id=\"plugin-descriptor-summary\">Select a job type to load schema and config.</div></div><div class=\"mb-3\"><h6>Admin Config Form</h6><div id=\"plugin-admin-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No admin form loaded.</div></div></div><div class=\"mb-3\"><h6>Worker Config Form</h6><div id=\"plugin-worker-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No worker form loaded.</div></div></div><div class=\"d-flex flex-wrap gap-2\"><button type=\"button\" class=\"btn btn-primary\" id=\"plugin-save-config-btn\"><i class=\"bi bi-floppy me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"bi bi-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btnLine truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next scheduled check</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"small text-muted\">Selected Job Type</div><div class=\"fw-semibold\" id=\"plugin-selected-job-type\">-</div></div><div class=\"mb-3\"><div class=\"d-flex justify-content-between align-items-center mb-2\"><h6 class=\"mb-0\">Descriptor</h6><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"plugin-refresh-schema-btn\"><i class=\"bi bi-cloud-download me-1\"></i>Refresh Schema</button></div><div class=\"alert alert-light border\" id=\"plugin-descriptor-summary\">Select a job type to load schema and config.</div></div><div class=\"mb-3\"><h6>Admin Config Form</h6><div id=\"plugin-admin-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No admin form loaded.</div></div></div><div class=\"mb-3\"><h6>Worker Config Form</h6><div id=\"plugin-worker-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No worker form loaded.</div></div></div><div class=\"d-flex flex-wrap gap-2\"><button type=\"button\" class=\"btn btn-primary\" id=\"plugin-save-config-btn\"><i class=\"bi bi-floppy me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"bi bi-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btnLine truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+7 -3
View File
@@ -13,6 +13,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
)
@@ -21,7 +22,10 @@ type LockClient struct {
// RequestContext, when set before using the client, supplies per-attempt
// metadata for lock, renewal and unlock RPCs. Generic clients retain their
// existing authority when it is nil.
RequestContext func(context.Context) context.Context
RequestContext func(context.Context) context.Context
// TokenSource supplies per-call filer authorization. A nil source preserves
// the existing anonymous behavior.
TokenSource security.FilerTokenSource
maxLockDuration time.Duration
sleepDuration time.Duration
seedFiler pb.ServerAddress
@@ -436,7 +440,7 @@ func (lock *LiveLock) StopShortLivedLock() error {
defer func() {
atomic.StoreInt32(&lock.isLocked, 0)
}()
return pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
ctx, cancel := context.WithTimeout(context.Background(), lock.lc.lockRpcTimeout)
defer cancel()
if lock.lc.RequestContext != nil {
@@ -495,7 +499,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
previousHostFiler := lock.hostFiler
previousOwner := lock.owner
err = pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
// Bound each attempt: a ring member that is reachable from the masters
// but not from this filer would otherwise block on the connect timeout.
ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)
+167
View File
@@ -2,8 +2,11 @@ package cluster
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net"
"strings"
"sync/atomic"
"testing"
"time"
@@ -11,8 +14,12 @@ import (
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
"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"
)
// The gateway must resolve a lock key to the same primary the filers do,
@@ -323,6 +330,166 @@ func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.L
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
}
type rotatingAuthLockFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
keys []security.SigningKey
authorizations chan int
}
type identityLockFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
seen chan bool
}
func (s *identityLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
md, _ := metadata.FromIncomingContext(ctx)
values := md.Get("authorization")
valid := len(values) == 1 && values[0] == "Bearer caller-identity"
s.seen <- valid
if !valid {
return nil, status.Error(codes.Unauthenticated, "missing caller identity")
}
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
}
func (s *rotatingAuthLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
md, _ := metadata.FromIncomingContext(ctx)
values := md.Get("authorization")
authenticatedBy := -1
if len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) {
for i, key := range s.keys {
if security.IsFilerAdminToken(key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) {
authenticatedBy = i
break
}
}
}
s.authorizations <- authenticatedBy
if authenticatedBy < 0 {
return nil, status.Error(codes.Unauthenticated, "missing or invalid filer authorization")
}
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
}
func lockTestSigningKey(t *testing.T) security.SigningKey {
t.Helper()
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
t.Fatal(err)
}
return security.SigningKey(hex.EncodeToString(bytes))
}
func TestLockClientResolvesFilerTokenForEachAttempt(t *testing.T) {
keys := []security.SigningKey{lockTestSigningKey(t), lockTestSigningKey(t)}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
filer := &rotatingAuthLockFiler{keys: keys, authorizations: make(chan int, 2)}
grpcServer := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(grpcServer, filer)
go grpcServer.Serve(listener)
defer grpcServer.Stop()
host, port, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
t.Fatalf("split host port: %v", err)
}
lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
var tokenNumber uint64
lc.TokenSource = func(context.Context) (security.EncodedJwt, error) {
n := atomic.AddUint64(&tokenNumber, 1)
return security.GenJwtForFilerAdmin(keys[(n-1)%uint64(len(keys))], 60), nil
}
lock := lc.NewShortLivedLock("test-key", "test-owner")
if lock == nil {
t.Fatal("expected the lock to be acquired")
}
if err := lock.AttemptToLock(time.Second); err != nil {
t.Fatalf("renew lock: %v", err)
}
first := <-filer.authorizations
second := <-filer.authorizations
if first < 0 || second < 0 {
t.Fatal("expected authorization on both attempts")
}
if first == second {
t.Fatal("expected a freshly resolved token on renewal")
}
}
func TestLockClientTokenSourceErrorDoesNotDispatch(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
filer := &rotatingAuthLockFiler{authorizations: make(chan int, 1)}
grpcServer := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(grpcServer, filer)
go grpcServer.Serve(listener)
defer grpcServer.Stop()
host, port, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
t.Fatalf("split host port: %v", err)
}
lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
lc.TokenSource = func(context.Context) (security.EncodedJwt, error) {
return "", fmt.Errorf("token source unavailable")
}
lock := &LiveLock{
key: "test-key",
hostFiler: lc.seedFiler,
grpcDialOption: lc.grpcDialOption,
lc: lc,
}
if _, _, err := lock.doLock(time.Second, time.Second); err == nil {
t.Fatal("expected token-source error")
}
select {
case <-filer.authorizations:
t.Fatal("token-source error dispatched a filer RPC")
case <-time.After(100 * time.Millisecond):
}
}
func TestLockClientNilTokenSourcePreservesRequestContext(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
filer := &identityLockFiler{seen: make(chan bool, 1)}
grpcServer := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(grpcServer, filer)
go grpcServer.Serve(listener)
defer grpcServer.Stop()
host, port, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
t.Fatalf("split host port: %v", err)
}
lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
lc.RequestContext = func(ctx context.Context) context.Context {
return metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer caller-identity")
}
lock := lc.NewShortLivedLock("test-key", "test-owner")
if lock == nil {
t.Fatal("expected the existing caller identity to acquire the lock")
}
select {
case valid := <-filer.seen:
if !valid {
t.Fatal("existing caller identity was not preserved")
}
case <-time.After(time.Second):
t.Fatal("filer did not receive the request")
}
}
// A ring member that accepts connections but never answers must not swallow
// the retry window: when its budget is spent the seed route still gets an
// attempt before acquisition gives up.
@@ -6,6 +6,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
const RenewInterval = time.Second * 3
@@ -21,51 +22,71 @@ type ReplicateFunc func(server pb.ServerAddress, key string, expiredAtNs int64,
type DistributedLockManager struct {
lockManager *LockManager
mutations *util.LockTable[string]
LockRing *LockRing
Host pb.ServerAddress
ReplicateFn ReplicateFunc // set by filer server after creation
// TransferFn waits for the receiver; an error may still mean it committed.
TransferFn func(pb.ServerAddress, *Lock) error
// RetryTransferFn enqueues work without waiting for this key gate.
RetryTransferFn func(string)
// Tests set this before concurrent use, to observe admission contention.
onMutationWait func(string)
}
func NewDistributedLockManager(host pb.ServerAddress) *DistributedLockManager {
return &DistributedLockManager{
lockManager: NewLockManager(),
mutations: util.NewLockTable[string](),
LockRing: NewLockRing(time.Second * 5),
Host: host,
}
}
func (dlm *DistributedLockManager) acquireMutation(key string) *util.ActiveLock {
if mutation, ok := dlm.mutations.TryAcquireLock("lock mutation", key, util.ExclusiveLock); ok {
return mutation
}
if dlm.onMutationWait != nil {
dlm.onMutationWait(key)
}
return dlm.mutations.AcquireLock("lock mutation", key, util.ExclusiveLock)
}
func (dlm *DistributedLockManager) LockWithTimeout(key string, expiredAtNs int64, token string, owner string) (lockOwner string, renewToken string, generation int64, movedTo pb.ServerAddress, err error) {
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
if primary == "" {
err = NoLockServerError
mutation := dlm.acquireMutation(key)
defer dlm.mutations.ReleaseLock(key, mutation)
if movedTo, err = dlm.serverLocked(key); err != nil || movedTo != "" {
return
}
if primary != dlm.Host {
// If this is a renewal (non-empty token) and we still hold the lock locally,
// serve it here rather than redirecting. This handles the window between
// ring update and lock transfer completion — the old primary remains
// authoritative for locks it still holds.
if token != "" {
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && (lock.Token == token || lock.PrevToken == token) {
var seq int64
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
if err == nil && renewToken != "" {
dlm.replicateToBackup(key, expiredAtNs, renewToken, token, owner, generation, seq, false)
}
return
}
}
movedTo = primary
return
}
var seq int64
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
var seq, leaseExpires int64
lockOwner, renewToken, generation, seq, leaseExpires, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
if err == nil && renewToken != "" {
dlm.replicateToBackup(key, expiredAtNs, renewToken, token, owner, generation, seq, false)
dlm.replicateToBackup(key, leaseExpires, renewToken, token, owner, generation, seq, false)
}
return
}
// serverLocked runs under key's mutation gate. It returns the primary to
// forward to, or "" when this node serves key. The new owner must receive any
// local lease first, since only it can rotate the renewal token; this holds
// even when a request wins admission before the topology callback.
func (dlm *DistributedLockManager) serverLocked(key string) (movedTo pb.ServerAddress, err error) {
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
if primary != "" && primary != dlm.Host {
if primary, err = dlm.transferToOwnerLocked(key); err != nil {
return "", err
}
}
if primary == "" {
return "", NoLockServerError
}
if primary == dlm.Host {
return "", nil
}
return primary, nil
}
func (dlm *DistributedLockManager) FindLockOwner(key string) (owner string, movedTo pb.ServerAddress, err error) {
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
if primary == "" {
@@ -88,32 +109,14 @@ func (dlm *DistributedLockManager) FindLockOwner(key string) (owner string, move
}
func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.ServerAddress, err error) {
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
if primary == "" {
err = NoLockServerError
mutation := dlm.acquireMutation(key)
defer dlm.mutations.ReleaseLock(key, mutation)
if movedTo, err = dlm.serverLocked(key); err != nil || movedTo != "" {
return
}
if primary != dlm.Host {
// If we still hold this lock locally, serve the unlock here
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && token != "" && (lock.Token == token || lock.PrevToken == token) {
var isUnlocked bool
var generation int64
var seq int64
isUnlocked, generation, seq, err = dlm.lockManager.Unlock(key, token)
if isUnlocked {
dlm.replicateToBackup(key, 0, "", "", "", generation, seq, true)
}
return
}
movedTo = primary
return
}
var isUnlocked bool
var generation int64
var seq int64
isUnlocked, generation, seq, err = dlm.lockManager.Unlock(key, token)
if isUnlocked {
dlm.replicateToBackup(key, 0, "", "", "", generation, seq, true)
released, err := dlm.lockManager.Unlock(key, token)
if released != nil {
dlm.replicateToBackup(key, released.ExpiredAtNs, released.Token, "", released.Owner, released.Generation, released.Seq, true)
}
return
}
@@ -122,8 +125,8 @@ func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.
// It is used when a server is down and the lock is moved to another server.
// After inserting, it replicates to the backup for this key.
func (dlm *DistributedLockManager) InsertLock(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
if dlm.lockManager.InsertLock(key, expiredAtNs, token, prevToken, owner, generation, seq) {
dlm.replicateToBackup(key, expiredAtNs, token, prevToken, owner, generation, seq, false)
if effectiveExpiry, accepted := dlm.lockManager.InsertLock(key, expiredAtNs, token, prevToken, owner, generation, seq); accepted {
dlm.replicateToBackup(key, effectiveExpiry, token, prevToken, owner, generation, seq, false)
}
}
@@ -137,9 +140,9 @@ func (dlm *DistributedLockManager) RemoveBackupLock(key string) {
dlm.lockManager.RemoveLock(key)
}
// RemoveBackupLockIfSeq removes a local copy only if the incoming mutation is not older.
func (dlm *DistributedLockManager) RemoveBackupLockIfSeq(key string, generation int64, seq int64) {
dlm.lockManager.RemoveBackupLockIfSeq(key, generation, seq)
// RemoveBackupLockIfSeq records a release and removes only the matching lease.
func (dlm *DistributedLockManager) RemoveBackupLockIfSeq(key string, generation int64, seq int64, token string, expiredAtNs int64) {
dlm.lockManager.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
}
func (dlm *DistributedLockManager) SelectNotOwnedLocks(servers []pb.ServerAddress) (locks []*Lock) {
@@ -180,6 +183,70 @@ func (dlm *DistributedLockManager) GetLock(key string) (*Lock, bool) {
return dlm.lockManager.GetLock(key)
}
// TransferLockToOwner serializes a fresh snapshot and handoff with local
// mutations. Incoming replication bypasses admission so the receiver can
// replicate back. The retry worker also calls it without a ring change.
func (dlm *DistributedLockManager) TransferLockToOwner(key string) error {
mutation := dlm.acquireMutation(key)
defer dlm.mutations.ReleaseLock(key, mutation)
_, err := dlm.transferToOwnerLocked(key)
return err
}
// transferToOwnerLocked returns the primary that owns the lease afterwards.
func (dlm *DistributedLockManager) transferToOwnerLocked(key string) (owner pb.ServerAddress, err error) {
defer func() {
if err != nil && dlm.RetryTransferFn != nil {
dlm.RetryTransferFn(key)
}
}()
primary, backup := dlm.LockRing.GetPrimaryAndBackup(key)
current, found := dlm.lockManager.GetLock(key)
if !found {
return primary, nil
}
if primary == "" {
return "", NoLockServerError
}
if primary == dlm.Host {
if current.handoff {
dlm.lockManager.PromoteLock(key)
}
return primary, nil
}
if current.IsBackup && !current.handoff && backup == dlm.Host {
return primary, nil
}
if dlm.TransferFn == nil {
return "", LockHandoffPending
}
transferred, found := dlm.lockManager.beginTransfer(key)
if !found {
return primary, nil
}
// On error keep the frozen copy: the receiver may have committed.
if err = dlm.TransferFn(primary, transferred); err != nil {
return primary, fmt.Errorf("%w: %w", LockHandoffPending, err)
}
// Background retries can overlap a newer topology callback. Never evict
// a lease now owned here or discard it before its newest owner receives it.
currentPrimary, currentBackup := dlm.LockRing.GetPrimaryAndBackup(key)
if currentPrimary == dlm.Host {
dlm.lockManager.PromoteLock(key)
} else if currentPrimary == primary {
dlm.lockManager.finishTransfer(key, transferred.Token, currentBackup == dlm.Host)
} else {
return "", LockHandoffPending
}
return currentPrimary, nil
}
// ReplicateLock sends an existing lease to its current backup after a topology
// change, recording that the local lease may now have a remote copy.
func (dlm *DistributedLockManager) ReplicateLock(lock *Lock) {
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq, false)
}
// replicateToBackup asynchronously replicates a lock operation to the backup server
func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
_, backup := dlm.LockRing.GetPrimaryAndBackup(key)
@@ -187,6 +254,9 @@ func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int
return // single-server deployment, no backup
}
if dlm.ReplicateFn != nil {
if !isUnlock && !dlm.lockManager.markReplicated(key, token) {
return
}
go dlm.ReplicateFn(backup, key, expiredAtNs, token, prevToken, owner, generation, seq, isUnlock)
}
}
@@ -33,6 +33,7 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
// Wire up replication: each node's ReplicateFn calls the backup's DLM directly
for _, dlm := range c.nodes {
d := dlm // capture
d.TransferFn = c.transferLease
d.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
c.mu.Lock()
target, ok := c.nodes[server]
@@ -41,7 +42,7 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
return // server is down
}
if isUnlock {
target.RemoveBackupLockIfSeq(key, generation, seq)
target.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
} else {
target.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
}
@@ -51,6 +52,17 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
return c
}
func (c *testCluster) transferLease(server pb.ServerAddress, lock *Lock) error {
c.mu.Lock()
target := c.nodes[server]
c.mu.Unlock()
if target == nil {
return fmt.Errorf("handoff target %s is down", server)
}
target.InsertLock(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq)
return nil
}
func (c *testCluster) removeNode(host pb.ServerAddress) {
c.mu.Lock()
delete(c.nodes, host)
@@ -70,6 +82,7 @@ func (c *testCluster) addNode(host pb.ServerAddress) {
c.mu.Unlock()
// Wire up replication
dlm.TransferFn = c.transferLease
dlm.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
c.mu.Lock()
target, ok := c.nodes[server]
@@ -78,7 +91,7 @@ func (c *testCluster) addNode(host pb.ServerAddress) {
return
}
if isUnlock {
target.RemoveBackupLockIfSeq(key, generation, seq)
target.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
} else {
target.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
}
@@ -630,7 +643,7 @@ func TestDLM_NodeDropAndJoin_OwnershipDisruption(t *testing.T) {
func TestDLM_RenewalDuringTransferWindow(t *testing.T) {
// When a new node joins and steals a key range from a surviving node,
// there's a window between ring update and lock transfer. During this
// window, a client renewal should still succeed on the old primary
// window, a client renewal through the old primary should hand off and redirect
// (because it still holds the lock locally).
hosts := []pb.ServerAddress{"filer1:8888", "filer2:8888", "filer3:8888"}
cluster := newTestCluster(hosts...)
@@ -664,11 +677,13 @@ func TestDLM_RenewalDuringTransferWindow(t *testing.T) {
newPrimary := cluster.get(primaryHost).LockRing.GetPrimary(key)
require.NotEqual(t, primaryHost, newPrimary, "key should have moved to a different primary")
// Renewal on the OLD primary should still succeed because it holds the lock locally
// Renewal through the old primary hands the lease off, then follows the redirect.
newToken, _, err := cluster.renewLock(key, "owner1", renewToken, 30*time.Second, primaryHost)
require.NoError(t, err, "renewal on old primary should succeed during transfer window")
assert.NotEmpty(t, newToken, "should get a new token from old primary")
t.Logf("Key %s: primary changed from %s to %s, but renewal on old primary succeeded", key, primaryHost, newPrimary)
assert.NotEmpty(t, newToken, "should get a new token from the new primary")
installed, found := cluster.get(newPrimary).GetLock(key)
require.True(t, found)
require.Equal(t, newToken, installed.Token, "the new primary must issue the renewal")
}
func TestDLM_ReplayedRenewalExtendsBackupExpiry(t *testing.T) {
@@ -767,13 +782,13 @@ func TestDLM_StaleReplicationRejected(t *testing.T) {
assert.Equal(t, int64(4), lock.Seq)
// Stale unlock (seq=2) should not delete the lock
removed := lm.RemoveBackupLockIfSeq("key1", 1, 2)
removed := lm.RemoveBackupLockIfSeq("key1", 1, 2, "token-newer", time.Now().Add(30*time.Second).UnixNano())
assert.False(t, removed, "stale unlock should be rejected")
_, found = lm.GetLock("key1")
assert.True(t, found, "lock should still exist after stale unlock")
// Valid unlock (seq=5) should delete
removed = lm.RemoveBackupLockIfSeq("key1", 1, 5)
removed = lm.RemoveBackupLockIfSeq("key1", 1, 5, "token-newer", time.Now().Add(30*time.Second).UnixNano())
assert.True(t, removed, "valid unlock should be accepted")
_, found = lm.GetLock("key1")
assert.False(t, found, "lock should be removed after valid unlock")
@@ -0,0 +1,253 @@
package lock_manager
import (
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/stretchr/testify/require"
)
func TestDLM_TransferLockUsesFreshSnapshot(t *testing.T) {
dlm := NewDistributedLockManager("handoff:8888")
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
expires := time.Now().Add(time.Minute).UnixNano()
_, original, _, _, err := dlm.LockWithTimeout("key", expires, "", "owner")
require.NoError(t, err)
// A topology callback may have enumerated this key before its renewal.
_, renewed, _, _, err := dlm.LockWithTimeout("key", expires, original, "owner")
require.NoError(t, err)
require.NoError(t, handOff(t, dlm, "key", true, func(current *Lock) error {
require.Equal(t, renewed, current.Token)
require.EqualValues(t, 2, current.Seq)
// The receiver can replicate the lease back before acknowledging.
within(t, "incoming replication during the handoff", func() {
dlm.InsertBackupLock(current.Key, current.ExpiredAtNs, current.Token, current.PrevToken, current.Owner, current.Generation, current.Seq)
})
return nil
}))
current, found := dlm.GetLock("key")
require.True(t, found)
require.True(t, current.IsBackup)
require.Equal(t, renewed, current.Token)
}
func TestDLM_TransferLockFailureFreezesAuthority(t *testing.T) {
dlm := NewDistributedLockManager("handoff:8888")
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
expires := time.Now().Add(time.Minute).UnixNano()
_, token, _, _, err := dlm.LockWithTimeout("key", expires, "", "owner")
require.NoError(t, err)
failed := errors.New("handoff failed")
target := NewDistributedLockManager("target:8888")
target.LockRing.SetSnapshot([]pb.ServerAddress{target.Host}, 1)
require.ErrorIs(t, handOff(t, dlm, "key", false, func(current *Lock) error {
// The receiver committed, but its acknowledgement was lost.
target.InsertLock(current.Key, current.ExpiredAtNs, current.Token, current.PrevToken, current.Owner, current.Generation, current.Seq)
// A stalled handoff must not hold a global mutex across its RPC.
var err error
within(t, "another key during the stalled handoff", func() {
_, _, _, _, err = dlm.LockWithTimeout("other-key", expires, "", "other-owner")
})
require.NoError(t, err)
return failed
}), failed)
// Back on the old ring, the frozen local copy itself must refuse.
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, dlm.LockRing.Version()+1)
current, found := dlm.GetLock("key")
require.True(t, found)
require.True(t, current.IsBackup)
_, renewed, _, _, err := dlm.LockWithTimeout("key", expires, token, "owner")
require.ErrorIs(t, err, LockHandoffPending)
require.Empty(t, renewed, "an ambiguous handoff cannot retain renewal authority")
_, renewed, _, _, err = target.LockWithTimeout("key", expires, token, "owner")
require.NoError(t, err)
require.NotEmpty(t, renewed)
require.NotEqual(t, token, renewed)
_, err = dlm.Unlock("key", token)
require.ErrorIs(t, err, LockHandoffPending)
}
func TestDLM_TransferCompletionPreservesDifferentLease(t *testing.T) {
for _, keepBackup := range []bool{false, true} {
t.Run(fmt.Sprint(keepBackup), func(t *testing.T) {
dlm := NewDistributedLockManager("handoff:8888")
expires := time.Now().Add(time.Minute).UnixNano()
dlm.InsertLock("key", expires, "original/secret", "", "owner", 1, 1)
require.NoError(t, handOff(t, dlm, "key", keepBackup, func(*Lock) error {
// Incoming replication is independent of client admission.
dlm.InsertLock("key", expires, "replacement/secret", "", "new-owner", 2, 1)
return nil
}))
current, found := dlm.GetLock("key")
require.True(t, found)
require.Equal(t, "replacement/secret", current.Token)
require.False(t, current.IsBackup, "completion must not demote a different lease")
})
}
}
// Confirm actual same-key admission contention, rather than inferring it from
// a goroutine start or a sleep in the RPC test.
func TestDLM_UnlockWaitsForHandoffAdmission(t *testing.T) {
source := NewDistributedLockManager("source:8888")
target := NewDistributedLockManager("target:8888")
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, 1)
expires := time.Now().Add(time.Minute).UnixNano()
_, token, _, _, err := source.LockWithTimeout("key", expires, "", "owner")
require.NoError(t, err)
source.LockRing.SetSnapshot([]pb.ServerAddress{target.Host}, 2)
entered, proceed := make(chan struct{}), make(chan struct{})
waiting := make(chan struct{})
source.onMutationWait = func(key string) {
if key == "key" {
close(waiting)
}
}
var unblockOnce sync.Once
unblock := func() { unblockOnce.Do(func() { close(proceed) }) }
defer unblock()
source.TransferFn = func(_ pb.ServerAddress, lock *Lock) error {
close(entered)
<-proceed
target.InsertLock(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq)
return nil
}
transferred := make(chan error, 1)
go func() { transferred <- source.TransferLockToOwner("key") }()
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("handoff did not start")
}
released := make(chan pb.ServerAddress, 1)
go func() { moved, _ := source.Unlock("key", token); released <- moved }()
select {
case <-waiting:
case <-time.After(5 * time.Second):
t.Fatal("unlock did not reach contended admission")
}
select {
case <-released:
t.Fatal("unlock bypassed the handoff gate")
default:
}
unblock()
select {
case err := <-transferred:
require.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatal("handoff did not finish")
}
select {
case moved := <-released:
require.Equal(t, target.Host, moved)
case <-time.After(5 * time.Second):
t.Fatal("unlock did not finish after the handoff")
}
}
func TestDLM_HandoffCompletionRechecksOwner(t *testing.T) {
for _, next := range []pb.ServerAddress{"source:8888", "third:8888"} {
t.Run(string(next), func(t *testing.T) {
source := NewDistributedLockManager("source:8888")
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, 1)
_, _, _, _, err := source.LockWithTimeout("key", time.Now().Add(time.Minute).UnixNano(), "", "owner")
require.NoError(t, err)
source.LockRing.SetSnapshot([]pb.ServerAddress{"target:8888"}, 2)
var destination pb.ServerAddress
var retries int
source.RetryTransferFn = func(key string) { require.Equal(t, "key", key); retries++ }
source.TransferFn = func(to pb.ServerAddress, _ *Lock) error {
destination = to
source.LockRing.SetSnapshot([]pb.ServerAddress{next}, 3)
return nil
}
err = source.TransferLockToOwner("key")
current, found := source.GetLock("key")
require.True(t, found, "an old handoff cannot discard the newest owner's lease")
if next == source.Host {
require.NoError(t, err)
require.False(t, current.IsBackup)
} else {
require.ErrorIs(t, err, LockHandoffPending)
require.Equal(t, 1, retries)
require.NoError(t, source.TransferLockToOwner("key"))
require.Equal(t, next, destination)
_, found = source.GetLock("key")
require.False(t, found)
}
})
}
}
func TestDLM_ServesLocallyWhenHandoffEndsHere(t *testing.T) {
source := NewDistributedLockManager("source:8888")
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, 1)
expires := time.Now().Add(time.Minute).UnixNano()
_, token, _, _, err := source.LockWithTimeout("key", expires, "", "owner")
require.NoError(t, err)
version := int64(1)
source.TransferFn = func(pb.ServerAddress, *Lock) error {
version++
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, version)
return nil
}
moveAway := func() {
version++
source.LockRing.SetSnapshot([]pb.ServerAddress{"target:8888"}, version)
}
moveAway()
_, renewed, _, movedTo, err := source.LockWithTimeout("key", expires, token, "owner")
require.NoError(t, err)
require.Empty(t, movedTo, "the ring moved back here during the handoff")
require.NotEqual(t, token, renewed)
moveAway()
movedTo, err = source.Unlock("key", renewed)
require.NoError(t, err)
require.Empty(t, movedTo)
_, found := source.GetLock("key")
require.False(t, found)
}
// handOff moves key away from dlm and sends it through transfer. With
// keepBackup, dlm stays in the ring as the key's backup.
func handOff(t *testing.T, dlm *DistributedLockManager, key string, keepBackup bool, transfer func(*Lock) error) error {
t.Helper()
moveAway(t, dlm, key, keepBackup)
dlm.TransferFn = func(_ pb.ServerAddress, lock *Lock) error { return transfer(lock) }
return dlm.TransferLockToOwner(key)
}
func moveAway(t *testing.T, dlm *DistributedLockManager, key string, keepBackup bool) {
t.Helper()
for i := 0; i < 100; i++ {
servers := []pb.ServerAddress{pb.ServerAddress(fmt.Sprintf("target-%d:8888", i))}
if keepBackup {
servers = append(servers, dlm.Host)
}
dlm.LockRing.SetSnapshot(servers, dlm.LockRing.Version()+1)
if primary, backup := dlm.LockRing.GetPrimaryAndBackup(key); primary != dlm.Host && (backup == dlm.Host) == keepBackup {
return
}
}
t.Fatalf("no ring moves %s away from %s", key, dlm.Host)
}
// within fails the test if fn has not returned after five seconds.
func within(t *testing.T, what string, fn func()) {
t.Helper()
done := make(chan struct{})
go func() {
defer close(done)
fn()
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatalf("%s did not finish", what)
}
}
+199 -84
View File
@@ -2,6 +2,7 @@ package lock_manager
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
@@ -15,13 +16,33 @@ var LockErrorNonEmptyTokenOnExpiredLock = fmt.Errorf("lock: non-empty token on a
var LockErrorTokenMismatch = fmt.Errorf("lock: token mismatch")
var UnlockErrorTokenMismatch = fmt.Errorf("unlock: token mismatch")
var LockNotFound = fmt.Errorf("lock not found")
var LockHandoffPending = fmt.Errorf("lock handoff pending")
// LockManager local lock manager, used by distributed lock manager
type LockManager struct {
locks map[string]*Lock
locks map[string]*Lock
// Released lease identities are retained only until their maximum expiry.
removed map[releasedLease]int64
accessLock sync.RWMutex
nextGeneration atomic.Int64
}
type releasedLease struct{ path, id string }
// Tokens are opaque to clients. Keep a stable acquisition ID while rotating the
// secret on renewal; local generation counters can overlap across primaries.
func leaseID(token string) string {
id, _, _ := strings.Cut(token, "/")
return id
}
func newLockToken(previous string) string {
id := leaseID(previous)
if id == "" {
id = uuid.New().String()
}
return id + "/" + uuid.New().String()
}
type Lock struct {
Token string
PrevToken string // token superseded by the latest renewal; a holder whose renewal response was lost still presents it
@@ -31,6 +52,8 @@ type Lock struct {
IsBackup bool // true if this node holds the lock as a backup
Generation int64 // monotonic fencing token, increments on fresh acquisition
Seq int64 // per-lock sequence number, increments on every mutation (acquire/renew/unlock)
replicated bool // a copy may exist elsewhere, requiring a release record
handoff bool // renewal authority has moved, but delivery may need retry
}
func NewLockManager() *LockManager {
@@ -72,13 +95,37 @@ func (lm *LockManager) advanceGenerationFloor(generation int64) {
}
}
func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner string) (lockOwner, renewToken string, generation int64, seq int64, err error) {
// rememberRemoval runs under accessLock. Delayed messages for this lease are
// rejected until its maximum expiry, after which inserts reject them as expired.
func (lm *LockManager) rememberRemoval(path, token string, expiredAtNs int64) {
if token == "" || expiredAtNs <= time.Now().UnixNano() {
return
}
if lm.removed == nil {
lm.removed = make(map[releasedLease]int64)
}
key := releasedLease{path, leaseID(token)}
lm.removed[key] = max(lm.removed[key], expiredAtNs)
}
func (lm *LockManager) wasRemoved(path, token string) bool {
return lm.removed[releasedLease{path, leaseID(token)}] > time.Now().UnixNano()
}
// Lock also returns the effective expiry for replication. Renewals cannot
// shorten it, so a release carries a validity bound for every older RPC.
func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner string) (lockOwner, renewToken string, generation int64, seq int64, leaseExpires int64, err error) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
leaseExpires = expiredAtNs
glog.V(4).Infof("lock %s %v %v %v", path, time.Unix(0, expiredAtNs), token, owner)
if oldValue, found := lm.locks[path]; found {
if oldValue.handoff && oldValue.ExpiredAtNs > time.Now().UnixNano() {
err = LockHandoffPending
return
}
if oldValue.ExpiredAtNs > 0 && oldValue.ExpiredAtNs < time.Now().UnixNano() {
// lock is expired, set to a new lock
if token != "" {
@@ -87,7 +134,7 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
return
} else {
// new lock
renewToken = uuid.New().String()
renewToken = newLockToken("")
generation = lm.NextGeneration()
seq = 1
glog.V(4).Infof("key %s new token %v owner %v generation %d", path, renewToken, owner, generation)
@@ -96,14 +143,15 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
}
}
// not expired
leaseExpires = max(expiredAtNs, oldValue.ExpiredAtNs)
lockOwner = oldValue.Owner
if oldValue.Token == token {
// token matches, renew the lock
renewToken = uuid.New().String()
renewToken = newLockToken(oldValue.Token)
generation = oldValue.Generation // keep same generation on renewal
seq = oldValue.Seq + 1
glog.V(4).Infof("key %s old token %v owner %v => %v owner %v", path, oldValue.Token, oldValue.Owner, renewToken, owner)
lm.locks[path] = &Lock{Token: renewToken, PrevToken: oldValue.Token, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
lm.locks[path] = &Lock{Token: renewToken, PrevToken: oldValue.Token, ExpiredAtNs: leaseExpires, Owner: owner, Generation: generation, Seq: seq, replicated: oldValue.replicated}
return
}
if token != "" && token == oldValue.PrevToken && owner == oldValue.Owner {
@@ -113,7 +161,7 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
renewToken = oldValue.Token
generation = oldValue.Generation
seq = oldValue.Seq + 1
oldValue.ExpiredAtNs = expiredAtNs
oldValue.ExpiredAtNs = leaseExpires
oldValue.Seq = seq
return
}
@@ -130,7 +178,7 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
glog.V(4).Infof("key %s no lock owner %v", path, owner)
if token == "" {
// new lock
renewToken = uuid.New().String()
renewToken = newLockToken("")
generation = lm.NextGeneration()
seq = 1
glog.V(4).Infof("key %s new token %v owner %v generation %d", path, renewToken, owner, generation)
@@ -144,55 +192,60 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
}
}
func (lm *LockManager) Unlock(path string, token string) (isUnlocked bool, generation int64, seq int64, err error) {
// Unlock returns the released lease and its maximum expiry atomically, including
// when the caller uses a superseded token after losing a renewal response.
func (lm *LockManager) Unlock(path, token string) (*Lock, error) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if oldValue, found := lm.locks[path]; found {
now := time.Now()
if oldValue.ExpiredAtNs > 0 && oldValue.ExpiredAtNs < now.UnixNano() {
// lock is expired, delete it
isUnlocked = true
generation = oldValue.Generation
seq = oldValue.Seq + 1
glog.V(4).Infof("key %s expired at %v", path, time.Unix(0, oldValue.ExpiredAtNs))
delete(lm.locks, path)
return
}
if oldValue.Token == token || (token != "" && token == oldValue.PrevToken) {
isUnlocked = true
generation = oldValue.Generation
seq = oldValue.Seq + 1
glog.V(4).Infof("key %s unlocked with %v", path, token)
delete(lm.locks, path)
return
} else {
isUnlocked = false
err = UnlockErrorTokenMismatch
return
}
old, found := lm.locks[path]
if !found {
return nil, LockNotFound
}
err = LockNotFound
return
if old.handoff {
return nil, LockHandoffPending
}
expired := old.ExpiredAtNs > 0 && old.ExpiredAtNs < time.Now().UnixNano()
if !expired && old.Token != token && (token == "" || token != old.PrevToken) {
return nil, UnlockErrorTokenMismatch
}
if expired {
glog.V(4).Infof("key %s expired at %v", path, time.Unix(0, old.ExpiredAtNs))
} else {
glog.V(4).Infof("key %s unlocked with %v", path, token)
}
released := *old
released.Seq++
if released.replicated {
lm.rememberRemoval(path, released.Token, released.ExpiredAtNs)
}
delete(lm.locks, path)
return &released, nil
}
func (lm *LockManager) CleanUp() {
for {
time.Sleep(1 * time.Minute)
now := time.Now().UnixNano()
time.Sleep(time.Minute)
lm.cleanUp(time.Now().UnixNano())
}
}
lm.accessLock.Lock()
for key, value := range lm.locks {
if value == nil {
continue
}
if now > value.ExpiredAtNs {
glog.V(4).Infof("key %s expired at %v", key, time.Unix(0, value.ExpiredAtNs))
delete(lm.locks, key)
}
func (lm *LockManager) cleanUp(now int64) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
for key, lock := range lm.locks {
if lock != nil && now >= lock.ExpiredAtNs {
glog.V(4).Infof("key %s expired at %v", key, time.Unix(0, lock.ExpiredAtNs))
delete(lm.locks, key)
}
lm.accessLock.Unlock()
}
for key, expires := range lm.removed {
if now >= expires {
delete(lm.removed, key)
}
}
if len(lm.removed) == 0 {
lm.removed = nil
}
}
@@ -220,20 +273,15 @@ func (lm *LockManager) SelectLocks(selectFn func(key string) bool) (locks []*Loc
return
}
// InsertLock inserts a lock from a transfer if it is newer than the current state.
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) bool {
// InsertLock inserts a lock from a transfer if it is newer than the current
// state, returning the effective expiry atomically with installation.
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) (leaseExpires int64, accepted bool) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if existing, found := lm.locks[path]; found {
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
glog.V(4).Infof("lock %s: rejecting stale transfer gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
return false
}
if lock := lm.insertCopyLocked(path, expiredAtNs, token, prevToken, owner, generation, seq, false); lock != nil {
return lock.ExpiredAtNs, true
}
lm.locks[path] = &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
lm.advanceGenerationFloor(generation)
return true
return 0, false
}
// InsertBackupLock inserts or updates a lock as a backup copy.
@@ -243,50 +291,115 @@ func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string,
func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lm.insertCopyLocked(path, expiredAtNs, token, prevToken, owner, generation, seq, true)
}
if existing, found := lm.locks[path]; found {
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
glog.V(4).Infof("backup lock %s: rejecting stale gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
return
}
lm.locks[path] = &Lock{
Token: token,
PrevToken: prevToken,
ExpiredAtNs: expiredAtNs,
Owner: owner,
IsBackup: existing.IsBackup,
Generation: generation,
Seq: seq,
}
lm.advanceGenerationFloor(generation)
return
// insertCopyLocked runs under accessLock. It rejects a copy that is expired,
// released, or not newer than the live lock, and never shortens the same lease.
func (lm *LockManager) insertCopyLocked(path string, expiredAtNs int64, token, prevToken, owner string, generation, seq int64, asBackup bool) *Lock {
now := time.Now().UnixNano()
if expiredAtNs <= now || lm.wasRemoved(path, token) {
return nil
}
lm.locks[path] = &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: true, Generation: generation, Seq: seq}
lock := &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: asBackup, Generation: generation, Seq: seq, replicated: true}
if existing, found := lm.locks[path]; found && existing.ExpiredAtNs > now {
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
glog.V(4).Infof("lock %s: rejecting stale copy gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
return nil
}
sameLease := leaseID(existing.Token) == leaseID(token)
if sameLease {
lock.ExpiredAtNs = max(expiredAtNs, existing.ExpiredAtNs)
}
if asBackup {
lock.IsBackup = existing.IsBackup
lock.handoff = existing.handoff && sameLease
}
}
lm.locks[path] = lock
lm.advanceGenerationFloor(generation)
return lock
}
// markReplicated must precede sending a copy. If release won the race, skip
// the send; otherwise unlock will retain this lease's identity until expiry.
func (lm *LockManager) markReplicated(path, token string) bool {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lock, found := lm.locks[path]
if !found || leaseID(lock.Token) != leaseID(token) {
return false
}
lock.replicated = true
return true
}
// beginTransfer freezes local renewal authority before sending an RPC. Even a
// failed RPC may have installed the lease on its receiver.
func (lm *LockManager) beginTransfer(path string) (*Lock, bool) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lock, found := lm.locks[path]
if !found || lock.ExpiredAtNs <= time.Now().UnixNano() {
return nil, false
}
lock.replicated, lock.handoff, lock.IsBackup = true, true, true
cp := *lock
cp.Key = path
return &cp, true
}
// finishTransfer changes only the lease that was handed off. A different lease
// installed by incoming replication while the RPC was in flight must survive.
func (lm *LockManager) finishTransfer(path, token string, keepBackup bool) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
if lock, found := lm.locks[path]; found && leaseID(lock.Token) == leaseID(token) {
if keepBackup {
lock.IsBackup = true
lock.handoff = false
} else {
delete(lm.locks, path)
}
}
}
// RemoveLock removes a lock by key
func (lm *LockManager) RemoveLock(path string) {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
// Ownership eviction is not a release: the same live mutation may return
// in a later transfer. Only completed releases create tombstones.
delete(lm.locks, path)
}
// RemoveBackupLockIfSeq removes the local copy only if the incoming mutation is
// not older than the current (generation, seq). This prevents a late unlock from
// deleting a newer reacquired lock whose seq has reset.
func (lm *LockManager) RemoveBackupLockIfSeq(path string, generation int64, seq int64) bool {
// RemoveBackupLockIfSeq records a release even if its acquire has not arrived.
// A release can only delete its own lease, never a different primary's lease
// whose local generation may be smaller or equal.
func (lm *LockManager) RemoveBackupLockIfSeq(path string, generation, seq int64, token string, expiredAtNs int64) bool {
lm.accessLock.Lock()
defer lm.accessLock.Unlock()
lm.advanceGenerationFloor(generation)
if existing, found := lm.locks[path]; found {
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) >= 0 {
delete(lm.locks, path)
return true
// Older primaries omitted release metadata. Preserve ordered releases
// for their legacy tokens without letting them delete a new lease.
// For slash-format tokens, equal generations can belong to different
// primaries. Without a lease ID it is safer to retain the lease until
// expiry than to delete an unrelated acquisition during an upgrade.
if token == "" && !strings.Contains(existing.Token, "/") {
token = existing.Token
}
glog.V(4).Infof("backup lock %s: rejecting stale unlock gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
return false
if existing.Generation != generation || leaseID(existing.Token) != leaseID(token) {
lm.rememberRemoval(path, token, expiredAtNs)
return false
}
if seq < existing.Seq {
return false
}
expiredAtNs = max(expiredAtNs, existing.ExpiredAtNs)
delete(lm.locks, path)
}
lm.rememberRemoval(path, token, expiredAtNs)
return true
}
@@ -347,6 +460,7 @@ func (lm *LockManager) PromoteLock(key string) bool {
if lock, found := lm.locks[key]; found && lock.IsBackup {
lock.IsBackup = false
lock.handoff = false
return true
}
return false
@@ -359,6 +473,7 @@ func (lm *LockManager) DemoteLock(key string) bool {
if lock, found := lm.locks[key]; found && !lock.IsBackup {
lock.IsBackup = true
lock.replicated = true
return true
}
return false
+18 -16
View File
@@ -35,7 +35,7 @@ func TestLockManager_InsertLockAdvancesGenerationCounter(t *testing.T) {
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token1", "", "owner1", 12, 1)
_, renewToken, generation, _, err := lm.Lock("key2", time.Now().Add(30*time.Second).UnixNano(), "", "owner2")
_, renewToken, generation, _, _, err := lm.Lock("key2", time.Now().Add(30*time.Second).UnixNano(), "", "owner2")
assert.NoError(t, err)
assert.NotEmpty(t, renewToken)
assert.Greater(t, generation, int64(12))
@@ -57,7 +57,7 @@ func TestLockManager_InsertBackupLockRejectsOlderGeneration(t *testing.T) {
func TestLockManager_InsertBackupLockKeepsPrimaryRole(t *testing.T) {
lm := NewLockManager()
ok := lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 8, 1)
ok := inserted(lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 8, 1))
assert.True(t, ok)
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 2)
@@ -75,7 +75,7 @@ func TestLockManager_RemoveBackupLockRejectsOlderGeneration(t *testing.T) {
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 1)
removed := lm.RemoveBackupLockIfSeq("key1", 7, 9)
removed := lm.RemoveBackupLockIfSeq("key1", 7, 9, "token-old", time.Now().Add(30*time.Second).UnixNano())
assert.False(t, removed)
lock, found := lm.GetLock("key1")
@@ -89,36 +89,36 @@ func TestLockManager_LostRenewalResponseReplaysToken(t *testing.T) {
lm := NewLockManager()
expires := time.Now().Add(30 * time.Second).UnixNano()
_, token1, _, _, err := lm.Lock("key1", expires, "", "owner1")
_, token1, _, _, _, err := lm.Lock("key1", expires, "", "owner1")
assert.NoError(t, err)
// The renewal rotated token1 to token2; the client never learned it.
_, token2, _, _, err := lm.Lock("key1", expires, token1, "owner1")
_, token2, _, _, _, err := lm.Lock("key1", expires, token1, "owner1")
assert.NoError(t, err)
assert.NotEqual(t, token1, token2)
// Retrying with the superseded token replays the current one instead of
// conflicting with its own lease until it expires.
owner, replayed, _, _, err := lm.Lock("key1", expires, token1, "owner1")
owner, replayed, _, _, _, err := lm.Lock("key1", expires, token1, "owner1")
assert.NoError(t, err)
assert.Equal(t, "owner1", owner)
assert.Equal(t, token2, replayed)
// A replay from a different owner still mismatches.
_, _, _, _, err = lm.Lock("key1", expires, token1, "intruder")
_, _, _, _, _, err = lm.Lock("key1", expires, token1, "intruder")
assert.Error(t, err)
// The next rotation retires the superseded token for good.
_, token3, _, _, err := lm.Lock("key1", expires, token2, "owner1")
_, token3, _, _, _, err := lm.Lock("key1", expires, token2, "owner1")
assert.NoError(t, err)
assert.NotEqual(t, token2, token3)
_, _, _, _, err = lm.Lock("key1", expires, token1, "owner1")
_, _, _, _, _, err = lm.Lock("key1", expires, token1, "owner1")
assert.Error(t, err)
// A superseded token still releases its own lock.
unlocked, _, _, err := lm.Unlock("key1", token2)
released, err := lm.Unlock("key1", token2)
assert.NoError(t, err)
assert.True(t, unlocked)
assert.NotNil(t, released)
}
func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
@@ -126,16 +126,16 @@ func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
expires := time.Now().Add(30 * time.Second).UnixNano()
later := time.Now().Add(60 * time.Second).UnixNano()
_, token1, _, _, err := lm.Lock("key1", expires, "", "owner1")
_, token1, _, _, _, err := lm.Lock("key1", expires, "", "owner1")
assert.NoError(t, err)
_, token2, _, seq2, err := lm.Lock("key1", expires, token1, "owner1")
_, token2, _, seq2, _, err := lm.Lock("key1", expires, token1, "owner1")
assert.NoError(t, err)
// A replay that extends the lease must advance seq, otherwise backups
// reject the replicated expiry as a stale mutation and can grant the
// lock when the old expiry passes after a promotion.
_, replayed, _, seq3, err := lm.Lock("key1", later, token1, "owner1")
_, replayed, _, seq3, _, err := lm.Lock("key1", later, token1, "owner1")
assert.NoError(t, err)
assert.Equal(t, token2, replayed)
assert.Equal(t, seq2+1, seq3)
@@ -146,7 +146,7 @@ func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
assert.Equal(t, seq3, lock.Seq)
// Repeated retries keep advancing instead of colliding at one seq.
_, _, _, seq4, err := lm.Lock("key1", later, token1, "owner1")
_, _, _, seq4, _, err := lm.Lock("key1", later, token1, "owner1")
assert.NoError(t, err)
assert.Equal(t, seq3+1, seq4)
}
@@ -166,8 +166,10 @@ func TestLockManager_InsertBackupLockKeepsPrevToken(t *testing.T) {
// Once promoted, the node still replays a retry of the superseded token.
assert.True(t, lm.PromoteLock("key1"))
owner, replayed, _, _, err := lm.Lock("key1", expires, "token1", "owner1")
owner, replayed, _, _, _, err := lm.Lock("key1", expires, "token1", "owner1")
assert.NoError(t, err)
assert.Equal(t, "owner1", owner)
assert.Equal(t, "token2", replayed)
}
func inserted(_ int64, accepted bool) bool { return accepted }
@@ -0,0 +1,49 @@
package lock_manager
import (
"testing"
"time"
)
func TestLiveLockMayReturnAfterOwnershipEviction(t *testing.T) {
for _, selectLocks := range []bool{false, true} {
manager := NewLockManager()
expiry := time.Now().Add(time.Minute).UnixNano()
manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)
if selectLocks {
manager.SelectLocks(func(string) bool { return true })
} else {
manager.RemoveLock("key")
}
if !inserted(manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)) {
t.Fatalf("live transfer rejected after eviction (SelectLocks=%v)", selectLocks)
}
if released, err := manager.Unlock("key", "token"); released == nil || err != nil {
t.Fatalf("unlock: released=%v err=%v", released, err)
}
if inserted(manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)) {
t.Fatal("completed unlock resurrected by transfer")
}
// Installing and then evicting a newer acquisition must not erase the
// earlier release record. The newer live lease may still return.
_, nextToken, gen, seq, _, err := manager.Lock("key", expiry, "", "next-owner")
if err != nil {
t.Fatal(err)
}
if selectLocks {
manager.SelectLocks(func(string) bool { return true })
} else {
manager.RemoveLock("key")
}
if inserted(manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)) {
t.Fatal("new acquisition and ownership eviction erased an earlier release")
}
manager.InsertBackupLock("key", expiry, "token", "", "owner", 3, 1)
if _, found := manager.GetLock("key"); found {
t.Fatal("earlier release resurrected by replication after ownership eviction")
}
if !inserted(manager.InsertLock("key", expiry, nextToken, "", "next-owner", gen, seq)) {
t.Fatal("newer live lease could not return after ownership eviction")
}
}
}
@@ -0,0 +1,296 @@
package lock_manager
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/stretchr/testify/require"
)
type leaseMutation struct {
key, token, prev, owner string
expires, gen, seq int64
unlock bool
}
func captureLeaseMutations(t *testing.T, dlm *DistributedLockManager) func() leaseMutation {
t.Helper()
messages := make(chan leaseMutation, 4)
dlm.ReplicateFn = func(_ pb.ServerAddress, key string, expires int64, token, prev, owner string, gen, seq int64, unlock bool) {
messages <- leaseMutation{key, token, prev, owner, expires, gen, seq, unlock}
}
return func() leaseMutation {
t.Helper()
select {
case m := <-messages:
return m
case <-time.After(5 * time.Second):
t.Fatal("replication callback not invoked")
return leaseMutation{}
}
}
}
func (m leaseMutation) deliver(dlm *DistributedLockManager) {
if m.unlock {
dlm.RemoveBackupLockIfSeq(m.key, m.gen, m.seq, m.token, m.expires)
} else {
dlm.InsertBackupLock(m.key, m.expires, m.token, m.prev, m.owner, m.gen, m.seq)
}
}
func TestDLM_FreshPrimaryAfterReleasedLease(t *testing.T) {
for _, previousGeneration := range []int{1, 20} {
t.Run(fmt.Sprint(previousGeneration), func(t *testing.T) {
a := NewDistributedLockManager("release-a:8888")
c := NewDistributedLockManager("release-c:8888")
initial := []pb.ServerAddress{a.Host, c.Host}
a.LockRing.SetSnapshot(initial, 1)
// A newly joined or restarted process has an empty generation counter.
b := NewDistributedLockManager("release-b:8888")
next := []pb.ServerAddress{a.Host, b.Host, c.Host}
b.LockRing.SetSnapshot(next, 2)
key := ""
for i := 0; i < 1000; i++ {
candidate := fmt.Sprintf("key-%d", i)
oldPrimary, _ := a.LockRing.GetPrimaryAndBackup(candidate)
primary, backup := b.LockRing.GetPrimaryAndBackup(candidate)
if oldPrimary == a.Host && primary == b.Host && backup == a.Host {
key = candidate
break
}
}
require.NotEmpty(t, key)
receiveA := captureLeaseMutations(t, a)
expires := time.Now().Add(time.Minute).UnixNano()
var acquire, release leaseMutation
var previousAcquires []leaseMutation
for i := 0; i < previousGeneration; i++ {
_, token, _, moved, err := a.LockWithTimeout(key, expires, "", "writer")
require.NoError(t, err)
require.Empty(t, moved)
acquire = receiveA()
previousAcquires = append(previousAcquires, acquire)
acquire.deliver(c)
_, err = a.Unlock(key, token)
require.NoError(t, err)
release = receiveA()
release.deliver(c)
}
require.NotEmpty(t, a.lockManager.removed)
require.Empty(t, a.AllLocks()) // topology handoff has no live lease to transfer
a.LockRing.SetSnapshot(next, 2)
receiveB := captureLeaseMutations(t, b)
_, token, gen, moved, err := b.LockWithTimeout(key, expires, "", "writer")
require.NoError(t, err)
require.Empty(t, moved)
require.EqualValues(t, 1, gen)
require.NotEqual(t, leaseID(acquire.token), leaseID(token))
receiveB().deliver(a)
lock, found := a.GetLock(key)
require.True(t, found, "new primary's valid lease must be replicated")
require.Equal(t, token, lock.Token)
// Old releases must not delete a distinct lease, even at an equal or
// higher generation. Old transfers must still be rejected.
release.deliver(a)
for _, delayed := range previousAcquires {
delayed.deliver(a)
require.False(t, inserted(a.lockManager.InsertLock(key, delayed.expires, delayed.token, delayed.prev, delayed.owner, delayed.gen, delayed.seq)))
}
lock, found = a.GetLock(key)
require.True(t, found)
require.Equal(t, token, lock.Token)
// B fails before its lease expires; A must preserve that lease.
a.LockRing.SetSnapshot([]pb.ServerAddress{a.Host}, 3)
require.True(t, a.PromoteLock(key))
_, conflicting, _, _, err := a.LockWithTimeout(key, expires, "", "another-owner")
require.Error(t, err)
require.Empty(t, conflicting)
_, renewed, _, _, err := a.LockWithTimeout(key, expires, token, "writer")
require.NoError(t, err)
require.NotEmpty(t, renewed)
})
}
}
func TestDLM_ReleaseCoversAllRenewalExpiries(t *testing.T) {
a := NewDistributedLockManager("expiry-a:8888")
b := NewDistributedLockManager("expiry-b:8888")
hosts := []pb.ServerAddress{a.Host, b.Host}
a.LockRing.SetSnapshot(hosts, 1)
b.LockRing.SetSnapshot(hosts, 1)
if primary, _ := a.LockRing.GetPrimaryAndBackup("key"); primary != a.Host {
a, b = b, a
}
receive := captureLeaseMutations(t, a)
expires := time.Now().Add(time.Minute).UnixNano()
_, token1, _, _, err := a.LockWithTimeout("key", expires, "", "owner")
require.NoError(t, err)
acquire := receive()
_, token2, _, _, err := a.LockWithTimeout("key", time.Now().Add(time.Second).UnixNano(), token1, "owner")
require.NoError(t, err)
renewal := receive()
require.NotEqual(t, token1, token2)
require.Equal(t, leaseID(token1), leaseID(token2))
require.Equal(t, expires, renewal.expires, "renewal cannot shorten the validity bound")
// Retry a lost response with a shorter requested TTL as well.
_, replayed, _, _, err := a.LockWithTimeout("key", time.Now().Add(time.Second).UnixNano(), token1, "owner")
require.NoError(t, err)
require.Equal(t, token2, replayed)
retry := receive()
_, err = a.Unlock("key", token1) // release using the superseded token
require.NoError(t, err)
release := receive()
require.True(t, release.unlock)
require.Equal(t, token2, release.token)
require.Equal(t, expires, release.expires)
release.deliver(b)
for _, delayed := range []leaseMutation{acquire, renewal, retry} {
delayed.deliver(b)
require.False(t, inserted(b.lockManager.InsertLock(delayed.key, delayed.expires, delayed.token, delayed.prev, delayed.owner, delayed.gen, delayed.seq)))
}
_, found := b.GetLock("key")
require.False(t, found)
require.NotEmpty(t, a.lockManager.removed, "renewal must preserve replication tracking")
b.lockManager.cleanUp(expires - 1)
require.Len(t, b.lockManager.removed, 1)
b.lockManager.cleanUp(expires)
require.Nil(t, b.lockManager.removed)
}
func TestDLM_LocalReleasesDoNotRetainRecords(t *testing.T) {
dlm := NewDistributedLockManager("single:8888")
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("object-%d", i)
_, token, _, _, err := dlm.LockWithTimeout(key, time.Now().Add(time.Minute).UnixNano(), "", "writer")
require.NoError(t, err)
_, err = dlm.Unlock(key, token)
require.NoError(t, err)
}
require.Empty(t, dlm.AllLocks())
require.Empty(t, dlm.lockManager.removed)
}
func TestLockManager_ReleaseRecordReclamation(t *testing.T) {
manager := NewLockManager()
expires := time.Now().Add(time.Minute).UnixNano()
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("object-%d", i)
token := fmt.Sprintf("lease-%d/secret", i)
require.True(t, inserted(manager.InsertLock(key, expires, token, "", "writer", int64(i+1), 1)))
released, err := manager.Unlock(key, token)
require.NoError(t, err)
require.NotNil(t, released)
}
require.Empty(t, manager.AllLocks())
require.Len(t, manager.removed, 1000)
manager.cleanUp(expires)
require.Nil(t, manager.removed)
// Replay the exact original payload after its actual validity bound passes.
expiredLease := time.Now().Add(100 * time.Millisecond).UnixNano()
require.True(t, inserted(manager.InsertLock("expired", expiredLease, "expired-lease/secret", "", "writer", 1, 1)))
released, err := manager.Unlock("expired", "expired-lease/secret")
require.NoError(t, err)
require.NotNil(t, released)
require.Eventually(t, func() bool { return time.Now().UnixNano() >= expiredLease }, time.Second, time.Millisecond)
manager.cleanUp(time.Now().UnixNano())
require.Nil(t, manager.removed)
require.False(t, inserted(manager.InsertLock("expired", expiredLease, "expired-lease/secret", "", "writer", 1, 1)))
manager.InsertBackupLock("expired", expiredLease, "expired-lease/secret", "", "writer", 1, 1)
manager.RemoveBackupLockIfSeq("expired", 1, 2, "expired-lease/secret", expiredLease)
require.Empty(t, manager.locks)
require.Nil(t, manager.removed)
}
func TestLockManager_FirstReplicationRacesWithRelease(t *testing.T) {
for _, replicateFirst := range []bool{false, true} {
t.Run(fmt.Sprint(replicateFirst), func(t *testing.T) {
manager := NewLockManager()
_, token, _, _, _, err := manager.Lock("key", time.Now().Add(time.Minute).UnixNano(), "", "owner")
require.NoError(t, err)
if replicateFirst {
require.True(t, manager.markReplicated("key", token))
}
released, err := manager.Unlock("key", token)
require.NoError(t, err)
require.NotNil(t, released)
require.False(t, manager.markReplicated("key", token), "a released local lease cannot be sent later")
require.Equal(t, replicateFirst, len(manager.removed) != 0)
})
}
}
func TestDLM_HandoffTracksPreviouslyLocalLease(t *testing.T) {
dlm := NewDistributedLockManager("handoff:8888")
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
expires := time.Now().Add(time.Minute).UnixNano()
_, token, _, _, err := dlm.LockWithTimeout("key", expires, "", "owner")
require.NoError(t, err)
locks := dlm.AllLocks()
require.Len(t, locks, 1)
require.NoError(t, handOff(t, dlm, "key", true, func(current *Lock) error {
require.Equal(t, token, current.Token)
return nil
}))
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, dlm.LockRing.Version()+1)
_, err = dlm.Unlock("key", token)
require.NoError(t, err)
require.NotEmpty(t, dlm.lockManager.removed)
require.NoError(t, handOff(t, dlm, "key", true, func(*Lock) error {
t.Fatal("released lease was handed off")
return nil
}))
require.False(t, inserted(dlm.lockManager.InsertLock("key", expires, token, "", "owner", locks[0].Generation, locks[0].Seq)))
}
func TestLockManager_LegacyReleaseMetadata(t *testing.T) {
manager := NewLockManager()
expires := time.Now().Add(time.Minute).UnixNano()
manager.InsertBackupLock("key", expires, "legacy-token", "", "owner", 1, 1)
require.True(t, manager.RemoveBackupLockIfSeq("key", 1, 2, "", 0))
_, found := manager.GetLock("key")
require.False(t, found)
require.True(t, inserted(manager.InsertLock("key", expires, "new-lease/secret", "", "owner", 1, 1)))
// An old primary could have released the previous generation-1 lease,
// or a handed-off slash-format lease. Its identityless message cannot
// distinguish those cases. Keep the valid lease until its expiry rather
// than permitting a stale release to delete a different acquisition.
require.False(t, manager.RemoveBackupLockIfSeq("key", 1, 2, "", 0))
lock, found := manager.GetLock("key")
require.True(t, found)
require.Equal(t, "new-lease/secret", lock.Token)
}
func TestDLM_TransferReplicatesEffectiveExpiry(t *testing.T) {
for _, incomingTTL := range []time.Duration{30 * time.Second, time.Minute, 90 * time.Second} {
t.Run(incomingTTL.String(), func(t *testing.T) {
a, b := NewDistributedLockManager("expiry-a:8888"), NewDistributedLockManager("expiry-b:8888")
hosts := []pb.ServerAddress{a.Host, b.Host}
a.LockRing.SetSnapshot(hosts, 1)
b.LockRing.SetSnapshot(hosts, 1)
if primary, _ := a.LockRing.GetPrimaryAndBackup("key"); primary != a.Host {
a, b = b, a
}
now := time.Now()
storedExpiry := now.Add(time.Minute).UnixNano()
incomingExpiry := now.Add(incomingTTL).UnixNano()
require.True(t, inserted(a.lockManager.InsertLock("key", storedExpiry, "lease/old", "", "owner", 1, 1)))
receive := captureLeaseMutations(t, a)
a.InsertLock("key", incomingExpiry, "lease/new", "lease/old", "owner", 1, 2)
mutation := receive()
require.Equal(t, max(storedExpiry, incomingExpiry), mutation.expires)
mutation.deliver(b)
primary, found := a.GetLock("key")
require.True(t, found)
backup, found := b.GetLock("key")
require.True(t, found)
require.Equal(t, primary.ExpiredAtNs, backup.ExpiredAtNs)
})
}
}
@@ -0,0 +1,132 @@
package lock_manager_test
import (
"testing"
"time"
lm "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
func TestLockManager_ReleasedLockDoesNotResurrect(t *testing.T) {
for _, releaseFirst := range []bool{false, true} {
name := "insert_release_delayed_renewal"
if releaseFirst {
name = "release_before_insert"
}
t.Run(name, func(t *testing.T) {
backup := lm.NewLockManager()
expires := time.Now().Add(time.Minute).UnixNano()
if !releaseFirst {
backup.InsertBackupLock("key", expires, "lease/token", "", "owner", 1, 1)
}
if !backup.RemoveBackupLockIfSeq("key", 1, 3, "lease/token3", expires) {
t.Fatal("release unexpectedly rejected")
}
backup.InsertBackupLock("key", expires, "lease/token2", "lease/token", "owner", 1, 2)
if got, ok := backup.GetLock("key"); ok {
t.Fatalf("released lock resurrected: owner=%s generation=%d seq=%d", got.Owner, got.Generation, got.Seq)
}
})
}
}
func TestLockManager_StaleTransferDoesNotResurrect(t *testing.T) {
manager := lm.NewLockManager()
expires := time.Now().Add(time.Minute).UnixNano()
manager.InsertLock("key", expires, "token", "", "owner", 3, 1)
if released, err := manager.Unlock("key", "token"); released == nil || err != nil {
t.Fatalf("unlock: released=%v err=%v", released, err)
}
if _, accepted := manager.InsertLock("key", expires, "token", "", "owner", 3, 1); accepted {
t.Fatal("completed release was undone by a stale transfer")
}
}
func TestLockManager_OrderedReleaseKeepsNewerLease(t *testing.T) {
backup := lm.NewLockManager()
expires := time.Now().Add(time.Minute).UnixNano()
backup.InsertBackupLock("key", expires, "lease/token", "", "owner", 1, 1)
backup.RemoveBackupLockIfSeq("key", 1, 2, "lease/token", expires)
if _, ok := backup.GetLock("key"); ok {
t.Fatal("ordered release failed")
}
backup.InsertBackupLock("key", expires, "new", "", "new-owner", 2, 1)
backup.RemoveBackupLockIfSeq("key", 1, 2, "lease/token", expires)
got, ok := backup.GetLock("key")
if !ok || got.Generation != 2 {
t.Fatal("older delete removed a newer live record")
}
}
// Drive the real asynchronous replication callback and actual DLM acquire /
// release APIs. The callback is a controllable reliable network: each captured
// message is delivered exactly once, with no loss, duplication or fabrication.
func TestDLM_AsyncReplicationReleaseFailover(t *testing.T) {
for _, reordered := range []bool{false, true} {
name := "ordered_control"
if reordered {
name = "reordered"
}
t.Run(name, func(t *testing.T) {
hosts := []pb.ServerAddress{"filer-a:8888", "filer-b:8888"}
a, b := lm.NewDistributedLockManager(hosts[0]), lm.NewDistributedLockManager(hosts[1])
a.LockRing.SetSnapshot(append([]pb.ServerAddress(nil), hosts...), 1)
b.LockRing.SetSnapshot(append([]pb.ServerAddress(nil), hosts...), 1)
key := "replication-key"
primary, _ := a.LockRing.GetPrimaryAndBackup(key)
if primary != a.Host {
a, b = b, a
}
type message struct {
expires, generation, seq int64
token, prev, owner string
isUnlock bool
}
network := make(chan message, 4)
a.ReplicateFn = func(_ pb.ServerAddress, _ string, expiry int64, token, prev, owner string, gen, seq int64, unlock bool) {
network <- message{expiry, gen, seq, token, prev, owner, unlock}
}
receive := func() message {
select {
case m := <-network:
return m
case <-time.After(5 * time.Second):
t.Fatal("replication callback not invoked")
return message{}
}
}
deliver := func(m message) {
if m.isUnlock {
b.RemoveBackupLockIfSeq(key, m.generation, m.seq, m.token, m.expires)
} else {
b.InsertBackupLock(key, m.expires, m.token, m.prev, m.owner, m.generation, m.seq)
}
}
expires := time.Now().Add(time.Minute).UnixNano()
_, token, _, moved, err := a.LockWithTimeout(key, expires, "", "alice")
if err != nil || moved != "" || token == "" {
t.Fatalf("acquire: %v moved=%s", err, moved)
}
acquire := receive()
if moved, err := a.Unlock(key, token); err != nil || moved != "" {
t.Fatalf("unlock: %v moved=%s", err, moved)
}
release := receive()
if reordered {
deliver(release)
deliver(acquire)
} else {
deliver(acquire)
deliver(release)
}
// Remove the old primary only after both replication RPCs completed.
b.LockRing.SetSnapshot([]pb.ServerAddress{b.Host}, 2)
b.PromoteLock(key)
_, newToken, _, moved, err := b.LockWithTimeout(key, expires, "", "bob")
if err != nil || moved != "" || newToken == "" {
t.Fatalf("completed release must allow new owner after failover: error=%v moved=%s token=%q", err, moved, newToken)
}
})
}
}
@@ -7,7 +7,6 @@ const DefaultMasterMaintenanceScripts = `
ec.encode -fullPercent=95 -quietFor=1h
ec.rebuild -apply
ec.balance -apply
fs.log.purge -daysAgo=7
volume.deleteEmpty -quietFor=24h -apply
volume.balance -apply
volume.fix.replication -apply
+3 -2
View File
@@ -167,7 +167,7 @@ func init() {
f.defaultLevelDbDirectory = cmdFiler.Flag.String("defaultStoreDir", ".", "if filer.toml is empty, use an embedded filer store in the directory")
f.concurrentUploadLimitMB = cmdFiler.Flag.Int("concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
f.concurrentFileUploadLimit = cmdFiler.Flag.Int("concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
f.inflightUploadDataTimeout = cmdFiler.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 429, 0 means no limit")
f.inflightUploadDataTimeout = cmdFiler.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 503 and Retry-After, 0 means no limit")
f.debug = cmdFiler.Flag.Bool("debug", false, "serves runtime profiling data, e.g., http://localhost:<debug.port>/debug/pprof/goroutine?debug=2")
f.debugPort = cmdFiler.Flag.Int("debug.port", 6060, "http port for debugging")
f.localSocket = cmdFiler.Flag.String("localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
@@ -537,7 +537,8 @@ func (fo *FilerOptions) startFiler() {
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
}
grpcTLSOption, grpcTLSReloadOption := security.LoadServerTLS(util.GetViper(), "grpc.filer")
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, fs.GrpcScopeServerOptions()...)
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, weed_server.FilerGrpcMetricsServerOptions()...)
grpcOptions = append(grpcOptions, fs.GrpcScopeServerOptions()...)
grpcS := pb.NewGrpcServer(grpcOptions...)
filer_pb.RegisterSeaweedFilerServer(grpcS, fs)
+17 -6
View File
@@ -157,7 +157,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
// snapshot below sets the start point; no checkpoint read needed
glog.V(0).Infof("initialSnapshot requested — walking live tree before subscribing")
} else {
lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, security.FilerAdminToken, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil {
return 0, fmt.Errorf("read backup offset: %w", err)
} else if lastOffsetTsNs > 0 {
@@ -181,11 +181,17 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
*backupOption.proxyByFiler); err != nil {
return resumeTsNs, fmt.Errorf("filersource initialization failed: %v", err)
}
filerSource.SetFilerTokenSource(security.FilerAdminToken)
dataSink.SetSourceFiler(filerSource)
if tokenSink, ok := dataSink.(interface {
SetFilerTokenSource(security.FilerTokenSource)
}); ok {
tokenSink.SetFilerTokenSource(security.FilerAdminToken)
}
if err := repl_util.InitializeSSEForReplication(filerSource); err != nil {
return resumeTsNs, fmt.Errorf("SSE initialization failed: %v", err)
}
dataSink.SetSourceFiler(filerSource)
if err := replication.CheckSinkDigest(filerSource.GrpcAddress(), filerSource.Digest, dataSink); err != nil {
if replication.IsDigestMismatch(err) {
glog.Exitf("%v", err)
@@ -220,7 +226,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
// The walk can take hours on large trees; retry the tiny KV write a
// handful of times before giving up so a flaky filer KV doesn't force
// the whole walk to repeat on the next retry loop iteration.
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs); err != nil {
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs, security.FilerAdminToken); err != nil {
glog.Errorf("initialSnapshot: FAILED to persist offset %d for sinkId %d after retries: %v — the next retry will redo the full walk", snapshotTsNs, sinkId, err)
return 0, fmt.Errorf("persist initial snapshot offset: %w", err)
}
@@ -300,7 +306,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
defer ticker.Stop()
persist := func() {
if ts := resumeTsNsFor(processor); ts != lastPersistedTsNs.Load() {
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, ts); err == nil {
if err := setOffset(grpcDialOption, sourceFiler, security.FilerAdminToken, BackupKeyPrefix, sinkId, ts); err == nil {
lastPersistedTsNs.Store(ts)
} else {
glog.Warningf("persist backup offset: %v", err)
@@ -366,6 +372,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
StartTsNs: startFrom.UnixNano(),
StopTsNs: 0,
EventErrorType: eventErrorType,
FilerTokenSource: security.FilerAdminToken,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
},
@@ -487,12 +494,16 @@ func eventSupersessionProbe(resp *filer_pb.SubscribeMetadataResponse) (util.Full
// errors. Losing this write forces a full re-walk on the next retry loop
// iteration, so a small retry budget here is far cheaper than paying the
// walk cost again on a large tree.
func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64) error {
func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64, tokenSource ...security.FilerTokenSource) error {
const attempts = 4
backoff := 500 * time.Millisecond
var source security.FilerTokenSource
if len(tokenSource) > 0 {
source = tokenSource[0]
}
var lastErr error
for i := 1; i <= attempts; i++ {
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, tsNs); err == nil {
if err := setOffset(grpcDialOption, sourceFiler, source, BackupKeyPrefix, sinkId, tsNs); err == nil {
return nil
} else {
lastErr = err
+113
View File
@@ -0,0 +1,113 @@
package command
import (
"context"
"crypto/rand"
"encoding/hex"
"net"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type backupAuthKVFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
key security.SigningKey
mu sync.Mutex
kv map[string][]byte
}
func (s *backupAuthKVFiler) authenticate(ctx context.Context) error {
md, _ := metadata.FromIncomingContext(ctx)
values := md.Get("authorization")
if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) ||
!security.IsFilerAdminToken(s.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) {
return status.Error(codes.Unauthenticated, "missing or invalid filer authorization")
}
return nil
}
func (s *backupAuthKVFiler) KvGet(_ context.Context, request *filer_pb.KvGetRequest) (*filer_pb.KvGetResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
return &filer_pb.KvGetResponse{Value: append([]byte(nil), s.kv[string(request.Key)]...)}, nil
}
func (s *backupAuthKVFiler) KvPut(_ context.Context, request *filer_pb.KvPutRequest) (*filer_pb.KvPutResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.kv[string(request.Key)] = append([]byte(nil), request.Value...)
return &filer_pb.KvPutResponse{}, nil
}
func backupAuthKey(t *testing.T) security.SigningKey {
t.Helper()
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
t.Fatal(err)
}
return security.SigningKey(hex.EncodeToString(buf))
}
func startBackupAuthKVFiler(t *testing.T, filer *backupAuthKVFiler) (pb.ServerAddress, grpc.DialOption) {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if err := filer.authenticate(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}))
filer_pb.RegisterSeaweedFilerServer(server, filer)
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() {
server.Stop()
_ = listener.Close()
})
port := listener.Addr().(*net.TCPAddr).Port
return pb.NewServerAddressWithGrpcPort("127.0.0.1:8888", port), grpc.WithTransportCredentials(insecure.NewCredentials())
}
func TestBackupOffsetUsesProtectedPerCallOperation(t *testing.T) {
key := backupAuthKey(t)
filer := &backupAuthKVFiler{key: key, kv: make(map[string][]byte)}
address, dial := startBackupAuthKVFiler(t, filer)
tokenSource := security.FilerTokenSource(func(context.Context) (security.EncodedJwt, error) {
return security.GenJwtForFilerAdmin(key, 60), nil
})
prefix := BackupKeyPrefix
const signature = int32(43)
if err := setOffset(dial, address, tokenSource, prefix, signature, 1234); err != nil {
t.Fatalf("protected backup offset write: %v", err)
}
got, err := getOffset(dial, address, tokenSource, prefix, signature)
if err != nil {
t.Fatalf("protected backup offset read: %v", err)
}
if got != 1234 {
t.Fatalf("backup offset = %d, want 1234", got)
}
// Keep this assertion at the stored-value boundary: it proves the real KV
// calls completed through the protected adapter, while avoiding token output.
keyBytes := []byte(prefix + "____")
util.Uint32toBytes(keyBytes[len(prefix):], uint32(signature))
filer.mu.Lock()
defer filer.mu.Unlock()
if _, ok := filer.kv[string(keyBytes)]; !ok {
t.Fatal("protected backup offset was not persisted")
}
}
+10 -10
View File
@@ -84,28 +84,28 @@ func TestBackupOffset_HistoricalFallbackThenIndependence(t *testing.T) {
sinkId, legacySinkId := backupCheckpointIds("/", s, false)
// pre-upgrade state: only the shared historical checkpoint exists
if err := setOffset(dial, filerAddr, BackupKeyPrefix, legacySinkId, 111); err != nil {
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 111); err != nil {
t.Fatalf("seed historical offset: %v", err)
}
got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil || got != 111 {
t.Fatalf("fallback read = (%d, %v), want (111, nil)", got, err)
}
// the backup checkpoints under its own key and prefers it from then on
if err := setOffset(dial, filerAddr, BackupKeyPrefix, sinkId, 222); err != nil {
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, sinkId, 222); err != nil {
t.Fatalf("write destination-scoped offset: %v", err)
}
got, err = getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
got, err = getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil || got != 222 {
t.Fatalf("destination-scoped read = (%d, %v), want (222, nil)", got, err)
}
// another backup advancing the historical key no longer moves this one
if err := setOffset(dial, filerAddr, BackupKeyPrefix, legacySinkId, 333); err != nil {
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 333); err != nil {
t.Fatalf("advance historical offset: %v", err)
}
got, err = getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
got, err = getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil || got != 222 {
t.Fatalf("read after historical advance = (%d, %v), want (222, nil)", got, err)
}
@@ -120,17 +120,17 @@ func TestBackupOffset_DistinctDestinationsDoNotShare(t *testing.T) {
idA, legacyA := backupCheckpointIds("/", &stubSink{name: "s3", dir: "/", destination: "s3.us-west-004.backblazeb2.com|seaweed-backup-a|/"}, false)
idB, legacyB := backupCheckpointIds("/", &stubSink{name: "s3", dir: "/", destination: "s3.us-east-005.backblazeb2.com|seaweed-backup-b|/"}, false)
if err := setOffset(dial, filerAddr, BackupKeyPrefix, idA, 1000); err != nil {
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idA, 1000); err != nil {
t.Fatalf("write A: %v", err)
}
if err := setOffset(dial, filerAddr, BackupKeyPrefix, idB, 2000); err != nil {
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idB, 2000); err != nil {
t.Fatalf("write B: %v", err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, idA, BackupKeyPrefix, legacyA); err != nil || got != 1000 {
if got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, idA, BackupKeyPrefix, legacyA); err != nil || got != 1000 {
t.Fatalf("A reads (%d, %v), want (1000, nil)", got, err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, idB, BackupKeyPrefix, legacyB); err != nil || got != 2000 {
if got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, idB, BackupKeyPrefix, legacyB); err != nil || got != 2000 {
t.Fatalf("B reads (%d, %v), want (2000, nil)", got, err)
}
}
+5 -1
View File
@@ -98,7 +98,7 @@ func runFilerCat(cmd *Command, args []string) bool {
writer = f
}
pb.WithFilerClient(false, util.RandomInt32(), filerCat.filerAddress, filerCat.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err = pb.WithGrpcFilerClient(false, util.RandomInt32(), filerCat.filerAddress, filerCat.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.LookupDirectoryEntryRequest{
Name: name,
@@ -119,6 +119,10 @@ func runFilerCat(cmd *Command, args []string) bool {
return filer.StreamContent(&filerCat, writer, respLookupEntry.Entry.GetChunks(), 0, int64(filer.FileSize(respLookupEntry.Entry)))
})
if err != nil {
fmt.Fprintf(os.Stderr, "read %s: %v\n", filerSource, err)
return false
}
return true
}
+6 -9
View File
@@ -186,7 +186,7 @@ func runCopy(cmd *Command, args []string) bool {
}
func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.ServerAddress) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, digest string, err error) {
err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer %s configuration: %v", filerGrpcAddress, err)
@@ -318,7 +318,7 @@ func (worker *FileCopyWorker) checkExistingFileFirst(task FileCopyTask, f *os.Fi
return
}
err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.LookupDirectoryEntryRequest{
Directory: task.destinationUrlPath,
@@ -387,7 +387,7 @@ func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) err
chunks = append(chunks, uploadResult.ToPbFileChunk(finalFileId, 0, time.Now().UnixNano()))
}
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.CreateEntryRequest{
Directory: task.destinationUrlPath,
Entry: &filer_pb.Entry{
@@ -524,7 +524,7 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
return fmt.Errorf("create manifest: %w", manifestErr)
}
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
request := &filer_pb.CreateEntryRequest{
Directory: task.destinationUrlPath,
Entry: &filer_pb.Entry{
@@ -614,12 +614,9 @@ func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, off
var _ = filer_pb.FilerClient(&FileCopyWorker{})
func (worker *FileCopyWorker) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) (err error) {
filerGrpcAddress := worker.filerAddress.ToGrpcAddress()
err = pb.WithGrpcClient(context.Background(), streamingMode, worker.signature, func(grpcConnection *grpc.ClientConn) error {
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
err = pb.WithGrpcFilerClient(streamingMode, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
return fn(client)
}, filerGrpcAddress, false, worker.options.grpcDialOption)
})
return
}
+2 -1
View File
@@ -388,6 +388,7 @@ func (metaBackup *FilerMetaBackupOptions) streamMetadataBackup(startTime time.Ti
StartTsNs: startTime.UnixNano(),
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
FilerTokenSource: security.FilerAdminToken,
}
return pb.FollowMetadata(pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
@@ -422,7 +423,7 @@ var _ = filer_pb.FilerClient(&FilerMetaBackupOptions{})
func (metaBackup *FilerMetaBackupOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithFilerClient(streamingMode, metaBackup.clientId, pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(streamingMode, metaBackup.clientId, pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
return fn(client)
})
+10 -9
View File
@@ -90,7 +90,7 @@ type scanFilerClient struct {
}
func (c *scanFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithFilerClient(streamingMode, c.signature, c.address, c.grpcDialOption, fn)
return pb.WithGrpcFilerClient(streamingMode, c.signature, c.address, c.grpcDialOption, security.FilerAdminToken, fn)
}
func (c *scanFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
@@ -298,14 +298,15 @@ func runFilerMetaScan(cmd *Command, args []string) bool {
scan := func(directRead bool) error {
option := &pb.MetadataFollowOption{
ClientName: "scan",
ClientId: util.RandomInt32(),
ClientEpoch: 0,
SelfSignature: 0,
PathPrefix: *scanPathPrefix,
StartTsNs: startTs.UnixNano(),
StopTsNs: stopTsNs,
EventErrorType: pb.TrivialOnError,
ClientName: "scan",
ClientId: util.RandomInt32(),
ClientEpoch: 0,
SelfSignature: 0,
FilerTokenSource: security.FilerAdminToken,
PathPrefix: *scanPathPrefix,
StartTsNs: startTs.UnixNano(),
StopTsNs: stopTsNs,
EventErrorType: pb.TrivialOnError,
}
if directRead {
// The server hands out log chunk fids and this reads them straight
+1
View File
@@ -118,6 +118,7 @@ func runFilerMetaTail(cmd *Command, args []string) bool {
StartTsNs: time.Now().Add(-*tailStart).UnixNano(),
StopTsNs: untilTsNs,
EventErrorType: pb.TrivialOnError,
FilerTokenSource: security.FilerAdminToken,
}
tailErr := pb.FollowMetadata(pb.ServerAddress(*tailFiler), grpcDialOption, metadataFollowOption, func(resp *filer_pb.SubscribeMetadataResponse) error {
+10 -7
View File
@@ -26,18 +26,19 @@ type RemoteGatewayOptions struct {
include *string
exclude *string
mappings *remote_pb.RemoteStorageMapping
remoteConfs map[string]*remote_pb.RemoteConf
bucketsDir string
clientId int32
clientEpoch int32
resumeTsNs int64
mappings *remote_pb.RemoteStorageMapping
remoteConfs map[string]*remote_pb.RemoteConf
bucketsDir string
clientId int32
clientEpoch int32
resumeTsNs int64
filerTokenSource security.FilerTokenSource
}
var _ = filer_pb.FilerClient(&RemoteGatewayOptions{})
func (option *RemoteGatewayOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, option.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
return fn(client)
})
}
@@ -88,6 +89,7 @@ func runFilerRemoteGateway(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
remoteGatewayOptions.grpcDialOption = grpcDialOption
remoteGatewayOptions.filerTokenSource = security.FilerAdminToken
filerAddress := pb.ServerAddress(*remoteGatewayOptions.filerAddress)
@@ -98,6 +100,7 @@ func runFilerRemoteGateway(cmd *Command, args []string) bool {
"/", // does not matter
*remoteGatewayOptions.readChunkFromFiler,
)
filerSource.SetFilerTokenSource(remoteGatewayOptions.filerTokenSource)
remoteGatewayOptions.bucketsDir = "/buckets"
// check buckets again
+5 -4
View File
@@ -33,7 +33,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
return err
}
lastOffsetTs, err := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo, option.resumeTsNs)
lastOffsetTs, err := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo, option.resumeTsNs, option.filerTokenSource)
if err != nil {
return err
}
@@ -51,7 +51,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
now := time.Now().UnixNano()
glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, time.Unix(0, offsetTsNs), float64(counter)/(float64(now-lastLogTsNs)/1e9))
lastLogTsNs = now
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor))
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor), option.filerTokenSource)
})
option.clientEpoch++
@@ -67,6 +67,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
StartTsNs: lastOffsetTs.UnixNano(),
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
FilerTokenSource: option.filerTokenSource,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
},
@@ -74,7 +75,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
}
err = pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
option.resumeTsNs = saveResumeOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, processor)
option.resumeTsNs = saveResumeOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, processor, option.filerTokenSource)
return err
}
@@ -709,7 +710,7 @@ func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) {
func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) {
if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress)); err != nil {
if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.filerTokenSource); err != nil {
if err == filer_pb.ErrNotFound {
return fmt.Errorf("remote storage is not configured in filer server")
}
+6 -3
View File
@@ -28,14 +28,15 @@ type RemoteSyncOptions struct {
resumeTsNs int64
// what resumeTsNs was earned under: the directory's remote location, and
// the offset stored when it was kept (resumeFor)
resumeLoc *remote_pb.RemoteStorageLocation
resumeStoredNs int64
resumeLoc *remote_pb.RemoteStorageLocation
resumeStoredNs int64
filerTokenSource security.FilerTokenSource
}
var _ = filer_pb.FilerClient(&RemoteSyncOptions{})
func (option *RemoteSyncOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, option.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
return fn(client)
})
}
@@ -98,6 +99,7 @@ func runFilerRemoteSynchronize(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
remoteSyncOptions.grpcDialOption = grpcDialOption
remoteSyncOptions.filerTokenSource = security.FilerAdminToken
dir := *remoteSyncOptions.dir
filerAddress := pb.ServerAddress(*remoteSyncOptions.filerAddress)
@@ -109,6 +111,7 @@ func runFilerRemoteSynchronize(cmd *Command, args []string) bool {
"/", // does not matter
*remoteSyncOptions.readChunkFromFiler,
)
filerSource.SetFilerTokenSource(remoteSyncOptions.filerTokenSource)
if *remoteSyncOptions.allMounts {
if dir != "" {
+1 -1
View File
@@ -110,7 +110,7 @@ func newMountSupervisor(option *RemoteSyncOptions, filerSource *source.FilerSour
return followMountedDir(o, filerSource, dir, watch)
}
m.readOffset = func(dir string) (int64, error) {
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), dir)
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), dir, option.filerTokenSource)
}
return m
}
+13 -9
View File
@@ -23,6 +23,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
"github.com/seaweedfs/seaweedfs/weed/replication/source"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
"google.golang.org/grpc"
@@ -75,23 +76,23 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource
// remote.unmount completing in between (its mapping write, its purge,
// then its offset) would start a follow that saw the directory mounted
// past the unmount's table, into its purge.
storedOffsetNs, err := remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
storedOffsetNs, err := remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource)
if err != nil {
return fmt.Errorf("read sync offset of %s: %w", mountedDir, err)
}
// read filer remote storage mount mappings
_, mountKey, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
_, mountKey, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource)
if err := option.resumeFor(mountedDir, mountKey, remoteStorageMountLocation, detectErr, storedOffsetNs); err != nil {
return err
}
dirLoc := dirRemoteLocation(mountKey, mountedDir, remoteStorageMountLocation)
guard := &offsetGuard{dir: mountedDir, last: storedOffsetNs,
read: func() (int64, error) {
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource)
},
write: func(ts int64) error {
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, ts)
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, ts, option.filerTokenSource)
},
}
@@ -105,7 +106,7 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource
return err
}
lastOffsetTs, err = startAfterMountOffset(lastOffsetTs, mountKey, mountedDir, *option.timeAgo, option.resumeTsNs, func() (int64, error) {
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountKey)
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountKey, option.filerTokenSource)
})
if err != nil {
return err
@@ -164,6 +165,7 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource
StartTsNs: lastOffsetTs.UnixNano(),
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
FilerTokenSource: option.filerTokenSource,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
},
@@ -233,9 +235,9 @@ func startAfterMountOffset(start time.Time, mountKey, dir string, timeAgo time.D
// recomputes -timeAgo from now, so a failure before the first checkpoint
// would otherwise start the retry after the event it failed on. The offset is
// returned for the retry in this process, which must not depend on the write.
func saveResumeOffset(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, processor *MetadataProcessor) int64 {
func saveResumeOffset(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, processor *MetadataProcessor, tokenSource ...security.FilerTokenSource) int64 {
return saveResumeOffsetWith(func(ts int64) error {
return remote_storage.SetSyncOffset(grpcDialOption, filerAddress, dir, ts)
return remote_storage.SetSyncOffset(grpcDialOption, filerAddress, dir, ts, tokenSource...)
}, dir, processor)
}
@@ -1490,7 +1492,7 @@ func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource fil
return
}
func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration, resumeTsNs int64) (time.Time, error) {
func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration, resumeTsNs int64, tokenSource ...security.FilerTokenSource) (time.Time, error) {
if resumeTsNs > 0 {
// the previous attempt pinned where it stopped, which can sit behind
// both the saved offset and a recomputed -timeAgo window
@@ -1504,7 +1506,9 @@ func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc
entry, _, _, err := filer_pb.GetEntry(ctx, filerClient, util.FullPath(mountedDir))
return entry, err
},
func() (int64, error) { return remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir) })
func() (int64, error) {
return remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir, tokenSource...)
})
}
// collectLastSyncOffsetFrom is collectLastSyncOffset with the saved offset
+31 -19
View File
@@ -78,6 +78,7 @@ type syncState struct {
sourcePath string
targetPath string
sourceFilerSignature int32
tokenSource security.FilerTokenSource
}
var (
@@ -177,6 +178,8 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
// per-cluster HTTPS clients for volume server connections
var httpClientA, httpClientB *util_http_client.HTTPClient
var jwtForFilerA, jwtForFilerB security.FilerJwtProvider
tokenSourceA := security.FilerAdminTokenFromFile(*syncOptions.aSecurity)
tokenSourceB := security.FilerAdminTokenFromFile(*syncOptions.bSecurity)
if *syncOptions.aSecurity != "" {
var err error
if httpClientA, err = security.LoadHTTPClientFromFile(*syncOptions.aSecurity); err != nil {
@@ -205,13 +208,13 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
go statsCollect.StartMetricsServer(*syncOptions.metricsHttpIp, *syncOptions.metricsHttpPort)
// read a filer signature
aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA)
aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA, tokenSourceA)
if aFilerErr != nil {
glog.Errorf("get filer 'a' signature %d error from %s to %s: %v", aFilerSignature, *syncOptions.filerA, *syncOptions.filerB, aFilerErr)
return true
}
// read b filer signature
bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB)
bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB, tokenSourceB)
if bFilerErr != nil {
glog.Errorf("get filer 'b' signature %d error from %s to %s: %v", bFilerSignature, *syncOptions.filerA, *syncOptions.filerB, bFilerErr)
return true
@@ -230,7 +233,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
if offsetTsNs == 0 {
return
}
if err := setOffset(state.grpcDialOption, state.targetFiler, getSignaturePrefixByPath(state.sourcePath, state.targetPath), state.sourceFilerSignature, offsetTsNs); err != nil {
if err := setOffset(state.grpcDialOption, state.targetFiler, state.tokenSource, getSignaturePrefixByPath(state.sourcePath, state.targetPath), state.sourceFilerSignature, offsetTsNs); err != nil {
glog.Errorf("failed to save checkpoint for %s on shutdown: %v", name, err)
} else {
glog.V(0).Infof("saved checkpoint for %s on shutdown: %v", name, time.Unix(0, offsetTsNs))
@@ -244,7 +247,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
go func() {
// a->b
// set synchronization start timestamp to offset
initOffsetError := initOffsetFromTsMs(grpcDialOptionB, filerB, aFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath, *syncOptions.bPath))
initOffsetError := initOffsetFromTsMs(grpcDialOptionB, filerB, tokenSourceB, aFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath, *syncOptions.bPath))
if initOffsetError != nil {
glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.aFromTsMs, *syncOptions.filerA, *syncOptions.filerB, initOffsetError)
os.Exit(2)
@@ -277,7 +280,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
httpClientA,
httpClientB,
jwtForFilerA,
jwtForFilerB)
jwtForFilerB,
tokenSourceA,
tokenSourceB)
if err != nil {
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
time.Sleep(1747 * time.Millisecond)
@@ -288,7 +293,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
if !*syncOptions.isActivePassive {
// b->a
// set synchronization start timestamp to offset
initOffsetError := initOffsetFromTsMs(grpcDialOptionA, filerA, bFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath, *syncOptions.aPath))
initOffsetError := initOffsetFromTsMs(grpcDialOptionA, filerA, tokenSourceA, bFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath, *syncOptions.aPath))
if initOffsetError != nil {
glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.bFromTsMs, *syncOptions.filerB, *syncOptions.filerA, initOffsetError)
os.Exit(2)
@@ -322,7 +327,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
httpClientB,
httpClientA,
jwtForFilerB,
jwtForFilerA)
jwtForFilerA,
tokenSourceB,
tokenSourceA)
if err != nil {
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
time.Sleep(2147 * time.Millisecond)
@@ -335,14 +342,14 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
}
// initOffsetFromTsMs Initialize offset
func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error {
func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, tokenSource security.FilerTokenSource, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error {
if fromTsMs <= 0 {
return nil
}
// convert to nanosecond
fromTsNs := fromTsMs * 1000_000
// If not successful, exit the program.
setOffsetErr := setOffset(grpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, fromTsNs)
setOffsetErr := setOffset(grpcDialOption, targetFiler, tokenSource, signaturePrefix, sourceFilerSignature, fromTsNs)
if setOffsetErr != nil {
return setOffsetErr
}
@@ -353,14 +360,15 @@ func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAdd
func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetGrpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, targetPath string,
replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, chunkConcurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32, statePtr *atomic.Pointer[syncState],
sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient,
sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider) error {
sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider,
sourceTokenSource security.FilerTokenSource, sinkTokenSource security.FilerTokenSource) error {
// if first time, start from now
// if has previously synced, resume from that point of time
// the historical key ignored the target path; falling back to it lets a
// sync that predates target-scoped keys survive the upgrade
signaturePrefix := getSignaturePrefixByPath(sourcePath, targetPath)
sourceFilerOffsetTsNs, err := getOffsetWithFallback(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, getSignaturePrefixByPath(sourcePath, "/"), sourceFilerSignature)
sourceFilerOffsetTsNs, err := getOffsetWithFallback(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, getSignaturePrefixByPath(sourcePath, "/"), sourceFilerSignature)
if err != nil {
return err
}
@@ -377,6 +385,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
if sourceJwtProvider != nil {
filerSource.SetFilerJwtProvider(sourceJwtProvider)
}
filerSource.SetFilerTokenSource(sourceTokenSource)
filerSink := &filersink.FilerSink{}
filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, targetGrpcDialOption, sinkWriteChunkByFiler)
filerSink.SetChunkConcurrency(chunkConcurrency)
@@ -386,6 +395,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
if sinkJwtProvider != nil {
filerSink.SetFilerJwtProvider(sinkJwtProvider)
}
filerSink.SetFilerTokenSource(sinkTokenSource)
filerSink.SetSourceFiler(filerSource)
persistEventFn := genProcessFunction(sourcePath, targetPath, sourceExcludePaths, nil, nil, nil, filerSink, doDeleteFiles, debug)
@@ -418,6 +428,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
sourcePath: sourcePath,
targetPath: targetPath,
sourceFilerSignature: sourceFilerSignature,
tokenSource: sinkTokenSource,
})
}
@@ -479,7 +490,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
lastProgressedTsNs = offsetTsNs
// collect synchronous offset
statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(offsetTsNs))
return setOffset(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor))
return setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor))
})
prefix := sourcePath
@@ -499,6 +510,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
StopTsNs: 0,
EventErrorType: pb.RetryForeverOnError,
FilerJwtProvider: sourceJwtProvider,
FilerTokenSource: sourceTokenSource,
GetResumeTsNs: func() int64 {
return resumeTsNsFor(processor)
},
@@ -540,9 +552,9 @@ func getSignaturePrefixByPath(sourcePath, targetPath string) string {
return prefix
}
func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
readErr = pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
readErr = pb.WithGrpcFilerClient(false, signature, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error {
syncKey := []byte(signaturePrefix + "____")
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
@@ -573,10 +585,10 @@ func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature
// instead of replaying from zero. Writes must go only to the current key:
// keeping the historical key warm would re-create the very sharing between
// streams that a key-scheme change separates.
func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, legacySignaturePrefix string, legacySignature int32) (int64, error) {
lastOffsetTsNs, err := getOffset(grpcDialOption, filer, signaturePrefix, signature)
func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32, legacySignaturePrefix string, legacySignature int32) (int64, error) {
lastOffsetTsNs, err := getOffset(grpcDialOption, filer, tokenSource, signaturePrefix, signature)
if err == nil && lastOffsetTsNs == 0 {
lastOffsetTsNs, err = getOffset(grpcDialOption, filer, legacySignaturePrefix, legacySignature)
lastOffsetTsNs, err = getOffset(grpcDialOption, filer, tokenSource, legacySignaturePrefix, legacySignature)
}
return lastOffsetTsNs, err
}
@@ -622,7 +634,7 @@ func resumeTsNsFor(p *MetadataProcessor) int64 {
// lands late can be told apart from the fresher write it would shadow.
var offsetWriteSeq atomic.Int64
func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error {
func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32, offsetTsNs int64) error {
syncKey := []byte(signaturePrefix + "____")
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
key := string(filer) + "\x00" + string(syncKey)
@@ -643,7 +655,7 @@ func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature
}
checkpoint.lastSeq = seq
return pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(false, signature, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error {
valueBuf := make([]byte, 8)
util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
+10 -10
View File
@@ -60,21 +60,21 @@ func TestSyncOffset_HistoricalFallbackThenIndependence(t *testing.T) {
prefixB := getSignaturePrefixByPath("/data", "/backup-b")
// pre-upgrade state: both syncs shared the historical key
if err := setOffset(dial, filerAddr, historical, sourceSig, 111); err != nil {
if err := setOffset(dial, filerAddr, nil, historical, sourceSig, 111); err != nil {
t.Fatalf("seed historical offset: %v", err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, prefixA, sourceSig, historical, sourceSig); err != nil || got != 111 {
if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixA, sourceSig, historical, sourceSig); err != nil || got != 111 {
t.Fatalf("A fallback read = (%d, %v), want (111, nil)", got, err)
}
// A checkpoints under its own key; B still resumes from the historical one
if err := setOffset(dial, filerAddr, prefixA, sourceSig, 222); err != nil {
if err := setOffset(dial, filerAddr, nil, prefixA, sourceSig, 222); err != nil {
t.Fatalf("write A offset: %v", err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, prefixA, sourceSig, historical, sourceSig); err != nil || got != 222 {
if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixA, sourceSig, historical, sourceSig); err != nil || got != 222 {
t.Fatalf("A read = (%d, %v), want (222, nil)", got, err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, prefixB, sourceSig, historical, sourceSig); err != nil || got != 111 {
if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixB, sourceSig, historical, sourceSig); err != nil || got != 111 {
t.Fatalf("B read = (%d, %v), want (111, nil)", got, err)
}
}
@@ -88,7 +88,7 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) {
prefix := getSignaturePrefixByPath("/data", "/backup-stale")
sourceSig := int32(77)
if err := setOffset(dial, filerAddr, prefix, sourceSig, 300); err != nil {
if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 300); err != nil {
t.Fatalf("seed offset: %v", err)
}
@@ -107,10 +107,10 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) {
checkpoint.lastSeq = offsetWriteSeq.Load() + 1000
checkpoint.Unlock()
if err := setOffset(dial, filerAddr, prefix, sourceSig, 100); err != nil {
if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 100); err != nil {
t.Fatalf("stale write: %v", err)
}
if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 300 {
if got, err := getOffset(dial, filerAddr, nil, prefix, sourceSig); err != nil || got != 300 {
t.Fatalf("after stale write = (%d, %v), want (300, nil)", got, err)
}
@@ -118,10 +118,10 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) {
checkpoint.Lock()
checkpoint.lastSeq = 0
checkpoint.Unlock()
if err := setOffset(dial, filerAddr, prefix, sourceSig, 199); err != nil {
if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 199); err != nil {
t.Fatalf("floored write: %v", err)
}
if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 199 {
if got, err := getOffset(dial, filerAddr, nil, prefix, sourceSig); err != nil || got != 199 {
t.Fatalf("after floored write = (%d, %v), want (199, nil)", got, err)
}
}
+10 -7
View File
@@ -89,6 +89,8 @@ func runFilerSyncVerify(cmd *Command, args []string) bool {
glog.Fatalf("load security config for filer B: %v", err)
}
}
tokenSourceA := security.FilerAdminTokenFromFile(*syncVerifyOptions.aSecurity)
tokenSourceB := security.FilerAdminTokenFromFile(*syncVerifyOptions.bSecurity)
filerA := pb.ServerAddress(*syncVerifyOptions.filerA)
filerB := pb.ServerAddress(*syncVerifyOptions.filerB)
@@ -96,7 +98,7 @@ func runFilerSyncVerify(cmd *Command, args []string) bool {
if err := runVerifySync(filerA, filerB, *syncVerifyOptions.aPath, *syncVerifyOptions.bPath,
*syncVerifyOptions.isActivePassive, *syncVerifyOptions.modifiedTimeAgo,
*syncVerifyOptions.jsonOutput,
grpcDialOptionA, grpcDialOptionB); err != nil {
grpcDialOptionA, grpcDialOptionB, tokenSourceA, tokenSourceB); err != nil {
glog.Errorf("verify sync: %v", err)
os.Exit(2)
}
@@ -184,13 +186,13 @@ type summaryRecord struct {
type simpleFilerClient struct {
grpcAddress pb.ServerAddress
grpcDialOption grpc.DialOption
tokenSource security.FilerTokenSource
}
func (c *simpleFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithGrpcClient(context.Background(), streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
return pb.WithGrpcFilerClient(streamingMode, 0, c.grpcAddress, c.grpcDialOption, c.tokenSource, func(client filer_pb.SeaweedFilerClient) error {
return fn(client)
}, c.grpcAddress.ToGrpcAddress(), false, c.grpcDialOption)
})
}
func (c *simpleFilerClient) AdjustedUrl(location *filer_pb.Location) string {
@@ -204,10 +206,11 @@ func (c *simpleFilerClient) GetDataCenter() string {
func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
isActivePassive bool, modifiedTimeAgo time.Duration,
jsonOutput bool,
grpcDialOptionA, grpcDialOptionB grpc.DialOption) error {
grpcDialOptionA, grpcDialOptionB grpc.DialOption,
tokenSourceA, tokenSourceB security.FilerTokenSource) error {
clientA := &simpleFilerClient{grpcAddress: filerA, grpcDialOption: grpcDialOptionA}
clientB := &simpleFilerClient{grpcAddress: filerB, grpcDialOption: grpcDialOptionB}
clientA := &simpleFilerClient{grpcAddress: filerA, grpcDialOption: grpcDialOptionA, tokenSource: tokenSourceA}
clientB := &simpleFilerClient{grpcAddress: filerB, grpcDialOption: grpcDialOptionB, tokenSource: tokenSourceB}
var cutoffTime time.Time
if modifiedTimeAgo > 0 {
+7
View File
@@ -274,6 +274,13 @@ func runFuse(cmd *Command, args []string) bool {
fmt.Fprintf(os.Stderr, "failed to parse 'writebackCache' value %q: %v\n", parameter.value, err)
return false
}
case "concurrentWriteMerge":
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
mountOptions.concurrentWriteMerge = &parsed
} else {
fmt.Fprintf(os.Stderr, "failed to parse 'concurrentWriteMerge' value %q: %v\n", parameter.value, err)
return false
}
case "asyncDio":
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
mountOptions.asyncDio = &parsed
+1 -1
View File
@@ -89,7 +89,7 @@ func (iamopt *IamOptions) startIamServer() bool {
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
var digest string
for {
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer configuration: %v", err)
+3 -3
View File
@@ -485,7 +485,7 @@ func initMiniFilerFlags() {
miniFilerOptions.saveToFilerLimit = cmdMini.Flag.Int("filer.saveToFilerLimit", 0, "files smaller than this limit will be saved in filer store")
miniFilerOptions.concurrentUploadLimitMB = cmdMini.Flag.Int("filer.concurrentUploadLimitMB", 0, "limit total concurrent upload size")
miniFilerOptions.concurrentFileUploadLimit = cmdMini.Flag.Int("filer.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads")
miniFilerOptions.inflightUploadDataTimeout = cmdMini.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 429, 0 means no limit")
miniFilerOptions.inflightUploadDataTimeout = cmdMini.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 503 and Retry-After, 0 means no limit")
miniFilerOptions.localSocket = cmdMini.Flag.String("filer.localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
miniFilerOptions.showUIDirectoryDelete = cmdMini.Flag.Bool("filer.ui.deleteDir", true, "enable filer UI show delete directory button")
miniFilerOptions.downloadMaxMBps = cmdMini.Flag.Int("filer.downloadMaxMBps", 0, "download max speed for each download request, in MB per second")
@@ -2474,7 +2474,7 @@ func ensureMiniBuckets(bucketSpec string) error {
// Derive from miniClientsCtx so Ctrl+C cancels the bucket RPCs, and bound
// with a short timeout (per bucket) so a stalled filer cannot block the
// welcome message indefinitely.
return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
for _, name := range names {
if err := s3bucket.VerifyS3BucketName(name); err != nil {
glog.Warningf("invalid bucket name %q: %v", name, err)
@@ -2552,7 +2552,7 @@ func createMiniTableBuckets(servable []tableBucketEntry) ([]tableBucketEntry, er
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
var ready []tableBucketEntry
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
manager := s3tables.NewManager()
mgrClient := s3tables.NewManagerClient(client)
for _, bucket := range servable {
+2 -2
View File
@@ -15,7 +15,7 @@ func TestMiniDefaultPluginJobTypes(t *testing.T) {
if err != nil {
t.Fatalf("buildPluginWorkerHandlers(mini default) err = %v", err)
}
if len(handlers) != 7 {
t.Fatalf("expected mini default job types to include 7 handlers, got %d", len(handlers))
if len(handlers) != 9 {
t.Fatalf("expected mini default job types to include 9 handlers, got %d", len(handlers))
}
}
+3 -1
View File
@@ -65,7 +65,8 @@ type MountOptions struct {
// Distributed locking for cross-mount write coordination and POSIX
// advisory locks (flock/fcntl)
distributedLock *bool
distributedLock *bool
concurrentWriteMerge *bool
// POSIX compliance options
posixDirNlink *bool
@@ -163,6 +164,7 @@ func init() {
// Distributed lock for cross-mount write coordination
mountOptions.distributedLock = cmdMount.Flag.Bool("dlm", false, "coordinate writes across mounts (only one mount writes a file at a time) and honor POSIX advisory locks (flock/fcntl) across mounts by routing them to the owner filer")
mountOptions.concurrentWriteMerge = cmdMount.Flag.Bool("concurrentWriteMerge", false, "when another mount wrote a file this mount has unflushed writes to, merge both mounts' writes instead of failing the later flush with EIO")
// POSIX compliance options
mountOptions.posixDirNlink = cmdMount.Flag.Bool("posix.dirNLink", false, "report POSIX-compliant directory nlink (2 + subdirectory count); costs one directory listing per stat")
+2 -1
View File
@@ -149,7 +149,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr
var err error
var digest string
for i := 0; i < 10; i++ {
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err)
@@ -253,6 +253,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
MetadataFlushSeconds: *option.metadataFlushSeconds,
DirIdleEvictSec: *option.dirIdleEvictSec,
EnableDistributedLock: option.distributedLock != nil && *option.distributedLock,
ConcurrentWriteMerge: option.concurrentWriteMerge != nil && *option.concurrentWriteMerge,
WritebackCache: option.writebackCache != nil && *option.writebackCache,
NfsExport: option.nfsExport != nil && *option.nfsExport,
EagerFilerCreate: p.eagerFilerCreate,
+1 -1
View File
@@ -328,7 +328,7 @@ func (s3opt *S3Options) startS3Server() bool {
var filerDigest string
for {
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer configuration: %v", err)
+9 -3
View File
@@ -17,12 +17,18 @@ recursive_delete = false
# increase this if using tools like Spark that create temporary directories.
#s3.empty_folder_cleanup_delay = "2m"
# where the filer's internal system metadata log chunks are stored.
# By default the log follows the filer's -collection flag; set this to keep
# the internal log in its own collection, out of the default one.
# By default the log has its own collection, so purging old log days frees
# whole volumes. Set it to "" to keep the log in the filer's -collection.
# Avoid a name a bucket maps to: deleting that bucket drops the collection.
# Keep the target stable: log chunks written under an older value are not
# moved, and old log entries keep referencing that collection's volumes.
#metaLog.collection = "filer-meta"
#metaLog.collection = "_meta"
#metaLog.replication = ""
# volumes added each time the metadata log collection needs to grow.
# Keep this many free volume slots for it beside the master's volume_growth
# count; 0 uses the master's count. When the collection cannot grow, log
# chunks go to the filer's -collection until it can.
#metaLog.volumeGrowthCount = 2
####################################################
# The following are filer store options
+2
View File
@@ -55,6 +55,8 @@ storage_class = "STANDARD_IA"
# 000 has only one copy, copy_1
# 010 and 001 has two copies, copy_2
# 011 has only 3 copies, copy_3
# The filer's metadata log collection grows by metaLog.volumeGrowthCount in
# filer.toml instead; volume servers keep room for both by default (-max=10).
[master.volume_growth]
copy_1 = 7 # create 1 x 7 = 7 actual volumes
copy_2 = 6 # create 2 x 6 = 12 actual volumes
+10
View File
@@ -214,6 +214,16 @@ allowed_wildcard_domain = "" # .mycompany.com
# allowlist and refuse to start when per-target keys are their only allowlist.
allowed_server_commonNames = "" # comma-separated server identities
allowed_server_wildcard_domain = "" # .mycompany.com
# Client certificate common names that every mTLS gRPC server accepts for the
# standard grpc.health.v1.Health service only. Give a monitoring probe a
# CA-signed client certificate with one of these names, e.g. blackbox_exporter's
# grpc prober, or grpc_health_probe with -tls-client-cert run as a Kubernetes
# exec probe (the built-in Kubernetes grpc probe cannot present a client
# certificate). The probe can check that the port serves and that the server
# certificate is valid, but any other RPC is refused with PermissionDenied. The
# names need no place in allowed_commonNames, and a name listed here stays
# confined even if it is.
health_check_commonNames = "" # comma-separated, e.g. "blackbox-exporter"
# Volume server gRPC options (server-side)
# Enables mTLS for incoming gRPC connections to volume server
+2 -2
View File
@@ -69,7 +69,7 @@ var (
serverDisableHttp = cmdServer.Flag.Bool("disableHttp", false, "disable http requests, only gRPC operations are allowed.")
serverIamConfig = cmdServer.Flag.String("iam.config", "", "path to the advanced IAM config file for S3. An alias for -s3.iam.config, but with lower priority.")
volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
volumeMinFreeSpacePercent = cmdServer.Flag.String("volume.minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
volumeMinFreeSpace = cmdServer.Flag.String("volume.minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
serverMetricsHttpPort = cmdServer.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
@@ -132,7 +132,7 @@ func init() {
filerOptions.saveToFilerLimit = cmdServer.Flag.Int("filer.saveToFilerLimit", 0, "Small files smaller than this limit can be cached in filer store.")
filerOptions.concurrentUploadLimitMB = cmdServer.Flag.Int("filer.concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
filerOptions.concurrentFileUploadLimit = cmdServer.Flag.Int("filer.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
filerOptions.inflightUploadDataTimeout = cmdServer.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 429, 0 means no limit")
filerOptions.inflightUploadDataTimeout = cmdServer.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 503 and Retry-After, 0 means no limit")
filerOptions.localSocket = cmdServer.Flag.String("filer.localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
filerOptions.showUIDirectoryDelete = cmdServer.Flag.Bool("filer.ui.deleteDir", true, "enable filer UI show delete directory button")
filerOptions.downloadMaxMBps = cmdServer.Flag.Int("filer.downloadMaxMBps", 0, "download max speed for each download request, in MB per second")
+1 -1
View File
@@ -137,7 +137,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
// Connect to the filer service and try to retrieve basic configuration.
for {
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
+1
View File
@@ -44,6 +44,7 @@ func runShell(command *Command, args []string) bool {
util.LoadSecurityConfiguration()
shellOptions.GrpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client")
shellOptions.FilerTokenSource = security.FilerAdminToken
shellOptions.Directory = "/"
util.LoadConfiguration("shell", false)
+2
View File
@@ -9,10 +9,12 @@ import (
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
func gracefulStopGrpc(grpcS *grpc.Server, timeout time.Duration) {
glog.V(0).Infof("Gracefully stopping gRPC server")
pb.StopHealthWatches(grpcS)
stopped := make(chan struct{})
go func() {
grpcS.GracefulStop()
+2 -1
View File
@@ -268,7 +268,7 @@ var cmdVolume = &Command{
var (
volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
maxVolumeCounts = cmdVolume.Flag.String("max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
maxVolumeCounts = cmdVolume.Flag.String("max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
@@ -591,6 +591,7 @@ func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server,
}
glog.V(0).Infof("graceful stop gRPC ...")
pb.StopHealthWatches(grpcS)
grpcS.GracefulStop()
volumeServer.Shutdown()
+1 -1
View File
@@ -118,7 +118,7 @@ func (wo *WebDavOption) startWebDav() bool {
var digest string
// connect to filer
for {
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
+2
View File
@@ -19,7 +19,9 @@ func TestWorkerDefaultJobTypes(t *testing.T) {
"admin_script",
"ec_balance",
"erasure_coding",
"filer_ttl",
"iceberg_maintenance",
"meta_log_purge",
"s3_lifecycle",
"vacuum",
"volume_balance",
@@ -5,6 +5,7 @@ import (
"net"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -14,11 +15,13 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"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"
"google.golang.org/protobuf/proto"
)
@@ -34,6 +37,68 @@ type policyTestFilerServer struct {
beforeUpdate func(string, string) error
}
const filerEtcAuthTestKey = "filer-etc-auth-test-key-32-bytes-long"
func TestFilerEtcStoreUsesPerCallAdminToken(t *testing.T) {
t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", "")
t.Setenv("WEED_JWT_FILER_SIGNING_KEY", filerEtcAuthTestKey)
server := newPolicyTestFilerServer()
checkAuth := func(ctx context.Context) error {
md, _ := metadata.FromIncomingContext(ctx)
values := md.Get("authorization")
if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) {
return status.Error(codes.Unauthenticated, "missing filer admin token")
}
token := security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))
if !security.IsFilerAdminToken(security.SigningKey(filerEtcAuthTestKey), token) {
return status.Error(codes.Unauthenticated, "invalid filer admin token")
}
return nil
}
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if err := checkAuth(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}),
grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := checkAuth(stream.Context()); err != nil {
return err
}
return handler(srv, stream)
}),
)
filer_pb.RegisterSeaweedFilerServer(grpcServer, server)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
go func() { _ = grpcServer.Serve(listener) }()
t.Cleanup(func() {
grpcServer.Stop()
_ = listener.Close()
})
host, portString, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
t.Fatal(err)
}
grpcPort, err := strconv.Atoi(portString)
if err != nil {
t.Fatal(err)
}
store := &FilerEtcStore{}
store.SetFilerAddressFunc(func() pb.ServerAddress {
return pb.NewServerAddress(host, 1, grpcPort)
}, grpc.WithTransportCredentials(insecure.NewCredentials()))
if _, err := store.ListPolicyNames(context.Background()); err != nil {
t.Fatalf("ListPolicyNames: %v", err)
}
}
func newPolicyTestFilerServer() *policyTestFilerServer {
return &policyTestFilerServer{
entries: make(map[string]*filer_pb.Entry),
+2 -1
View File
@@ -7,6 +7,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
)
@@ -71,7 +72,7 @@ func (store *FilerEtcStore) withFilerClient(fn func(client filer_pb.SeaweedFiler
}
// Use the pb.WithGrpcFilerClient helper similar to existing code
return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, fn)
return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, security.FilerAdminToken, fn)
}
func (store *FilerEtcStore) Shutdown() {
+1 -1
View File
@@ -246,7 +246,7 @@ func (group *ChunkGroup) SetChunks(chunks []*filer_pb.FileChunk) error {
return err
}
dataChunks = append(dataChunks, resolvedChunks...)
dataChunks = append(dataChunks, cutToManifestSpan(chunk, resolvedChunks)...)
}
sections := make(map[SectionIndex]*FileChunkSection)
Loaded 100 of 332 files, more files were not shown because too many files have changed in this diff. Show more