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
115 changed files with 8411 additions and 1746 deletions

No files matched your search

+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 -1063
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

+384
View File
@@ -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",
+1
View File
@@ -4662,6 +4662,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"uuid",
"webpki-roots",
"windows-sys 0.61.2",
"x509-parser",
"xxhash-rust",
+1
View File
@@ -68,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
+88 -45
View File
@@ -175,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.
@@ -1157,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;
}
@@ -1305,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.
@@ -1343,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> {
@@ -2339,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();
@@ -2355,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();
+99 -21
View File
@@ -169,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!(
@@ -204,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');
@@ -217,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()
@@ -1281,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();
+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"
+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")
+3 -2
View File
@@ -90,8 +90,9 @@ var jobTypeLaneMap = map[string]SchedulerLane{
"iceberg_maintenance": LaneIceberg,
// S3 lifecycle management
"s3_lifecycle": LaneLifecycle,
"filer_ttl": 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
@@ -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
+2 -1
View File
@@ -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)
+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
+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) != 8 {
t.Fatalf("expected mini default job types to include 8 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")
+1
View File
@@ -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,
+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
+1 -1
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")
+1 -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.")
+1
View File
@@ -21,6 +21,7 @@ func TestWorkerDefaultJobTypes(t *testing.T) {
"erasure_coding",
"filer_ttl",
"iceberg_maintenance",
"meta_log_purge",
"s3_lifecycle",
"vacuum",
"volume_balance",
+18
View File
@@ -47,6 +47,9 @@ func FileSize(entry *filer_pb.Entry) (size uint64) {
func ETag(entry *filer_pb.Entry) (etag string) {
if entry.Attributes == nil || entry.Attributes.Md5 == nil {
if etag, ok := ETagOfInlineContent(entry); ok {
return etag
}
return ETagChunks(entry.GetChunks())
}
return fmt.Sprintf("%x", entry.Attributes.Md5)
@@ -57,11 +60,26 @@ func ETagEntry(entry *Entry) (etag string) {
return entry.Remote.RemoteETag
}
if entry.Attr.Md5 == nil {
if len(entry.GetChunks()) == 0 && entry.FileSize <= uint64(len(entry.Content)) {
return util.Md5String(entry.Content)
}
return ETagChunks(entry.GetChunks())
}
return fmt.Sprintf("%x", entry.Attr.Md5)
}
// ETagOfInlineContent is the ETag of an entry that stores no MD5 and whose
// bytes are its inline content, possibly none: their MD5, as for content the
// filer stored itself. A mount writes such an entry for an empty file, and for
// a small one it keeps inline. ok is false for an entry with chunks, or with a
// size past its content (a hole no chunk covers), which ETagChunks names.
func ETagOfInlineContent(entry *filer_pb.Entry) (etag string, ok bool) {
if len(entry.GetChunks()) != 0 || FileSize(entry) > uint64(len(entry.Content)) {
return "", false
}
return util.Md5String(entry.Content), true
}
func ETagChunks(chunks []*filer_pb.FileChunk) (etag string) {
if len(chunks) == 1 {
return fmt.Sprintf("%x", util.Base64Md5ToBytes(chunks[0].ETag))
+41
View File
@@ -626,3 +626,44 @@ func TestViewFromChunksPropagatesError(t *testing.T) {
t.Fatalf("expected nil views on error, got %v", views)
}
}
// An entry without a stored MD5 and without chunks has its bytes inline,
// possibly none: a mount writes one for an empty file. Its ETag is the MD5 of
// those bytes, the same as when the filer stored the content itself, and not
// the chunk form for zero chunks ("...-0").
func TestETagOfAnEntryWithoutChunks(t *testing.T) {
const md5OfNothing = "d41d8cd98f00b204e9800998ecf8427e"
const md5OfHello = "5d41402abc4b2a76b9719d911017c592"
oneChunk := []*filer_pb.FileChunk{{FileId: "1,1", Size: 5, ETag: "XUFAKrxLKna5cZ2REBfFkg=="}}
tests := []struct {
name string
entry *filer_pb.Entry
want string
}{
{"empty file", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}, md5OfNothing},
{"empty file, no attributes", &filer_pb.Entry{}, md5OfNothing},
{"inline content", &filer_pb.Entry{Content: []byte("hello"), Attributes: &filer_pb.FuseAttributes{FileSize: 5}}, md5OfHello},
{"inline content, size not set", &filer_pb.Entry{Content: []byte("hello"), Attributes: &filer_pb.FuseAttributes{}}, md5OfHello},
{"a stored MD5 wins", &filer_pb.Entry{Content: []byte("hello"), Attributes: &filer_pb.FuseAttributes{Md5: []byte{0xab, 0xcd}}}, "abcd"},
{"one chunk", &filer_pb.Entry{Chunks: oneChunk, Attributes: &filer_pb.FuseAttributes{FileSize: 5}}, md5OfHello},
// a hole no chunk covers is not inline content: the chunk form stays
{"a hole only", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{FileSize: 4096}}, md5OfNothing + "-0"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ETag(tt.entry); got != tt.want {
t.Errorf("ETag() = %q, want %q", got, tt.want)
}
// the filer's own entry gives the same
fsEntry := &Entry{Content: tt.entry.Content, Chunks: tt.entry.Chunks}
if tt.entry.Attributes != nil {
fsEntry.Attr.Md5 = tt.entry.Attributes.Md5
fsEntry.Attr.FileSize = tt.entry.Attributes.FileSize
}
if got := ETagEntry(fsEntry); got != tt.want {
t.Errorf("ETagEntry() = %q, want %q", got, tt.want)
}
})
}
}
+15 -10
View File
@@ -54,6 +54,10 @@ type DialOptions struct {
Volume grpc.DialOption
}
// No bucket maps to this collection: bucket names cannot contain "_", and a
// filer group's buckets map to "<group>_<bucket>", with a "_" after the group.
const defaultMetaLogCollection = "_meta"
type Filer struct {
UniqueFilerId int32
UniqueFilerEpoch int32
@@ -73,11 +77,13 @@ type Filer struct {
LocalMetaLogBuffer *log_buffer.LogBuffer
metaLogCollection string
metaLogReplication string
// Override where system metadata-log chunks are assigned, keeping the
// internal log out of the default collection; empty keeps today's
// behaviour. Set via viper: filer.options.metaLog.collection / .replication.
// Where system metadata-log chunks are assigned, keeping the internal log
// out of the default collection; empty follows the filer's collection.
// Set via viper: filer.options.metaLog.collection / .replication.
metaLogTargetCollection string
metaLogTargetReplication string
metaLogVolumeGrowthCount uint32
metaLogOwnAssignPausedUntil atomic.Int64
DefaultDiskType string
MetaAggregator *MetaAggregator
Signature int32
@@ -181,15 +187,13 @@ func NewFiler(masters pb.ServerDiscovery, dialOptions *DialOptions, filerHost pb
f.metaLogCollection = collection
f.metaLogReplication = replication
// Optional override for where the system metadata-log chunks land, so
// operators can keep internal log volumes out of the default collection.
// Unset (""), this changes nothing: meta logs keep following the filer
// default exactly as before.
v := util.GetViper()
v.SetDefault("filer.options.metaLog.collection", "")
v.SetDefault("filer.options.metaLog.collection", defaultMetaLogCollection)
v.SetDefault("filer.options.metaLog.replication", "")
v.SetDefault("filer.options.metaLog.volumeGrowthCount", 2)
f.metaLogTargetCollection = v.GetString("filer.options.metaLog.collection")
f.metaLogTargetReplication = v.GetString("filer.options.metaLog.replication")
f.metaLogVolumeGrowthCount = v.GetUint32("filer.options.metaLog.volumeGrowthCount")
if f.metaLogTargetCollection != "" {
glog.V(0).Infof("system metadata logs will be stored in collection %q", f.metaLogTargetCollection)
}
@@ -1170,9 +1174,10 @@ func (f *Filer) FindEntryWithoutRemoteFetch(ctx context.Context, p util.FullPath
// transaction. A replacement must account for its chunks and hard links and
// publish its deletion after commit: once overwritten, no later lookup can
// discover it for expiry cleanup. Ordinary lookups still see it as absent.
// A miss the store itself answered is not read again.
func (f *Filer) FindEntryForOverwrite(ctx context.Context, p util.FullPath) (*Entry, error) {
entry, err := f.FindEntry(ctx, p)
if errors.Is(err, filer_pb.ErrNotFound) && ctx.Value(storeTransactionKey{}) != nil {
entry, fromStore, err := f.findEntry(ctx, p)
if errors.Is(err, filer_pb.ErrNotFound) && !fromStore && ctx.Value(storeTransactionKey{}) != nil {
return f.Store.FindEntry(ctx, p)
}
return entry, err
@@ -252,6 +252,27 @@ func TestDeleteBucketNamedAfterSharedCollection(t *testing.T) {
}
}
// A filer logging elsewhere still keeps the default meta log collection:
// other filers may write their logs there.
func TestDeleteBucketKeepsDefaultMetaLogCollection(t *testing.T) {
f, store, master := newFilerWithFakeMaster(t)
f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/a",
Collection: defaultMetaLogCollection,
})
seedBucket(t, store, util.FullPath("/buckets/a"))
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/a", true, false, true, false, nil, time.Time{}); err != nil {
t.Fatalf("DeleteEntryMetaAndData: %v", err)
}
select {
case call := <-master.calls:
t.Fatalf("default meta log collection was deleted: %q", call.name)
default:
}
}
// A rule pointing a non-bucket path at the same collection keeps it: the
// collection serves files the bucket delete must not orphan.
func TestDeleteBucketKeepsCollectionUsedByNonBucketPath(t *testing.T) {
+3 -5
View File
@@ -338,11 +338,9 @@ func (f *Filer) bucketCollection(ctx context.Context, bucket string) (collection
// Rule-less writes outside buckets fall back to the filer's default
// collection, so a bucket resolving there shares it with them. The
// system metadata-log collection (when explicitly redirected via
// filer.options.metaLog.collection) is in the same boat: it backs internal
// log volumes, so a bucket that resolves there must never drop it
// either.
if collection == f.metaLogCollection {
// metadata-log collections back internal log volumes, and the default one
// can serve other filers even when this one logs elsewhere.
if collection == f.metaLogCollection || collection == defaultMetaLogCollection {
return ""
}
if f.metaLogTargetCollection != "" && collection == f.metaLogTargetCollection {
+439
View File
@@ -0,0 +1,439 @@
package filer
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/require"
)
// What a listing reads the store for besides the listing itself: the shared
// record of every hard-linked entry. A store that reads KV keys in batches is
// asked for the records of the waiting entries together; the caller of the
// listing must not be able to tell, except by how long it takes.
// rowListingStore hands over an entry of its own for each name it lists, as a
// store that decodes rows does. It can fail a listing part of the way.
type rowListingStore struct {
*stubFilerStore
failAfter int // fail the listing once it has handed over this many entries
listErr error // with this
// A store may take one more step after its caller ended the listing, as
// TiKV moves its iterator on before it looks at the answer. stopErr is
// that step failing behind the entry numbered failStopAt.
failStopAt int
stopErr error
}
func (s *rowListingStore) list(listed func(each ListEachEntryFunc) (string, error), eachEntryFunc ListEachEntryFunc) (string, error) {
handed, endedAt := 0, 0
lastFileName, err := listed(func(entry *Entry) (bool, error) {
if s.listErr != nil && handed == s.failAfter {
return false, s.listErr
}
handed++
more, err := eachEntryFunc(entry.ShallowClone())
if err == nil && !more {
endedAt = handed
}
return more, err
})
if err == nil && s.stopErr != nil && endedAt == s.failStopAt {
return lastFileName, s.stopErr
}
return lastFileName, err
}
func (s *rowListingStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (string, error) {
return s.list(func(each ListEachEntryFunc) (string, error) {
return s.stubFilerStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, each)
}, eachEntryFunc)
}
func (s *rowListingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (string, error) {
return s.list(func(each ListEachEntryFunc) (string, error) {
return s.stubFilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, each)
}, eachEntryFunc)
}
// batchReadingStore also reads KV keys in batches.
type batchReadingStore struct {
*rowListingStore
batches [][]string // the keys of each batch it was asked for
batchErr error
}
func (s *batchReadingStore) KvBatchGet(_ context.Context, keys [][]byte) (map[string][]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
batch := make([]string, 0, len(keys))
for _, key := range keys {
batch = append(batch, string(key))
}
s.batches = append(s.batches, batch)
if s.batchErr != nil {
return nil, s.batchErr
}
values := make(map[string][]byte)
for _, key := range keys {
if value, found := s.kv[string(key)]; found {
values[string(key)] = append([]byte(nil), value...)
}
}
return values, nil
}
// linkListingStores returns the same directory in a store that reads records
// one at a time and in one that reads them in batches, each with a count of
// the single reads it serves.
func linkListingStores(t *testing.T, fill func(store *stubFilerStore)) (oneByOne *rowListingStore, oneReads *int, batched *batchReadingStore, batchedReads *int) {
t.Helper()
build := func() (*rowListingStore, *int) {
stub := newStubFilerStore()
fill(stub)
reads := new(int)
stub.kvGetHook = func([]byte) { *reads++ }
return &rowListingStore{stubFilerStore: stub}, reads
}
oneByOne, oneReads = build()
rows, batchedReads := build()
return oneByOne, oneReads, &batchReadingStore{rowListingStore: rows}, batchedReads
}
// linkedName stores name as one more name of a hard-linked file. The row keeps
// what the name was written with; the record, which a listing must answer
// with, has moved on: size bytes and count names.
func linkedName(t *testing.T, store *stubFilerStore, id HardLinkId, name string, size uint64, count int32) {
t.Helper()
store.entries[name] = &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o644, Mtime: time.Unix(1700000000, 0)},
HardLinkId: id,
HardLinkCounter: 1,
}
if size == 0 {
return // a name whose record is gone
}
store.kv[string(id)] = encodeLinkRecord(t, &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o600, Mtime: time.Unix(1700000500, 0), FileSize: size},
HardLinkId: id,
HardLinkCounter: count,
Chunks: []*filer_pb.FileChunk{{FileId: fmt.Sprintf("7,%02x", size), Size: size}},
})
}
// listed is what a caller of a listing can see of an entry.
type listed struct {
Name string
Size uint64
Mode uint32
Links int32
Chunks string
}
func see(entry *Entry) listed {
return listed{
Name: entry.Name(),
Size: entry.FileSize,
Mode: uint32(entry.Mode),
Links: entry.HardLinkCounter,
Chunks: strings.Join(filer_pb.FileIdsString(entry.GetChunks()), " "),
}
}
func listAll(t *testing.T, store FilerStore, dir string, startFileName string, limit int64) (entries []listed, lastFileName string) {
t.Helper()
lastFileName, err := NewFilerStoreWrapper(store).ListDirectoryEntries(context.Background(), util.FullPath(dir), startFileName, false, limit, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return true, nil
})
require.NoError(t, err)
return entries, lastFileName
}
func mixedDirectory(t *testing.T) func(store *stubFilerStore) {
x, y, gone := HardLinkId("link-x-0123456789"), HardLinkId("link-y-0123456789"), HardLinkId("link-gone-0123456")
return func(store *stubFilerStore) {
store.entries["/d/a"] = fileAt("/d/a")
linkedName(t, store, x, "/d/b", 11, 2)
store.entries["/d/c"] = fileAt("/d/c")
linkedName(t, store, y, "/d/d", 22, 3)
linkedName(t, store, x, "/d/e", 11, 2)
linkedName(t, store, gone, "/d/f", 0, 0)
store.entries["/d/g"] = fileAt("/d/g")
linkedName(t, store, y, "/elsewhere/y", 22, 3)
}
}
func TestListingReadsHardLinkRecordsTogether(t *testing.T) {
oneByOne, oneReads, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
want, wantLast := listAll(t, oneByOne, "/d", "", 100)
got, gotLast := listAll(t, batched, "/d", "", 100)
require.Equal(t, []string{"a", "b", "c", "d", "e", "f", "g"}, namesOf(want))
require.Equal(t, listed{Name: "b", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}, want[1], "a linked name lists what its record holds")
require.Equal(t, listed{Name: "f", Mode: 0o644, Links: 1}, want[5], "a name whose record is gone lists its row")
require.Equal(t, want, got, "the entries of a listing do not depend on how their records were read")
require.Equal(t, wantLast, gotLast)
require.Equal(t, 4, *oneReads, "one read for each hard-linked name")
require.Zero(t, *batchedReads)
require.Equal(t, [][]string{{"link-x-0123456789", "link-y-0123456789", "link-gone-0123456"}}, batched.batches,
"one read for all of them, each record asked for once")
}
func TestListingWithAPrefixReadsHardLinkRecordsTogether(t *testing.T) {
_, _, batched, batchedReads := linkListingStores(t, func(store *stubFilerStore) {
for i := 0; i < 6; i++ {
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%d-0123456789", i)), fmt.Sprintf("/d/p%d", i), uint64(10+i), 2)
store.entries[fmt.Sprintf("/d/q%d", i)] = fileAt(fmt.Sprintf("/d/q%d", i))
}
})
var got []listed
lastFileName, err := NewFilerStoreWrapper(batched).ListDirectoryPrefixedEntries(context.Background(), "/d", "", false, 100, "p", func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return true, nil
})
require.NoError(t, err)
require.Equal(t, "p5", lastFileName)
require.Equal(t, []string{"p0", "p1", "p2", "p3", "p4", "p5"}, namesOf(got))
require.Equal(t, uint64(13), got[3].Size)
require.Zero(t, *batchedReads)
require.Len(t, batched.batches, 1)
}
// More names than wait at once: the entries still come in the store's order,
// page after page, each once.
func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
const names = 2*hardLinkBatchSize + 300
oneByOne, _, batched, batchedReads := linkListingStores(t, func(store *stubFilerStore) {
for i := 0; i < names; i++ {
name := fmt.Sprintf("/d/n%05d", i)
if i%3 == 1 {
store.entries[name] = fileAt(name)
continue
}
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%05d-012345", i)), name, uint64(1+i), 2)
}
})
want, _ := listAll(t, oneByOne, "/d", "", names+1)
got, lastFileName := listAll(t, batched, "/d", "", names+1)
require.Len(t, got, names)
require.Equal(t, want, got)
require.Equal(t, fmt.Sprintf("n%05d", names-1), lastFileName)
require.Zero(t, *batchedReads)
// the first name is linked, so every hardLinkBatchSize entries wait together
require.Len(t, batched.batches, (names+hardLinkBatchSize-1)/hardLinkBatchSize)
for _, batch := range batched.batches {
require.LessOrEqual(t, len(batch), hardLinkBatchSize)
}
// read in pages, as ListEntries reads a directory
const pageSize = hardLinkBatchSize + 100
var paged []listed
for start := ""; ; {
page, last := listAll(t, batched, "/d", start, pageSize)
paged = append(paged, page...)
if len(page) < pageSize {
break
}
start = last
}
require.Equal(t, want, paged)
}
// The caller ends a listing at an entry whose record was read with those of
// the entries behind it. The listing ends there for the caller: it gets none
// of the entries behind it, and the listing that continues from the name it
// is given back has every one of them.
func TestListingEndedByItsCallerContinuesFromWhereItEnded(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
want, _ := listAll(t, oneByOne, "/d", "", 100)
for stopAt := 1; stopAt <= len(want); stopAt++ {
var got []listed
lastFileName, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return len(got) < stopAt, nil
})
require.NoError(t, err)
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
rest, _ := listAll(t, batched, "/d", lastFileName, 100)
require.Equal(t, want[stopAt:], append([]listed{}, rest...), "continued after entry %d", stopAt)
}
}
// A caller's error ends the listing with that error, and with nothing handed
// on after it.
func TestListingReturnsItsCallersError(t *testing.T) {
_, _, batched, _ := linkListingStores(t, mixedDirectory(t))
refused := errors.New("refused")
for failAt := 1; failAt <= 7; failAt++ {
handed := 0
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
handed++
if handed == failAt {
return false, refused
}
return true, nil
})
require.ErrorIs(t, err, refused, "failed at entry %d", failAt)
require.Equal(t, failAt, handed, "failed at entry %d", failAt)
}
}
// The records are then read one at a time, as from a store without batches.
func TestListingReadsRecordsOneByOneWhenTheBatchFails(t *testing.T) {
oneByOne, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
batched.batchErr = errors.New("region unavailable")
want, _ := listAll(t, oneByOne, "/d", "", 100)
got, _ := listAll(t, batched, "/d", "", 100)
require.Equal(t, want, got)
require.Equal(t, 4, *batchedReads)
}
// A store that fails its listing part of the way has handed some entries over
// already. They reach the caller before the error does, as they do when each
// is handed on as it arrives.
func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
broken := errors.New("iterator closed")
want, _ := listAll(t, oneByOne, "/d", "", 100)
for failAfter := 0; failAfter <= 6; failAfter++ {
batched.failAfter, batched.listErr = failAfter, broken
var got []listed
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return true, nil
})
require.ErrorIs(t, err, broken, "failed after %d entries", failAfter)
require.Equal(t, want[:failAfter], append([]listed{}, got...), "failed after %d entries", failAfter)
}
}
// listUntil lists dir and ends the listing at its entry numbered stopAt.
func listUntil(store FilerStore, dir string, stopAt int) (entries []listed, lastFileName string, err error) {
lastFileName, err = NewFilerStoreWrapper(store).ListDirectoryEntries(context.Background(), util.FullPath(dir), "", false, 100000, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return len(entries) < stopAt, nil
})
return entries, lastFileName, err
}
// The store goes on past the entry its caller ends the listing at, to the
// entries that wait with it, and may fail there. Handed each entry as it
// arrived, the caller would have stopped the store before that: the listing
// ends where the caller ended it, and its own failure is the one it gets.
func TestListingEndedByItsCallerIsNotFailedByWhatTheStoreMetBehind(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
want, _ := listAll(t, oneByOne, "/d", "", 100)
broken := errors.New("iterator closed")
// the store hands over a to e and then fails; b to e wait for their records
oneByOne.failAfter, oneByOne.listErr = 5, broken
batched.failAfter, batched.listErr = 5, broken
for stopAt := 1; stopAt <= 5; stopAt++ {
_, _, err := listUntil(oneByOne, "/d", stopAt)
require.NoError(t, err, "one at a time, ended at entry %d", stopAt)
got, lastFileName, err := listUntil(batched, "/d", stopAt)
require.NoError(t, err, "ended at entry %d", stopAt)
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
}
refused := errors.New("refused")
for failAt := 2; failAt <= 5; failAt++ {
handed := 0
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
handed++
if handed == failAt {
return false, refused
}
return true, nil
})
require.ErrorIs(t, err, refused, "failed at entry %d", failAt)
require.NotErrorIs(t, err, broken, "failed at entry %d", failAt)
}
}
// The same for the step a store takes after its caller has ended the listing.
// It fails behind the last entry that waits: a caller that ended the listing
// at an earlier one had stopped the store before, and a caller that ended it
// at that last one gets the failure, as it does from a store that hands each
// entry on as it arrives.
func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
const names = hardLinkBatchSize + 50
oneByOne, _, batched, _ := linkListingStores(t, func(store *stubFilerStore) {
for i := 0; i < names; i++ {
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%05d-012345", i)), fmt.Sprintf("/d/n%05d", i), uint64(1+i), 2)
}
})
broken := errors.New("iterator closed")
oneByOne.failStopAt, oneByOne.stopErr = hardLinkBatchSize, broken
batched.failStopAt, batched.stopErr = hardLinkBatchSize, broken
for _, stopAt := range []int{1, 10, hardLinkBatchSize - 1, hardLinkBatchSize, hardLinkBatchSize + 1, names} {
want, wantLast, wantErr := listUntil(oneByOne, "/d", stopAt)
got, gotLast, gotErr := listUntil(batched, "/d", stopAt)
require.Equal(t, stopAt == hardLinkBatchSize, wantErr != nil, "one at a time, ended at entry %d", stopAt)
require.Equal(t, wantErr, gotErr, "ended at entry %d", stopAt)
require.Equal(t, want, got, "ended at entry %d", stopAt)
if wantErr == nil {
require.Equal(t, wantLast, gotLast, "ended at entry %d", stopAt)
}
}
}
// The records are in the default store. A directory another store lists keeps
// the read per entry: nothing says that store's listing hands over entries
// that can wait.
func TestListingOfAPathSpecificStoreReadsRecordsOneByOne(t *testing.T) {
_, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
other := &rowListingStore{stubFilerStore: newStubFilerStore()}
// the store keeps its paths without the prefix it is mounted at
other.entries["/d/n"] = &Entry{
FullPath: "/d/n",
Attr: Attr{Mode: 0o644},
HardLinkId: HardLinkId("link-x-0123456789"),
}
wrapper := NewFilerStoreWrapper(batched)
wrapper.AddPathSpecificStore("/other/", "other", other)
var got []listed
_, err := wrapper.ListDirectoryEntries(context.Background(), "/other/d", "", false, 100, func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return true, nil
})
require.NoError(t, err)
require.Equal(t, []listed{{Name: "n", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}}, got)
require.Equal(t, 1, *batchedReads)
require.Empty(t, batched.batches)
}
func namesOf(entries []listed) (names []string) {
for _, entry := range entries {
names = append(names, entry.Name)
}
return names
}
+1 -1
View File
@@ -473,7 +473,7 @@ func (f *Filer) ReadPersistedLogBuffer(ctx context.Context, startPosition log_bu
return 0, false, ctx.Err()
}
visitor, visitErr := f.collectPersistedLogBuffer(startPosition, stopTsNs)
visitor, visitErr := f.collectPersistedLogBuffer(ctx, startPosition, stopTsNs)
if visitErr != nil {
if visitErr == io.EOF {
return
+59 -12
View File
@@ -95,6 +95,64 @@ func (f *Filer) metaLogReplicationFor(ruleReplication string) string {
return util.Nvl(f.metaLogTargetReplication, f.metaLogReplication, ruleReplication)
}
// metaLogAssignRequests lists the assigns to try, in order, for a metadata log
// piece: the meta log collection, then the collection the log uses without
// it, so a meta log collection that cannot grow does not stall the log.
func (f *Filer) metaLogAssignRequests(targetFile string, size int) []*operation.VolumeAssignRequest {
diskType, rule := f.resolveMetadataLogAssignDiskType(targetFile)
request := &operation.VolumeAssignRequest{
Count: 1,
Collection: f.metaLogCollectionFor(rule.Collection),
Replication: f.metaLogReplicationFor(rule.Replication),
DiskType: diskType,
WritableVolumeCount: rule.VolumeGrowthCount,
ExpectedDataSize: uint64(size),
}
if f.metaLogTargetCollection == "" {
return []*operation.VolumeAssignRequest{request}
}
request.WritableVolumeCount = f.metaLogVolumeGrowthCount
shared := *request
shared.Collection = util.Nvl(f.metaLogCollection, rule.Collection)
shared.Replication = util.Nvl(f.metaLogReplication, rule.Replication)
shared.WritableVolumeCount = rule.VolumeGrowthCount
if shared.Collection == request.Collection {
return []*operation.VolumeAssignRequest{request}
}
return []*operation.VolumeAssignRequest{request, &shared}
}
var (
metaLogOwnAssignBudget = 10 * time.Second
metaLogOwnAssignPause = time.Minute
)
// assignMetaLogPiece gives the meta log collection a bounded share of the
// assign budget, since a collection that cannot grow can keep answering with
// retryable errors. After it fails, pieces go straight to the fallback for a
// while instead of waiting on it again at every flush, until the fallback
// fails too.
func (f *Filer) assignMetaLogPiece(ctx context.Context, requests []*operation.VolumeAssignRequest) (*operation.AssignResult, error) {
if len(requests) == 1 {
return operation.Assign(ctx, f.GetMaster, f.masterGrpcDialOption(), requests[0])
}
if time.Now().UnixNano() >= f.metaLogOwnAssignPausedUntil.Load() {
ownCtx, cancel := context.WithTimeout(ctx, metaLogOwnAssignBudget)
assignResult, err := operation.Assign(ownCtx, f.GetMaster, f.masterGrpcDialOption(), requests[0])
cancel()
if err == nil || ctx.Err() != nil {
return assignResult, err
}
glog.V(1).Infof("assign metadata log piece in collection %q: %v; using %q for %v", requests[0].Collection, err, requests[1].Collection, metaLogOwnAssignPause)
f.metaLogOwnAssignPausedUntil.Store(time.Now().Add(metaLogOwnAssignPause).UnixNano())
}
assignResult, err := operation.Assign(ctx, f.GetMaster, f.masterGrpcDialOption(), requests[1])
if err != nil {
f.metaLogOwnAssignPausedUntil.Store(0)
}
return assignResult, err
}
func (f *Filer) assignAndUpload(ctx context.Context, targetFile string, data []byte) (*operation.AssignResult, *operation.UploadResult, error) {
// Consecutive events repeat whole chunk lists, but the uploader only
// samples the first bytes before deciding to compress.
@@ -103,18 +161,7 @@ func (f *Filer) assignAndUpload(ctx context.Context, targetFile string, data []b
data, isCompressed = compressed, true
}
// assign a volume location
diskType, rule := f.resolveMetadataLogAssignDiskType(targetFile)
assignRequest := &operation.VolumeAssignRequest{
Count: 1,
Collection: f.metaLogCollectionFor(rule.Collection),
Replication: f.metaLogReplicationFor(rule.Replication),
DiskType: diskType,
WritableVolumeCount: rule.VolumeGrowthCount,
ExpectedDataSize: uint64(len(data)),
}
assignResult, err := operation.Assign(ctx, f.GetMaster, f.masterGrpcDialOption(), assignRequest)
assignResult, err := f.assignMetaLogPiece(ctx, f.metaLogAssignRequests(targetFile, len(data)))
if err != nil {
return nil, nil, fmt.Errorf("AssignVolume: %w", err)
}
@@ -11,12 +11,16 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"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/status"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/operation"
@@ -133,3 +137,139 @@ func TestMetaLogPieceUploadsIncompressibleAsIs(t *testing.T) {
assert.Zero(t, uploadResult.Gzip)
assert.Equal(t, uint32(len(data)), uploadResult.Size)
}
type fullCollectionMaster struct {
assignMaster
full string
fullErr error
attempts atomic.Int32
}
func (m *fullCollectionMaster) Assign(ctx context.Context, req *master_pb.AssignRequest) (*master_pb.AssignResponse, error) {
if req.Collection == m.full {
if m.attempts.Add(1) == 1 {
m.requests <- req
}
if m.fullErr != nil {
return nil, m.fullErr
}
return nil, fmt.Errorf("no free volumes left for collection %s", m.full)
}
return m.assignMaster.Assign(ctx, req)
}
func TestMetaLogPieceFallsBackWhenMetaCollectionIsFull(t *testing.T) {
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(operation.UploadResult{Size: 1})
}))
t.Cleanup(volume.Close)
master := &fullCollectionMaster{
assignMaster: assignMaster{
collectionDeleteMaster: collectionDeleteMaster{calls: make(chan collectionDeleteCall, 1)},
volumeUrl: strings.TrimPrefix(volume.URL, "http://"),
requests: make(chan *master_pb.AssignRequest, 2),
},
full: "filer-meta",
}
f, _ := newFilerWithMaster(t, master)
f.GrpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
f.metaLogTargetCollection = "filer-meta"
f.metaLogTargetReplication = "001"
f.metaLogVolumeGrowthCount = 2
f.metaLogCollection = "mydata"
_, _, err := f.assignAndUpload(context.Background(), string(appendTestLog), []byte("x"))
require.NoError(t, err)
own, shared := <-master.requests, <-master.requests
assert.Equal(t, "filer-meta", own.GetCollection())
assert.Equal(t, "001", own.GetReplication())
assert.Equal(t, uint32(2), own.GetWritableVolumeCount())
assert.Equal(t, "mydata", shared.GetCollection())
assert.Empty(t, shared.GetReplication())
assert.Zero(t, shared.GetWritableVolumeCount(), "the shared collection keeps its own growth count")
}
func TestMetaLogPieceFallsBackWhileMetaCollectionKeepsGrowing(t *testing.T) {
budget := metaLogOwnAssignBudget
metaLogOwnAssignBudget = time.Second
t.Cleanup(func() { metaLogOwnAssignBudget = budget })
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(operation.UploadResult{Size: 1})
}))
t.Cleanup(volume.Close)
master := &fullCollectionMaster{
assignMaster: assignMaster{
collectionDeleteMaster: collectionDeleteMaster{calls: make(chan collectionDeleteCall, 1)},
volumeUrl: strings.TrimPrefix(volume.URL, "http://"),
requests: make(chan *master_pb.AssignRequest, 3),
},
full: "meta",
fullErr: status.Error(codes.ResourceExhausted, "no writable volumes for meta, volume growth in progress"),
}
f, _ := newFilerWithMaster(t, master)
f.GrpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
f.metaLogTargetCollection = "meta"
f.metaLogCollection = "mydata"
start := time.Now()
_, _, err := f.assignAndUpload(context.Background(), string(appendTestLog), []byte("x"))
require.NoError(t, err)
assert.Less(t, time.Since(start), 5*time.Second, "the fallback must not wait for the whole assign budget")
assert.Equal(t, "meta", (<-master.requests).GetCollection())
assert.Equal(t, "mydata", (<-master.requests).GetCollection())
attempts := master.attempts.Load()
_, _, err = f.assignAndUpload(context.Background(), string(appendTestLog), []byte("x"))
require.NoError(t, err)
assert.Equal(t, "mydata", (<-master.requests).GetCollection())
assert.Equal(t, attempts, master.attempts.Load(), "the next piece skips the collection that just failed")
}
func TestMetaLogPieceRetriesMetaCollectionWhenFallbackFails(t *testing.T) {
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(operation.UploadResult{Size: 1})
}))
t.Cleanup(volume.Close)
master := &fullCollectionMaster{
assignMaster: assignMaster{
collectionDeleteMaster: collectionDeleteMaster{calls: make(chan collectionDeleteCall, 1)},
volumeUrl: strings.TrimPrefix(volume.URL, "http://"),
requests: make(chan *master_pb.AssignRequest, 2),
},
full: "mydata",
}
f, _ := newFilerWithMaster(t, master)
f.GrpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
f.metaLogTargetCollection = "meta"
f.metaLogCollection = "mydata"
f.metaLogOwnAssignPausedUntil.Store(time.Now().Add(time.Hour).UnixNano())
_, _, err := f.assignAndUpload(context.Background(), string(appendTestLog), []byte("x"))
require.Error(t, err)
assert.Equal(t, "mydata", (<-master.requests).GetCollection())
_, _, err = f.assignAndUpload(context.Background(), string(appendTestLog), []byte("x"))
require.NoError(t, err, "a failed fallback ends the pause on the meta collection")
assert.Equal(t, "meta", (<-master.requests).GetCollection())
}
func TestMetaLogAssignWithoutOwnCollection(t *testing.T) {
f := &Filer{metaLogCollection: "mydata", metaLogVolumeGrowthCount: 2}
requests := f.metaLogAssignRequests(string(appendTestLog), 1)
require.Len(t, requests, 1)
assert.Equal(t, "mydata", requests[0].Collection)
assert.Zero(t, requests[0].WritableVolumeCount, "the growth count is only for the meta log collection")
f.metaLogTargetCollection = "mydata"
requests = f.metaLogAssignRequests(string(appendTestLog), 1)
require.Len(t, requests, 1)
assert.Equal(t, uint32(2), requests[0].WritableVolumeCount)
}
+43 -9
View File
@@ -147,7 +147,7 @@ func PersistedLogScanStartTsNs(t time.Time) int64 {
return persistedLogScanStart(t).Truncate(time.Minute).UnixNano()
}
func (f *Filer) collectPersistedLogBuffer(startPosition log_buffer.MessagePosition, stopTsNs int64) (v *OrderedLogVisitor, err error) {
func (f *Filer) collectPersistedLogBuffer(ctx context.Context, startPosition log_buffer.MessagePosition, stopTsNs int64) (v *OrderedLogVisitor, err error) {
if stopTsNs != 0 && startPosition.Time.UnixNano() > stopTsNs {
return nil, io.EOF
@@ -156,12 +156,12 @@ func (f *Filer) collectPersistedLogBuffer(startPosition log_buffer.MessagePositi
scanFrom := persistedLogScanStart(startPosition.Time)
startDate := fmt.Sprintf("%04d-%02d-%02d", scanFrom.Year(), scanFrom.Month(), scanFrom.Day())
dayEntries, _, listDayErr := f.ListDirectoryEntries(context.Background(), SystemLogDir, startDate, true, math.MaxInt32, "", "", "")
dayEntries, listDayErr := f.listLogDir(ctx, SystemLogDir, startDate, true)
if listDayErr != nil {
return nil, fmt.Errorf("fail to list log by day: %w", listDayErr)
}
return NewOrderedLogVisitor(f, startPosition, stopTsNs, dayEntries)
return NewOrderedLogVisitor(ctx, f, startPosition, stopTsNs, dayEntries)
}
@@ -183,7 +183,7 @@ func (f *Filer) CollectLogFileRefs(ctx context.Context, startPosition log_buffer
stopHourMinute = fmt.Sprintf("%02d-%02d", stopTime.Hour(), stopTime.Minute())
}
dayEntries, _, listDayErr := f.ListDirectoryEntries(ctx, SystemLogDir, startDate, true, math.MaxInt32, "", "", "")
dayEntries, listDayErr := f.listLogDir(ctx, SystemLogDir, startDate, true)
if listDayErr != nil {
return nil, 0, fmt.Errorf("fail to list log by day: %w", listDayErr)
}
@@ -194,7 +194,7 @@ func (f *Filer) CollectLogFileRefs(ctx context.Context, startPosition log_buffer
}
listFrom, inclusive := f.logDayListStart(dayEntry.Name(), startDate, startHourMinute)
hourMinuteEntries, _, listErr := f.ListDirectoryEntries(ctx, util.NewFullPath(SystemLogDir, dayEntry.Name()), listFrom, inclusive, math.MaxInt32, "", "", "")
hourMinuteEntries, listErr := f.listLogDir(ctx, util.NewFullPath(SystemLogDir, dayEntry.Name()), listFrom, inclusive)
if listErr != nil {
return nil, 0, fmt.Errorf("fail to list log %s: %w", dayEntry.Name(), listErr)
}
@@ -250,6 +250,38 @@ func clampLogRefsCursor(lastTsNs, startTsNs int64) int64 {
return lastTsNs
}
// listLogDir lists a metadata log directory from startFileName. Under
// WithPeerLogFiles the files of peers with their own store are merged in by
// name, as one shared store lists the same file on every filer using it.
func (f *Filer) listLogDir(ctx context.Context, dir util.FullPath, startFileName string, inclusive bool) ([]*Entry, error) {
entries, _, err := f.ListDirectoryEntries(ctx, dir, startFileName, inclusive, math.MaxInt32, "", "", "")
if err != nil || !readsPeerLogFiles(ctx) || f.MetaAggregator == nil {
return entries, err
}
names := make(map[string]bool, len(entries))
for _, entry := range entries {
names[entry.Name()] = true
}
peerEntries, err := f.MetaAggregator.listPeerLogDir(ctx, dir, startFileName, inclusive)
if err != nil {
return nil, err
}
merged := false
for _, entry := range peerEntries {
name := entry.Name()
if names[name] || name < startFileName || (name == startFileName && !inclusive) {
continue
}
names[name] = true
entries = append(entries, entry)
merged = true
}
if merged {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
}
return entries, nil
}
func (f *Filer) HasPersistedLogFiles(startPosition log_buffer.MessagePosition) (bool, error) {
startDate := fmt.Sprintf("%04d-%02d-%02d", startPosition.Time.Year(), startPosition.Time.Month(), startPosition.Time.Day())
dayEntries, _, listDayErr := f.ListDirectoryEntries(context.Background(), SystemLogDir, startDate, true, 1, "", "", "")
@@ -296,7 +328,7 @@ type OrderedLogVisitor struct {
logFileEntryCollector *LogFileEntryCollector
}
func NewOrderedLogVisitor(f *Filer, startPosition log_buffer.MessagePosition, stopTsNs int64, dayEntries []*Entry) (*OrderedLogVisitor, error) {
func NewOrderedLogVisitor(ctx context.Context, f *Filer, startPosition log_buffer.MessagePosition, stopTsNs int64, dayEntries []*Entry) (*OrderedLogVisitor, error) {
perFilerQueueMap := make(map[string]*LogFileQueueIterator)
// initialize the priority queue
@@ -306,7 +338,7 @@ func NewOrderedLogVisitor(f *Filer, startPosition log_buffer.MessagePosition, st
t := &OrderedLogVisitor{
perFilerIteratorMap: perFilerQueueMap,
pq: pq,
logFileEntryCollector: NewLogFileEntryCollector(f, startPosition, stopTsNs, dayEntries),
logFileEntryCollector: NewLogFileEntryCollector(ctx, f, startPosition, stopTsNs, dayEntries),
}
if err := t.logFileEntryCollector.collectMore(t); err != nil && err != io.EOF {
return nil, err
@@ -374,6 +406,7 @@ func (f *Filer) logDayListStart(day, startDate, startHourMinute string) (startFi
// ----------
type LogFileEntryCollector struct {
ctx context.Context
f *Filer
startTsNs int64
stopTsNs int64
@@ -384,7 +417,7 @@ type LogFileEntryCollector struct {
stopHourMinute string
}
func NewLogFileEntryCollector(f *Filer, startPosition log_buffer.MessagePosition, stopTsNs int64, dayEntries []*Entry) *LogFileEntryCollector {
func NewLogFileEntryCollector(ctx context.Context, f *Filer, startPosition log_buffer.MessagePosition, stopTsNs int64, dayEntries []*Entry) *LogFileEntryCollector {
dayEntryQueue := util.NewQueue[*Entry]()
for _, dayEntry := range dayEntries {
dayEntryQueue.Enqueue(dayEntry)
@@ -402,6 +435,7 @@ func NewLogFileEntryCollector(f *Filer, startPosition log_buffer.MessagePosition
}
return &LogFileEntryCollector{
ctx: ctx,
f: f,
startTsNs: startPosition.Time.UnixNano(),
stopTsNs: stopTsNs,
@@ -426,7 +460,7 @@ func (c *LogFileEntryCollector) collectMore(v *OrderedLogVisitor) (err error) {
}
listFrom, inclusive := c.f.logDayListStart(dayEntry.Name(), c.startDate, c.startHourMinute)
hourMinuteEntries, _, listHourMinuteErr := c.f.ListDirectoryEntries(context.Background(), util.NewFullPath(SystemLogDir, dayEntry.Name()), listFrom, inclusive, math.MaxInt32, "", "", "")
hourMinuteEntries, listHourMinuteErr := c.f.listLogDir(c.ctx, util.NewFullPath(SystemLogDir, dayEntry.Name()), listFrom, inclusive)
if listHourMinuteErr != nil {
return fmt.Errorf("fail to list log %s by day: %v", dayEntry.Name(), listHourMinuteErr)
}
+2 -2
View File
@@ -95,7 +95,7 @@ func TestPersistedLogScanListsFromScanStart(t *testing.T) {
f.persistedLogCache = newPersistedLogCache(1 << 20)
fillLogDay(store.stubFilerStore, "2026-10-25", 12*60+30, false)
v, err := f.collectPersistedLogBuffer(log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2), 0)
v, err := f.collectPersistedLogBuffer(context.Background(), log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2), 0)
if err != nil {
t.Fatalf("collectPersistedLogBuffer: %v", err)
}
@@ -166,7 +166,7 @@ func TestLogListingsOnUnorderedStoreListWholeDay(t *testing.T) {
})
t.Run("persisted log scan", func(t *testing.T) {
store, f := newStore(false)
v, err := f.collectPersistedLogBuffer(log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2), 0)
v, err := f.collectPersistedLogBuffer(context.Background(), log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2), 0)
if err != nil {
t.Fatalf("collectPersistedLogBuffer: %v", err)
}
+182
View File
@@ -0,0 +1,182 @@
package filer
import (
"context"
"os"
"sort"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
func peerTestLogFile(day, name string, withChunks bool) *Entry {
entry := &Entry{FullPath: util.NewFullPath(string(util.NewFullPath(SystemLogDir, day)), name)}
if withChunks {
entry.Chunks = []*filer_pb.FileChunk{{FileId: "1,0a", Size: 10}}
}
return entry
}
func peerTestLogDay(day string) *Entry {
return &Entry{FullPath: util.NewFullPath(SystemLogDir, day), Attr: Attr{Mode: os.ModeDir | 0755}}
}
// newPeerLogTestFiler returns a filer whose own store holds its 12-30 file and
// that follows a peer with its own store, a peer on its store, and itself.
// Only the first is asked for its log directories.
func newPeerLogTestFiler(t *testing.T, withChunks bool) *Filer {
store := newStubFilerStore()
f := newReplayTestFiler(store)
store.entries[string(SystemLogDir)] = &Entry{FullPath: SystemLogDir, Attr: Attr{Mode: os.ModeDir | 0755}}
for _, e := range []*Entry{peerTestLogDay("2026-10-25"), peerTestLogFile("2026-10-25", "12-30.0000abcd", withChunks)} {
store.entries[string(e.FullPath)] = e
}
own := pb.ServerAddress("own:8888")
shared := pb.ServerAddress("shared:8888")
self := pb.ServerAddress("self:8888")
ma := NewMetaAggregator(f, self, nil)
for _, peer := range []pb.ServerAddress{own, shared, self} {
ma.peerChans[peer] = make(chan struct{})
}
ma.peerSharesStore[shared] = true
peerDirs := map[util.FullPath][]*Entry{
SystemLogDir: {peerTestLogDay("2026-10-24"), peerTestLogDay("2026-10-25")},
util.NewFullPath(SystemLogDir, "2026-10-24"): {peerTestLogFile("2026-10-24", "23-59.0000beef", withChunks)},
util.NewFullPath(SystemLogDir, "2026-10-25"): {
peerTestLogFile("2026-10-25", "12-28.0000beef", withChunks),
peerTestLogFile("2026-10-25", "12-29.0000beef", withChunks),
peerTestLogFile("2026-10-25", "12-30.0000abcd", withChunks),
peerTestLogFile("2026-10-25", "12-31.0000beef", withChunks),
},
}
ma.peerLogDirLister = func(ctx context.Context, peer pb.ServerAddress, dir util.FullPath, startFileName string, inclusive bool) ([]*Entry, error) {
if peer != own {
t.Errorf("listed %s on %s, which needs no listing", dir, peer)
}
return peerDirs[dir], nil
}
f.MetaAggregator = ma
return f
}
func refNames(refs []*filer_pb.LogFileChunkRef) []string {
var names []string
for _, ref := range refs {
names = append(names, time.Unix(0, ref.FileTsNs).UTC().Format("15-04")+"."+ref.FilerId)
}
sort.Strings(names)
return names
}
// TestAggregatedLogFileRefsIncludePeerFiles: a peer with its own store keeps
// its log files there, so the aggregated read lists them from the peer, from
// the scan start on and once per name. A local read stays local.
func TestAggregatedLogFileRefsIncludePeerFiles(t *testing.T) {
f := newPeerLogTestFiler(t, true)
start := log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2)
refs, _, err := f.CollectLogFileRefs(WithPeerLogFiles(context.Background()), start, 0)
if err != nil {
t.Fatalf("CollectLogFileRefs: %v", err)
}
want := []string{"12-29.0000beef", "12-30.0000abcd", "12-31.0000beef"}
if got := refNames(refs); !equalStrings(got, want) {
t.Fatalf("aggregated refs = %v, want %v", got, want)
}
refs, _, err = f.CollectLogFileRefs(context.Background(), start, 0)
if err != nil {
t.Fatalf("CollectLogFileRefs: %v", err)
}
if got := refNames(refs); !equalStrings(got, []string{"12-30.0000abcd"}) {
t.Fatalf("local refs = %v, want only the own file", got)
}
}
// TestAggregatedPersistedLogScanIncludesPeerFiles: the same for the pass that
// reads the persisted log for an aggregated subscription.
func TestAggregatedPersistedLogScanIncludesPeerFiles(t *testing.T) {
// cached mode: the files hold no chunks, so nothing is read from volumes
f := newPeerLogTestFiler(t, false)
f.persistedLogCache = newPersistedLogCache(1 << 20)
start := log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2)
for _, tc := range []struct {
ctx context.Context
want []string
}{
{WithPeerLogFiles(context.Background()), []string{"0000abcd", "0000beef"}},
{context.Background(), []string{"0000abcd"}},
} {
v, err := f.collectPersistedLogBuffer(tc.ctx, start, 0)
if err != nil {
t.Fatalf("collectPersistedLogBuffer: %v", err)
}
var got []string
for filerId := range v.perFilerIteratorMap {
got = append(got, filerId)
}
sort.Strings(got)
if !equalStrings(got, tc.want) {
t.Fatalf("filers read = %v, want %v", got, tc.want)
}
}
}
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// TestAggregatedLogListingFailsOnPeerError: a peer listing that fails fails
// the read instead of hiding that peer's files, unless the peer was already
// retired as unreachable, also once its removal mark expired.
func TestAggregatedLogListingFailsOnPeerError(t *testing.T) {
f := newPeerLogTestFiler(t, true)
ma := f.MetaAggregator
ma.peerLogDirLister = func(ctx context.Context, peer pb.ServerAddress, dir util.FullPath, startFileName string, inclusive bool) ([]*Entry, error) {
return nil, context.DeadlineExceeded
}
start := log_buffer.NewMessagePosition(listingTestCursor.UnixNano(), -2)
if _, _, err := f.CollectLogFileRefs(WithPeerLogFiles(context.Background()), start, 0); err == nil {
t.Fatalf("CollectLogFileRefs succeeded with a peer it could not list")
}
own := pb.ServerAddress("own:8888")
ma.peerUnreachableSinceNs[own] = time.Now().UnixNano()
if _, _, err := f.CollectLogFileRefs(WithPeerLogFiles(context.Background()), start, 0); err == nil {
t.Fatalf("CollectLogFileRefs succeeded with a peer unreachable only briefly")
}
for _, retire := range []struct {
name string
mark func()
}{
{"marked removed", func() { ma.peerRemovedAtNs[own] = time.Now().UnixNano() }},
{"mark expired, still unreachable", func() {
delete(ma.peerRemovedAtNs, own)
ma.peerUnreachableSinceNs[own] = time.Now().Add(-peerUnreachableRemovalAfter - time.Hour).UnixNano()
}},
} {
retire.mark()
refs, _, err := f.CollectLogFileRefs(WithPeerLogFiles(context.Background()), start, 0)
if err != nil {
t.Fatalf("%s: CollectLogFileRefs: %v", retire.name, err)
}
if got := refNames(refs); !equalStrings(got, []string{"12-30.0000abcd"}) {
t.Fatalf("%s: refs = %v, want only the own file", retire.name, got)
}
}
}
+10 -2
View File
@@ -69,7 +69,11 @@ func (f *Filer) StreamListDirectoryEntries(ctx context.Context, p util.FullPath,
missedCount, lastFileName, err = f.doListPatternMatchedEntries(ctx, p, startFileName, inclusive, limit, prefix, restNamePattern, namePatternExclude, eachEntryFunc)
for missedCount > 0 && err == nil {
missedCount, lastFileName, err = f.doListPatternMatchedEntries(ctx, p, lastFileName, false, missedCount, prefix, restNamePattern, namePatternExclude, eachEntryFunc)
var refillLastFileName string
missedCount, refillLastFileName, err = f.doListPatternMatchedEntries(ctx, p, lastFileName, false, missedCount, prefix, restNamePattern, namePatternExclude, eachEntryFunc)
if refillLastFileName != "" {
lastFileName = refillLastFileName
}
}
return
@@ -119,7 +123,11 @@ func (f *Filer) doListValidEntries(ctx context.Context, p util.FullPath, startFi
var expiredCount int64
expiredCount, lastFileName, err = f.doListDirectoryEntries(ctx, p, startFileName, inclusive, limit, prefix, eachEntryFunc)
for expiredCount > 0 && err == nil {
expiredCount, lastFileName, err = f.doListDirectoryEntries(ctx, p, lastFileName, false, expiredCount, prefix, eachEntryFunc)
var refillLastFileName string
expiredCount, refillLastFileName, err = f.doListDirectoryEntries(ctx, p, lastFileName, false, expiredCount, prefix, eachEntryFunc)
if refillLastFileName != "" {
lastFileName = refillLastFileName
}
}
return
}
+35
View File
@@ -0,0 +1,35 @@
package filer
import (
"context"
"fmt"
"testing"
"time"
)
// A page that lost entries to expiry is filled again from its last name. When
// that refill lists nothing, the page still ends at the last name it listed: a
// caller resuming from an empty name would list the directory again.
func TestStreamListKeepsTheLastNameWhenARefillListsNothing(t *testing.T) {
f, store := newTestFilerWithStubStore(t)
putSweepTestEntry(t, store, "/dir", true, 0, time.Now())
for i := 0; i < 20; i++ {
crtime := time.Now()
if i < 5 {
crtime = crtime.Add(-time.Hour)
}
putSweepTestEntry(t, store, fmt.Sprintf("/dir/f%02d", i), false, 60, crtime)
}
listed := 0
last, err := f.StreamListDirectoryEntries(context.Background(), "/dir", "", false, 100, "", "", "", func(*Entry) (bool, error) {
listed++
return true, nil
})
if err != nil {
t.Fatal(err)
}
if listed != 15 || last != "f19" {
t.Fatalf("listed %d entries ending at %q, want 15 ending at f19", listed, last)
}
}
+38
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/require"
)
@@ -179,3 +180,40 @@ func TestNewLinkedNameStillReadsThePath(t *testing.T) {
require.Equal(t, 2, store.findCount(), "a linked name is counted from the store, not from the create's lookup")
}
// A rename to a new name finds nothing at the path; the store is read once.
func TestLookupForOverwriteReadsAMissingPathOnce(t *testing.T) {
f, store := writeCountingFiler(t)
txCtx, err := f.BeginTransaction(context.Background())
require.NoError(t, err)
entry, err := f.FindEntryForOverwrite(txCtx, util.FullPath("/d/none"))
require.ErrorIs(t, err, filer_pb.ErrNotFound)
require.Nil(t, entry)
require.Equal(t, 1, store.findCount(), "the store said the path is empty; asking again repeats the read")
}
// The expired S3 row a transaction keeps still comes back from the second read.
func TestLookupForOverwriteReturnsAnExpiredRowTheTransactionKeeps(t *testing.T) {
f, store := writeCountingFiler(t)
expired := fileAt("/d/expired")
expired.TtlSec = 1
expired.Mtime = time.Now().Add(-time.Hour)
expired.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
store.entries["/d/expired"] = expired
txCtx, err := f.BeginTransaction(context.Background())
require.NoError(t, err)
_, err = f.FindEntry(txCtx, util.FullPath("/d/expired"))
require.ErrorIs(t, err, filer_pb.ErrNotFound, "an ordinary lookup does not see an expired entry")
store.resetFindCount()
entry, err := f.FindEntryForOverwrite(txCtx, util.FullPath("/d/expired"))
require.NoError(t, err)
require.NotNil(t, entry)
require.Equal(t, "5,0c050a", entry.GetChunks()[0].FileId, "a write over the path owes the expired entry its chunks")
require.Equal(t, 2, store.findCount())
require.Contains(t, store.entries, "/d/expired", "the transaction keeps the row")
}
+13
View File
@@ -72,6 +72,19 @@ type EntryScanner interface {
ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error
}
// KvBatchReader is implemented by a store that reads several KV keys in one
// round trip. A directory listing reads the shared record of every hard-linked
// entry it lists; from such a store it reads the records of a run of entries
// together, instead of one at a time while the store iterates.
//
// The listing keeps the entries the store hands over until their records are
// read, so each of them is an *Entry of its own.
type KvBatchReader interface {
// KvBatchGet returns the values of the keys the store holds, by key. A
// key it does not hold is left out.
KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error)
}
type BucketAware interface {
OnBucketCreation(bucket string)
OnBucketDeletion(bucket string)
+133
View File
@@ -456,6 +456,139 @@ func (fsw *FilerStoreWrapper) maybeReadHardLink(ctx context.Context, entry *Entr
return nil
}
// hardLinkBatchSize is how many entries of a listing wait for their hard link
// records at most, and so how many records are read together at most. The
// entries that wait are held in memory, chunk lists and all.
const hardLinkBatchSize = 256
// hardLinkListing hands the entries of one store listing on to the listing's
// caller, each with its hard link read as maybeReadHardLink reads it.
//
// Read as each entry arrives, that is a round trip to the store for every
// hard-linked name, made one after the other while the store iterates: a
// directory of hard-linked files lists many times slower than one of plain
// files. Where the store that lists is the default store, which holds the
// records, and reads KV keys in batches (KvBatchReader), the entries from the
// first hard-linked one on wait, up to hardLinkBatchSize of them, and their
// records are read together. The caller gets the entries in the order the
// store lists them either way.
type hardLinkListing struct {
fsw *FilerStoreWrapper
ctx context.Context
each ListEachEntryFunc
reader KvBatchReader // nil: a record is read when its entry arrives
held []*Entry // waiting for their records; the first has a hard link
last string // the name of the last entry handed on
ended bool // each ended the listing or failed
passed bool // each ended it at an entry with others waiting behind
}
func (fsw *FilerStoreWrapper) newHardLinkListing(ctx context.Context, actualStore FilerStore, eachEntryFunc ListEachEntryFunc) *hardLinkListing {
listing := &hardLinkListing{fsw: fsw, ctx: ctx, each: eachEntryFunc}
if actualStore == fsw.defaultStore {
listing.reader, _ = actualStore.(KvBatchReader)
}
return listing
}
// add takes the next entry of the store's listing.
func (l *hardLinkListing) add(entry *Entry) (bool, error) {
if l.reader == nil {
l.fsw.maybeReadHardLink(l.ctx, entry)
return l.handOn(entry)
}
if len(l.held) == 0 && len(entry.HardLinkId) == 0 {
return l.handOn(entry)
}
l.held = append(l.held, entry)
if len(l.held) < hardLinkBatchSize {
return true, nil
}
return l.release()
}
// release reads the records of the entries that wait and hands the entries on.
func (l *hardLinkListing) release() (bool, error) {
held := l.held
l.held = nil
keys := make([][]byte, 0, len(held))
asked := make(map[string]struct{}, len(held))
for _, entry := range held {
if len(entry.HardLinkId) == 0 {
continue
}
// a directory may hold several names of one file
if _, found := asked[string(entry.HardLinkId)]; !found {
asked[string(entry.HardLinkId)] = struct{}{}
keys = append(keys, entry.HardLinkId)
}
}
records, batchErr := l.reader.KvBatchGet(l.ctx, keys)
if batchErr != nil {
glog.ErrorfCtx(l.ctx, "read %d hard link records together: %v", len(keys), batchErr)
}
for i, entry := range held {
if len(entry.HardLinkId) != 0 {
if batchErr != nil {
// one at a time, as from a store without batches
l.fsw.maybeReadHardLink(l.ctx, entry)
} else if record, found := records[string(entry.HardLinkId)]; found {
if err := entry.DecodeAttributesAndChunks(record); err != nil {
glog.ErrorfCtx(l.ctx, "decode %s HardLinkId %x: %v", entry.FullPath, entry.HardLinkId, err)
}
}
}
if more, err := l.handOn(entry); err != nil || !more {
l.passed = err == nil && i < len(held)-1
return more, err
}
}
return true, nil
}
func (l *hardLinkListing) handOn(entry *Entry) (bool, error) {
filer_pb.AfterEntryDeserialization(entry.GetChunks())
more, err := l.each(entry)
if err != nil {
l.ended = true
return more, err
}
l.last = entry.Name()
l.ended = !more
return more, nil
}
// finish takes what the store's listing returned, hands on the entries that
// still wait, and returns what the listing returns to its caller.
//
// The store may have gone past the entry its caller ended the listing at,
// with entries that waited behind it. The last name listed is then the one
// the caller ended at, and a listing that continues from there has them. An
// error the store ran into past that entry is not the caller's either: handed
// each entry as it arrived, the caller would have stopped the store before.
func (l *hardLinkListing) finish(lastFileName string, err error) (string, error) {
if l.reader == nil {
return lastFileName, err
}
if !l.ended && len(l.held) > 0 {
// The store handed these over and went on, to the end of its listing
// or to an error. Where the caller ends the listing among them, or
// fails, that is how the listing ends.
more, eachErr := l.release()
if eachErr != nil {
return lastFileName, eachErr
}
if !more {
return l.last, nil
}
return lastFileName, err
}
if l.ended && (err == nil || l.passed) {
return l.last, nil
}
return lastFileName, err
}
func (fsw *FilerStoreWrapper) DeleteHardLink(ctx context.Context, hardLinkId HardLinkId) error {
if !fsw.countsLinks {
return fsw.deleteHardLink(ctx, hardLinkId)
+14 -9
View File
@@ -380,7 +380,7 @@ func (fsw *FilerStoreWrapper) DeleteFolderChildren(ctx context.Context, fp util.
return actualStore.DeleteFolderChildren(ctx, fp)
}
func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (string, error) {
func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) {
ctx = context.WithoutCancel(ctx)
actualStore := fsw.getActualStore(dirPath + "/")
stats.FilerStoreCounter.WithLabelValues(actualStore.GetName(), "list").Inc()
@@ -389,12 +389,15 @@ func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath
stats.FilerStoreHistogram.WithLabelValues(actualStore.GetName(), "list").Observe(time.Since(start).Seconds())
}()
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
defer func() {
lastFileName, err = listing.finish(lastFileName, err)
}()
// glog.V(4).Infof("ListDirectoryEntries %s from %s limit %d", dirPath, startFileName, limit)
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, func(entry *Entry) (bool, error) {
fsw.maybeReadHardLink(ctx, entry)
filer_pb.AfterEntryDeserialization(entry.GetChunks())
return eachEntryFunc(entry)
})
adjustedEntryFunc := func(entry *Entry) (bool, error) {
return listing.add(entry)
}
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, adjustedEntryFunc)
}
func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) {
@@ -408,11 +411,13 @@ func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context,
if limit > math.MaxInt32-1 {
limit = math.MaxInt32 - 1
}
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
defer func() {
lastFileName, err = listing.finish(lastFileName, err)
}()
// glog.V(4).Infof("ListDirectoryPrefixedEntries %s from %s prefix %s limit %d", dirPath, startFileName, prefix, limit)
adjustedEntryFunc := func(entry *Entry) (bool, error) {
fsw.maybeReadHardLink(ctx, entry)
filer_pb.AfterEntryDeserialization(entry.GetChunks())
return eachEntryFunc(entry)
return listing.add(entry)
}
lastFileName, err = actualStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, adjustedEntryFunc)
if err == ErrUnsupportedListDirectoryPrefixed {
+52 -49
View File
@@ -592,9 +592,7 @@ func (store *FoundationDBStore) ListDirectoryEntries(ctx context.Context, dirPat
}
func (store *FoundationDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
// Cap limit for optimal FoundationDB performance
// Large batches can cause transaction timeouts and increase memory pressure
if limit > MAX_DIRECTORY_LIST_LIMIT || limit <= 0 {
if limit <= 0 {
limit = MAX_DIRECTORY_LIST_LIMIT
}
@@ -651,65 +649,70 @@ func (store *FoundationDBStore) ListDirectoryPrefixedEntries(ctx context.Context
// End selector is the end of our calculated range
endSelector := fdb.FirstGreaterOrEqual(endKey)
var kvs []fdb.KeyValue
var rangeErr error
// Check if there's a transaction in context
if tx, exists := store.getTransactionFromContext(ctx); exists {
sr := fdb.SelectorRange{Begin: beginSelector, End: endSelector}
kvs, rangeErr = tx.GetRange(sr, fdb.RangeOptions{Limit: int(limit)}).GetSliceWithError()
// Read in batches: large ranges can cause transaction timeouts and increase memory pressure
var count int64
for count < limit {
batchLimit := min(limit-count, MAX_DIRECTORY_LIST_LIMIT)
kvs, rangeErr := store.getRange(ctx, fdb.SelectorRange{Begin: beginSelector, End: endSelector}, int(batchLimit))
if rangeErr != nil {
return "", fmt.Errorf("scanning %s: %w", dirPath, rangeErr)
return lastFileName, fmt.Errorf("scanning %s: %w", dirPath, rangeErr)
}
} else {
result, err := store.database.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
sr := fdb.SelectorRange{Begin: beginSelector, End: endSelector}
kvSlice, err := rtr.GetRange(sr, fdb.RangeOptions{Limit: int(limit)}).GetSliceWithError()
if err != nil {
return nil, err
for _, kv := range kvs {
fileName, extractErr := store.extractFileName(kv.Key)
if extractErr != nil {
glog.Warningf("list %s: failed to extract fileName from key %v: %v", dirPath, kv.Key, extractErr)
continue
}
return kvSlice, nil
})
if err != nil {
return "", fmt.Errorf("scanning %s: %w", dirPath, err)
}
var ok bool
kvs, ok = result.([]fdb.KeyValue)
if !ok {
return "", fmt.Errorf("unexpected type from ReadTransact: %T, expected []fdb.KeyValue", result)
}
}
for _, kv := range kvs {
fileName, extractErr := store.extractFileName(kv.Key)
if extractErr != nil {
glog.Warningf("list %s: failed to extract fileName from key %v: %v", dirPath, kv.Key, extractErr)
continue
entry := &filer.Entry{
FullPath: util.NewFullPath(string(dirPath), fileName),
}
if decodeErr := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(kv.Value)); decodeErr != nil {
glog.V(0).Infof("list %s : %v", entry.FullPath, decodeErr)
continue
}
resEachEntryFunc, resEachEntryFuncErr := eachEntryFunc(entry)
if resEachEntryFuncErr != nil {
glog.ErrorfCtx(ctx, "failed to process eachEntryFunc for entry %q: %v", fileName, resEachEntryFuncErr)
return lastFileName, fmt.Errorf("failed to process eachEntryFunc for entry %q: %w", fileName, resEachEntryFuncErr)
}
if !resEachEntryFunc {
return lastFileName, nil
}
lastFileName = fileName
count++
}
entry := &filer.Entry{
FullPath: util.NewFullPath(string(dirPath), fileName),
}
if decodeErr := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(kv.Value)); decodeErr != nil {
glog.V(0).Infof("list %s : %v", entry.FullPath, decodeErr)
continue
}
resEachEntryFunc, resEachEntryFuncErr := eachEntryFunc(entry)
if resEachEntryFuncErr != nil {
glog.ErrorfCtx(ctx, "failed to process eachEntryFunc for entry %q: %v", fileName, resEachEntryFuncErr)
return lastFileName, fmt.Errorf("failed to process eachEntryFunc for entry %q: %w", fileName, resEachEntryFuncErr)
}
if !resEachEntryFunc {
if int64(len(kvs)) < batchLimit {
break
}
lastFileName = fileName
beginSelector = fdb.FirstGreaterThan(kvs[len(kvs)-1].Key)
}
return lastFileName, nil
}
func (store *FoundationDBStore) getRange(ctx context.Context, sr fdb.SelectorRange, limit int) ([]fdb.KeyValue, error) {
if tx, exists := store.getTransactionFromContext(ctx); exists {
return tx.GetRange(sr, fdb.RangeOptions{Limit: limit}).GetSliceWithError()
}
result, err := store.database.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
return rtr.GetRange(sr, fdb.RangeOptions{Limit: limit}).GetSliceWithError()
})
if err != nil {
return nil, err
}
kvs, ok := result.([]fdb.KeyValue)
if !ok {
return nil, fmt.Errorf("unexpected type from ReadTransact: %T, expected []fdb.KeyValue", result)
}
return kvs, nil
}
// KV operations
func (store *FoundationDBStore) KvPut(ctx context.Context, key []byte, value []byte) error {
fdbKey := store.kvDir.Pack(tuple.Tuple{key})
@@ -12,6 +12,9 @@ import (
"testing"
"time"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/apple/foundationdb/bindings/go/src/fdb/tuple"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -683,3 +686,49 @@ func TestFoundationDBStore_DeleteFolderChildrenWithBatching(t *testing.T) {
// Cleanup
store.DeleteFolderChildren(ctx, testDir)
}
// A listing longer than one range read reads on in batches, and an entry it
// cannot decode does not count toward the limit.
func TestFoundationDBStore_ListDirectoryEntriesFillsThePage(t *testing.T) {
store := getTestStore(t)
defer store.Shutdown()
ctx := context.Background()
dir := util.FullPath(fmt.Sprintf("/test_list_pages_%d", time.Now().UnixNano()))
defer store.DeleteFolderChildren(ctx, dir)
files := MAX_DIRECTORY_LIST_LIMIT + 105
for i := 0; i < files; i++ {
entry := &filer.Entry{FullPath: dir.Child(fmt.Sprintf("f%04d", i)), Attr: filer.Attr{Mode: 0644, Mtime: time.Now()}}
if err := store.InsertEntry(ctx, entry); err != nil {
t.Fatalf("InsertEntry: %v", err)
}
}
if _, err := store.database.Transact(func(tr fdb.Transaction) (interface{}, error) {
tr.Set(store.seaweedfsDir.Pack(tuple.Tuple{string(dir), "f0010"}), []byte{0xff, 0xff})
return nil, nil
}); err != nil {
t.Fatalf("plant an undecodable entry: %v", err)
}
for _, tt := range []struct {
limit int64
want int
last string
}{
{limit: int64(MAX_DIRECTORY_LIST_LIMIT) + 100, want: MAX_DIRECTORY_LIST_LIMIT + 100, last: fmt.Sprintf("f%04d", MAX_DIRECTORY_LIST_LIMIT+100)},
{limit: int64(files) + 100, want: files - 1, last: fmt.Sprintf("f%04d", files-1)},
} {
listed := 0
last, err := store.ListDirectoryEntries(ctx, dir, "", false, tt.limit, func(entry *filer.Entry) (bool, error) {
listed++
return true, nil
})
if err != nil {
t.Fatalf("ListDirectoryEntries: %v", err)
}
if listed != tt.want || last != tt.last {
t.Errorf("limit %d: listed %d entries up to %q, want %d up to %q", tt.limit, listed, last, tt.want, tt.last)
}
}
}
+50
View File
@@ -84,6 +84,9 @@ type MetaAggregator struct {
// peerSubscribeLoop is replaceable so a test can observe the subscribe
// start without a live peer.
peerSubscribeLoop func(f *Filer, self, peer pb.ServerAddress, startFrom time.Time, stopChan chan struct{})
// peerLogDirLister is replaceable so a test can serve a peer's log files
// without a live peer.
peerLogDirLister func(ctx context.Context, peer pb.ServerAddress, dir util.FullPath, startFileName string, inclusive bool) ([]*Entry, error)
// stopped is set under peerChansLock by Shutdown; OnPeerUpdate then
// rejects adds so no subscription can outlive the shutdown wait and run
// against a store Filer.Shutdown has already closed.
@@ -107,6 +110,7 @@ func NewMetaAggregator(filer *Filer, self pb.ServerAddress, grpcDialOption grpc.
peerSharesStore: make(map[pb.ServerAddress]bool),
}
t.peerSubscribeLoop = t.loopSubscribeToOneFiler
t.peerLogDirLister = t.readPeerLogDir
// nil notifyFn: aggregated subscribers wake through the buffer's
// subscriber channels, not a cond.
t.MetaLogBuffer = log_buffer.NewLogBuffer("aggr", LogFlushInterval, nil, nil, nil)
@@ -227,6 +231,52 @@ func (ma *MetaAggregator) SharesStore(peer pb.ServerAddress) bool {
return ma.peerSharesStore[peer]
}
// peerLogListTimeout bounds one peer's log directory listing.
const peerLogListTimeout = 30 * time.Second
// listPeerLogDir lists a metadata log directory on every followed peer not
// known to share this filer's store, from the bound the caller chose for its
// own store. A failed listing fails the read: the files it hides would be
// skipped for good. Peers marked removed, or refusing connections for
// peerUnreachableRemovalAfter even after their mark expired, are left out, as
// their unflushed events are once the settled horizon passes.
func (ma *MetaAggregator) listPeerLogDir(ctx context.Context, dir util.FullPath, startFileName string, inclusive bool) (entries []*Entry, err error) {
nowNs := time.Now().UnixNano()
ma.peerChansLock.Lock()
ma.peerWatermarksLock.Lock()
var peers []pb.ServerAddress
for peer := range ma.peerChans {
_, removed := ma.peerRemovedAtNs[peer]
since, failing := ma.peerUnreachableSinceNs[peer]
retired := removed || failing && nowNs-since >= int64(peerUnreachableRemovalAfter)
if peer != ma.self && !ma.peerSharesStore[peer] && !retired {
peers = append(peers, peer)
}
}
ma.peerWatermarksLock.Unlock()
ma.peerChansLock.Unlock()
for _, peer := range peers {
listCtx, cancel := context.WithTimeout(ctx, peerLogListTimeout)
peerEntries, listErr := ma.peerLogDirLister(listCtx, peer, dir, startFileName, inclusive)
cancel()
if listErr != nil {
return nil, fmt.Errorf("list %s on peer %s: %w", dir, peer, listErr)
}
entries = append(entries, peerEntries...)
}
return entries, nil
}
func (ma *MetaAggregator) readPeerLogDir(ctx context.Context, peer pb.ServerAddress, dir util.FullPath, startFileName string, inclusive bool) (entries []*Entry, err error) {
err = pb.WithFilerClient(false, 0, peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return filer_pb.SeaweedList(ma.filer.peerCallContext(ctx), client, string(dir), "", func(entry *filer_pb.Entry, isLast bool) error {
entries = append(entries, FromPbEntry(string(dir), entry))
return nil
}, startFileName, inclusive, math.MaxInt32)
})
return entries, err
}
// initPeerWatermark adds the peer with a zero (unknown) watermark; a re-added
// peer keeps its prior values and stops being considered removed.
func (ma *MetaAggregator) initPeerWatermark(peer pb.ServerAddress) {
+8
View File
@@ -33,3 +33,11 @@ func (ma *MetaAggregator) ReportPeerWatermarksForTesting(peer pb.ServerAddress,
ma.advancePeerWatermark(peer, deliveredTsNs)
ma.advancePeerFlushWatermark(peer, flushedTsNs)
}
// NotePeerStoreForTesting records whether a tracked peer runs on this filer's
// store, as its stream does once connected. Test support only.
func (ma *MetaAggregator) NotePeerStoreForTesting(peer pb.ServerAddress, sharesStore bool) {
ma.peerChansLock.Lock()
defer ma.peerChansLock.Unlock()
ma.peerSharesStore[peer] = sharesStore
}
+27 -5
View File
@@ -7,6 +7,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -94,12 +95,12 @@ func TestMetaLogReplicationResolution(t *testing.T) {
// are read into the fields a running filer uses.
func TestViperReadsMetaLogOverrides(t *testing.T) {
v := util.GetViper()
v.Set("filer.options.metaLog.collection", "filer-meta")
v.Set("filer.options.metaLog.collection", "meta-elsewhere")
v.Set("filer.options.metaLog.replication", "100")
defer func() {
// Reset so other tests see the unset default.
v.Set("filer.options.metaLog.collection", "")
v.Set("filer.options.metaLog.replication", "")
// nil drops the override, so later reads see the defaults again.
v.Set("filer.options.metaLog.collection", nil)
v.Set("filer.options.metaLog.replication", nil)
}()
f := NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
@@ -109,7 +110,7 @@ func TestViperReadsMetaLogOverrides(t *testing.T) {
f.LocalMetaLogBuffer.ShutdownLogBuffer()
f.LocalMetaLogBuffer.WaitForShutdown()
}()
if got := f.metaLogTargetCollection; got != "filer-meta" {
if got := f.metaLogTargetCollection; got != "meta-elsewhere" {
t.Fatalf("NewFiler did not read the collection override: %q", got)
}
if got := f.metaLogTargetReplication; got != "100" {
@@ -142,3 +143,24 @@ func TestBucketCollectionKeepsMetaLogTargetCollection(t *testing.T) {
default:
}
}
func TestMetaLogDefaultsToOwnCollection(t *testing.T) {
f := NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
defer func() {
close(f.deletionQuit)
f.flushCancel()
f.LocalMetaLogBuffer.ShutdownLogBuffer()
f.LocalMetaLogBuffer.WaitForShutdown()
}()
if f.metaLogTargetCollection != "_meta" || f.metaLogVolumeGrowthCount != 2 {
t.Fatalf("defaults: collection %q growth %d", f.metaLogTargetCollection, f.metaLogVolumeGrowthCount)
}
if s3bucket.VerifyS3BucketName(defaultMetaLogCollection) == nil {
t.Fatalf("a bucket can be named %q, so deleting it would drop the metadata log", defaultMetaLogCollection)
}
for i, c := range defaultMetaLogCollection {
if c == '_' && i > 0 && s3bucket.VerifyS3BucketName(defaultMetaLogCollection[i+1:]) == nil {
t.Fatalf("filer group %q with bucket %q maps to %q", defaultMetaLogCollection[:i], defaultMetaLogCollection[i+1:], defaultMetaLogCollection)
}
}
}
+17
View File
@@ -37,3 +37,20 @@ func recordCreatedParent(ctx context.Context, dirEntry *Entry) bool {
*created = append(*created, dirEntry)
return true
}
type peerLogFilesKey struct{}
// WithPeerLogFiles makes persisted-log reads under ctx also list the log
// files of followed peers that keep their own store. The aggregated stream
// needs them: those files never reach this filer's store.
func WithPeerLogFiles(ctx context.Context) context.Context {
return context.WithValue(ctx, peerLogFilesKey{}, true)
}
func readsPeerLogFiles(ctx context.Context) bool {
if ctx == nil {
return false
}
peers, _ := ctx.Value(peerLogFilesKey{}).(bool)
return peers
}
+3
View File
@@ -334,6 +334,9 @@ func (store *MongodbStore) ListDirectoryPrefixedEntries(ctx context.Context, dir
break
}
}
if err == nil {
err = cur.Err()
}
if errClose := cur.Close(ctx); errClose != nil {
glog.V(0).InfofCtx(ctx, "list iterator close: %v", errClose)
+340 -98
View File
@@ -1,6 +1,8 @@
package posixlock
import (
"errors"
"math"
"sync"
"time"
)
@@ -15,76 +17,170 @@ import (
// key is an opaque inode identity supplied by the caller — the file's path, or
// "hl:"+hex(HardLinkId) for a hardlinked inode — so all names of one inode share
// a Set. The Manager is safe for concurrent use.
//
// Unscoped sessions (empty Principal) are leased as a whole once they renew.
// A scoped session is leased per key from its first acquisition: the lease ends
// at the earlier of Lease.TTL after its last acquisition or renewal on that key
// and Lease.NotAfter; no request moves it earlier, so a late request under an
// older token cannot cut short a replacement's renewal. A renewal also extends
// the session's other keys taken under the same Lease.Grant, skipping the scan
// while those keys already last long enough, so a mount renewing many keys one
// by one costs linear, not quadratic, work. Expired scoped locks are dropped
// before any operation on their key, so they never block a new holder until
// the next sweep.
type Manager struct {
mu sync.Mutex
byKey map[string]*Set // inode key -> held locks
bySid map[uint64]map[string]bool // session -> keys it currently holds locks on
lastSeen map[uint64]time.Time // session -> last keepalive; only renewing sessions are leased
now func() time.Time
byKey map[string]*Set // inode key -> held locks
sessions map[Session]*sessionState // session -> keys it holds locks on, and its leases
}
// sessionState is one session's index and lease state. keys maps each key the
// session holds locks on to its lease there, which only a scoped session has.
// lastSeen is an unscoped session's last keepalive, zero until it renews: only
// renewing sessions are leased. floors maps a scoped session's grant to the
// deadline every live key under it reaches.
type sessionState struct {
keys map[string]keyLease
lastSeen time.Time
floors map[string]time.Time
}
// ErrLeaseEnded refuses a scoped lock whose lease would end before it is
// granted, such as a request admitted just before its token expired.
var ErrLeaseEnded = errors.New("posix lock lease has already ended")
// Session is a mount session under the authority that holds it. Sid is chosen
// by the client; Principal, set by the server from the verified credential, is
// empty for unscoped callers.
type Session struct {
Principal string
Sid uint64
}
// Lease bounds a scoped session's hold on a key. It is ignored for unscoped
// sessions.
//
// Grant identifies the authority the caller holds, such as a digest of its
// verified grants. A key remembers the Grant it was acquired or re-asserted
// under, and a renewal under the same non-empty Grant extends every such key of
// the session: the caller could renew each of them on its own, and renewing
// them together keeps a mount that holds many keys from losing some while it
// renews them one by one. A key taken under another Grant, or under none, is
// renewed only by name.
type Lease struct {
TTL time.Duration
NotAfter time.Time
Grant string
}
// keyLease is a scoped session's lease on one key.
type keyLease struct {
deadline time.Time
grant string
}
func NewManager() *Manager {
return NewManagerWithClock(time.Now)
}
// NewManagerWithClock returns a Manager whose leases follow now.
func NewManagerWithClock(now func() time.Time) *Manager {
return &Manager{
now: now,
byKey: make(map[string]*Set),
bySid: make(map[uint64]map[string]bool),
lastSeen: make(map[uint64]time.Time),
sessions: make(map[Session]*sessionState),
}
}
// Renew records a keepalive from a session, placing it under lease management.
// Only sessions that have renewed are subject to ReapExpired, so a session that
// never sends keepalives (e.g. before the mount keepalive exists) is never reaped.
func (m *Manager) Renew(sid uint64) {
// Renew records a keepalive from a session. An unscoped session is placed under
// lease management as a whole, regardless of key: only sessions that have
// renewed are subject to ReapExpired, so a session that never sends keepalives
// (e.g. before the mount keepalive exists) is never reaped. A scoped session
// renews its existing lease on key, keeping the Grant the key was taken under,
// and its other live leases taken under lease.Grant.
func (m *Manager) Renew(key string, ss Session, lease Lease) {
m.mu.Lock()
defer m.mu.Unlock()
m.lastSeen[sid] = time.Now()
if ss.Principal == "" {
m.session(ss).lastSeen = m.now()
return
}
m.live(key)
if st := m.sessions[ss]; st != nil {
if l, held := st.keys[key]; held {
l.deadline = laterOf(l.deadline, m.deadline(lease))
st.keys[key] = l
st.lowerFloor(l)
}
}
m.renewGrant(ss, lease)
}
// ReapExpired releases the locks of every leased session whose last keepalive is
// older than ttl — a dead or partitioned mount. Sessions that never renewed are
// left untouched. Returns the reaped session ids.
// ReapExpired releases the locks of every leased unscoped session whose last
// keepalive is older than ttl — a dead or partitioned mount — and of every
// scoped lease past its deadline. Unscoped sessions that never renewed are left
// untouched. Returns the reaped session ids.
func (m *Manager) ReapExpired(ttl time.Duration) []uint64 {
m.mu.Lock()
defer m.mu.Unlock()
cutoff := time.Now().Add(-ttl)
now := m.now()
cutoff := now.Add(-ttl)
var reaped []uint64
for sid, seen := range m.lastSeen {
if seen.After(cutoff) {
continue
}
for key := range m.bySid[sid] {
s := m.byKey[key]
if s == nil {
for ss, st := range m.sessions {
if ss.Principal == "" {
if st.lastSeen.IsZero() || st.lastSeen.After(cutoff) {
continue
}
s.ReleaseSession(sid)
if s.Empty() {
delete(m.byKey, key)
for key := range st.keys {
m.releaseOn(key, ss)
}
delete(m.sessions, ss)
reaped = append(reaped, ss.Sid)
continue
}
expired := false
for key, l := range st.keys {
if now.Before(l.deadline) {
continue
}
m.releaseOn(key, ss)
m.deindex(ss, key)
expired = true
}
if expired {
reaped = append(reaped, ss.Sid)
}
delete(m.bySid, sid)
delete(m.lastSeen, sid)
reaped = append(reaped, sid)
}
return reaped
}
// TryLock grants lk on key, or returns the conflicting lock and false. The set
// is created on first use and dropped again when it empties.
func (m *Manager) TryLock(key string, lk Range) (Range, bool) {
// is created on first use and dropped again when it empties. A grant to a
// scoped session starts or extends its lease on key; when that lease has
// already ended, nothing is granted and the error is ErrLeaseEnded.
func (m *Manager) TryLock(key string, lk Range, lease Lease) (Range, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
s, ok := m.byKey[key]
if !ok {
if lk.Principal != "" && !m.now().Before(m.deadline(lease)) {
return Range{}, false, ErrLeaseEnded
}
s := m.live(key)
created := s == nil
if created {
s = &Set{}
}
if c, granted := s.Acquire(lk); !granted {
return c, false
return c, false, nil
}
if !ok {
if created {
m.byKey[key] = s
}
m.index(lk.Sid, key)
return Range{}, true
m.index(lk.Session(), key)
if lk.Principal != "" {
m.lease(lk.Session(), key, lease)
}
return Range{}, true, nil
}
// Track records a lock the server already granted, without arbitration. A mount
@@ -99,7 +195,7 @@ func (m *Manager) Track(key string, lk Range) {
m.byKey[key] = s
}
s.Grant(lk)
m.index(lk.Sid, key)
m.index(lk.Session(), key)
}
// Snapshot returns a copy of the held locks per key. A mount calls it to drive
@@ -114,17 +210,21 @@ func (m *Manager) Snapshot() map[string][]Range {
return out
}
// Reassert rebuilds session sid's locks on key from the client's authoritative
// list, renewing the lease. It replaces sid's existing locks on the key, then
// re-acquires each asserted lock — arbitrating against other sessions so it never
// double-grants. Locks that lost to another session in a migration window are
// returned as conflicts. The owner filer calls this on a re-assertion keepalive.
func (m *Manager) Reassert(key string, sid uint64, locks []Range) (conflicts []Range) {
// Reassert rebuilds session ss's locks on key from the client's authoritative
// list, renewing the lease. It replaces ss's existing locks on the key, then
// re-acquires each asserted lock as ss — arbitrating against other sessions so
// it never double-grants. Locks that lost to another session in a migration
// window are returned as conflicts. A scoped re-assertion also renews ss's other
// live leases taken under lease.Grant, as Renew does. The owner filer calls this
// on a re-assertion keepalive.
func (m *Manager) Reassert(key string, ss Session, locks []Range, lease Lease) (conflicts []Range) {
m.mu.Lock()
defer m.mu.Unlock()
m.lastSeen[sid] = time.Now()
if ss.Principal == "" {
m.session(ss).lastSeen = m.now()
}
s := m.byKey[key]
s := m.live(key)
if s == nil {
if len(locks) == 0 {
return nil
@@ -132,21 +232,27 @@ func (m *Manager) Reassert(key string, sid uint64, locks []Range) (conflicts []R
s = &Set{}
m.byKey[key] = s
}
s.ReleaseSession(sid)
s.ReleaseSession(ss)
for _, lk := range locks {
lk.Sid = sid
lk.Sid, lk.Principal = ss.Sid, ss.Principal
if c, granted := s.Acquire(lk); !granted {
conflicts = append(conflicts, c)
}
}
if setHasSession(s, sid) {
m.index(sid, key)
if setHasSession(s, ss) {
m.index(ss, key)
if ss.Principal != "" {
m.lease(ss, key, lease)
}
} else {
m.deindex(sid, key)
m.deindex(ss, key)
}
if s.Empty() {
delete(m.byKey, key)
}
if ss.Principal != "" {
m.renewGrant(ss, lease)
}
return conflicts
}
@@ -154,104 +260,240 @@ func (m *Manager) Reassert(key string, sid uint64, locks []Range) (conflicts []R
func (m *Manager) Unlock(key string, lk Range) {
m.mu.Lock()
defer m.mu.Unlock()
s := m.byKey[key]
s := m.live(key)
if s == nil {
return
}
s.Release(lk)
m.afterRelease(key, s, lk.Sid)
m.afterRelease(key, s, lk.Session())
}
// GetLk reports the lock that would block proposed on key, if any.
func (m *Manager) GetLk(key string, proposed Range) (Range, bool) {
m.mu.Lock()
defer m.mu.Unlock()
s := m.byKey[key]
s := m.live(key)
if s == nil {
return Range{}, false
}
return s.Conflict(proposed)
}
// ReleasePosixOwner drops (sid, owner)'s fcntl locks on key — the flush-time path.
func (m *Manager) ReleasePosixOwner(key string, sid, owner uint64) {
// ReleasePosixOwner drops (ss, owner)'s fcntl locks on key — the flush-time path.
func (m *Manager) ReleasePosixOwner(key string, ss Session, owner uint64) {
m.mu.Lock()
defer m.mu.Unlock()
s := m.byKey[key]
s := m.live(key)
if s == nil {
return
}
s.ReleasePosixOwner(sid, owner)
m.afterRelease(key, s, sid)
s.ReleasePosixOwner(ss, owner)
m.afterRelease(key, s, ss)
}
// ReleaseFlockOwner drops (sid, owner)'s flock locks on key — the release-time path.
func (m *Manager) ReleaseFlockOwner(key string, sid, owner uint64) {
// ReleaseFlockOwner drops (ss, owner)'s flock locks on key — the release-time path.
func (m *Manager) ReleaseFlockOwner(key string, ss Session, owner uint64) {
m.mu.Lock()
defer m.mu.Unlock()
s := m.byKey[key]
s := m.live(key)
if s == nil {
return
}
s.ReleaseFlockOwner(sid, owner)
m.afterRelease(key, s, sid)
s.ReleaseFlockOwner(ss, owner)
m.afterRelease(key, s, ss)
}
// ReleaseSession drops every lock held by a session across all inodes it touched,
// reaping a mount whose lease expired. O(locks held by the session).
func (m *Manager) ReleaseSession(sid uint64) {
func (m *Manager) ReleaseSession(ss Session) {
m.mu.Lock()
defer m.mu.Unlock()
for key := range m.bySid[sid] {
s := m.byKey[key]
if s == nil {
continue
}
s.ReleaseSession(sid)
if s.Empty() {
delete(m.byKey, key)
if st := m.sessions[ss]; st != nil {
for key := range st.keys {
m.releaseOn(key, ss)
}
}
delete(m.bySid, sid)
delete(m.sessions, ss)
}
// afterRelease prunes the session index when sid no longer holds any lock on key,
// and drops the set when it empties. Only sid's presence can have changed, since
// a release only removes sid's locks.
func (m *Manager) afterRelease(key string, s *Set, sid uint64) {
// releaseOn drops ss's locks on key, and the set when it empties.
func (m *Manager) releaseOn(key string, ss Session) {
s := m.byKey[key]
if s == nil {
return
}
s.ReleaseSession(ss)
if s.Empty() {
delete(m.byKey, key)
m.deindex(sid, key)
}
}
// live returns key's set after dropping the locks of scoped sessions whose
// lease on key has ended, or nil when nothing is held.
func (m *Manager) live(key string) *Set {
s := m.byKey[key]
if s == nil {
return nil
}
now := m.now()
// One pass finds the expired sessions and one more drops all their ranges,
// however many sessions expired and ranges they hold.
var expired map[Session]struct{}
for _, l := range s.locks {
ss := l.Session()
if ss.Principal == "" {
continue
}
if _, seen := expired[ss]; seen {
continue
}
if st := m.sessions[ss]; st != nil {
if l, ok := st.keys[key]; ok && now.Before(l.deadline) {
continue
}
}
if expired == nil {
expired = make(map[Session]struct{})
}
expired[ss] = struct{}{}
}
if expired != nil {
s.remove(func(h Range) bool {
_, gone := expired[h.Session()]
return gone
}, 0, math.MaxUint64)
for ss := range expired {
m.deindex(ss, key)
}
}
if s.Empty() {
delete(m.byKey, key)
return nil
}
return s
}
// lease sets ss's lease on key to lease's deadline, held under lease.Grant.
func (m *Manager) lease(ss Session, key string, lease Lease) {
st := m.session(ss)
l := keyLease{deadline: laterOf(st.keys[key].deadline, m.deadline(lease)), grant: lease.Grant}
st.keys[key] = l
st.lowerFloor(l)
}
// lowerFloor keeps the floor for l.grant at or below l's deadline, so a key
// leased for less than the last same-grant renewal gave its peers is never
// skipped by the next one.
func (st *sessionState) lowerFloor(l keyLease) {
if f, ok := st.floors[l.grant]; ok && l.deadline.Before(f) {
st.floors[l.grant] = l.deadline
}
}
// deadline is the earlier of lease.TTL from now and lease.NotAfter.
func (m *Manager) deadline(lease Lease) time.Time {
deadline := m.now().Add(lease.TTL)
if lease.NotAfter.Before(deadline) {
deadline = lease.NotAfter
}
return deadline
}
// renewGrant extends ss's leases taken under lease.Grant to lease's deadline.
// A lease that has already ended stays ended even before it is swept, so when
// a lease ends never depends on when the sweep runs.
//
// A mount renews its keys one by one, and a scan per renewal would cost N² for
// N keys. So the scan is skipped while every live key under the grant already
// lasts until the earlier of lease's deadline and three quarters of a TTL from
// now: the floor the last scan set, lowered by any key leased for less since.
// A renewal with a later deadline than the floor, such as one under a
// replacement token that expires later, scans as soon as the floor falls short.
func (m *Manager) renewGrant(ss Session, lease Lease) {
st := m.sessions[ss]
if lease.Grant == "" || st == nil {
return
}
if !setHasSession(s, sid) {
m.deindex(sid, key)
now, deadline := m.now(), m.deadline(lease)
enough := now.Add(lease.TTL * 3 / 4)
if deadline.Before(enough) {
enough = deadline
}
}
func (m *Manager) index(sid uint64, key string) {
keys := m.bySid[sid]
if keys == nil {
keys = make(map[string]bool)
m.bySid[sid] = keys
}
keys[key] = true
}
func (m *Manager) deindex(sid uint64, key string) {
keys := m.bySid[sid]
if keys == nil {
if f, ok := st.floors[lease.Grant]; ok && !f.Before(enough) {
return
}
delete(keys, key)
if len(keys) == 0 {
delete(m.bySid, sid)
renewed := false
for key, l := range st.keys {
if l.grant == lease.Grant && now.Before(l.deadline) {
l.deadline = laterOf(l.deadline, deadline)
st.keys[key] = l
renewed = true
}
}
if !renewed {
return
}
if st.floors == nil {
st.floors = make(map[string]time.Time)
}
st.floors[lease.Grant] = deadline
}
func laterOf(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
// afterRelease prunes the session index when ss no longer holds any lock on key,
// and drops the set when it empties. Only ss's presence can have changed, since
// a release only removes ss's locks.
func (m *Manager) afterRelease(key string, s *Set, ss Session) {
if s.Empty() {
delete(m.byKey, key)
m.deindex(ss, key)
return
}
if !setHasSession(s, ss) {
m.deindex(ss, key)
}
}
func setHasSession(s *Set, sid uint64) bool {
// session returns ss's state, creating it on first use.
func (m *Manager) session(ss Session) *sessionState {
st := m.sessions[ss]
if st == nil {
st = &sessionState{keys: make(map[string]keyLease)}
m.sessions[ss] = st
}
return st
}
func (m *Manager) index(ss Session, key string) {
st := m.session(ss)
if _, ok := st.keys[key]; !ok {
st.keys[key] = keyLease{}
}
}
// deindex forgets that ss holds locks on key, along with its lease there. A
// session holding no keys is forgotten, with its floors, unless it is an
// unscoped session that has renewed.
func (m *Manager) deindex(ss Session, key string) {
st := m.sessions[ss]
if st == nil {
return
}
delete(st.keys, key)
if len(st.keys) == 0 && st.lastSeen.IsZero() {
delete(m.sessions, ss)
}
}
func setHasSession(s *Set, ss Session) bool {
for _, l := range s.Locks() {
if l.Sid == sid {
if l.Session() == ss {
return true
}
}
+39 -30
View File
@@ -11,14 +11,14 @@ import (
func TestManagerGrantAndConflict(t *testing.T) {
m := NewManager()
if _, granted := m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}); !granted {
if _, granted, _ := m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{}); !granted {
t.Fatal("first lock should be granted")
}
if c, granted := m.TryLock("a", Range{Start: 50, End: 149, Type: Write, Sid: 2, Owner: 1}); granted {
if c, granted, _ := m.TryLock("a", Range{Start: 50, End: 149, Type: Write, Sid: 2, Owner: 1}, Lease{}); granted {
t.Fatalf("overlapping lock from another session should conflict, got grant; conflict=%+v", c)
}
// A different key is independent.
if _, granted := m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}); !granted {
if _, granted, _ := m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}, Lease{}); !granted {
t.Fatal("lock on a different key should be granted")
}
}
@@ -26,9 +26,9 @@ func TestManagerGrantAndConflict(t *testing.T) {
func TestManagerUnlockCleansEmptyKeyAndIndex(t *testing.T) {
m := NewManager()
lk := Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}
m.TryLock("a", lk)
m.TryLock("a", lk, Lease{})
if !m.bySid[1]["a"] {
if !holds(m, Session{Sid: 1}, "a") {
t.Fatal("session index should record the held key")
}
m.Unlock("a", Range{Start: 0, End: 99, Type: Unlock, Sid: 1, Owner: 1})
@@ -36,19 +36,19 @@ func TestManagerUnlockCleansEmptyKeyAndIndex(t *testing.T) {
if _, ok := m.byKey["a"]; ok {
t.Fatal("empty set should be dropped from byKey")
}
if _, ok := m.bySid[1]; ok {
if _, ok := m.sessions[Session{Sid: 1}]; ok {
t.Fatal("session index should be pruned when it holds nothing")
}
}
func TestManagerPartialUnlockKeepsIndex(t *testing.T) {
m := NewManager()
m.TryLock("a", Range{Start: 0, End: 49, Type: Write, Sid: 1, Owner: 1})
m.TryLock("a", Range{Start: 100, End: 149, Type: Write, Sid: 1, Owner: 1})
m.TryLock("a", Range{Start: 0, End: 49, Type: Write, Sid: 1, Owner: 1}, Lease{})
m.TryLock("a", Range{Start: 100, End: 149, Type: Write, Sid: 1, Owner: 1}, Lease{})
// Release one of the two ranges; the session still holds the other.
m.Unlock("a", Range{Start: 0, End: 49, Type: Unlock, Sid: 1, Owner: 1})
if !m.bySid[1]["a"] {
if !holds(m, Session{Sid: 1}, "a") {
t.Fatal("session still holds a lock on the key; index must remain")
}
if _, ok := m.byKey["a"]; !ok {
@@ -58,7 +58,7 @@ func TestManagerPartialUnlockKeepsIndex(t *testing.T) {
func TestManagerGetLk(t *testing.T) {
m := NewManager()
m.TryLock("a", Range{Start: 10, End: 50, Type: Write, Sid: 1, Owner: 1, Pid: 7})
m.TryLock("a", Range{Start: 10, End: 50, Type: Write, Sid: 1, Owner: 1, Pid: 7}, Lease{})
c, found := m.GetLk("a", Range{Start: 30, End: 70, Type: Read, Sid: 2, Owner: 1})
if !found || c.Pid != 7 {
t.Fatalf("expected conflict from pid 7, got %+v found=%v", c, found)
@@ -70,13 +70,13 @@ func TestManagerGetLk(t *testing.T) {
func TestManagerReleasePosixOwnerKeepsFlockAndIndex(t *testing.T) {
m := NewManager()
m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1})
m.TryLock("a", Range{Start: 0, End: math.MaxUint64, Type: Write, Sid: 1, Owner: 1, IsFlock: true})
m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{})
m.TryLock("a", Range{Start: 0, End: math.MaxUint64, Type: Write, Sid: 1, Owner: 1, IsFlock: true}, Lease{})
m.ReleasePosixOwner("a", 1, 1)
m.ReleasePosixOwner("a", Session{Sid: 1}, 1)
// flock lock for the same session remains, so the index must remain too.
if !m.bySid[1]["a"] {
if !holds(m, Session{Sid: 1}, "a") {
t.Fatal("session still holds the flock lock; index must remain")
}
if _, found := m.GetLk("a", Range{Start: 0, End: 10, Type: Write, Sid: 2, Owner: 2, IsFlock: true}); !found {
@@ -89,13 +89,13 @@ func TestManagerReleasePosixOwnerKeepsFlockAndIndex(t *testing.T) {
func TestManagerReleaseSessionReapsAcrossKeys(t *testing.T) {
m := NewManager()
m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1})
m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 2})
m.TryLock("b", Range{Start: 200, End: 299, Type: Write, Sid: 2, Owner: 1})
m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{})
m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 2}, Lease{})
m.TryLock("b", Range{Start: 200, End: 299, Type: Write, Sid: 2, Owner: 1}, Lease{})
m.ReleaseSession(1)
m.ReleaseSession(Session{Sid: 1})
if _, ok := m.bySid[1]; ok {
if _, ok := m.sessions[Session{Sid: 1}]; ok {
t.Fatal("reaped session should be gone from the index")
}
if _, ok := m.byKey["a"]; ok {
@@ -105,7 +105,7 @@ func TestManagerReleaseSessionReapsAcrossKeys(t *testing.T) {
if _, found := m.GetLk("b", Range{Start: 200, End: 299, Type: Write, Sid: 9, Owner: 9}); !found {
t.Fatal("session 2's lock on b should remain after reaping session 1")
}
if !m.bySid[2]["b"] {
if !holds(m, Session{Sid: 2}, "b") {
t.Fatal("session 2 index entry should remain")
}
}
@@ -113,14 +113,14 @@ func TestManagerReleaseSessionReapsAcrossKeys(t *testing.T) {
func TestManagerReapsOnlyStaleLeasedSessions(t *testing.T) {
m := NewManager()
// Session 1: holds a lock, leased but stale (renewed long ago).
m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1})
m.Renew(1)
m.lastSeen[1] = time.Now().Add(-time.Hour)
m.TryLock("a", Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1}, Lease{})
m.Renew("", Session{Sid: 1}, Lease{})
m.sessions[Session{Sid: 1}].lastSeen = time.Now().Add(-time.Hour)
// Session 2: holds a lock, leased and fresh.
m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1})
m.Renew(2)
m.TryLock("b", Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1}, Lease{})
m.Renew("", Session{Sid: 2}, Lease{})
// Session 3: holds a lock but never renewed (no lease) — must not be reaped.
m.TryLock("c", Range{Start: 0, End: 99, Type: Write, Sid: 3, Owner: 1})
m.TryLock("c", Range{Start: 0, End: 99, Type: Write, Sid: 3, Owner: 1}, Lease{})
reaped := m.ReapExpired(30 * time.Second)
@@ -136,7 +136,7 @@ func TestManagerReapsOnlyStaleLeasedSessions(t *testing.T) {
if _, ok := m.byKey["c"]; !ok {
t.Fatal("never-renewed session must not be reaped")
}
if _, ok := m.lastSeen[1]; ok {
if _, ok := m.sessions[Session{Sid: 1}]; ok {
t.Fatal("reaped session's lease entry should be cleared")
}
}
@@ -165,7 +165,7 @@ func TestManagerConcurrentFlockMutualExclusion(t *testing.T) {
token := int64(id + 1)
for i := 0; i < iters; i++ {
for {
if _, granted := m.TryLock(key, lk); granted {
if _, granted, _ := m.TryLock(key, lk, Lease{}); granted {
break
}
runtime.Gosched()
@@ -188,7 +188,16 @@ func TestManagerConcurrentFlockMutualExclusion(t *testing.T) {
if len(m.byKey) != 0 {
t.Fatalf("all locks released; byKey should be empty, got %d", len(m.byKey))
}
if len(m.bySid) != 0 {
t.Fatalf("all locks released; bySid should be empty, got %d", len(m.bySid))
if len(m.sessions) != 0 {
t.Fatalf("all locks released; sessions should be empty, got %d", len(m.sessions))
}
}
func holds(m *Manager, ss Session, key string) bool {
st := m.sessions[ss]
if st == nil {
return false
}
_, ok := st.keys[key]
return ok
}
+35 -26
View File
@@ -24,22 +24,31 @@ const (
Unlock uint32 = 3
)
// Range is one held advisory byte-range lock. Owner identity is the (Sid, Owner)
// pair: Sid is the mount session, Owner the FUSE lock owner within it, so owners
// from different mounts never alias. End is inclusive; math.MaxUint64 means EOF.
// IsFlock separates the flock and fcntl namespaces, which never conflict.
// Range is one held advisory byte-range lock. Owner identity is the
// (Principal, Sid, Owner) triple: Sid is the mount session, Owner the FUSE lock
// owner within it, so owners from different mounts never alias. Principal is the
// verified authority the server holds the lock under, empty for unscoped
// callers; it is server-side state and never leaves the filer. End is
// inclusive; math.MaxUint64 means EOF. IsFlock separates the flock and fcntl
// namespaces, which never conflict.
type Range struct {
Start uint64
End uint64
Type uint32
Sid uint64
Owner uint64
Pid uint32
IsFlock bool
Start uint64
End uint64
Type uint32
Sid uint64
Owner uint64
Pid uint32
IsFlock bool
Principal string
}
// Session returns the session that holds r.
func (r Range) Session() Session {
return Session{Principal: r.Principal, Sid: r.Sid}
}
func (r Range) sameOwner(o Range) bool {
return r.Sid == o.Sid && r.Owner == o.Owner
return r.Principal == o.Principal && r.Sid == o.Sid && r.Owner == o.Owner
}
// Set is the authoritative set of advisory locks held on one inode. The zero
@@ -172,41 +181,41 @@ func (s *Set) Release(lk Range) {
}, lk.Start, lk.End)
}
// ReleaseOwner removes every lock held by (sid, owner) in both namespaces.
func (s *Set) ReleaseOwner(sid, owner uint64) {
// ReleaseOwner removes every lock held by (ss, owner) in both namespaces.
func (s *Set) ReleaseOwner(ss Session, owner uint64) {
s.remove(func(h Range) bool {
return h.Sid == sid && h.Owner == owner
return h.Session() == ss && h.Owner == owner
}, 0, math.MaxUint64)
}
// ReleaseFlockOwner removes only the flock locks of (sid, owner) — the close-time
// ReleaseFlockOwner removes only the flock locks of (ss, owner) — the close-time
// path for a released file description (FUSE_RELEASE_FLOCK_UNLOCK).
func (s *Set) ReleaseFlockOwner(sid, owner uint64) {
func (s *Set) ReleaseFlockOwner(ss Session, owner uint64) {
s.remove(func(h Range) bool {
return h.IsFlock && h.Sid == sid && h.Owner == owner
return h.IsFlock && h.Session() == ss && h.Owner == owner
}, 0, math.MaxUint64)
}
// ReleasePosixOwner removes only the fcntl locks of (sid, owner) — the close-time
// ReleasePosixOwner removes only the fcntl locks of (ss, owner) — the close-time
// path for a flushing POSIX lock owner.
func (s *Set) ReleasePosixOwner(sid, owner uint64) {
func (s *Set) ReleasePosixOwner(ss Session, owner uint64) {
s.remove(func(h Range) bool {
return !h.IsFlock && h.Sid == sid && h.Owner == owner
return !h.IsFlock && h.Session() == ss && h.Owner == owner
}, 0, math.MaxUint64)
}
// ReleaseSession removes every lock held by a session, reaping a mount that has
// died or disconnected (its lease expired).
func (s *Set) ReleaseSession(sid uint64) {
s.remove(func(h Range) bool { return h.Sid == sid }, 0, math.MaxUint64)
func (s *Set) ReleaseSession(ss Session) {
s.remove(func(h Range) bool { return h.Session() == ss }, 0, math.MaxUint64)
}
// HasPosix reports whether (sid, owner) holds any fcntl lock, mirroring the
// HasPosix reports whether (ss, owner) holds any fcntl lock, mirroring the
// mount's flush-time check that avoids treating a lock-free flush as
// lock-sensitive.
func (s *Set) HasPosix(sid, owner uint64) bool {
func (s *Set) HasPosix(ss Session, owner uint64) bool {
for _, h := range s.locks {
if !h.IsFlock && h.Sid == sid && h.Owner == owner {
if !h.IsFlock && h.Session() == ss && h.Owner == owner {
return true
}
}
+7 -7
View File
@@ -124,7 +124,7 @@ func TestReleaseOwner(t *testing.T) {
mustAcquire(t, s, Range{Start: 50, End: 99, Type: Write, Owner: 1, Pid: 10})
mustAcquire(t, s, Range{Start: 200, End: 299, Type: Read, Owner: 2, Pid: 20})
s.ReleaseOwner(0, 1)
s.ReleaseOwner(Session{}, 1)
if _, found := s.Conflict(Range{Start: 0, End: 99, Type: Write, Owner: 3, Pid: 30}); found {
t.Fatal("owner 1's locks should be gone")
@@ -144,7 +144,7 @@ func TestFlockAndFcntlDoNotConflict(t *testing.T) {
func TestReleasePosixOwnerKeepsFlock(t *testing.T) {
s := &Set{}
mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 1, Pid: 10, IsFlock: true})
s.ReleasePosixOwner(0, 1)
s.ReleasePosixOwner(Session{}, 1)
if _, found := s.Conflict(Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 2, Pid: 20, IsFlock: true}); !found {
t.Fatal("flock lock should remain after ReleasePosixOwner")
}
@@ -155,7 +155,7 @@ func TestReleaseFlockOwnerKeepsPosix(t *testing.T) {
mustAcquire(t, s, Range{Start: 0, End: 99, Type: Write, Owner: 1, Pid: 10})
mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 2, Pid: 10, IsFlock: true})
s.ReleaseFlockOwner(0, 2)
s.ReleaseFlockOwner(Session{}, 2)
if _, found := s.Conflict(Range{Start: 0, End: 99, Type: Write, Owner: 3, Pid: 30}); !found {
t.Fatal("fcntl lock should remain after ReleaseFlockOwner")
@@ -167,15 +167,15 @@ func TestReleaseFlockOwnerKeepsPosix(t *testing.T) {
func TestHasPosixIgnoresMissingOwnerAndFlock(t *testing.T) {
s := &Set{}
if s.HasPosix(0, 1) {
if s.HasPosix(Session{}, 1) {
t.Fatal("empty set should report no posix owner")
}
mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Owner: 1, Pid: 10, IsFlock: true})
if s.HasPosix(0, 1) {
if s.HasPosix(Session{}, 1) {
t.Fatal("a flock owner is not a posix owner")
}
mustAcquire(t, s, Range{Start: 0, End: 99, Type: Write, Owner: 2, Pid: 20})
if !s.HasPosix(0, 2) {
if !s.HasPosix(Session{}, 2) {
t.Fatal("posix owner should be reported")
}
}
@@ -266,7 +266,7 @@ func TestReleaseSessionReapsOnlyThatSession(t *testing.T) {
mustAcquire(t, s, Range{Start: 0, End: math.MaxUint64, Type: Write, Sid: 1, Owner: 2, Pid: 11, IsFlock: true})
mustAcquire(t, s, Range{Start: 50, End: 99, Type: Write, Sid: 2, Owner: 1, Pid: 20})
s.ReleaseSession(1)
s.ReleaseSession(Session{Sid: 1})
for _, h := range s.locks {
if h.Sid == 1 {
+508
View File
@@ -0,0 +1,508 @@
package posixlock
import (
"errors"
"fmt"
"reflect"
"sync"
"testing"
"time"
)
type testClock struct {
mu sync.Mutex
now time.Time
}
func (c *testClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *testClock) Set(t time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
c.now = t
}
func newScopedTestManager() (*Manager, *testClock, time.Time) {
start := time.Unix(1_000_000, 0)
clock := &testClock{now: start}
return NewManagerWithClock(clock.Now), clock, start
}
func TestManagerOwnersWithEqualSidAndOwnerDifferUnderAnotherPrincipal(t *testing.T) {
m, _, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}
holder := Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1, Pid: 7, Principal: "a"}
if _, granted, _ := m.TryLock("k", holder, lease); !granted {
t.Fatal("holder should be granted")
}
for _, other := range []string{"b", ""} {
same := holder
same.Principal = other
if c, granted, _ := m.TryLock("k", same, lease); granted || c.Pid != 7 {
t.Fatalf("principal %q with the holder's sid/owner must conflict, got granted=%v conflict=%+v", other, granted, c)
}
if _, found := m.GetLk("k", same); !found {
t.Fatalf("GET_LK under principal %q must report the holder", other)
}
unlock := same
unlock.Type, unlock.Start, unlock.End = Unlock, 10, 20
m.Unlock("k", unlock)
m.ReleasePosixOwner("k", same.Session(), same.Owner)
m.ReleaseSession(same.Session())
m.Reassert("k", same.Session(), []Range{same}, lease)
m.Renew("k", same.Session(), lease)
}
if got := m.Snapshot()["k"]; !reflect.DeepEqual(got, []Range{holder}) {
t.Fatalf("holder's lock changed by other principals: %+v", got)
}
if _, found := m.GetLk("k", holder); found {
t.Fatal("the holder must not conflict with itself")
}
}
func TestManagerAdjacentRangesOfDifferentPrincipalsNeverCoalesce(t *testing.T) {
m, _, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}
m.TryLock("k", Range{Start: 0, End: 9, Type: Read, Sid: 1, Owner: 1, Principal: "a"}, lease)
m.TryLock("k", Range{Start: 10, End: 19, Type: Read, Sid: 1, Owner: 1, Principal: "b"}, lease)
m.TryLock("k", Range{Start: 20, End: 29, Type: Read, Sid: 1, Owner: 1}, lease)
if got := m.Snapshot()["k"]; len(got) != 3 {
t.Fatalf("ranges of different principals must stay separate, got %+v", got)
}
// A partial unlock by one principal splits only its own range.
m.Unlock("k", Range{Start: 3, End: 5, Type: Unlock, Sid: 1, Owner: 1, Principal: "a"})
if got := m.Snapshot()["k"]; len(got) != 4 || got[0].End != 2 || got[1].Start != 6 || got[2].Principal != "b" {
t.Fatalf("partial unlock should split only principal a's range, got %+v", got)
}
}
func TestManagerScopedLeaseEndsAtEarlierOfTTLAndNotAfter(t *testing.T) {
cases := []struct {
name string
notAfter time.Duration
ends time.Duration
}{
{name: "ttl first", notAfter: time.Hour, ends: 15 * time.Second},
{name: "token expiry first", notAfter: 5 * time.Second, ends: 5 * time.Second},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
m, clock, start := newScopedTestManager()
lk := Range{Start: 0, End: 99, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
m.TryLock("k", lk, Lease{TTL: 15 * time.Second, NotAfter: start.Add(tc.notAfter)})
other := Range{Start: 0, End: 99, Type: Write, Sid: 2, Owner: 1, Principal: "b"}
clock.Set(start.Add(tc.ends - time.Nanosecond))
if _, found := m.GetLk("k", other); !found {
t.Fatal("lease must hold until its deadline")
}
clock.Set(start.Add(tc.ends))
if _, granted, _ := m.TryLock("k", other, Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}); !granted {
t.Fatal("an expired lease must not block a new holder")
}
if _, ok := m.sessions[lk.Session()]; ok {
t.Fatal("expired session and its lease should be forgotten")
}
})
}
}
func TestManagerScopedRenewalExtendsOnlyTheRenewedKey(t *testing.T) {
m, clock, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}
ss := Session{Principal: "a", Sid: 1}
m.TryLock("a", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}, lease)
m.TryLock("b", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}, lease)
clock.Set(start.Add(10 * time.Second))
m.Renew("a", ss, lease)
clock.Set(start.Add(15 * time.Second))
other := Range{Start: 0, End: 9, Type: Write, Sid: 2, Owner: 1, Principal: "b"}
if _, found := m.GetLk("a", other); !found {
t.Fatal("renewed key a must still be held")
}
if _, found := m.GetLk("b", other); found {
t.Fatal("key b was not renewed and must have expired")
}
if holds(m, ss, "b") {
t.Fatal("key b's lease and index entry should be gone")
}
clock.Set(start.Add(25 * time.Second))
if _, found := m.GetLk("a", other); found {
t.Fatal("key a's renewed lease ends 15s after the renewal")
}
}
func TestManagerScopedRenewWithoutLocksLeasesNothing(t *testing.T) {
m, _, start := newScopedTestManager()
m.Renew("k", Session{Principal: "a", Sid: 1}, Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)})
if len(m.sessions) != 0 {
t.Fatalf("a renewal of nothing must record nothing: %v", m.sessions)
}
}
func TestManagerReapExpiredDropsScopedLeasesAndKeepsUnleasedUnscopedLocks(t *testing.T) {
m, clock, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}
m.TryLock("scoped", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}, lease)
m.TryLock("unscoped", Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1}, lease)
clock.Set(start.Add(time.Hour))
if reaped := m.ReapExpired(15 * time.Second); len(reaped) != 1 || reaped[0] != 1 {
t.Fatalf("only the scoped lease should be reaped, got %v", reaped)
}
held := m.Snapshot()
if len(held["scoped"]) != 0 || len(held["unscoped"]) != 1 {
t.Fatalf("sweep should drop the scoped lock and keep the never-renewed unscoped one: %+v", held)
}
if _, ok := m.sessions[Session{Principal: "a", Sid: 1}]; ok {
t.Fatal("reaped leases should be forgotten")
}
if !holds(m, Session{Sid: 1}, "unscoped") {
t.Fatal("the unscoped session's index must survive")
}
}
func TestManagerExpiredScopedSessionWithManyRangesIsDroppedWhole(t *testing.T) {
m, clock, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}
keep := Range{Start: 0, End: 9, Type: Read, Sid: 2, Owner: 2, Principal: "b"}
if _, granted, _ := m.TryLock("k", keep, lease); !granted {
t.Fatal("unexpired holder should be granted")
}
// Disjoint ranges that never coalesce, interleaved with another session's.
for i := uint64(1); i <= 50; i++ {
lk := Range{Start: i * 100, End: i*100 + 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
if _, granted, _ := m.TryLock("k", lk, lease); !granted {
t.Fatalf("range %d should be granted", i)
}
}
clock.Set(start.Add(10 * time.Second))
m.Renew("k", keep.Session(), lease)
clock.Set(start.Add(16 * time.Second))
other := Range{Start: 100, End: 5009, Type: Write, Sid: 3, Owner: 3, Principal: "c"}
if c, granted, _ := m.TryLock("k", other, lease); !granted {
t.Fatalf("expired session's ranges should be gone, conflict %+v", c)
}
expired := Session{Principal: "a", Sid: 1}
if _, indexed := m.sessions[expired]; indexed {
t.Fatal("expired session is still indexed")
}
if got := m.Snapshot()["k"]; len(got) != 2 || got[0] != keep {
t.Fatalf("unexpired holder or new grant missing: %+v", got)
}
}
func TestManagerSeveralExpiredScopedSessionsAreDroppedTogether(t *testing.T) {
m, clock, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour)}
keep := Range{Start: 0, End: 9, Type: Read, Sid: 9, Owner: 9, Principal: "keep"}
m.TryLock("k", keep, lease)
for i := uint64(1); i <= 20; i++ {
principal := []string{"a", "b", "c"}[i%3]
lk := Range{Start: i * 100, End: i*100 + 9, Type: Read, Sid: i % 3, Owner: 1, Principal: principal}
if _, granted, _ := m.TryLock("k", lk, lease); !granted {
t.Fatalf("range %d should be granted", i)
}
}
clock.Set(start.Add(10 * time.Second))
m.Renew("k", keep.Session(), lease)
clock.Set(start.Add(16 * time.Second))
if got := m.Snapshot()["k"]; len(got) != 21 {
t.Fatalf("snapshot should not reap, got %d ranges", len(got))
}
if _, found := m.GetLk("k", Range{Start: 100, End: 2009, Type: Write, Sid: 5, Owner: 5, Principal: "w"}); found {
t.Fatal("ranges of the expired sessions are still held")
}
for _, p := range []string{"a", "b", "c"} {
for sid := uint64(0); sid < 3; sid++ {
if _, indexed := m.sessions[Session{Principal: p, Sid: sid}]; indexed {
t.Fatalf("expired session %s/%d is still indexed", p, sid)
}
}
}
if got := m.Snapshot()["k"]; len(got) != 1 || got[0] != keep {
t.Fatalf("only the renewed holder should remain: %+v", got)
}
}
func TestManagerScopedRenewalExtendsTheSessionsKeysUnderTheSameGrant(t *testing.T) {
// A bare keepalive keeps the grant a key was taken under; a re-assertion
// takes the key again, under the request's grant.
renewals := []struct {
name string
renew func(m *Manager, key string, ss Session, lease Lease)
keptGrant string
}{
{name: "bare keepalive", keptGrant: "narrow", renew: func(m *Manager, key string, ss Session, lease Lease) { m.Renew(key, ss, lease) }},
{name: "reassertion", keptGrant: "g", renew: func(m *Manager, key string, ss Session, lease Lease) {
m.Reassert(key, ss, []Range{{Start: 0, End: 9, Type: Write, Owner: 1}}, lease)
}},
}
for _, r := range renewals {
t.Run(r.name, func(t *testing.T) {
m, clock, start := newScopedTestManager()
lease := func(grant string) Lease {
return Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: grant}
}
lock := func(key, principal string, sid uint64, grant string) {
lk := Range{Start: 0, End: 9, Type: Write, Sid: sid, Owner: 1, Principal: principal}
if _, granted, _ := m.TryLock(key, lk, lease(grant)); !granted {
t.Fatalf("%s should be granted", key)
}
}
ss := Session{Principal: "a", Sid: 1}
for _, key := range []string{"k1", "k2", "k3"} {
lock(key, "a", 1, "g")
}
lock("narrow1", "a", 1, "narrow")
lock("narrow2", "a", 1, "narrow")
lock("other-sid", "a", 2, "g")
lock("other-principal", "b", 1, "g")
clock.Set(start.Add(10 * time.Second))
r.renew(m, "k1", ss, lease("g"))
r.renew(m, "narrow1", ss, lease("g"))
clock.Set(start.Add(25*time.Second - time.Nanosecond))
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
for key, want := range map[string]bool{
"k1": true, "k2": true, "k3": true, // same session, same grant
"narrow1": true, // renewed by name
"narrow2": false, // another grant, not named
"other-sid": false,
"other-principal": false,
} {
if _, held := m.GetLk(key, probe); held != want {
t.Errorf("%s held=%v, want %v", key, held, want)
}
}
if got := m.sessions[ss].keys["narrow1"].grant; got != r.keptGrant {
t.Fatalf("narrow1 is held under grant %q, want %q", got, r.keptGrant)
}
clock.Set(start.Add(25 * time.Second))
for _, key := range []string{"k1", "k2", "k3", "narrow1"} {
if _, held := m.GetLk(key, probe); held {
t.Errorf("%s should end 15s after the renewal", key)
}
}
})
}
}
func TestManagerSameGrantRenewalIsBoundedAndDoesNotReviveEndedLeases(t *testing.T) {
m, clock, start := newScopedTestManager()
ss := Session{Principal: "a", Sid: 1}
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
m.TryLock("ended", lk, lease)
clock.Set(start.Add(10 * time.Second))
m.TryLock("live", lk, lease)
m.TryLock("bounded", lk, lease)
// "ended" lapsed at 15s and has not been swept; a renewal must not revive it.
clock.Set(start.Add(15 * time.Second))
expiring := lease
expiring.NotAfter = start.Add(28 * time.Second)
m.Renew("live", ss, expiring)
if _, held := m.GetLk("ended", probe); held {
t.Fatal("a same-grant renewal revived an ended lease")
}
clock.Set(start.Add(28*time.Second - time.Nanosecond))
if _, held := m.GetLk("bounded", probe); !held {
t.Fatal("bounded should be held until the renewal's NotAfter")
}
clock.Set(start.Add(28 * time.Second))
for _, key := range []string{"live", "bounded"} {
if _, held := m.GetLk(key, probe); held {
t.Fatalf("%s outlived the renewal's NotAfter", key)
}
}
}
func TestManagerScopedTryLockRefusesALeaseThatHasAlreadyEnded(t *testing.T) {
m, _, start := newScopedTestManager()
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
// The token expired while the request waited for the manager.
ended := Lease{TTL: 15 * time.Second, NotAfter: start, Grant: "g"}
if _, granted, err := m.TryLock("k", lk, ended); granted || !errors.Is(err, ErrLeaseEnded) {
t.Fatalf("granted=%v err=%v, want a refusal with ErrLeaseEnded", granted, err)
}
if _, held := m.GetLk("k", probe); held {
t.Fatal("a refused grant must leave no lock behind")
}
if len(m.sessions) != 0 || len(m.byKey) != 0 {
t.Fatalf("a refused grant must leave no state: %v %v", m.sessions, m.byKey)
}
live := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Nanosecond), Grant: "g"}
if _, granted, err := m.TryLock("k", lk, live); !granted || err != nil {
t.Fatalf("granted=%v err=%v, want a grant while the lease is still running", granted, err)
}
// Unscoped locks carry no lease.
unscoped := Range{Start: 0, End: 9, Type: Write, Sid: 2, Owner: 1}
if _, granted, err := m.TryLock("u", unscoped, Lease{}); !granted || err != nil {
t.Fatalf("granted=%v err=%v, want an unscoped grant", granted, err)
}
}
func TestManagerSameGrantRenewalSkipsTheScanWhileKeysLastLongEnough(t *testing.T) {
m, clock, start := newScopedTestManager()
ss := Session{Principal: "a", Sid: 1}
lease := Lease{TTL: 16 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
for _, key := range []string{"k1", "k2", "k3"} {
m.TryLock(key, lk, lease)
}
deadlines := func() []time.Duration {
var out []time.Duration
for _, key := range []string{"k1", "k2", "k3"} {
out = append(out, m.sessions[ss].keys[key].deadline.Sub(start))
}
return out
}
steps := []struct {
at time.Duration
key string
want []time.Duration
}{
// Scans: every key ends at 26s.
{10 * time.Second, "k1", []time.Duration{26 * time.Second, 26 * time.Second, 26 * time.Second}},
// Every key still lasts 12s (three quarters of the TTL): only k2 moves.
{13 * time.Second, "k2", []time.Duration{26 * time.Second, 29 * time.Second, 26 * time.Second}},
{14 * time.Second, "k1", []time.Duration{30 * time.Second, 29 * time.Second, 26 * time.Second}},
// k3 would last less than 12s: scans again.
{14*time.Second + time.Millisecond, "k2", []time.Duration{30001 * time.Millisecond, 30001 * time.Millisecond, 30001 * time.Millisecond}},
}
for _, step := range steps {
clock.Set(start.Add(step.at))
m.Renew(step.key, ss, lease)
if got := deadlines(); !reflect.DeepEqual(got, step.want) {
t.Fatalf("after renewing %s at %v: deadlines %v, want %v", step.key, step.at, got, step.want)
}
}
}
func TestManagerSameGrantRenewalUnderALaterExpiringTokenScansAtOnce(t *testing.T) {
// A replacement token with the same id and grants but a later expiry must
// not leave the other keys on the old token's expiry.
m, clock, start := newScopedTestManager()
ss := Session{Principal: "a", Sid: 1}
expiring := Lease{TTL: 15 * time.Second, NotAfter: start.Add(2 * time.Second), Grant: "g"}
replaced := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
m.TryLock("k1", lk, expiring)
m.TryLock("k2", lk, expiring)
m.Renew("k1", ss, expiring) // every key ends at the token's expiry, 2s
clock.Set(start.Add(time.Second))
m.Renew("k1", ss, replaced)
clock.Set(start.Add(3 * time.Second))
if _, held := m.GetLk("k2", probe); !held {
t.Fatal("k2 expired with the old token although the replacement renewed its grant")
}
}
func TestManagerSameGrantRenewalScansAgainAfterAKeyIsLeasedForLess(t *testing.T) {
m, clock, start := newScopedTestManager()
ss := Session{Principal: "a", Sid: 1}
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
short := Lease{TTL: 15 * time.Second, NotAfter: start.Add(4 * time.Second), Grant: "g"}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
m.TryLock("k1", lk, lease)
m.Renew("k1", ss, lease) // floor at 15s
m.TryLock("k2", lk, short)
clock.Set(start.Add(time.Second))
m.Renew("k1", ss, lease) // k2 ends at 4s, below the floor: must scan
clock.Set(start.Add(5 * time.Second))
if _, held := m.GetLk("k2", probe); !held {
t.Fatal("k2 kept its shorter lease although its grant was renewed")
}
}
func TestManagerScopedKeepalivesWithoutLocksLeaveNoState(t *testing.T) {
m, _, start := newScopedTestManager()
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
for sid := uint64(1); sid <= 100; sid++ {
m.Renew("k", Session{Principal: "a", Sid: sid}, lease)
}
if len(m.sessions) != 0 {
t.Fatalf("keepalives of sessions without locks left state for %d sessions", len(m.sessions))
}
// A session's floors go with its last lease.
ss := Session{Principal: "a", Sid: 1}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
m.TryLock("k", lk, lease)
m.Renew("k", ss, lease)
if len(m.sessions[ss].floors) != 1 {
t.Fatalf("a renewing session should have one floor, got %v", m.sessions[ss].floors)
}
m.Unlock("k", lk)
if len(m.sessions) != 0 {
t.Fatalf("unlocking the last lock left state: %v", m.sessions)
}
}
func TestManagerManyKeysRenewedOneByOneStayHeldThroughLongRounds(t *testing.T) {
// A mount renews its keys one keepalive at a time; a round over 128 keys at
// 200ms each takes 25.6s, longer than the 15s lease.
m, clock, start := newScopedTestManager()
ss := Session{Principal: "a", Sid: 1}
lease := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
keys := make([]string, 128)
for i := range keys {
keys[i] = fmt.Sprintf("k%03d", i)
m.TryLock(keys[i], lk, lease)
}
now := start
for step := 0; step < 3*len(keys); step++ {
now = now.Add(200 * time.Millisecond)
clock.Set(now)
m.Renew(keys[step%len(keys)], ss, lease)
for _, key := range keys {
if _, held := m.GetLk(key, probe); !held {
t.Fatalf("%s was lost at %v while its session kept renewing", key, now.Sub(start))
}
}
}
}
func TestManagerScopedRenewalUnderAnEarlierExpiringTokenKeepsTheLaterLease(t *testing.T) {
// A request under the old token can land after the replacement renewed the
// key; it must not cut the lease back to the old token's expiry.
m, clock, start := newScopedTestManager()
ss := Session{Principal: "a", Sid: 1}
expiring := Lease{TTL: 15 * time.Second, NotAfter: start.Add(2 * time.Second), Grant: "g"}
replaced := Lease{TTL: 15 * time.Second, NotAfter: start.Add(time.Hour), Grant: "g"}
lk := Range{Start: 0, End: 9, Type: Write, Sid: 1, Owner: 1, Principal: "a"}
probe := Range{Start: 0, End: 9, Type: Write, Sid: 9, Owner: 9, Principal: "probe"}
for name, late := range map[string]func(){
"renew": func() { m.Renew("k", ss, expiring) },
"reassert": func() { m.Reassert("k", ss, []Range{lk}, expiring) },
"trylock": func() { m.TryLock("k", lk, expiring) },
} {
t.Run(name, func(t *testing.T) {
clock.Set(start)
m.ReleaseSession(ss)
m.TryLock("k", lk, replaced)
clock.Set(start.Add(time.Second))
late()
clock.Set(start.Add(3 * time.Second))
if _, held := m.GetLk("k", probe); !held {
t.Fatal("the old token's request cut the replacement's lease back to its own expiry")
}
})
}
}
+10 -10
View File
@@ -20,16 +20,16 @@ func TestReassertRebuildsOnFreshOwner(t *testing.T) {
// Fresh owner (post-restart / new ring owner) knows nothing.
owner := NewManager()
for key, locks := range client.Snapshot() {
if c := owner.Reassert(key, sid, locks); c != nil {
if c := owner.Reassert(key, Session{Sid: sid}, locks, Lease{}); c != nil {
t.Fatalf("unexpected conflict reasserting %s: %+v", key, c)
}
}
// The owner now reports the same conflicts a foreign session would hit.
if _, granted := owner.TryLock("a", Range{Start: 50, End: 60, Type: Write, Sid: 99, Owner: 1}); granted {
if _, granted, _ := owner.TryLock("a", Range{Start: 50, End: 60, Type: Write, Sid: 99, Owner: 1}, Lease{}); granted {
t.Fatal("owner should block a foreign write after rebuild")
}
if _, granted := owner.TryLock("b", Range{Start: 0, End: 0, Type: Read, Sid: 99, Owner: 1, IsFlock: true}); granted {
if _, granted, _ := owner.TryLock("b", Range{Start: 0, End: 0, Type: Read, Sid: 99, Owner: 1, IsFlock: true}, Lease{}); granted {
t.Fatal("owner should block a foreign flock read after rebuild")
}
}
@@ -38,11 +38,11 @@ func TestReassertRebuildsOnFreshOwner(t *testing.T) {
func TestReassertIdempotent(t *testing.T) {
const sid = uint64(1)
m := NewManager()
m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: sid, Owner: 1})
m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: sid, Owner: 1}, Lease{})
before := append([]Range(nil), m.byKey["k"].locks...)
m.Reassert("k", sid, before)
m.Reassert("k", sid, before)
m.Reassert("k", Session{Sid: sid}, before, Lease{})
m.Reassert("k", Session{Sid: sid}, before, Lease{})
if !reflect.DeepEqual(m.byKey["k"].locks, before) {
t.Fatalf("reassert not idempotent:\n got %+v\nwant %+v", m.byKey["k"].locks, before)
@@ -55,9 +55,9 @@ func TestReassertReportsConflict(t *testing.T) {
const mine, other = uint64(1), uint64(2)
m := NewManager()
// Another mount took the lock on this (new) owner during the gap.
m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: other, Owner: 1})
m.TryLock("k", Range{Start: 0, End: 99, Type: Write, Sid: other, Owner: 1}, Lease{})
conflicts := m.Reassert("k", mine, []Range{{Start: 0, End: 99, Type: Write, Sid: mine, Owner: 1}})
conflicts := m.Reassert("k", Session{Sid: mine}, []Range{{Start: 0, End: 99, Type: Write, Sid: mine, Owner: 1}}, Lease{})
if len(conflicts) != 1 {
t.Fatalf("expected 1 conflict, got %d: %+v", len(conflicts), conflicts)
}
@@ -71,8 +71,8 @@ func TestReassertReportsConflict(t *testing.T) {
func TestReassertRenewsLease(t *testing.T) {
const sid = uint64(1)
m := NewManager()
m.Renew(sid)
m.Reassert("k", sid, []Range{{Start: 0, End: 9, Type: Write, Sid: sid, Owner: 1}})
m.Renew("", Session{Sid: sid}, Lease{})
m.Reassert("k", Session{Sid: sid}, []Range{{Start: 0, End: 9, Type: Write, Sid: sid, Owner: 1}}, Lease{})
if reaped := m.ReapExpired(time.Hour); len(reaped) != 0 {
t.Fatalf("freshly re-asserted session should not be reaped: %v", reaped)
+6 -5
View File
@@ -182,14 +182,13 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP
return strings.Compare(a, b)
})
// limit
if limit < int64(len(members)) {
members = members[:limit]
}
var entry *filer.Entry
var count int64
// fetch entry meta
for _, fileName := range members {
if count >= limit {
break
}
path := util.NewFullPath(string(dirPath), fileName)
entry, err = store.FindEntry(ctx, path)
lastFileName = fileName
@@ -200,6 +199,7 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP
err = nil
continue
}
break
} else {
if entry.TtlSec > 0 {
if entry.Attr.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
@@ -209,6 +209,7 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP
}
}
count++
resEachEntryFunc, resEachEntryFuncErr := eachEntryFunc(entry)
if resEachEntryFuncErr != nil {
err = fmt.Errorf("failed to process eachEntryFunc: %w", resEachEntryFuncErr)
@@ -108,6 +108,38 @@ func TestListDirectoryEntriesRemovesOrphanedIndexMembers(t *testing.T) {
}
}
// Orphaned members do not shorten the page: the listing reads on past them
// until it has handed over limit entries.
func TestListDirectoryEntriesFillsThePagePastOrphanedMembers(t *testing.T) {
store, dir := newTestStore(t)
ctx := context.Background()
var want []string
for i := 0; i < 10; i++ {
name := fmt.Sprintf("f%02d", i)
insertTestEntry(t, store, dir.Child(name))
if i == 1 || i == 2 {
if err := store.Client.Del(ctx, string(dir.Child(name))).Err(); err != nil {
t.Fatalf("drop value key: %v", err)
}
continue
}
want = append(want, name)
}
var names []string
lastFileName, err := store.ListDirectoryEntries(ctx, dir, "", false, 5, func(entry *filer.Entry) (bool, error) {
names = append(names, entry.Name())
return true, nil
})
if err != nil {
t.Fatalf("ListDirectoryEntries %s: %v", dir, err)
}
if fmt.Sprint(names) != fmt.Sprint(want[:5]) || lastFileName != want[4] {
t.Fatalf("listed %v up to %q, want %v up to %q", names, lastFileName, want[:5], want[4])
}
}
func TestRemoveOrphanedDirectoryListMemberKeepsRecreatedEntry(t *testing.T) {
store, dir := newTestStore(t)
+37 -32
View File
@@ -209,53 +209,58 @@ func (store *UniversalRedis2Store) ListDirectoryEntries(ctx context.Context, dir
}
}
members, err := store.Client.ZRangeByLex(ctx, dirListKey, &redis.ZRangeBy{
Min: min,
Max: "+",
Offset: 0,
Count: limit,
}).Result()
if err != nil {
return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
}
// fetch entry meta
var entry *filer.Entry
var gets []*redis.StringCmd
for i, fileName := range members {
if i%listFetchBatchSize == 0 {
gets = store.getEntries(ctx, dirPath, members[i:])
}
path := util.NewFullPath(string(dirPath), fileName)
entry, err = decodeEntry(path, gets[i%listFetchBatchSize])
lastFileName = fileName
var count int64
for count < limit {
pageLimit := limit - count
members, err := store.Client.ZRangeByLex(ctx, dirListKey, &redis.ZRangeBy{
Min: min,
Max: "+",
Offset: 0,
Count: pageLimit,
}).Result()
if err != nil {
glog.V(0).InfofCtx(ctx, "list %s : %v", path, err)
if err == filer_pb.ErrNotFound {
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
err = nil
continue
return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
}
// fetch entry meta
var gets []*redis.StringCmd
for i, fileName := range members {
if i%listFetchBatchSize == 0 {
gets = store.getEntries(ctx, dirPath, members[i:])
}
path := util.NewFullPath(string(dirPath), fileName)
entry, err := decodeEntry(path, gets[i%listFetchBatchSize])
lastFileName = fileName
if err != nil {
glog.V(0).InfofCtx(ctx, "list %s : %v", path, err)
if err == filer_pb.ErrNotFound {
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
continue
}
return lastFileName, err
}
break
} else {
if isLogicallyExpired(entry) {
store.deleteExpiredEntry(ctx, dirPath, path, fileName)
continue
}
count++
resEachEntryFunc, resEachEntryFuncErr := eachEntryFunc(entry)
if resEachEntryFuncErr != nil {
err = fmt.Errorf("failed to process eachEntryFunc: %w", resEachEntryFuncErr)
break
return lastFileName, fmt.Errorf("failed to process eachEntryFunc: %w", resEachEntryFuncErr)
}
if !resEachEntryFunc {
break
return lastFileName, nil
}
}
if int64(len(members)) < pageLimit {
break
}
min = "(" + lastFileName
}
return lastFileName, err
return lastFileName, nil
}
// getEntries pipelines the GETs for up to listFetchBatchSize of members. Each
@@ -318,6 +318,42 @@ func TestListDirectoryEntriesAcrossFetchBatches(t *testing.T) {
}
}
// Members dropped as missing or expired do not shorten the page: the listing
// reads on past them until it has handed over limit entries.
func TestListDirectoryEntriesFillsThePagePastDroppedMembers(t *testing.T) {
store, dir := newTestStore(t, "")
ctx := context.Background()
var want []string
for i := 0; i < 10; i++ {
name := fmt.Sprintf("f%02d", i)
switch {
case i == 1:
insertLogicallyExpiredTestEntry(t, store, dir.Child(name))
case i == 2 || i == 3:
insertTestEntry(t, store, dir.Child(name), 0)
if err := store.Client.Del(ctx, store.getKey(string(dir.Child(name)))).Err(); err != nil {
t.Fatalf("drop value key: %v", err)
}
default:
insertTestEntry(t, store, dir.Child(name), 0)
want = append(want, name)
}
}
var names []string
lastFileName, err := store.ListDirectoryEntries(ctx, dir, "", false, 5, func(entry *filer.Entry) (bool, error) {
names = append(names, entry.Name())
return true, nil
})
if err != nil {
t.Fatalf("ListDirectoryEntries %s: %v", dir, err)
}
if fmt.Sprint(names) != fmt.Sprint(want[:5]) || lastFileName != want[4] {
t.Fatalf("listed %v up to %q, want %v up to %q", names, lastFileName, want[:5], want[4])
}
}
func TestListDirectoryEntriesStopsAtUnreadableMember(t *testing.T) {
store, dir := newTestStore(t, "")
ctx := context.Background()
+13 -11
View File
@@ -197,13 +197,6 @@ func enumerate(iter *gorocksdb.Iterator, prefix, lastKey []byte, includeLastKey
i := int64(0)
for iter.Valid() {
if limit > 0 {
i++
if i > limit {
break
}
}
key := iter.Key().Data()
if !bytes.HasPrefix(key, prefix) {
@@ -220,6 +213,13 @@ func enumerate(iter *gorocksdb.Iterator, prefix, lastKey []byte, includeLastKey
continue
}
if limit > 0 {
i++
if i > limit {
break
}
}
ret := fn(key, iter.Value().Data())
if !ret {
@@ -251,7 +251,7 @@ func (store *RocksDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dir
defer ro.Destroy()
ro.SetFillCache(false)
var callbackErr error
var callbackErr, decodeErr error
iter := store.db.NewIterator(ro)
defer iter.Close()
err = enumerate(iter, directoryPrefix, lastFileStart, includeStartFile, limit, startFileName, func(key, value []byte) bool {
@@ -265,9 +265,8 @@ func (store *RocksDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dir
lastFileName = fileName
// println("list", entry.FullPath, "chunks", len(entry.GetChunks()))
if decodeErr := entry.DecodeAttributesAndChunks(value); decodeErr != nil {
err = decodeErr
glog.V(0).InfofCtx(ctx, "list %s : %v", entry.FullPath, err)
if decodeErr = entry.DecodeAttributesAndChunks(value); decodeErr != nil {
glog.V(0).InfofCtx(ctx, "list %s : %v", entry.FullPath, decodeErr)
return false
}
@@ -292,6 +291,9 @@ func (store *RocksDBStore) ListDirectoryPrefixedEntries(ctx context.Context, dir
)
}
if decodeErr != nil {
err = decodeErr
}
if err != nil {
return lastFileName, fmt.Errorf("prefix list %s : %v", dirPath, err)
}
+56 -3
View File
@@ -16,7 +16,7 @@ import (
)
func TestCreateAndFind(t *testing.T) {
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", 0, "", "", "", nil)
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
dir := t.TempDir()
store := &RocksDBStore{}
store.initialize(dir)
@@ -69,7 +69,7 @@ func TestCreateAndFind(t *testing.T) {
}
func TestEmptyRoot(t *testing.T) {
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", 0, "", "", "", nil)
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
dir := t.TempDir()
store := &RocksDBStore{}
store.initialize(dir)
@@ -91,7 +91,7 @@ func TestEmptyRoot(t *testing.T) {
}
func BenchmarkInsertEntry(b *testing.B) {
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", 0, "", "", "", nil)
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
dir := b.TempDir()
store := &RocksDBStore{}
store.initialize(dir)
@@ -183,3 +183,56 @@ func TestListDirectoryWithPrefix(t *testing.T) {
}
}
}
// A page that starts after a name it skips still holds limit entries.
func TestListDirectoryEntriesFillsThePageAfterTheStartName(t *testing.T) {
store := &RocksDBStore{}
store.initialize(t.TempDir())
defer store.Shutdown()
ctx := context.Background()
for i := 0; i < 10; i++ {
entry := &filer.Entry{FullPath: util.FullPath(fmt.Sprintf("/dir/f%02d", i)), Attr: filer.Attr{Mode: 0644}}
if err := store.InsertEntry(ctx, entry); err != nil {
t.Fatalf("InsertEntry: %v", err)
}
}
var names []string
last, err := store.ListDirectoryEntries(ctx, "/dir", "f02", false, 5, func(entry *filer.Entry) (bool, error) {
names = append(names, entry.Name())
return true, nil
})
if err != nil {
t.Fatalf("ListDirectoryEntries: %v", err)
}
if fmt.Sprint(names) != "[f03 f04 f05 f06 f07]" || last != "f07" {
t.Fatalf("listed %v up to %q, want [f03 f04 f05 f06 f07] up to f07", names, last)
}
}
func TestListDirectoryEntriesFailsOnAnUndecodableEntry(t *testing.T) {
store := &RocksDBStore{}
store.initialize(t.TempDir())
defer store.Shutdown()
ctx := context.Background()
for i := 0; i < 4; i++ {
entry := &filer.Entry{FullPath: util.FullPath(fmt.Sprintf("/dir/f%02d", i)), Attr: filer.Attr{Mode: 0644}}
if err := store.InsertEntry(ctx, entry); err != nil {
t.Fatalf("InsertEntry: %v", err)
}
}
if err := store.db.Put(store.wo, genKey("/dir", "f01"), []byte{0xff, 0xff}); err != nil {
t.Fatalf("Put: %v", err)
}
var names []string
_, err := store.ListDirectoryEntries(ctx, "/dir", "", false, 10, func(entry *filer.Entry) (bool, error) {
names = append(names, entry.Name())
return true, nil
})
if err == nil {
t.Fatalf("listed %v without an error, want the decode error", names)
}
}
+5 -10
View File
@@ -269,34 +269,29 @@ func (store *TarantoolStore) ListDirectoryEntries(ctx context.Context, dirPath w
rows, ok := results[0].([]interface{})
if !ok {
glog.ErrorfCtx(ctx, "Can't convert results[0] to list")
return
return lastFileName, fmt.Errorf("list %s: reply is %T, not a list", dirPath, results[0])
}
for _, result := range rows {
row, ok := result.([]interface{})
if !ok {
glog.ErrorfCtx(ctx, "Can't convert result to list")
return
return lastFileName, fmt.Errorf("list %s: row is %T, not a list", dirPath, result)
}
if len(row) < 5 {
glog.ErrorfCtx(ctx, "Length of result is less than needed: %v", len(row))
return
return lastFileName, fmt.Errorf("list %s: row has %d fields, want 5", dirPath, len(row))
}
nameRaw := row[2]
name, ok := nameRaw.(string)
if !ok {
glog.ErrorfCtx(ctx, "Can't convert name field to string. Actual type: %v, value: %v", reflect.TypeOf(nameRaw), nameRaw)
return
return lastFileName, fmt.Errorf("list %s: name field is %v, not a string", dirPath, reflect.TypeOf(nameRaw))
}
dataRaw := row[4]
data, ok := dataRaw.(string)
if !ok {
glog.ErrorfCtx(ctx, "Can't convert data field to string. Actual type: %v, value: %v", reflect.TypeOf(dataRaw), dataRaw)
return
return lastFileName, fmt.Errorf("list %s: data field of %s is %v, not a string", dirPath, name, reflect.TypeOf(dataRaw))
}
entry := &filer.Entry{
+26 -5
View File
@@ -111,8 +111,8 @@ func (store *TikvStore) FindEntry(ctx context.Context, path util.FullPath) (*fil
return nil, err
}
var value []byte = nil
err = txn.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
val, err := txn.Get(ctx, key)
err = txn.RunInTxn(ctx, func(*txnkv.KVTxn) error {
val, err := txn.get(ctx, key)
if err == nil {
value = val
}
@@ -278,13 +278,15 @@ func (store *TikvStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPat
}
fileName := store.getNameFromKey(key)
if fileName == "" {
if err := iter.Next(); err != nil {
if nextErr := iter.Next(); nextErr != nil {
err = nextErr
break
}
continue
}
if fileName == startFileName && !includeStartFile {
if err := iter.Next(); err != nil {
if nextErr := iter.Next(); nextErr != nil {
err = nextErr
break
}
continue
@@ -313,7 +315,8 @@ func (store *TikvStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPat
if deleteErr := store.deleteExpiredEntry(ctx, entry.FullPath); deleteErr != nil {
glog.V(0).InfofCtx(ctx, "failed to delete expired entry %s: %v", entry.FullPath, deleteErr)
}
if err := iter.Next(); err != nil {
if nextErr := iter.Next(); nextErr != nil {
err = nextErr
break
}
continue
@@ -431,6 +434,24 @@ func (w *TxnWrapper) RunInTxn(ctx context.Context, f func(txn *txnkv.KVTxn) erro
return err
}
// get reads key in the transaction. In a caller's transaction it reads a batch
// of one: the client keeps batch-get answers, misses included, with the
// transaction's snapshot, so a later read of the key does not ask TiKV again.
func (w *TxnWrapper) get(ctx context.Context, key []byte) ([]byte, error) {
if !w.inContext {
return w.KVTxn.Get(ctx, key)
}
values, err := w.KVTxn.BatchGet(ctx, [][]byte{key})
if err != nil {
return nil, err
}
value, found := values[string(key)]
if !found {
return nil, tikverr.ErrNotExist
}
return value, nil
}
func (store *TikvStore) getTxn(ctx context.Context) (*TxnWrapper, error) {
if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
return &TxnWrapper{tx, true}, nil
+19 -2
View File
@@ -21,8 +21,8 @@ func (store *TikvStore) KvGet(ctx context.Context, key []byte) ([]byte, error) {
return nil, err
}
var data []byte = nil
err = tw.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
val, err := txn.Get(ctx, key)
err = tw.RunInTxn(ctx, func(*txnkv.KVTxn) error {
val, err := tw.get(ctx, key)
if err == nil {
data = val
}
@@ -34,6 +34,23 @@ func (store *TikvStore) KvGet(ctx context.Context, key []byte) ([]byte, error) {
return data, err
}
// KvBatchGet reads the keys with one request for each region they are in.
func (store *TikvStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
tw, err := store.getTxn(ctx)
if err != nil {
return nil, err
}
var values map[string][]byte
err = tw.RunInTxn(ctx, func(txn *txnkv.KVTxn) error {
var err error
values, err = txn.BatchGet(ctx, keys)
return err
})
return values, err
}
var _ filer.KvBatchReader = (*TikvStore)(nil)
func (store *TikvStore) KvDelete(ctx context.Context, key []byte) error {
return store.runTxn(ctx, func(txn *txnkv.KVTxn) error {
return txn.Delete(key)
+174
View File
@@ -0,0 +1,174 @@
//go:build tikv
package tikv
import (
"context"
"fmt"
"reflect"
"sync"
"testing"
"time"
"github.com/tikv/client-go/v2/testutils"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/txnkv"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// kvRequests counts the requests the store sends to TiKV, by kind.
type kvRequests struct {
tikv.Client
mu sync.Mutex
sent map[tikvrpc.CmdType]int
}
func (r *kvRequests) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) {
r.mu.Lock()
r.sent[req.Type]++
r.mu.Unlock()
return r.Client.SendRequest(ctx, addr, req, timeout)
}
// during runs f and returns the gets and batch gets it sent.
func (r *kvRequests) during(f func()) (gets, batchGets int) {
r.mu.Lock()
r.sent = map[tikvrpc.CmdType]int{}
r.mu.Unlock()
f()
r.mu.Lock()
defer r.mu.Unlock()
return r.sent[tikvrpc.CmdGet], r.sent[tikvrpc.CmdBatchGet]
}
// newStoreOnMockTiKV is a store on the client library's in-process TiKV.
func newStoreOnMockTiKV(t *testing.T) (*TikvStore, *kvRequests) {
t.Helper()
client, cluster, pdClient, err := testutils.NewMockTiKV("", nil)
if err != nil {
t.Fatalf("mock tikv: %v", err)
}
testutils.BootstrapWithSingleStore(cluster)
requests := &kvRequests{sent: map[tikvrpc.CmdType]int{}}
kvStore, err := tikv.NewTestTiKVStore(client, pdClient, func(c tikv.Client) tikv.Client {
requests.Client = c
return requests
}, nil, 0)
if err != nil {
t.Fatalf("mock tikv store: %v", err)
}
store := &TikvStore{client: &txnkv.Client{KVStore: kvStore}}
t.Cleanup(store.Shutdown)
return store, requests
}
func TestKvBatchGetReadsItsKeysInOneRequest(t *testing.T) {
store, requests := newStoreOnMockTiKV(t)
ctx := context.Background()
for _, key := range []string{"a", "b", "c"} {
if err := store.KvPut(ctx, []byte(key), []byte("value of "+key)); err != nil {
t.Fatalf("put %s: %v", key, err)
}
}
var values map[string][]byte
gets, batchGets := requests.during(func() {
var err error
if values, err = store.KvBatchGet(ctx, [][]byte{[]byte("a"), []byte("missing"), []byte("c")}); err != nil {
t.Fatalf("batch get: %v", err)
}
})
want := map[string][]byte{"a": []byte("value of a"), "c": []byte("value of c")}
if !reflect.DeepEqual(values, want) {
t.Errorf("batch get = %q, want %q: the keys held, and no others", values, want)
}
if gets != 0 || batchGets != 1 {
t.Errorf("sent %d gets and %d batch gets, want one batch get", gets, batchGets)
}
// inside a transaction it reads what the transaction wrote
txCtx, err := store.BeginTransaction(ctx)
if err != nil {
t.Fatalf("begin: %v", err)
}
defer store.RollbackTransaction(txCtx)
if err := store.KvPut(txCtx, []byte("d"), []byte("value of d")); err != nil {
t.Fatalf("put in transaction: %v", err)
}
if err := store.KvDelete(txCtx, []byte("a")); err != nil {
t.Fatalf("delete in transaction: %v", err)
}
values, err = store.KvBatchGet(txCtx, [][]byte{[]byte("a"), []byte("c"), []byte("d")})
if err != nil {
t.Fatalf("batch get in transaction: %v", err)
}
want = map[string][]byte{"c": []byte("value of c"), "d": []byte("value of d")}
if !reflect.DeepEqual(values, want) {
t.Errorf("batch get in transaction = %q, want %q", values, want)
}
}
// oneByOne hides the store's batch read, which leaves a listing to read each
// hard link record as its entry arrives.
type oneByOne struct{ filer.FilerStore }
// A page of hard-linked names costs one request for their records, where it
// cost one for each name.
func TestListingReadsTheHardLinkRecordsOfAPageInOneRequest(t *testing.T) {
store, requests := newStoreOnMockTiKV(t)
ctx := context.Background()
const names = 200
writer := filer.NewFilerStoreWrapper(store)
for i := 0; i < names; i++ {
entry := &filer.Entry{
FullPath: util.FullPath(fmt.Sprintf("/d/n%03d", i)),
Attr: filer.Attr{Mode: 0644, Mtime: time.Unix(1700000000, 0), FileSize: uint64(1 + i)},
HardLinkId: filer.HardLinkId(fmt.Sprintf("link-%03d-01234567", i)),
HardLinkCounter: 2,
Chunks: []*filer_pb.FileChunk{{FileId: fmt.Sprintf("3,%04x", i), Size: uint64(1 + i)}},
}
if err := writer.InsertEntry(ctx, entry); err != nil {
t.Fatalf("insert %s: %v", entry.FullPath, err)
}
}
type seen struct {
name string
size uint64
links int32
chunk string
}
list := func(listing filer.FilerStore) (entries []seen, gets, batchGets int) {
gets, batchGets = requests.during(func() {
_, err := filer.NewFilerStoreWrapper(listing).ListDirectoryEntries(ctx, "/d", "", false, 1024, func(entry *filer.Entry) (bool, error) {
entries = append(entries, seen{entry.Name(), entry.FileSize, entry.HardLinkCounter, entry.GetChunks()[0].FileId})
return true, nil
})
if err != nil {
t.Fatalf("list: %v", err)
}
})
return
}
want, gets, batchGets := list(oneByOne{store})
if len(want) != names || want[7] != (seen{"n007", 8, 2, "3,0007"}) {
t.Fatalf("listed %d entries, the eighth %+v", len(want), want[7])
}
if gets != names || batchGets != 0 {
t.Errorf("read one at a time, the records took %d gets and %d batch gets, want %d gets", gets, batchGets, names)
}
got, gets, batchGets := list(store)
if !reflect.DeepEqual(got, want) {
t.Errorf("read together, the listing differs from the one read one at a time")
}
if gets != 0 || batchGets != 1 {
t.Errorf("read together, the records took %d gets and %d batch gets, want one batch get", gets, batchGets)
}
}
+210
View File
@@ -0,0 +1,210 @@
//go:build tikv
package tikv
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/tikv/client-go/v2/testutils"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/txnkv"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// readCountingClient counts the reads of keys the store sends to TiKV.
type readCountingClient struct {
tikv.Client
reads atomic.Int64
}
func (c *readCountingClient) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) {
if req.Type == tikvrpc.CmdGet || req.Type == tikvrpc.CmdBatchGet {
c.reads.Add(1)
}
return c.Client.SendRequest(ctx, addr, req, timeout)
}
// newReadCountingStore is a store on the client library's in-process TiKV.
func newReadCountingStore(t *testing.T) (*TikvStore, *readCountingClient) {
t.Helper()
client, cluster, pdClient, err := testutils.NewMockTiKV("", nil)
if err != nil {
t.Fatalf("mock tikv: %v", err)
}
testutils.BootstrapWithSingleStore(cluster)
counting := &readCountingClient{}
kvStore, err := tikv.NewTestTiKVStore(client, pdClient, func(c tikv.Client) tikv.Client {
counting.Client = c
return counting
}, nil, 0)
if err != nil {
t.Fatalf("mock tikv store: %v", err)
}
store := &TikvStore{client: &txnkv.Client{KVStore: kvStore}}
t.Cleanup(store.Shutdown)
return store, counting
}
func testFile(path string, size uint64) *filer.Entry {
return &filer.Entry{
FullPath: util.FullPath(path),
Attr: filer.Attr{Mode: 0644, Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0), FileSize: size},
}
}
// during runs f and returns the reads of keys it sent to TiKV.
func (c *readCountingClient) during(f func()) int64 {
before := c.reads.Load()
f()
return c.reads.Load() - before
}
// A rename looks its source up when it starts and again to delete it, and its
// target before the create and in it, all in one transaction. Each of those
// was a request to TiKV for a key the transaction had read already.
func TestTransactionReadsAKeyFromTiKVOnce(t *testing.T) {
store, client := newReadCountingStore(t)
ctx := context.Background()
if err := store.InsertEntry(ctx, testFile("/d/stored", 7)); err != nil {
t.Fatalf("insert: %v", err)
}
if err := store.KvPut(ctx, []byte("stored-key"), []byte("value")); err != nil {
t.Fatalf("kv put: %v", err)
}
txCtx, err := store.BeginTransaction(ctx)
if err != nil {
t.Fatalf("begin: %v", err)
}
defer store.RollbackTransaction(txCtx)
if sent := client.during(func() {
for i := 0; i < 3; i++ {
entry, err := store.FindEntry(txCtx, "/d/stored")
if err != nil || entry.FileSize != 7 {
t.Fatalf("find %d: %+v, %v", i, entry, err)
}
}
}); sent != 1 {
t.Errorf("three lookups of one entry sent %d reads to TiKV, want 1", sent)
}
// a path that is not there is not asked for again either
if sent := client.during(func() {
for i := 0; i < 3; i++ {
if _, err := store.FindEntry(txCtx, "/d/missing"); err != filer_pb.ErrNotFound {
t.Fatalf("find missing %d: %v, want not found", i, err)
}
}
}); sent != 1 {
t.Errorf("three lookups of a missing path sent %d reads to TiKV, want 1", sent)
}
if sent := client.during(func() {
for i := 0; i < 3; i++ {
if value, err := store.KvGet(txCtx, []byte("stored-key")); err != nil || string(value) != "value" {
t.Fatalf("kv get %d: %q, %v", i, value, err)
}
if _, err := store.KvGet(txCtx, []byte("missing-key")); !errors.Is(err, filer.ErrKvNotFound) {
t.Fatalf("kv get missing %d: %v, want not found", i, err)
}
}
}); sent != 2 {
t.Errorf("three reads each of two keys sent %d reads to TiKV, want 2", sent)
}
}
// What the transaction reads is what it read before the change: the store as
// it was when the transaction began, under its own writes.
func TestTransactionReadsItsSnapshotUnderItsOwnWrites(t *testing.T) {
store, _ := newReadCountingStore(t)
ctx := context.Background()
for _, path := range []string{"/d/kept", "/d/rewritten", "/d/deleted"} {
if err := store.InsertEntry(ctx, testFile(path, 1)); err != nil {
t.Fatalf("insert %s: %v", path, err)
}
}
txCtx, err := store.BeginTransaction(ctx)
if err != nil {
t.Fatalf("begin: %v", err)
}
defer store.RollbackTransaction(txCtx)
sizeOf := func(readCtx context.Context, path string) (size uint64, found bool) {
t.Helper()
entry, err := store.FindEntry(readCtx, util.FullPath(path))
if err == filer_pb.ErrNotFound {
return 0, false
}
if err != nil {
t.Fatalf("find %s: %v", path, err)
}
return entry.FileSize, true
}
for _, path := range []string{"/d/kept", "/d/rewritten", "/d/deleted", "/d/created"} {
sizeOf(txCtx, path)
}
// the transaction's own writes show in its next read
if err := store.UpdateEntry(txCtx, testFile("/d/rewritten", 2)); err != nil {
t.Fatalf("update: %v", err)
}
if err := store.DeleteEntry(txCtx, "/d/deleted"); err != nil {
t.Fatalf("delete: %v", err)
}
if err := store.InsertEntry(txCtx, testFile("/d/created", 3)); err != nil {
t.Fatalf("insert: %v", err)
}
if size, found := sizeOf(txCtx, "/d/rewritten"); !found || size != 2 {
t.Errorf("an entry the transaction rewrote reads size %d found %v, want its write", size, found)
}
if _, found := sizeOf(txCtx, "/d/deleted"); found {
t.Errorf("an entry the transaction deleted is still read")
}
if size, found := sizeOf(txCtx, "/d/created"); !found || size != 3 {
t.Errorf("an entry the transaction created reads size %d found %v, want its write", size, found)
}
// another writer's commit shows to a new read, and not to the transaction
if err := store.UpdateEntry(ctx, testFile("/d/kept", 9)); err != nil {
t.Fatalf("update by another writer: %v", err)
}
if size, _ := sizeOf(ctx, "/d/kept"); size != 9 {
t.Errorf("a read outside the transaction reads size %d, want the other writer's 9", size)
}
if size, _ := sizeOf(txCtx, "/d/kept"); size != 1 {
t.Errorf("the transaction reads size %d, want the 1 it began with", size)
}
}
// A read outside a caller's transaction is a transaction of its own, and
// reads what is stored by then.
func TestReadsOutsideATransactionEachAskTiKV(t *testing.T) {
store, client := newReadCountingStore(t)
ctx := context.Background()
if err := store.InsertEntry(ctx, testFile("/d/f", 1)); err != nil {
t.Fatalf("insert: %v", err)
}
if sent := client.during(func() {
for size := uint64(1); size <= 3; size++ {
entry, err := store.FindEntry(ctx, "/d/f")
if err != nil || entry.FileSize != size {
t.Fatalf("find: %+v, %v, want size %d", entry, err, size)
}
if err := store.UpdateEntry(ctx, testFile("/d/f", size+1)); err != nil {
t.Fatalf("update: %v", err)
}
}
}); sent != 3 {
t.Errorf("three lookups outside a transaction sent %d reads to TiKV, want 3", sent)
}
}
+86 -11
View File
@@ -88,6 +88,7 @@ func TestContentFlushPreservesPeerChunks(t *testing.T) {
for _, name := range []string{"single-writer", "peer-append", "replaced", "deleted", "deferred-create", "deferred-create-race"} {
t.Run(name, func(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
observed := flushConditionEntry(1)
live := flushConditionEntry(1, 3)
live.Chunks[1].Offset = 2
@@ -252,6 +253,7 @@ func chunkFileKeys(e *filer_pb.Entry) (keys []uint64) {
// overwrite a peer's append either.
func TestPeriodicMetadataFlushPreservesPeerChunks(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
current := flushConditionEntry(1, 2)
fake := &contentFlushConditionFiler{entry: proto.Clone(current).(*filer_pb.Entry)}
startFakeFiler(t, wfs, fake)
@@ -285,6 +287,7 @@ func TestPeriodicMetadataFlushPreservesPeerChunks(t *testing.T) {
// the peer's chunk is not dropped by the next publication from this handle.
func TestContentFlushMergeThenRepeat(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
fake := &contentFlushConditionFiler{entry: flushConditionEntry(1, 2)}
startFakeFiler(t, wfs, fake)
observed := flushConditionEntry(1)
@@ -318,8 +321,8 @@ func TestContentFlushMergeThenRepeat(t *testing.T) {
}
// The merge keeps a peer's attribute and extended changes the handle did not
// make, applies the ones it did, and lets a local truncation clip the peer's
// chunks past the new end.
// make, applies the ones it did, and lets a local truncation clip the base's
// chunks past the new end, but not the chunks a peer wrote since.
func TestMergeContentEntry(t *testing.T) {
base := flushConditionEntry(1, 2)
base.Extended = map[string][]byte{"user.a": []byte("1"), "user.b": []byte("1")}
@@ -352,25 +355,54 @@ func TestMergeContentEntry(t *testing.T) {
truncated := proto.Clone(base).(*filer_pb.Entry)
truncated.Chunks = truncated.Chunks[:1]
truncated.Attributes.FileSize = 1
merged, ok = mergeContentEntry(stored, base, truncated, truncated, -1, false)
if _, ok := mergeContentEntry(stored, base, truncated, truncated, -1, false); ok {
t.Fatal("a stale truncate dropped the chunk a peer wrote")
}
peerChmod := proto.Clone(base).(*filer_pb.Entry)
peerChmod.Attributes.FileMode = 0600
merged, ok = mergeContentEntry(peerChmod, base, truncated, truncated, -1, false)
if !ok {
t.Fatal("truncation not merged")
}
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1}) || merged.Attributes.FileSize != 1 {
t.Fatalf("truncated merge kept %v, size %d", got, merged.Attributes.FileSize)
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1}) || merged.Attributes.FileSize != 1 || merged.Attributes.FileMode != 0600 {
t.Fatalf("truncated merge kept %v, size %d, mode %o", got, merged.Attributes.FileSize, merged.Attributes.FileMode)
}
// Truncated to 1, then written at 7: the peer chunk at 2 stays cut.
// Truncated to 1, then written at 7: the base chunk at 1 stays cut, and a
// peer chunk inside the truncated size stays.
regrown := proto.Clone(truncated).(*filer_pb.Entry)
regrown.Chunks = append(regrown.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 7, Cookie: 1}, Offset: 7, Size: 1, ModifiedTsNs: 7})
regrown.Attributes.FileSize = 8
merged, ok = mergeContentEntry(stored, base, regrown, regrown, 1, false)
peerInside := proto.Clone(base).(*filer_pb.Entry)
peerInside.Chunks = append(peerInside.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 0, Size: 1, ModifiedTsNs: 9})
merged, ok = mergeContentEntry(peerInside, base, regrown, regrown, 1, false)
if !ok {
t.Fatal("truncate then write not merged")
}
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1, 7}) || merged.Attributes.FileSize != 8 {
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1, 9, 7}) || merged.Attributes.FileSize != 8 {
t.Fatalf("truncate then write kept %v, size %d", got, merged.Attributes.FileSize)
}
if _, ok := mergeContentEntry(stored, base, regrown, regrown, 1, false); ok {
t.Fatal("a stale truncate cut the chunk a peer wrote")
}
// The handle's own commit whose answer was lost is no peer write.
committed := proto.Clone(base).(*filer_pb.Entry)
committed.Chunks = append(committed.Chunks, regrown.Chunks[1])
merged, ok = mergeContentEntry(committed, base, regrown, regrown, 1, false)
if !ok {
t.Fatal("refused the handle's own committed chunk")
}
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1, 7}) || merged.Attributes.FileSize != 8 {
t.Fatalf("replayed commit kept %v, size %d", got, merged.Attributes.FileSize)
}
grown := proto.Clone(base).(*filer_pb.Entry)
grown.Chunks = append(grown.Chunks, regrown.Chunks[1])
grown.Attributes.FileSize = 8
committed.Attributes.FileSize = 8
merged, ok = mergeContentEntry(committed, base, grown, grown, -1, false)
if got := chunkFileKeys(merged); !ok || !slices.Equal(got, []uint64{1, 2, 7}) {
t.Fatalf("replayed commit without a truncate kept %v", got)
}
// Shortening a manifest reference leaves its members whole.
peerManifest := proto.Clone(base).(*filer_pb.Entry)
@@ -413,11 +445,19 @@ func TestMergeContentEntry(t *testing.T) {
unstamped.Chunks[0].Size, unstamped.Chunks[0].ModifiedTsNs = 3, 0
shortened := proto.Clone(unstamped).(*filer_pb.Entry)
shortened.Chunks[0].Size, shortened.Attributes.FileSize = 2, 2
peerAppend := proto.Clone(unstamped).(*filer_pb.Entry)
peerAppend.Chunks = append(peerAppend.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 3, Size: 1, ModifiedTsNs: 9})
if _, ok := mergeContentEntry(peerAppend, unstamped, shortened, shortened, 2, false); !ok {
peerWrite := proto.Clone(unstamped).(*filer_pb.Entry)
peerWrite.Chunks = append(peerWrite.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 1, Size: 1, ModifiedTsNs: 9})
if _, ok := mergeContentEntry(peerWrite, unstamped, shortened, shortened, 2, false); !ok {
t.Fatal("refused a truncate that shortened an unstamped base chunk")
}
// A base chunk the peer shortened holds no peer data: the truncate cuts it.
peerShortened := proto.Clone(unstamped).(*filer_pb.Entry)
peerShortened.Chunks[0].Size, peerShortened.Attributes.FileSize = 2, 2
cut := proto.Clone(unstamped).(*filer_pb.Entry)
cut.Chunks[0].Size, cut.Attributes.FileSize = 1, 1
if merged, ok := mergeContentEntry(peerShortened, unstamped, cut, cut, 1, false); !ok || merged.Attributes.FileSize != 1 {
t.Fatal("refused a truncate over a base chunk the peer shortened")
}
noInode := proto.Clone(base).(*filer_pb.Entry)
noInode.Attributes.Inode, noInode.Attributes.Crtime = 0, 5
@@ -444,6 +484,41 @@ func TestMergeContentEntry(t *testing.T) {
}
}
// A delayed flush keeps the later of two moved times, and a time only the
// handle moved, even back.
func TestMergeContentEntryKeepsLaterTime(t *testing.T) {
base := flushConditionEntry(1)
base.Attributes.Mtime, base.Attributes.Ctime = 100, 100
stored := proto.Clone(base).(*filer_pb.Entry)
stored.Chunks = append(stored.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 1, Size: 1, ModifiedTsNs: 9})
stored.Attributes.Mtime, stored.Attributes.MtimeNs = 300, 5
stored.Attributes.Ctime, stored.Attributes.CtimeNs = 300, 5
local := proto.Clone(base).(*filer_pb.Entry)
local.Chunks = append(local.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 7, Cookie: 1}, Offset: 2, Size: 1, ModifiedTsNs: 7})
local.Attributes.Mtime, local.Attributes.MtimeNs = 300, 1
local.Attributes.Ctime, local.Attributes.CtimeNs = 200, 0
merged, ok := mergeContentEntry(stored, base, local, local, -1, false)
if !ok {
t.Fatal("not merged")
}
if a := merged.Attributes; a.Mtime != 300 || a.MtimeNs != 5 || a.Ctime != 300 || a.CtimeNs != 5 {
t.Fatalf("delayed flush moved times back: mtime %d.%d ctime %d.%d", a.Mtime, a.MtimeNs, a.Ctime, a.CtimeNs)
}
local.Attributes.Mtime, local.Attributes.MtimeNs = 400, 0
if merged, _ = mergeContentEntry(stored, base, local, local, -1, false); merged.Attributes.Mtime != 400 || merged.Attributes.MtimeNs != 0 {
t.Fatalf("later local mtime not kept: %d.%d", merged.Attributes.Mtime, merged.Attributes.MtimeNs)
}
peerChmod := proto.Clone(base).(*filer_pb.Entry)
peerChmod.Attributes.FileMode = 0600
local.Attributes.Mtime, local.Attributes.MtimeNs = 50, 0
if merged, _ = mergeContentEntry(peerChmod, base, local, local, -1, false); merged.Attributes.Mtime != 50 {
t.Fatalf("mtime only the handle set: %d", merged.Attributes.Mtime)
}
}
// A miss on state no peer changed is republished once against the stored
// entry: a rename while open, or a filer uid the local id mapping cannot
// reproduce (newInvalidateTestWFS maps local 1000 to filer 2000).
+14 -3
View File
@@ -15,7 +15,7 @@ import (
)
// These caller controls measure published bytes; none imports #12608 internals.
func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
func masterAssertPeerMergeOutcome(t *testing.T, periodic, merge bool) {
for _, scenario := range []string{"peer-append", "peer-replaced-file", "peer-truncate"} {
t.Run(scenario, func(t *testing.T) {
base := attributeAppendEntry(1)
@@ -46,6 +46,7 @@ func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
original := proto.Clone(stored).(*filer_pb.Entry)
peer := &g6ConditionalPeer{entry: proto.Clone(stored).(*filer_pb.Entry), blobs: blobs}
w := newInvalidateTestWFS(t)
w.option.ConcurrentWriteMerge = merge
startFakeFiler(t, w, peer)
w.mapPbIdFromFilerToLocal(base)
w.mapPbIdFromFilerToLocal(pending)
@@ -67,6 +68,12 @@ func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
defer peer.mu.Unlock()
actual := g6StoredBytes(t, peer)
t.Logf("scenario=%s status=%v size=%d rejected=%d gap[256,512)-zero=%v", scenario, code, len(actual), peer.rejected, len(actual) >= 512 && bytes.Equal(actual[256:512], make([]byte, 256)))
if !merge {
if code != fuse.EIO || !g6EntryEqual(peer.entry, original) {
t.Fatal("a peer's chunk change must fail the flush without merging")
}
return
}
if scenario == "peer-replaced-file" {
if code != fuse.EIO || !g6EntryEqual(peer.entry, original) || !bytes.Equal(actual, bytes.Repeat([]byte{'R'}, 256)) {
t.Fatal("replacement must be refused without publishing stale content")
@@ -208,5 +215,9 @@ func TestMasterConflictThenAppendCannotPublishGap(t *testing.T) {
}
}
func TestContentGapPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, false) }
func TestContentGapPeriodicPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, true) }
func TestContentGapPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, false, true) }
func TestContentGapPeriodicPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, true, true) }
func TestContentGapPeerConflict(t *testing.T) { masterAssertPeerMergeOutcome(t, false, false) }
func TestContentGapPeriodicPeerConflict(t *testing.T) {
masterAssertPeerMergeOutcome(t, true, false)
}
+43
View File
@@ -598,3 +598,46 @@ func TestLostAnswerToOwnShrinkingFlushIsNotAConflict(t *testing.T) {
t.Fatal("lost answer was not exercised or the overwrite did not land")
}
}
type g6LostLookupFiler struct {
*g6LostAnswerFiler
lookupFails atomic.Bool
}
func (s *g6LostLookupFiler) LookupDirectoryEntry(ctx context.Context, r *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
if s.lookupFails.Load() {
return nil, status.Error(codes.Internal, "lookup failed")
}
return s.g6LostAnswerFiler.LookupDirectoryEntry(ctx, r)
}
func TestTruncateAfterLostTruncateFlushIsNotAConflict(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 2200)
fake := &g6LostLookupFiler{g6LostAnswerFiler: &g6LostAnswerFiler{g6ConditionalPeer: peer}}
fake.lookupFails.Store(true)
startFakeFiler(t, w, fake)
truncate := func(size uint64) fuse.Status {
return w.SetAttr(nil, &fuse.SetAttrIn{SetAttrInCommon: fuse.SetAttrInCommon{InHeader: fuse.InHeader{NodeId: 42}, Valid: fuse.FATTR_SIZE | fuse.FATTR_FH, Fh: handle, Size: size}}, &fuse.AttrOut{})
}
if code := truncate(200); code == fuse.OK {
t.Fatal("truncate whose answer and lookup were lost reported success")
}
peer.mu.Lock()
committed := peer.entry.Attributes.FileSize
peer.mu.Unlock()
if !fake.lost.Load() || committed != 200 {
t.Fatal("lost answer was not exercised", committed)
}
fake.lookupFails.Store(false)
if code := truncate(100); code != fuse.OK {
t.Fatal("own committed truncate reported as a conflict", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
chunks := peer.entry.Chunks
if peer.entry.Attributes.FileSize != 100 || len(chunks) != 1 || chunks[0].Fid.FileKey != 1 || chunks[0].Offset != 0 || chunks[0].Size != 100 {
t.Fatal("second truncate did not land", peer.entry.Attributes.FileSize, chunks)
}
}
+104 -4
View File
@@ -230,6 +230,7 @@ func (fh *FileHandle) rebaseEntry(merged, sent *filer_pb.Entry) {
inSent[contentChunkKey(c)] = true
}
merged = proto.Clone(merged).(*filer_pb.Entry)
fh.wfs.readAuth.Track(fh.FullPath(), merged.Chunks)
fh.UpdateEntry(func(e *filer_pb.Entry) {
chunks := merged.Chunks
for _, c := range e.Chunks {
@@ -256,6 +257,7 @@ func (fh *FileHandle) rebaseEntry(merged, sent *filer_pb.Entry) {
// naming them would send reads to needles a vacuum removes. Chunks attached
// after snapshot was taken were not part of the merge and stay.
func (fh *FileHandle) installRewrittenChunks(snapshot, rewritten []*filer_pb.FileChunk) {
fh.wfs.readAuth.Track(fh.FullPath(), rewritten)
fh.UpdateEntry(func(e *filer_pb.Entry) {
chunks := withChunksAttachedSince(snapshot, rewritten, e.Chunks)
e.Chunks = chunks
@@ -267,6 +269,26 @@ func (fh *FileHandle) installRewrittenChunks(snapshot, rewritten []*filer_pb.Fil
})
}
// installStoredChunks gives the handle the chunks an acknowledged create
// stored when they differ from those sent held (the filer folds a flat list):
// they are its base, and a later merge takes the chunks the handle holds that
// its base lacks for writes of its own.
func (fh *FileHandle) installStoredChunks(stored, sent *filer_pb.Entry) {
count := make(map[string]int, len(sent.GetChunks()))
for _, c := range sent.GetChunks() {
count[contentChunkKey(c)]++
}
same := len(stored.GetChunks()) == len(sent.GetChunks())
for _, c := range stored.GetChunks() {
key := contentChunkKey(c)
same = same && count[key] > 0
count[key]--
}
if !same {
fh.installRewrittenChunks(sent.Chunks, stored.Chunks)
}
}
// withChunksAttachedSince returns processed, the chunks a flush made from
// snapshot, followed by the chunks uploads attached to current after snapshot
// was taken: they attach without the handle lock.
@@ -302,7 +324,7 @@ func (fh *FileHandle) mergePeerContent(peer, base *filer_pb.Entry) bool {
local = proto.Clone(e).(*filer_pb.Entry)
})
mark := fh.markSince(base)
merged, ok := mergeContentEntry(peer, base, local, local, mark.truncatedTo, mark.rewrote)
merged, ok := fh.wfs.mergeOwnContent(mark.unfoldOwn(peer, local), base, local, local, mark)
ok = ok && mergeKeepsBuffered(merged, local)
if ok {
fh.rebaseEntry(merged, local)
@@ -318,12 +340,90 @@ func mergeKeepsBuffered(merged, local *filer_pb.Entry) bool {
}
// baseMark records what the handle did over base that its entry does not
// show: the lowest size a truncate set (-1 for none), and a whole-file
// rewrite of its chunks.
// show: the lowest size a truncate set (-1 for none), a whole-file rewrite of
// its chunks, and what the flushes that failed over base sent where the filer
// may have stored one (committed with its answer lost).
type baseMark struct {
base *filer_pb.Entry
truncatedTo int64
rewrote bool
folds []*chunkFold
sent *sentChunks
}
// sentChunks holds what the chunks such flushes sent add over base: the file
// ids base lacks, and the references a truncate shortened from base's files.
// Every copy of a mark over one base shares it, and it only grows until the
// base moves: the filer may hold any of those flushes, and a merge that
// forgot one of its chunks would refuse the handle's own cut write as a
// peer's. Each id is kept once.
type sentChunks struct {
sync.Mutex
ids map[string]bool
}
// maxFailedFolds bounds the folds of failed flushes a handle keeps over one
// base. A stored manifest of a fold past it is read when a refused merge
// cannot place it.
const maxFailedFolds = 4
// noteFailedFlush records a flush that failed over the current base: its
// fold, and the chunks it sent.
func (fh *FileHandle) noteFailedFlush(f *chunkFold, sent []*filer_pb.FileChunk) {
fh.markBase(func(m *baseMark) {
if f != nil && len(m.folds) < maxFailedFolds {
m.folds = append(m.folds[:len(m.folds):len(m.folds)], f)
}
if m.sent == nil {
m.sent = &sentChunks{ids: make(map[string]bool, len(sent))}
}
inBase := make(map[string]bool, 2*len(m.base.GetChunks()))
for _, c := range m.base.GetChunks() {
inBase[contentFileIdKey(c)] = true
inBase[contentChunkKey(c)] = true
}
m.sent.Lock()
defer m.sent.Unlock()
for _, c := range sent {
if key := contentFileIdKey(c); !inBase[key] {
m.sent.ids[key] = true
} else if ref := contentChunkKey(c); !inBase[ref] {
m.sent.ids[ref] = true
}
}
})
}
// unfoldOwn returns stored with the manifests of the handle's failed flushes
// replaced by the chunks they hold, and without the chunks those flushes sent
// that local no longer holds: they are the handle's own writes, which it has
// cut or replaced since, not a peer's.
func (m baseMark) unfoldOwn(stored, local *filer_pb.Entry) *filer_pb.Entry {
for _, f := range m.folds {
stored = f.unfold(stored)
}
if m.sent == nil || stored == nil {
return stored
}
inLocal := make(map[string]bool, len(local.GetChunks()))
for _, c := range local.GetChunks() {
inLocal[contentChunkKey(c)] = true
}
var kept []*filer_pb.FileChunk
m.sent.Lock()
for _, c := range stored.Chunks {
key := contentChunkKey(c)
if !m.sent.ids[contentFileIdKey(c)] && !m.sent.ids[key] || inLocal[key] {
kept = append(kept, c)
}
}
m.sent.Unlock()
if len(kept) == len(stored.Chunks) {
return stored
}
stored = proto.Clone(stored).(*filer_pb.Entry)
stored.Chunks = kept
return stored
}
func (fh *FileHandle) markBase(update func(m *baseMark)) {
@@ -361,7 +461,7 @@ func (fh *FileHandle) adoptPeerBase(base *filer_pb.Entry) {
old := fh.baseEntry.Swap(base)
if m := fh.sinceBase.Load(); m != nil && m.base == old {
moved := *m
moved.base = base
moved.base, moved.folds, moved.sent = base, nil, nil
fh.sinceBase.CompareAndSwap(m, &moved)
}
}
+350
View File
@@ -6,9 +6,12 @@ import (
"io"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/filer"
@@ -134,6 +137,42 @@ func TestMergeAfterFoldDoesNotRestoreChunksThePeerDropped(t *testing.T) {
require.Len(t, manifests, 1)
}
// A flush that truncated, folded and committed but lost the answer: the next
// merge finds the fold's manifest stored and takes it for the handle's own
// chunks, not for a peer's write across the truncate.
func TestMergeTakesAFailedFlushsFoldForItsOwn(t *testing.T) {
base := flushConditionEntry(1, 2)
var written []*filer_pb.FileChunk
for i := 0; i < filer.SmallChunkManifestBatch+4; i++ {
written = append(written, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
after, err := filer.MaybeManifestize((&foldMergeSaver{}).save, nil, written)
require.NoError(t, err)
fold := newChunkFold(written, after)
require.NotNil(t, fold)
local := proto.Clone(base).(*filer_pb.Entry)
local.Chunks = written
local.Attributes.FileSize = uint64(len(written)) * 300
stored := proto.Clone(local).(*filer_pb.Entry)
stored.Chunks = after
_, ok := mergeContentEntry(stored, base, local, local, 0, false)
require.False(t, ok, "an unknown manifest across the truncate is a peer's")
fh := &FileHandle{}
fh.baseEntry.Store(base)
fh.noteFailedFlush(fold, nil)
mark := fh.markSince(base)
require.Len(t, mark.folds, 1)
merged, ok := mergeContentEntry(mark.unfoldOwn(stored, local), base, local, local, 0, false)
require.True(t, ok)
require.Equal(t, referenceCounts(written), referenceCounts(merged.Chunks))
require.Equal(t, local.Attributes.FileSize, merged.Attributes.FileSize)
fh.adoptPeerBase(stored)
require.Empty(t, fh.markSince(stored).folds)
}
// foldMergeFiler keeps the stored entry and its IF_ENTRY_EQUAL condition like
// contentFlushConditionFiler, and points AssignVolume at a volume stub, so a
// flush can store the manifests it folds.
@@ -159,6 +198,7 @@ func (s *foldMergeFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignV
func TestFlushMergeAfterFoldLeavesThePeersRewrite(t *testing.T) {
const n = filer.SmallChunkManifestBatch + 44
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
@@ -201,6 +241,260 @@ func TestFlushMergeAfterFoldLeavesThePeersRewrite(t *testing.T) {
require.Equal(t, 1, keys[contentChunkKey(appended)])
}
// lostAnswerFiler fails every create without a verdict while stalled, then
// stores the first create and fails it like a dropped
// connection, so the client retries the same request.
type lostAnswerFiler struct {
foldMergeFiler
lost atomic.Bool
failLookups atomic.Int32
stall atomic.Bool
}
func (s *lostAnswerFiler) LookupDirectoryEntry(ctx context.Context, r *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
if s.failLookups.Add(-1) >= 0 {
return nil, status.Error(codes.Internal, "lookup failed")
}
return s.foldMergeFiler.LookupDirectoryEntry(ctx, r)
}
func (s *lostAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if s.stall.Load() {
return nil, status.Error(codes.Internal, "store stalled")
}
resp, err := s.foldMergeFiler.CreateEntry(ctx, r)
if err == nil && resp.GetError() == "" && s.lost.CompareAndSwap(false, true) {
return nil, status.Error(codes.Unavailable, "connection lost after commit")
}
return resp, err
}
// A flush that truncated and folded its writes commits, loses the answer, and
// retries the same request: the retry is refused over the manifest it stored
// itself, which the merge must take for the flush's own chunks.
func TestFlushRetryAfterLostAnswerTakesItsOwnFold(t *testing.T) {
for _, failLookups := range []int32{0, 1} {
t.Run(fmt.Sprintf("failed lookups %d", failLookups), func(t *testing.T) {
testFlushRetryAfterLostAnswer(t, failLookups)
})
}
}
// With the refusal lookup failing, the flush fails; the next flush must still
// know the stored manifest for its own.
func testFlushRetryAfterLostAnswer(t *testing.T, failLookups int32) {
const n = filer.SmallChunkManifestBatch + 4
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &lostAnswerFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
base := flushConditionEntry(1, 2)
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
live.Chunks = nil
for i := 0; i < n; i++ {
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
live.Attributes.FileSize = n * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.noteTruncate(0)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
fake.failLookups.Store(failLookups)
if failLookups > 0 {
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.Len(t, fh.markSince(fh.baseEntry.Load()).folds, 1, "the fold the filer may hold is kept")
}
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.True(t, fake.lost.Load(), "the first commit's answer was dropped")
fake.mu.Lock()
defer fake.mu.Unlock()
require.Equal(t, referenceCounts(live.Chunks), referenceCounts(fake.entry.Chunks))
}
// A flush commits the handle's appended chunks, loses the answer and fails;
// the handle then truncates them away. The next flush is refused over the
// stored chunks, which are the handle's own cut writes, not a peer's: it must
// publish the truncate instead of refusing the merge.
// When the filer folded the chunks itself, the merge reads its manifest.
// With the handle's folds full from flushes that got no answer, the lost
// flush also sent a chunk none of them did.
func TestFlushAfterLostAnswerTakesItsOwnTruncate(t *testing.T) {
for _, c := range []struct {
n int
filerFolds bool
foldsFull bool
}{{1, false, false}, {filer.SmallChunkManifestBatch + 4, false, false}, {filer.SmallChunkManifestBatch + 4, true, false}, {filer.SmallChunkManifestBatch + 4, false, true}} {
t.Run(fmt.Sprintf("%d appended, filer folds %v, folds full %v", c.n, c.filerFolds, c.foldsFull), func(t *testing.T) {
testFlushAfterLostAnswerTakesItsOwnTruncate(t, c.n, c.filerFolds, c.foldsFull)
})
}
}
// refoldingLostAnswerFiler assigns no volume, so the mount cannot fold, and
// folds a create before lostAnswerFiler stores it.
type refoldingLostAnswerFiler struct {
*lostAnswerFiler
saver foldMergeSaver
}
func (s *refoldingLostAnswerFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{Error: "no writable volumes"}, nil
}
func (s *refoldingLostAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
r = proto.Clone(r).(*filer_pb.CreateEntryRequest)
folded, err := filer.MaybeManifestize(s.saver.save, nil, r.Entry.Chunks)
if err != nil {
return nil, err
}
r.Entry.Chunks = folded
return s.lostAnswerFiler.CreateEntry(ctx, r)
}
func testFlushAfterLostAnswerTakesItsOwnTruncate(t *testing.T, n int, filerFolds, foldsFull bool) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &lostAnswerFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}}
var server filer_pb.SeaweedFilerServer = fake
if filerFolds {
server = &refoldingLostAnswerFiler{lostAnswerFiler: fake, saver: foldMergeSaver{saved: 500}}
}
startFakeFiler(t, wfs, server)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
base := flushConditionEntry(1, 2)
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
for i := 0; i < n; i++ {
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: 3 + int64(i)*300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
live.Attributes.FileSize = 3 + uint64(n)*300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
if foldsFull {
oldSleep := metadataFlushSleep
metadataFlushSleep = func(context.Context, time.Duration) {}
t.Cleanup(func() { metadataFlushSleep = oldSleep })
fake.stall.Store(true)
failUntilFoldsFull(t, wfs, fh, observed)
fake.stall.Store(false)
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Chunks = append(e.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 999, Cookie: 1}, Offset: int64(e.Attributes.FileSize), Size: 300, ModifiedTsNs: 999})
e.Attributes.FileSize += 300
})
}
if filerFolds || foldsFull {
var written []*filer_pb.FileChunk
fh.UpdateEntry(func(e *filer_pb.Entry) { written = proto.Clone(e).(*filer_pb.Entry).Chunks })
saved := truncateManifestResolver
t.Cleanup(func() { truncateManifestResolver = saved })
truncateManifestResolver = func(ctx context.Context, wfs *WFS, manifest *filer_pb.FileChunk) (held []*filer_pb.FileChunk, err error) {
for _, c := range written {
if c.Offset >= manifest.Offset && chunkSpanEnd(c) <= chunkSpanEnd(manifest) {
held = append(held, proto.Clone(c).(*filer_pb.FileChunk))
}
}
return held, nil
}
}
fake.failLookups.Store(1)
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.True(t, fake.lost.Load(), "the first commit's answer was dropped")
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Chunks = e.Chunks[:2]
e.Attributes.FileSize = 3
})
fh.noteTruncate(3)
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
fake.mu.Lock()
defer fake.mu.Unlock()
require.Equal(t, referenceCounts(base.Chunks), referenceCounts(fake.entry.Chunks))
require.Equal(t, uint64(3), fake.entry.Attributes.FileSize)
}
// noAnswerFiler fails every create without a verdict, as a stalled store
// does: the filer may hold any of them.
type noAnswerFiler struct{ foldMergeFiler }
func (s *noAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
return nil, status.Error(codes.Internal, "store stalled")
}
// Flushes that keep failing without an answer keep at most maxFailedFolds
// folds, and the later ones still fold.
func TestFailedFlushesKeepBoundedFolds(t *testing.T) {
const n = filer.SmallChunkManifestBatch + 4
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &noAnswerFiler{foldMergeFiler{volume: newVolumeStub(t)}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
base := flushConditionEntry(1, 2)
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
for i := 0; i < n; i++ {
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
live.Attributes.FileSize = n * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
oldSleep := metadataFlushSleep
metadataFlushSleep = func(context.Context, time.Duration) {}
t.Cleanup(func() { metadataFlushSleep = oldSleep })
failUntilFoldsFull(t, wfs, fh, observed)
assigns := fake.assigns.Load()
for i := 0; i < 2; i++ {
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
}
require.Len(t, fh.markSince(observed).folds, maxFailedFolds)
require.Greater(t, fake.assigns.Load(), assigns)
}
// failUntilFoldsFull fails flushes until the handle keeps maxFailedFolds
// folds over base.
func failUntilFoldsFull(t *testing.T, wfs *WFS, fh *FileHandle, base *filer_pb.Entry) {
for i := 0; i < maxFailedFolds && len(fh.markSince(base).folds) < maxFailedFolds; i++ {
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
}
require.Len(t, fh.markSince(base).folds, maxFailedFolds)
}
// refoldingFiler folds the small chunks of a create before it stores and
// acknowledges it, as the filer's cleanupChunks does.
type refoldingFiler struct {
@@ -265,3 +559,59 @@ func TestFlushMergeInstallsTheEntryTheFilerStored(t *testing.T) {
require.Equal(t, stored, referenceCounts(fh.GetEntry().GetEntry().Chunks), "the handle holds what the filer stored")
require.Equal(t, stored, referenceCounts(fh.baseEntry.Load().Chunks), "the base is what the filer stored")
}
// noAssignFiler assigns no volume, so the mount cannot fold, and folds a
// create itself like refoldingFiler.
type noAssignFiler struct{ refoldingFiler }
func (s *noAssignFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{Error: "no writable volumes"}, nil
}
// A flush the filer folds and acknowledges leaves the handle holding what the
// filer stored, as after a merge: its flat chunks under the folded base would
// count as writes of its own.
func TestFlushInstallsTheChunksTheFilerFolded(t *testing.T) {
const n = filer.SmallChunkManifestBatch - 1
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
wfs.readAuth = newReadAuth(wfs)
fake := &noAssignFiler{refoldingFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}, saver: foldMergeSaver{saved: 500}}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
attrs := &filer_pb.FuseAttributes{Inode: 42, FileMode: 0644, Uid: 2000, Gid: 20, FileSize: n * 300}
base := &filer_pb.Entry{Name: "file", Attributes: attrs}
for i := 0; i < n; i++ {
base.Chunks = append(base.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: n + 1, Cookie: 1}, Offset: n * 300, Size: 300, ModifiedTsNs: 100 + n})
live.Attributes.FileSize = (n + 1) * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
fake.mu.Lock()
stored := referenceCounts(fake.entry.Chunks)
fake.mu.Unlock()
manifests, _ := filer.SeparateManifestChunks(fake.entry.Chunks)
require.Len(t, manifests, 1, "the filer folded the chunks")
require.Equal(t, stored, referenceCounts(fh.GetEntry().GetEntry().Chunks), "the handle holds what the filer stored")
require.Equal(t, stored, referenceCounts(fh.baseEntry.Load().Chunks), "the base is what the filer stored")
wfs.readAuth.mu.Lock()
defer wfs.readAuth.mu.Unlock()
require.Equal(t, util.FullPath("/dir/file"), wfs.readAuth.paths[manifests[0].GetFileIdString()], "its manifest reads with the file's token")
}
+1 -7
View File
@@ -622,15 +622,9 @@ func (mc *MetaCache) entryVersionBlocksLocked(ctx context.Context, fp util.FullP
// event can correct it.
return false
}
entry, err := mc.localStore.FindEntry(ctx, fp)
live := err == nil && entry != nil && !isTtlExpired(entry)
if !tombstone && !live {
if !tombstone && !mc.entryExistsLocked(ctx, fp) {
recordTsNs = 0
}
// A live entry reflects its own commit, even under an older listing floor.
if live && entry.CommitTsNs > recordTsNs {
recordTsNs = entry.CommitTsNs
}
floorTsNs := mc.entryVersionFloorLocked(fp, recordTsNs)
if removal && !tombstone {
return floorTsNs > tsNs
@@ -957,64 +957,3 @@ func TestUnversionedWriteDoesNotInheritDirectoryFloor(t *testing.T) {
}
mc.WaitForEntryInvalidations()
}
// A listing snapshot can trail the listed entries: a peer's held watermark
// caps it below writes already in the store. A delayed older event must not
// roll a listed entry back to the state it replaced.
func TestBuildKeepsListedEntryNewerThanSnapshot(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
"/": true,
"/dir": true,
})
defer mc.Shutdown()
if err := mc.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
t.Fatalf("begin build: %v", err)
}
if err := mc.doBatchInsertEntries(context.Background(), []*filer.Entry{{
FullPath: "/dir/file",
Attr: filer.Attr{
Crtime: time.Unix(1, 0),
Mtime: time.Unix(1, 0),
Mode: 0100644,
FileSize: 300,
},
CommitTsNs: 3000,
}}); err != nil {
t.Fatalf("batch insert: %v", err)
}
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
t.Fatalf("complete build: %v", err)
}
apply := func(tsNs int64, oldEntry, newEntry *filer_pb.Entry) {
t.Helper()
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: tsNs,
EventNotification: &filer_pb.EventNotification{
OldEntry: oldEntry,
NewEntry: newEntry,
NewParentPath: "/dir",
},
}
if err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply event at %d: %v", tsNs, err)
}
}
wantSize := func(want uint64, why string) {
t.Helper()
entry, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/file"))
if err != nil || entry.FileSize != want {
t.Fatalf("entry = %+v, %v; want size %d (%s)", entry, err, want, why)
}
}
apply(2500, nil, &filer_pb.Entry{Name: "file", CommitTsNs: 2500, Attributes: &filer_pb.FuseAttributes{FileMode: 0100644}})
wantSize(300, "the create below the listed commit is already reflected")
apply(2500, &filer_pb.Entry{Name: "file"}, nil)
wantSize(300, "a removal below the listed commit is already reflected")
apply(3500, &filer_pb.Entry{Name: "file"}, &filer_pb.Entry{Name: "file", CommitTsNs: 3500, Attributes: &filer_pb.FuseAttributes{FileSize: 500, FileMode: 0100644}})
wantSize(500, "a change past the listed commit applies")
mc.WaitForEntryInvalidations()
}
+5
View File
@@ -117,6 +117,10 @@ type Option struct {
// mounts. Disabled under writeback cache, which implies single-writer.
EnableDistributedLock bool
// ConcurrentWriteMerge merges a handle's writes with chunks another mount
// committed since the handle's base; otherwise its flush fails with EIO.
ConcurrentWriteMerge bool
// WritebackCache enables async flush on close for improved small file write performance.
// When true, Flush() returns immediately and data upload + metadata flush happen in background.
WritebackCache bool
@@ -185,6 +189,7 @@ type WFS struct {
posixSid uint64 // this mount's session id, for routed-lock owner identity
posixHint *posixLockHint // local fcntl-lock hint for routed mode
posixOwn *posixlock.Manager // mirror of locks this mount holds, re-asserted via keepalive
posixLostKeys sync.Map // keys whose lock loss was already reported, see notePosixLockLoss
fhLocks fhLockOwners // non-flock lock owners per open fh, drained at release
peerRegistrar *PeerRegistrar
peerDirectory *PeerDirectory
+33
View File
@@ -31,6 +31,7 @@ type attributeCASFiler struct {
mu sync.Mutex
entry *filer_pb.Entry
updates, conflicts int
unconditional int
beforeUpdate func(int, *filer_pb.Entry)
afterCommit func()
updateErr error
@@ -56,6 +57,9 @@ func (s *attributeCASFiler) UpdateEntry(ctx context.Context, req *filer_pb.Updat
if s.beforeUpdate != nil {
s.beforeUpdate(s.updates, s.entry)
}
if len(req.GetCondition().GetClauses()) == 0 {
s.unconditional++
}
if clauses := req.GetCondition().GetClauses(); len(clauses) > 0 && !proto.Equal(clauses[0].GetExpectedEntry(), s.entry) {
s.conflicts++
return nil, status.Error(codes.FailedPrecondition, "entry changed")
@@ -121,6 +125,35 @@ func TestAttributeOnlyConflictOutcomes(t *testing.T) {
}
}
// An open with O_TRUNC over a cached entry another mount has changed since
// truncates the owner's entry: the stale copy is refused, never written.
func TestTruncateEntryReplaysOnOwnerEntry(t *testing.T) {
wfs := newInvalidateTestWFS(t)
cached := attributeAppendEntry(1)
stored := attributeAppendEntry(1)
stored.Attributes.FileMode = 0640
fake := &attributeCASFiler{entry: stored}
startFakeFiler(t, wfs, fake)
path := util.FullPath("/dir/file")
wfs.inodeToPath.Lookup(util.FullPath("/dir"), 1, true, false, 0, false)
wfs.inodeToPath.Lookup(path, 1, false, false, 42, true)
if code := wfs.truncateEntry(context.Background(), path, cached); code != fuse.OK {
t.Fatalf("truncateEntry: %v", code)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if fake.unconditional != 0 || fake.conflicts != 1 || fake.updates != 2 {
t.Fatalf("updates=%d conflicts=%d unconditional=%d, want 2, 1, 0", fake.updates, fake.conflicts, fake.unconditional)
}
if len(fake.entry.Chunks) != 0 || fake.entry.Attributes.FileSize != 0 {
t.Fatalf("stored chunks=%d size=%d, want an empty file", len(fake.entry.Chunks), fake.entry.Attributes.FileSize)
}
if fake.entry.Attributes.FileMode != 0640 {
t.Fatalf("stored mode=%o, want the peer's 640", fake.entry.Attributes.FileMode)
}
}
func (s *attributeCASFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
+24 -19
View File
@@ -169,7 +169,7 @@ func (wfs *WFS) openExistingForCreate(ctx context.Context, in *fuse.CreateIn, en
return status
}
if in.Flags&syscall.O_TRUNC != 0 && in.Flags&fuse.O_ANYWRITE != 0 {
if code := wfs.truncateEntry(entryFullPath, entry); code != fuse.OK {
if code := wfs.truncateEntry(ctx, entryFullPath, entry); code != fuse.OK {
wfs.ReleaseHandle(openFh)
return code
}
@@ -614,25 +614,30 @@ func (wfs *WFS) asyncCreateEntry(dirFullPath util.FullPath, entry *filer_pb.Entr
}()
}
func (wfs *WFS) truncateEntry(entryFullPath util.FullPath, entry *filer_pb.Entry) fuse.Status {
// truncateEntry empties the file as a conditional update: like an attribute
// change it goes to the entry's write owner and, refused, is replayed on the
// owner's entry. Written unconditionally to another filer, it dropped chunks
// that a write already accepted by the owner put back.
func (wfs *WFS) truncateEntry(ctx context.Context, entryFullPath util.FullPath, entry *filer_pb.Entry) fuse.Status {
if entry == nil {
return fuse.EIO
}
if entry.Attributes == nil {
entry.Attributes = &filer_pb.FuseAttributes{}
}
entry.Content = nil
entry.Chunks = nil
entry.Attributes.FileSize = 0
clearS3Encryption(entry)
truncNow := time.Now()
entry.Attributes.Mtime = truncNow.Unix()
entry.Attributes.MtimeNs = int32(truncNow.Nanosecond())
entry.Attributes.Ctime = truncNow.Unix()
entry.Attributes.CtimeNs = int32(truncNow.Nanosecond())
if code := wfs.saveEntry(entryFullPath, entry); code != fuse.OK {
truncated, code := wfs.saveEntryAttributes(ctx, entryFullPath, entry, 0, func(next *filer_pb.Entry) fuse.Status {
if next.Attributes == nil {
next.Attributes = &filer_pb.FuseAttributes{}
}
next.Content = nil
next.Chunks = nil
next.Attributes.FileSize = 0
clearS3Encryption(next)
truncNow := time.Now()
next.Attributes.Mtime = truncNow.Unix()
next.Attributes.MtimeNs = int32(truncNow.Nanosecond())
next.Attributes.Ctime = truncNow.Unix()
next.Attributes.CtimeNs = int32(truncNow.Nanosecond())
return fuse.OK
}, func(live, acked *filer_pb.Entry) {})
if code != fuse.OK {
return code
}
@@ -641,8 +646,8 @@ func (wfs *WFS) truncateEntry(entryFullPath util.FullPath, entry *filer_pb.Entry
if fh, fhFound := wfs.fhMap.FindFileHandle(inode); fhFound {
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("truncateEntry", fh.fh, util.ExclusiveLock)
fh.ResetDirtyPages()
fh.SetEntry(entry)
fh.setAuthoritativeBase(proto.Clone(entry).(*filer_pb.Entry))
fh.SetEntry(truncated)
fh.setAuthoritativeBase(proto.Clone(truncated).(*filer_pb.Entry))
fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
}
}
+1 -1
View File
@@ -303,7 +303,7 @@ func TestTruncateEntryClearsDirtyPagesForOpenHandle(t *testing.T) {
},
}
if status := wfs.truncateEntry(fullPath, truncatedEntry); status != fuse.OK {
if status := wfs.truncateEntry(context.Background(), fullPath, truncatedEntry); status != fuse.OK {
t.Fatalf("truncateEntry status = %v, want OK", status)
}
if fh.dirtyPages == oldDirtyPages {
+146 -8
View File
@@ -430,6 +430,8 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
merged = wfs.ackedBase(resp, merged)
fh.rebaseEntry(merged, requestEntry)
baseSnapshot = merged
} else {
fh.installStoredChunks(wfs.ackedBase(resp, baseSnapshot), baseSnapshot)
}
event := resp.GetMetadataEvent()
@@ -516,6 +518,20 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
guard = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: expected}
}
sent := request.Entry
// A failed flush the filer may have stored keeps what it sent, to tell it
// from a peer's chunks. Only the first request carries the flush's fold:
// unless the filer refused its only send, the filer may hold its manifests.
foldSends, foldRefused, mayStore := 0, false, false
defer func() {
if err == nil || !mayStore {
return
}
kept := fold
if foldSends == 1 && foldRefused {
kept = nil
}
fh.noteFailedFlush(kept, fold.unfoldChunks(sent.Chunks))
}()
for attempt := 0; ; attempt++ {
if guardErr := wfs.checkContentPublication(fh, guard.ExpectedEntry); guardErr != nil {
return nil, nil, guardErr
@@ -527,6 +543,11 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
if errors.Is(callErr, filer_pb.ErrPreconditionFailed) {
publication.refused = true
}
if attempt == 0 {
foldSends++
foldRefused = filer_pb.IsFilerVerdict(callErr)
}
mayStore = mayStore || callErr != nil && !filer_pb.IsFilerVerdict(callErr)
return callErr
})
if err == nil && request.Entry != sent {
@@ -541,9 +562,16 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
return resp, nil, err
}
mark := fh.markSince(base)
// The flush's own fold is no change of content: merge the chunks.
// The flush's own fold is no change of content: merge the chunks. A
// retried request may have stored it already.
unfoldedLocal := fold.unfold(local)
next, ok := mergeContentEntry(stored, base, unfoldedLocal, fold.unfold(sent), mark.truncatedTo, mark.rewrote)
own := mark.unfoldOwn(fold.unfold(stored), unfoldedLocal)
next, ok := wfs.mergeOwnContent(own, base, unfoldedLocal, fold.unfold(sent), mark)
if !ok && sameContentFile(stored, base) {
if expanded := wfs.expandStoredManifests(ctx, util.FullPath(request.Directory).Child(request.Entry.Name), own, base, unfoldedLocal); expanded != nil {
next, ok = wfs.mergeOwnContent(mark.unfoldOwn(expanded, unfoldedLocal), base, unfoldedLocal, fold.unfold(sent), mark)
}
}
if !ok || buffered && !mergeKeepsBuffered(next, unfoldedLocal) {
return resp, nil, err
}
@@ -568,6 +596,87 @@ func (wfs *WFS) lookupRefusedEntry(ctx context.Context, dir, name string) (store
return stored
}
// expandStoredManifests returns stored with each manifest base and local lack
// replaced by the chunks it holds, or nil when it has none or one cannot be
// read. A fold changes no content, and the handle cannot name every fold of
// its own chunks: one the filer made, or one past maxFailedFolds.
func (wfs *WFS) expandStoredManifests(ctx context.Context, path util.FullPath, stored, base, local *filer_pb.Entry) *filer_pb.Entry {
known := make(map[string]bool, len(base.GetChunks())+len(local.GetChunks()))
for _, e := range []*filer_pb.Entry{base, local} {
for _, c := range e.GetChunks() {
known[contentChunkKey(c)] = true
}
}
var unknown []*filer_pb.FileChunk
for _, c := range stored.GetChunks() {
if c.IsChunkManifest && !known[contentChunkKey(c)] {
unknown = append(unknown, c)
}
}
if len(unknown) == 0 {
return nil
}
wfs.readAuth.Track(path, unknown)
ctx, cancel := context.WithTimeout(ctx, wfs.filerRPCWait())
defer cancel()
resolve := func(manifest *filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) {
return truncateManifestResolver(ctx, wfs, manifest)
}
chunks := make([]*filer_pb.FileChunk, 0, len(stored.Chunks))
for _, c := range stored.Chunks {
if !c.IsChunkManifest || known[contentChunkKey(c)] {
chunks = append(chunks, c)
continue
}
held, err := expandManifestAt(c, -1, resolve, 1)
if err != nil {
glog.V(1).Infof("content flush %s: %v", path, err)
return nil
}
chunks = append(chunks, held...)
}
expanded := proto.Clone(stored).(*filer_pb.Entry)
expanded.Chunks = chunks
return expanded
}
// mergeOwnContent merges as mergeContentEntry does. Without
// ConcurrentWriteMerge a stored chunk change that is neither base's nor the
// handle's is not merged: only attributes, and the handle's own commits, are.
func (wfs *WFS) mergeOwnContent(stored, base, local, sent *filer_pb.Entry, mark baseMark) (*filer_pb.Entry, bool) {
if !wfs.option.ConcurrentWriteMerge && peerChangedChunks(stored, base, local) {
return nil, false
}
return mergeContentEntry(stored, base, local, sent, mark.truncatedTo, mark.rewrote)
}
// peerChangedChunks reports a chunk change in stored that is neither base's
// nor local's: a chunk added beside them, or a base chunk local still holds
// but stored dropped.
func peerChangedChunks(stored, base, local *filer_pb.Entry) bool {
held := make(map[string]bool, len(base.GetChunks())+len(local.GetChunks()))
for _, c := range local.GetChunks() {
held[contentChunkKey(c)] = true
}
inStored := make(map[string]bool, len(stored.GetChunks()))
for _, c := range stored.GetChunks() {
inStored[contentChunkKey(c)] = true
}
for _, c := range base.GetChunks() {
key := contentChunkKey(c)
if held[key] && !inStored[key] {
return true
}
held[key] = true
}
for _, c := range stored.GetChunks() {
if !held[contentChunkKey(c)] {
return true
}
}
return false
}
// maxContentFlushMerges bounds how often one flush rebases onto a moving entry.
const maxContentFlushMerges = 3
@@ -577,12 +686,13 @@ const maxContentFlushMerges = 3
// space). Everything else keeps the stored value. A local truncation keeps
// the handle's size and clips stored chunks at the lowest size truncated to
// (truncatedTo, or -1); otherwise the stored size stands unless the handle
// changed its size or wrote past it.
// changed its size or wrote past it. A time both sides moved keeps the later.
// A different file at the path, inline content changed on both sides,
// inline content next to chunks (reads stop at the inline bytes), a manifest
// across the truncate (its members keep their sizes), or a local
// whole-file rewrite (rewrote) over a peer's chunk change cannot be merged:
// the rewrite carries the handle's stale view.
// across the truncate (its members keep their sizes), a local truncate across
// a chunk a peer wrote since base, or a local whole-file rewrite (rewrote)
// over a peer's chunk change cannot be merged: the truncate and the rewrite
// carry the handle's stale view.
func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo int64, rewrote bool) (*filer_pb.Entry, bool) {
if !sameContentFile(stored, base) {
return nil, false
@@ -597,8 +707,10 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
}
inBase := make(map[string]bool, len(base.Chunks))
baseFiles := make(map[string]bool, len(base.Chunks))
for _, c := range base.Chunks {
inBase[contentChunkKey(c)] = true
baseFiles[contentFileIdKey(c)] = true
}
inLocal := make(map[string]bool, len(local.Chunks))
for _, c := range local.Chunks {
@@ -613,7 +725,10 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
for _, c := range stored.Chunks {
key := contentChunkKey(c)
peerChanged = peerChanged || !inBase[key]
if inBase[key] && !inLocal[key] || truncatedTo >= 0 && c.Offset >= truncatedTo {
if truncatedTo >= 0 && c.Offset+int64(c.Size) > truncatedTo && !baseFiles[contentFileIdKey(c)] && !inLocal[key] {
return nil, false
}
if inBase[key] != inLocal[key] || truncatedTo >= 0 && c.Offset >= truncatedTo {
continue
}
c = proto.Clone(c).(*filer_pb.FileChunk)
@@ -657,7 +772,11 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
fields := m.Descriptor().Fields()
for i := 0; i < fields.Len(); i++ {
fd := fields.Get(i)
if fd.Name() == "file_size" || l.Get(fd).Equal(b.Get(fd)) {
switch fd.Name() {
case "file_size", "mtime", "mtime_ns", "ctime", "ctime_ns":
continue
}
if l.Get(fd).Equal(b.Get(fd)) {
continue
}
if s.Has(fd) {
@@ -667,6 +786,14 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
}
}
sa, sn := stored.GetAttributes(), sent.GetAttributes()
if takesHandleTime(fuseTime(sa.GetMtime(), sa.GetMtimeNs()), fuseTime(baseAttrs.Mtime, baseAttrs.MtimeNs), fuseTime(localAttrs.Mtime, localAttrs.MtimeNs), fuseTime(sn.GetMtime(), sn.GetMtimeNs())) {
merged.Attributes.Mtime, merged.Attributes.MtimeNs = sn.GetMtime(), sn.GetMtimeNs()
}
if takesHandleTime(fuseTime(sa.GetCtime(), sa.GetCtimeNs()), fuseTime(baseAttrs.Ctime, baseAttrs.CtimeNs), fuseTime(localAttrs.Ctime, localAttrs.CtimeNs), fuseTime(sn.GetCtime(), sn.GetCtimeNs())) {
merged.Attributes.Ctime, merged.Attributes.CtimeNs = sn.GetCtime(), sn.GetCtimeNs()
}
for k, v := range local.Extended {
if old, found := base.Extended[k]; !found || !bytes.Equal(old, v) {
if merged.Extended == nil {
@@ -692,6 +819,17 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
return merged, true
}
// takesHandleTime reports whether a merge takes the time the handle sends:
// the handle moved it since base, and no peer moved it later. A delayed flush
// must not move a peer's time back.
func takesHandleTime(stored, base, local, sent time.Time) bool {
return !local.Equal(base) && (stored.Equal(base) || !stored.After(sent))
}
func fuseTime(sec int64, nsec int32) time.Time {
return time.Unix(sec, int64(nsec))
}
// sameContentFile reports whether stored is still the regular file base was:
// the same inode, or for an entry without one, the same creation time. A
// synthesized base with neither cannot tell.
@@ -2087,8 +2087,17 @@ func TestAckFromAnotherFilerIsNotDroppedBehindForeignFence(t *testing.T) {
// A peer's append reaching a dirty handle is merged under the handle's own
// writes: the uploaded chunk and the unflushed pages both survive.
func TestPeerAppendMergesIntoDirtyHandle(t *testing.T) {
func TestPeerAppendMergesIntoDirtyHandle(t *testing.T) { assertPeerAppendIntoDirtyHandle(t, true) }
// Without ConcurrentWriteMerge the handle keeps its writes and base, so its
// flush fails instead of merging.
func TestPeerAppendLeavesDirtyHandleByDefault(t *testing.T) {
assertPeerAppendIntoDirtyHandle(t, false)
}
func assertPeerAppendIntoDirtyHandle(t *testing.T, merge bool) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = merge
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, flushConditionEntry(1), 0, 0)
@@ -2117,6 +2126,15 @@ func TestPeerAppendMergesIntoDirtyHandle(t *testing.T) {
t.Fatal("dirty pages destroyed by a peer append")
}
entry := fh.GetEntry().GetEntry()
if !merge {
if got := len(entry.Chunks); got != 2 {
t.Fatalf("handle has %d chunks; want only its own", got)
}
if base := fh.baseEntry.Load(); len(base.GetChunks()) != 1 {
t.Fatalf("base %v, want the handle's own base", base)
}
return
}
if got := len(entry.Chunks); got != 3 || entry.Attributes.FileSize != 4 {
t.Fatalf("handle has %d chunks, size %d; want the peer's and its own", got, entry.Attributes.FileSize)
}
+2
View File
@@ -204,6 +204,8 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
merged = wfs.ackedBase(resp, merged)
fh.rebaseEntry(merged, requestEntry)
baseSnapshot = merged
} else {
fh.installStoredChunks(wfs.ackedBase(resp, baseSnapshot), baseSnapshot)
}
event := resp.GetMetadataEvent()
+40 -7
View File
@@ -305,7 +305,7 @@ func (wfs *WFS) routedReleasePosixOwner(inode, owner uint64) bool {
if !ok {
return false
}
wfs.posixOwn.ReleasePosixOwner(key, wfs.posixSid, owner)
wfs.posixOwn.ReleasePosixOwner(key, posixlock.Session{Sid: wfs.posixSid}, owner)
ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout)
defer cancel()
if _, err := wfs.callPosixLock(ctx, key, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, posixlock.Range{Sid: wfs.posixSid, Owner: owner}); err != nil {
@@ -324,7 +324,7 @@ func (wfs *WFS) routedReleaseFlockOwner(inode, owner uint64) {
if !ok {
return
}
wfs.posixOwn.ReleaseFlockOwner(key, wfs.posixSid, owner)
wfs.posixOwn.ReleaseFlockOwner(key, posixlock.Session{Sid: wfs.posixSid}, owner)
ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout)
defer cancel()
if _, err := wfs.callPosixLock(ctx, key, filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER, posixlock.Range{Sid: wfs.posixSid, Owner: owner}); err != nil {
@@ -373,8 +373,10 @@ func (wfs *WFS) hasPosixOwner(inode, owner uint64) bool {
// callPosixReassert sends the mount's held locks on key to the key's current
// owner filer as a KEEP_ALIVE, which renews the lease and lets the owner rebuild
// its in-memory state after a takeover or restart.
func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posixlock.Range) error {
// its in-memory state after a takeover or restart. It returns a lock another
// session now holds in place of one of this mount's, or nil; filers that do not
// report losses always return nil.
func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posixlock.Range) (lost *filer_pb.PosixLockRange, err error) {
pbLocks := make([]*filer_pb.PosixLockRange, 0, len(locks))
for _, l := range locks {
pbLocks = append(pbLocks, &filer_pb.PosixLockRange{
@@ -382,15 +384,36 @@ func (wfs *WFS) callPosixReassert(ctx context.Context, key string, locks []posix
Sid: l.Sid, Owner: l.Owner, Pid: l.Pid, IsFlock: l.IsFlock,
})
}
return wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
_, e := client.PosixLock(ctx, &filer_pb.PosixLockRequest{
err = wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
resp, e := client.PosixLock(ctx, &filer_pb.PosixLockRequest{
Key: key,
Op: filer_pb.PosixLockOp_KEEP_ALIVE,
Lock: &filer_pb.PosixLockRange{Sid: wfs.posixSid},
Locks: pbLocks,
})
if e == nil && resp.GetHasConflict() {
lost = resp.GetConflict()
}
return e
})
return lost, err
}
// notePosixLockLoss warns once when a re-assertion finds that another session
// holds a lock this mount still believes it holds on key, typically after the
// mount's lease lapsed, and forgets the loss once a re-assertion succeeds. The
// application is not told: POSIX has no signal for a lost lock. It reports
// whether it warned.
func (wfs *WFS) notePosixLockLoss(key string, lost *filer_pb.PosixLockRange) bool {
if lost == nil {
wfs.posixLostKeys.Delete(key)
return false
}
if _, warned := wfs.posixLostKeys.LoadOrStore(key, struct{}{}); warned {
return false
}
glog.Warningf("posix lock on %s lost: another session holds [%d, %d]; this mount's application may still believe it holds the lock", key, lost.GetStart(), lost.GetEnd())
return true
}
// posixKeepaliveConcurrency bounds the parallel keepalive RPCs per tick. A mount
@@ -420,11 +443,21 @@ func (wfs *WFS) loopRenewPosixLeases() {
// and get reaped.
ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout)
defer cancel()
if err := wfs.callPosixReassert(ctx, key, locks); err != nil {
lost, err := wfs.callPosixReassert(ctx, key, locks)
if err != nil {
glog.V(2).Infof("posix reassert %s: %v", key, err)
return
}
wfs.notePosixLockLoss(key, lost)
}()
}
wg.Wait()
// Forget losses on keys this mount no longer holds locks on.
wfs.posixLostKeys.Range(func(key, _ any) bool {
if _, stillHeld := held[key.(string)]; !stillHeld {
wfs.posixLostKeys.Delete(key)
}
return true
})
}
}
@@ -9,6 +9,7 @@ import (
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer/posixlock"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func TestPosixLockTypeMapping(t *testing.T) {
@@ -94,3 +95,23 @@ func TestPosixLockHint(t *testing.T) {
t.Fatal("inode entry should be removed when its last owner drops")
}
}
func TestNotePosixLockLossWarnsOncePerLoss(t *testing.T) {
wfs := &WFS{}
lost := &filer_pb.PosixLockRange{Start: 0, End: 99, Pid: 7}
if !wfs.notePosixLockLoss("k", lost) {
t.Fatal("first loss on a key should warn")
}
if wfs.notePosixLockLoss("k", lost) {
t.Fatal("a loss already reported should not warn again on every keepalive")
}
if !wfs.notePosixLockLoss("other", lost) {
t.Fatal("a loss on another key should warn")
}
if wfs.notePosixLockLoss("k", nil) {
t.Fatal("a successful re-assertion should not warn")
}
if !wfs.notePosixLockLoss("k", lost) {
t.Fatal("a new loss after a successful re-assertion should warn again")
}
}
+1 -2
View File
@@ -25,8 +25,7 @@ const (
adminScriptDetectTickMinutes = 17
)
const defaultAdminScript = `fs.log.purge -daysAgo=7
volume.deleteEmpty -quietFor=24h -apply
const defaultAdminScript = `volume.deleteEmpty -quietFor=24h -apply
volume.fix.replication -apply
s3.clean.uploads -timeAgo=24h`
@@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster/maintenance"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -167,3 +168,14 @@ func TestAdminScriptDetectCreatesProposalWhenIntervalElapsed(t *testing.T) {
t.Fatalf("unexpected completion message: %+v", sender.complete)
}
}
func TestDefaultScriptsLeaveLogPurgeToItsJob(t *testing.T) {
for name, script := range map[string]string{
"admin_script": defaultAdminScript,
"master": maintenance.DefaultMasterMaintenanceScripts,
} {
if strings.Contains(script, "fs.log.purge") {
t.Errorf("%s default script still purges the metadata log:\n%s", name, script)
}
}
}
+73
View File
@@ -0,0 +1,73 @@
package pluginworker
import (
"context"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
)
// AdminFilerClient reaches one filer with the admin token, so files such as
// filer.conf are read from that filer's own store, including chunk-backed ones.
type AdminFilerClient struct {
Address pb.ServerAddress
GrpcDialOption grpc.DialOption
}
func (c *AdminFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithGrpcFilerClient(streamingMode, 0, c.Address, c.GrpcDialOption, security.FilerAdminToken, fn)
}
func (c *AdminFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
func (c *AdminFilerClient) GetDataCenter() string { return "" }
func (c *AdminFilerClient) GetLookupFileIdFunction() wdclient.LookupFileIdFunctionType {
return filer.LookupFn(c)
}
// ClusterFilerAddresses returns the non-empty filer addresses of the cluster context.
func ClusterFilerAddresses(clusterContext *plugin_pb.ClusterContext) []pb.ServerAddress {
var filers []pb.ServerAddress
for _, address := range clusterContext.GetFilerAddresses() {
if address != "" {
filers = append(filers, pb.ServerAddress(address))
}
}
return filers
}
// OneFilerPerStore keeps the first reachable filer of each store signature:
// filers sharing a store share its rows, and a filer with its own store has
// rows no other filer's job reaches.
func OneFilerPerStore(ctx context.Context, filers []pb.ServerAddress, grpcDialOption grpc.DialOption, sender DetectionSender) []pb.ServerAddress {
seen := make(map[int32]bool)
var picked []pb.ServerAddress
for _, address := range filers {
var signature int32
err := pb.WithGrpcFilerClient(false, 0, address, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return err
}
signature = resp.Signature
return nil
})
if err != nil {
_ = sender.SendActivity(BuildDetectorActivity("filer_unreachable", fmt.Sprintf("filer %s: %v", address, err), nil))
continue
}
if seen[signature] {
continue
}
seen[signature] = true
picked = append(picked, address)
}
return picked
}
+1
View File
@@ -10,6 +10,7 @@ import (
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding" // register erasure_coding handler
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/filer_ttl" // register filer_ttl handler
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/iceberg" // register iceberg_maintenance handler
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/meta_log_purge" // register meta_log_purge handler
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/s3_lifecycle" // register s3_lifecycle handler
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum" // register vacuum handler
)
@@ -306,3 +306,28 @@ func TestSetResponseHeadersIgnoresOverridesForAnonymous(t *testing.T) {
}
}
}
// A file written through a mount stores no MD5. When it also has no chunks
// (it is empty, or small and kept inline) S3 answers with the MD5 of its
// bytes, as AWS does for an empty object, not with an empty ETag.
func TestObjectETagOfAnEntryWithoutChunks(t *testing.T) {
s3a := &S3ApiServer{}
tests := []struct {
name string
entry *filer_pb.Entry
want string
}{
{"empty file", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}, `"d41d8cd98f00b204e9800998ecf8427e"`},
{"inline content", &filer_pb.Entry{Content: []byte("hello"), Attributes: &filer_pb.FuseAttributes{FileSize: 5}}, `"5d41402abc4b2a76b9719d911017c592"`},
{"a stored MD5 wins", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{Md5: []byte{0xab, 0xcd}}}, `"abcd"`},
// a hole no chunk covers is not inline content: no hash to give
{"a hole only", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{FileSize: 4096}}, `""`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := s3a.getObjectETag(tt.entry); got != tt.want {
t.Errorf("getObjectETag() = %s, want %s", got, tt.want)
}
})
}
}
+58 -3
View File
@@ -183,7 +183,24 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
}
objectContentType := r.Header.Get("Content-Type")
if strings.HasSuffix(object, "/") && r.ContentLength <= 1024 {
isDirectoryMarker := strings.HasSuffix(object, "/")
if isDirectoryMarker && directoryMarkerBodySize(r) > maxDirectoryMarkerContentSize {
// Past what a marker holds, only a versioned write keeps the key whole.
// Otherwise the body is refused before any of it is read; one of unknown
// length is checked as it is read, below.
versioningState, vErr := s3a.getVersioningState(bucket)
if vErr != nil && !errors.Is(vErr, filer_pb.ErrNotFound) {
glog.Errorf("PutObjectHandler: failed to check versioning for bucket %s: %v", bucket, vErr)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
if versioningState != s3_constants.VersioningEnabled {
s3err.WriteErrorResponse(w, r, s3err.ErrEntityTooLarge)
return
}
isDirectoryMarker = false
}
if isDirectoryMarker {
// The filer mkdir below would implicitly create a missing bucket, so gate it
// on the same auto-create policy as regular uploads.
if err := s3a.checkBucket(r, bucket); err == s3err.ErrNoSuchBucket {
@@ -229,11 +246,12 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
fullDirPath = fullDirPath + "/" + dirName
}
// Read any content through dataReader (handles chunked encoding properly)
// Read any content through dataReader (handles chunked encoding properly),
// never more than a marker holds plus the byte that proves it too large.
var dirContent []byte
if r.ContentLength != 0 {
var readErr error
dirContent, readErr = io.ReadAll(dataReader)
dirContent, readErr = io.ReadAll(io.LimitReader(dataReader, maxDirectoryMarkerContentSize+1))
if readErr != nil {
glog.Errorf("PutObjectHandler: failed to read directory marker content %s/%s: %v", bucket, object, readErr)
if strings.Contains(readErr.Error(), s3err.ErrMsgContentSha256Mismatch) {
@@ -245,6 +263,10 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
}
return
}
if len(dirContent) > maxDirectoryMarkerContentSize {
s3err.WriteErrorResponse(w, r, s3err.ErrEntityTooLarge)
return
}
}
// ETag of the marker content, empty or not
@@ -363,6 +385,13 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
}
}
// A "dir/" key gets here only past what a marker holds; recheck against
// the state this write uses, in case versioning changed since.
if strings.HasSuffix(object, "/") && versioningState != s3_constants.VersioningEnabled {
s3err.WriteErrorResponse(w, r, s3err.ErrEntityTooLarge)
return
}
var aclCode s3err.ErrorCode
r, aclCode = s3a.preparePutObjectACL(r, bucket)
if aclCode != s3err.ErrNone {
@@ -473,6 +502,27 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
writeSuccessResponseEmpty(w, r)
}
// maxDirectoryMarkerContentSize is the most content a "dir/" marker can carry. The
// key is stored as the filer directory itself, its content inline in the entry,
// where every listing of the parent and every metadata subscriber receives it.
// Only a versioning-enabled bucket takes a larger body, as a versioned object:
// the unversioned paths name the entry by the last path element, so "dir/"
// would land on the object "dir/dir".
const maxDirectoryMarkerContentSize = 1024
// directoryMarkerBodySize is the length the body of a "dir/" PUT declares, or -1
// when it declares none. An aws-chunked body counts by its decoded length, which
// getRequestDataReader holds it to, never by the encoded Content-Length.
func directoryMarkerBodySize(r *http.Request) int64 {
if isAwsChunkedUpload(r) {
if decoded, ok := decodedContentLength(r); ok {
return decoded
}
return -1
}
return r.ContentLength
}
func (s3a *S3ApiServer) withObjectWriteLock(bucket, object string, preconditionFn func() s3err.ErrorCode, fn func() s3err.ErrorCode) s3err.ErrorCode {
runPrecondition := func() s3err.ErrorCode {
if preconditionFn == nil {
@@ -2917,6 +2967,11 @@ func objectETag(entry *filer_pb.Entry) string {
if entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
return fmt.Sprintf("\"%x\"", entry.Attributes.Md5)
}
// No stored MD5 and no chunks: the bytes are the inline content, possibly
// none (an empty file written through a mount), and the ETag is their MD5
if etag, ok := filer.ETagOfInlineContent(entry); ok {
return quoteETag(etag)
}
// Fallback: calculate ETag from chunks
if len(entry.Chunks) == 0 {
return `""`
@@ -0,0 +1,235 @@
package s3api
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/require"
)
// The most content a "dir/" key keeps inline in its directory entry.
const testMarkerContentLimit = 1024
// byteCountingBody counts the bytes a handler reads of the request body.
type byteCountingBody struct {
r io.Reader
read atomic.Int64
}
func (b *byteCountingBody) Read(p []byte) (int, error) {
n, err := b.r.Read(p)
b.read.Add(int64(n))
return n, err
}
func (b *byteCountingBody) Close() error { return nil }
// markerDrainProbe notes how many body bytes the handler had read when
// WriteErrorResponse starts draining the rest.
type markerDrainProbe struct {
*httptest.ResponseRecorder
body *byteCountingBody
readAtDrain int64
}
func (p *markerDrainProbe) SetReadDeadline(time.Time) error {
if p.readAtDrain < 0 {
p.readAtDrain = p.body.read.Load()
}
return nil
}
// The ways a client can send the body of a "dir/" PUT: with its length
// declared, or streamed without one, plainly or aws-chunked as an SDK sends it
// with a checksum trailer. An aws-chunked body declares its decoded length in
// X-Amz-Decoded-Content-Length; its Content-Length, when sent, is the encoded
// length, which is larger.
var dirKeyBodyRequests = []struct {
name string
declared bool
new func(payload []byte) *http.Request
}{
{"content-length", true, func(payload []byte) *http.Request {
req := httptest.NewRequest(http.MethodPut, "/b/dir/", bytes.NewReader(payload))
req.ContentLength = int64(len(payload))
return req
}},
{"transfer-encoding chunked", false, func(payload []byte) *http.Request {
req := httptest.NewRequest(http.MethodPut, "/b/dir/", bytes.NewReader(payload))
req.ContentLength = -1
req.TransferEncoding = []string{"chunked"}
return req
}},
{"aws-chunked", true, func(payload []byte) *http.Request {
req := unsignedChunkedRequest(string(payload), strconv.Itoa(len(payload)))
req.URL.Path = "/b/dir/"
return req
}},
{"aws-chunked with encoded content-length", true, func(payload []byte) *http.Request {
req := unsignedChunkedRequest(string(payload), strconv.Itoa(len(payload)))
req.URL.Path = "/b/dir/"
encoded, _ := io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewReader(encoded))
req.ContentLength = int64(len(encoded))
return req
}},
{"aws-chunked without decoded length", false, func(payload []byte) *http.Request {
req := unsignedChunkedRequest(string(payload), "")
req.URL.Path = "/b/dir/"
encoded, _ := io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewReader(encoded))
req.ContentLength = int64(len(encoded))
return req
}},
}
func newDirKeyPut(new func([]byte) *http.Request, payload []byte) (*http.Request, *markerDrainProbe) {
req := new(payload)
body := &byteCountingBody{r: req.Body}
req.Body = body
req = mux.SetURLVars(req, map[string]string{"bucket": "b", "object": "dir/"})
return req, &markerDrainProbe{ResponseRecorder: httptest.NewRecorder(), body: body, readAtDrain: -1}
}
// A "dir/" key is stored as the directory itself, so a body larger than a
// marker holds is refused, however its length is sent: one of unknown length
// is not read whole into memory and stored inline in the directory entry, and
// none lands on the object "dir/dir" as the regular upload path would put it.
func TestPutObjectDirectoryKeyRefusesBodyLargerThanMarker(t *testing.T) {
for _, tc := range dirKeyBodyRequests {
for _, size := range []int{testMarkerContentLimit + 1, 8 << 20} {
t.Run(fmt.Sprintf("%s/%d bytes", tc.name, size), func(t *testing.T) {
s3a, filer, volume := newHeaderTestServer(t, "")
child := httptest.NewRequest(http.MethodPut, "/b/dir/dir", strings.NewReader("child object"))
child.ContentLength = int64(len("child object"))
child = mux.SetURLVars(child, map[string]string{"bucket": "b", "object": "dir/dir"})
s3a.PutObjectHandler(httptest.NewRecorder(), child)
filer.mu.Lock()
require.NotNil(t, filer.entries["/buckets/b/dir/dir"], "object dir/dir not created")
childMd5 := filer.entries["/buckets/b/dir/dir"].Attributes.GetMd5()
filer.mu.Unlock()
storedBefore := volume.storedCount()
req, probe := newDirKeyPut(tc.new, bytes.Repeat([]byte("m"), size))
s3a.PutObjectHandler(probe, req)
apiErr := s3err.GetAPIError(s3err.ErrEntityTooLarge)
require.Equal(t, apiErr.HTTPStatusCode, probe.Code, probe.Body.String())
require.Contains(t, probe.Body.String(), "<Code>"+apiErr.Code+"</Code>")
if tc.declared {
require.Zero(t, probe.readAtDrain, "body bytes read before refusing a declared length")
} else {
// The chunked reader buffers ahead; what matters is that the
// body is not read whole.
require.Less(t, probe.readAtDrain, int64(64<<10), "body bytes read before refusing it")
}
require.Equal(t, storedBefore, volume.storedCount(), "chunks stored on the volume server")
filer.mu.Lock()
defer filer.mu.Unlock()
require.Nil(t, filer.entries["/buckets/b/dir"], "directory marker created")
require.Equal(t, childMd5, filer.entries["/buckets/b/dir/dir"].Attributes.GetMd5(), "object dir/dir overwritten")
})
}
}
}
// A "dir/" PUT declaring more than a marker holds used to take the regular
// upload path, which names the entry by its last path element: it answered 200,
// left "dir/" missing, and wrote the bytes to the object "dir/dir", replacing
// one already there. It is refused now, and neither key changes.
func TestPutObjectDirectoryKeyWithDeclaredLargeBodyLeavesDirDirAlone(t *testing.T) {
for _, existing := range []bool{false, true} {
t.Run(fmt.Sprintf("dir/dir exists=%v", existing), func(t *testing.T) {
s3a, filer, _ := newHeaderTestServer(t, "")
var childMd5 []byte
if existing {
child := httptest.NewRequest(http.MethodPut, "/b/dir/dir", strings.NewReader("child object"))
child.ContentLength = int64(len("child object"))
child = mux.SetURLVars(child, map[string]string{"bucket": "b", "object": "dir/dir"})
s3a.PutObjectHandler(httptest.NewRecorder(), child)
filer.mu.Lock()
require.NotNil(t, filer.entries["/buckets/b/dir/dir"], "object dir/dir not created")
childMd5 = filer.entries["/buckets/b/dir/dir"].Attributes.GetMd5()
filer.mu.Unlock()
}
req, probe := newDirKeyPut(dirKeyBodyRequests[0].new, bytes.Repeat([]byte("m"), 2000))
s3a.PutObjectHandler(probe, req)
filer.mu.Lock()
child := filer.entries["/buckets/b/dir/dir"]
if existing {
require.NotNil(t, child, "object dir/dir removed")
require.Equal(t, childMd5, child.Attributes.GetMd5(), "PUT dir/ overwrote the object dir/dir")
} else {
require.Nil(t, child, "PUT dir/ created the object dir/dir")
}
require.Nil(t, filer.entries["/buckets/b/dir"], "directory marker created")
filer.mu.Unlock()
apiErr := s3err.GetAPIError(s3err.ErrEntityTooLarge)
require.Equal(t, apiErr.HTTPStatusCode, probe.Code, probe.Body.String())
require.Contains(t, probe.Body.String(), "<Code>"+apiErr.Code+"</Code>")
})
}
}
// A marker small enough to keep inline stays a marker however its length is
// sent; an aws-chunked one counts by its decoded length.
func TestPutObjectDirectoryKeyKeepsMarkerUpToLimit(t *testing.T) {
for _, tc := range dirKeyBodyRequests {
for _, size := range []int{0, 100, testMarkerContentLimit} {
if size == 0 && tc.name != "content-length" && tc.name != "transfer-encoding chunked" {
continue // an aws-chunked body carries at least one data chunk
}
t.Run(fmt.Sprintf("%s/%d bytes", tc.name, size), func(t *testing.T) {
s3a, filer, volume := newHeaderTestServer(t, "")
payload := bytes.Repeat([]byte("m"), size)
req, probe := newDirKeyPut(tc.new, payload)
s3a.PutObjectHandler(probe, req)
require.Equal(t, http.StatusOK, probe.Code, probe.Body.String())
require.Equal(t, []string{fmt.Sprintf("%q", fmt.Sprintf("%x", util.Md5(payload)))}, probe.Header()["ETag"])
require.Zero(t, volume.storedCount(), "a marker uploads no chunks")
filer.mu.Lock()
defer filer.mu.Unlock()
marker := filer.entries["/buckets/b/dir"]
require.NotNil(t, marker, "directory marker not created")
require.True(t, marker.IsDirectory)
require.Equal(t, payload, append([]byte{}, marker.Content...))
require.Nil(t, filer.entries["/buckets/b/dir/dir"], "the marker was written as the object dir/dir")
})
}
}
}
// A suspended bucket writes the null version of "dir/" through the unversioned
// path, which would land on "dir/dir", so a body past what a marker holds is
// refused there too. Only a versioning-enabled bucket stores it, as a version.
func TestPutObjectDirectoryKeyLargerThanMarkerInSuspendedBucket(t *testing.T) {
s3a, filer, volume := newHeaderTestServer(t, s3_constants.VersioningSuspended)
req, probe := newDirKeyPut(dirKeyBodyRequests[0].new, bytes.Repeat([]byte("v"), 2000))
s3a.PutObjectHandler(probe, req)
apiErr := s3err.GetAPIError(s3err.ErrEntityTooLarge)
require.Equal(t, apiErr.HTTPStatusCode, probe.Code, probe.Body.String())
require.Zero(t, probe.readAtDrain, "body bytes read before refusing a declared length")
require.Zero(t, volume.storedCount(), "chunks stored on the volume server")
filer.mu.Lock()
defer filer.mu.Unlock()
require.Nil(t, filer.entries["/buckets/b/dir"], "directory marker created")
require.Nil(t, filer.entries["/buckets/b/dir/dir"], "PUT dir/ created the object dir/dir")
}
@@ -72,6 +72,9 @@ type cursorFile struct {
RuleSetHash []byte `json:"rule_set_hash"`
PromotedHash []byte `json:"promoted_hash"`
LastWalkedNs int64 `json:"last_walked_ns,omitempty"`
// SavedNs changes on every save, so the file's mtime shows the shard
// is live even while its position stays put.
SavedNs int64 `json:"saved_ns,omitempty"`
}
// CursorPersister loads and saves daily-replay cursors. The Phase 2
@@ -150,6 +153,7 @@ func (p *FilerCursorPersister) Save(ctx context.Context, shardID int, c Cursor)
RuleSetHash: c.RuleSetHash[:],
PromotedHash: c.PromotedHash[:],
LastWalkedNs: c.LastWalkedNs,
SavedNs: time.Now().UnixNano(),
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
@@ -183,3 +183,18 @@ func TestFilerCursorPersister_FullPassRejectsUnknownVersion(t *testing.T) {
_, _, err := (&FilerCursorPersister{Store: store}).LoadFullPass(context.Background())
assert.Error(t, err)
}
func TestFilerCursorPersister_UnchangedCursorStillRewritten(t *testing.T) {
store := newFakeStore()
p := &FilerCursorPersister{Store: store}
c := Cursor{TsNs: 1700000000_000000123}
require.NoError(t, p.Save(context.Background(), 3, c))
first := string(store.files[store.key(CursorDir, cursorFileName(3))])
time.Sleep(time.Millisecond)
require.NoError(t, p.Save(context.Background(), 3, c))
assert.NotEqual(t, first, string(store.files[store.key(CursorDir, cursorFileName(3))]), "an unchanged cursor must still rewrite its file so its mtime advances")
got, found, err := p.Load(context.Background(), 3)
require.NoError(t, err)
require.True(t, found)
assert.Equal(t, c, got)
}
@@ -49,19 +49,22 @@ type walkCheckpointFile struct {
SavedNs int64 `json:"saved_ns,omitempty"`
}
// WalkCheckpointPrefix starts the name of every walk checkpoint in CursorDir.
const WalkCheckpointPrefix = "walk-"
func walkCheckpointFileName(shards []int) string {
contiguous := len(shards) > 1
for i := 1; i < len(shards); i++ {
contiguous = contiguous && shards[i] == shards[i-1]+1
}
if contiguous {
return fmt.Sprintf("walk-%02d-%02d.json", shards[0], shards[len(shards)-1])
return fmt.Sprintf(WalkCheckpointPrefix+"%02d-%02d.json", shards[0], shards[len(shards)-1])
}
parts := make([]string, len(shards))
for i, sh := range shards {
parts[i] = fmt.Sprintf("%02d", sh)
}
return "walk-" + strings.Join(parts, "_") + ".json"
return WalkCheckpointPrefix + strings.Join(parts, "_") + ".json"
}
func (p *FilerCursorPersister) LoadWalk(ctx context.Context, shards []int) (WalkCheckpoint, bool, error) {
@@ -143,11 +146,12 @@ func loadWalkProgress(ctx context.Context, store WalkCheckpointPersister, view *
sorted := slices.Clone(shards)
slices.Sort(sorted)
now := time.Now()
// A fresh walk saves at its first progress: until then no record holds
// the metadata log its completion will replay.
w := &walkProgress{
store: store,
cp: WalkCheckpoint{ViewHash: engine.WalkContentHash(view), Shards: sorted, Resume: map[string]string{}, StartedAt: now},
done: map[string]bool{},
savedAt: now,
store: store,
cp: WalkCheckpoint{ViewHash: engine.WalkContentHash(view), Shards: sorted, Resume: map[string]string{}, StartedAt: now},
done: map[string]bool{},
}
if store == nil {
return w
@@ -182,6 +186,7 @@ func loadWalkProgress(ctx context.Context, store WalkCheckpointPersister, view *
w.cp.SavedAt = saved.SavedAt
w.resumed = len(w.done) > 0 || len(w.cp.Resume) > 0
if w.resumed {
w.savedAt = now
w.cp.StartedAt = saved.StartedAt
glog.V(0).Infof("walker: shards %v resume with %d bucket(s) done and %d partly walked", sorted, len(w.done), len(w.cp.Resume))
}
@@ -328,6 +328,21 @@ func TestWalkBuckets_ResumesFromPeriodicSave(t *testing.T) {
assert.Zero(t, left)
}
func TestWalkProgress_FreshWalkSavesAtFirstProgress(t *testing.T) {
h := newCheckpointHarness(t)
view := checkpointTestView(t, "")
w := loadWalkProgress(context.Background(), h.p, view, allShards(), []string{"a", "b"})
w.bucketDone(context.Background(), "a")
require.Len(t, h.store.saves, 1, "a walk that stalls after its first bucket must already hold the log")
w.bucketDone(context.Background(), "b")
assert.Len(t, h.store.saves, 1, "later saves wait for the interval")
resumed := loadWalkProgress(context.Background(), h.p, view, allShards(), []string{"a", "b", "c"})
require.True(t, resumed.resumed)
resumed.bucketDone(context.Background(), "c")
assert.Len(t, h.store.saves, 1, "a resumed walk already has its record on disk")
}
func TestWalkProgress_FailedPeriodicSaveWaitsForTheInterval(t *testing.T) {
h := newCheckpointHarness(t)
h.store.failAll = true
+80
View File
@@ -0,0 +1,80 @@
package weed_server
import (
"context"
"errors"
"strings"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
)
// FilerGrpcMetricsServerOptions returns the gRPC server options that count the
// filer's gRPC calls and time them (SeaweedFS_filer_grpc_request_total and
// SeaweedFS_filer_grpc_request_seconds). The mounts and the S3 gateway work
// through this port: without it the filer's request metrics show its HTTP API
// and say nothing of a lookup, a create, a rename or a listing they send.
//
// The options go before the interceptors that may refuse a call, so a refused
// call is counted with its code.
func FilerGrpcMetricsServerOptions() []grpc.ServerOption {
return []grpc.ServerOption{
grpc.ChainUnaryInterceptor(filerGrpcMetricsUnary),
grpc.ChainStreamInterceptor(filerGrpcMetricsStream),
}
}
func filerGrpcMetricsUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
start := time.Now()
resp, err := handler(ctx, req)
method := filerGrpcMethodLabel(info.FullMethod)
stats.FilerGrpcRequestCounter.WithLabelValues(method, filerGrpcCodeLabel(err)).Inc()
stats.FilerGrpcRequestHistogram.WithLabelValues(method).Observe(time.Since(start).Seconds())
return resp, err
}
// A stream is counted when it ends, and timed unless the client holds it open
// for as long as it runs: how long a subscription lasted says nothing about
// the filer, and would fill the top bucket.
func filerGrpcMetricsStream(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
start := time.Now()
err := handler(srv, ss)
method := filerGrpcMethodLabel(info.FullMethod)
stats.FilerGrpcRequestCounter.WithLabelValues(method, filerGrpcCodeLabel(err)).Inc()
if !info.IsClientStream && !strings.HasPrefix(method, "Subscribe") && method != "grpc.health.v1.Health/Watch" {
stats.FilerGrpcRequestHistogram.WithLabelValues(method).Observe(time.Since(start).Seconds())
}
return err
}
// filerGrpcMethodLabel names a call by its method for the filer's own
// service, "CreateEntry" for "/filer_pb.SeaweedFiler/CreateEntry", and by
// service and method for any other service on the port.
func filerGrpcMethodLabel(fullMethod string) string {
name := strings.TrimPrefix(fullMethod, "/")
if method, ok := strings.CutPrefix(name, "filer_pb.SeaweedFiler/"); ok {
return method
}
return name
}
// filerGrpcCodeLabel is the gRPC status code a call ends with. A lookup of a
// name that does not exist returns filer_pb.ErrNotFound as it is, which
// carries no status and reaches the client as Unknown; it is labelled
// NotFound, so that the everyday miss stays apart from the errors nothing
// names.
func filerGrpcCodeLabel(err error) string {
if errors.Is(err, filer_pb.ErrNotFound) {
return codes.NotFound.String()
}
s, ok := status.FromError(err)
if !ok {
s = status.FromContextError(err)
}
return s.Code().String()
}
+168
View File
@@ -0,0 +1,168 @@
package weed_server
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
)
func grpcRequests(method, code string) float64 {
return testutil.ToFloat64(stats.FilerGrpcRequestCounter.WithLabelValues(method, code))
}
// grpcTimed is how many calls of method the histogram has observed.
func grpcTimed(t *testing.T, method string) uint64 {
t.Helper()
families, err := stats.Gather.Gather()
if err != nil {
t.Fatalf("gather: %v", err)
}
for _, family := range families {
if family.GetName() != "SeaweedFS_filer_grpc_request_seconds" {
continue
}
for _, metric := range family.GetMetric() {
for _, label := range metric.GetLabel() {
if label.GetName() == "method" && label.GetValue() == method {
return metric.GetHistogram().GetSampleCount()
}
}
}
}
return 0
}
// A unary call is counted under its method and the status code it ends with,
// and timed, whether the handler answers or fails.
func TestFilerGrpcMetricsCountUnaryCallsByMethodAndCode(t *testing.T) {
info := &grpc.UnaryServerInfo{FullMethod: "/filer_pb.SeaweedFiler/MetricsTestUnary"}
ok0, aborted0, unknown0 := grpcRequests("MetricsTestUnary", "OK"), grpcRequests("MetricsTestUnary", "Aborted"), grpcRequests("MetricsTestUnary", "Unknown")
timed0 := grpcTimed(t, "MetricsTestUnary")
resp, err := filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) {
return "resp", nil
})
if resp != "resp" || err != nil {
t.Fatalf("the handler's answer did not come through: %v, %v", resp, err)
}
conflict := status.Error(codes.Aborted, "transaction conflict")
if _, err := filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) {
return nil, conflict
}); err != conflict {
t.Fatalf("the handler's error did not come through: %v", err)
}
// an error without a gRPC status is what the client sees as Unknown
filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) {
return nil, errors.New("plain")
})
if got := grpcRequests("MetricsTestUnary", "OK") - ok0; got != 1 {
t.Errorf("OK calls counted: %v, want 1", got)
}
if got := grpcRequests("MetricsTestUnary", "Aborted") - aborted0; got != 1 {
t.Errorf("Aborted calls counted: %v, want 1", got)
}
if got := grpcRequests("MetricsTestUnary", "Unknown") - unknown0; got != 1 {
t.Errorf("Unknown calls counted: %v, want 1", got)
}
if got := grpcTimed(t, "MetricsTestUnary") - timed0; got != 3 {
t.Errorf("calls timed: %d, want 3", got)
}
}
// A stream is counted when it ends. A listing is timed; a subscription or a
// health watch, which the client holds open, and a client stream are not.
func TestFilerGrpcMetricsCountStreamsAndTimeTheFiniteOnes(t *testing.T) {
run := func(method string, clientStream bool, err error) {
fullMethod := "/filer_pb.SeaweedFiler/" + method
if strings.Contains(method, "/") {
fullMethod = "/" + method
}
info := &grpc.StreamServerInfo{FullMethod: fullMethod, IsServerStream: true, IsClientStream: clientStream}
if got := filerGrpcMetricsStream(nil, nil, info, func(srv any, stream grpc.ServerStream) error { return err }); got != err {
t.Fatalf("%s: the handler's error did not come through: %v", method, got)
}
}
tests := []struct {
method string
clientStream bool
err error
code string
timed uint64
}{
{"MetricsTestList", false, nil, "OK", 1},
{"SubscribeMetricsTest", false, status.Error(codes.Canceled, "client left"), "Canceled", 0},
{"MetricsTestBidi", true, nil, "OK", 0},
{"grpc.health.v1.Health/Watch", false, status.Error(codes.Canceled, "client left"), "Canceled", 0},
}
for _, tt := range tests {
counted0, timed0 := grpcRequests(tt.method, tt.code), grpcTimed(t, tt.method)
run(tt.method, tt.clientStream, tt.err)
if got := grpcRequests(tt.method, tt.code) - counted0; got != 1 {
t.Errorf("%s: %s streams counted: %v, want 1", tt.method, tt.code, got)
}
if got := grpcTimed(t, tt.method) - timed0; got != tt.timed {
t.Errorf("%s: streams timed: %d, want %d", tt.method, got, tt.timed)
}
}
}
// A lookup that finds nothing returns filer_pb.ErrNotFound without a status:
// it is counted as NotFound, not with the errors that have no code.
func TestFilerGrpcMetricsCountAMissAsNotFound(t *testing.T) {
info := &grpc.UnaryServerInfo{FullMethod: "/filer_pb.SeaweedFiler/MetricsTestLookup"}
notFound0, unknown0 := grpcRequests("MetricsTestLookup", "NotFound"), grpcRequests("MetricsTestLookup", "Unknown")
for _, err := range []error{filer_pb.ErrNotFound, fmt.Errorf("lookup /a/b: %w", filer_pb.ErrNotFound)} {
if _, got := filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) {
return nil, err
}); got != err {
t.Fatalf("the handler's error did not come through: %v", got)
}
}
if got := grpcRequests("MetricsTestLookup", "NotFound") - notFound0; got != 2 {
t.Errorf("NotFound calls counted: %v, want 2", got)
}
if got := grpcRequests("MetricsTestLookup", "Unknown") - unknown0; got != 0 {
t.Errorf("Unknown calls counted: %v, want 0", got)
}
}
// A handler that returns its context's error reaches the client as Canceled or
// DeadlineExceeded, and is counted so, wrapped or not.
func TestFilerGrpcMetricsCountContextErrorsAsTheClientSeesThem(t *testing.T) {
for err, want := range map[error]string{
context.Canceled: "Canceled",
context.DeadlineExceeded: "DeadlineExceeded",
fmt.Errorf("batch: %w", context.Canceled): "Canceled",
fmt.Errorf("cache: %w", context.DeadlineExceeded): "DeadlineExceeded",
fmt.Errorf("op: %w", status.Error(codes.Aborted, "conflict")): "Aborted",
errors.New("plain"): "Unknown",
} {
if got := filerGrpcCodeLabel(err); got != want {
t.Errorf("filerGrpcCodeLabel(%v) = %q, want %q", err, got, want)
}
}
}
func TestFilerGrpcMethodLabel(t *testing.T) {
for full, want := range map[string]string{
"/filer_pb.SeaweedFiler/CreateEntry": "CreateEntry",
"/filer_pb.SeaweedFiler/ListEntries": "ListEntries",
"/iam_pb.SeaweedIdentityAccessManagement/GetUser": "iam_pb.SeaweedIdentityAccessManagement/GetUser",
"/grpc.health.v1.Health/Check": "grpc.health.v1.Health/Check",
} {
if got := filerGrpcMethodLabel(full); got != want {
t.Errorf("filerGrpcMethodLabel(%q) = %q, want %q", full, got, want)
}
}
}
@@ -0,0 +1,566 @@
package weed_server
import (
"context"
"fmt"
"net"
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/filer/posixlock"
"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/status"
)
const posixOwnershipKey = scopePosixLockKeyPrefix + "/locks/file"
type posixTestClock struct {
mu sync.Mutex
now time.Time
}
func (c *posixTestClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
// posixOwnershipHarness serves a real FilerServer PosixLock handler behind the
// scope interceptor, with the lock manager on a controllable clock.
type posixOwnershipHarness struct {
t *testing.T
fs *FilerServer
clock *posixTestClock
start time.Time
addr string
keys atomic.Value // [2]string: current and previous verification key
}
func newPosixOwnershipHarness(t *testing.T, leeway time.Duration) *posixOwnershipHarness {
t.Helper()
h := &posixOwnershipHarness{t: t, clock: &posixTestClock{now: time.Now()}}
h.start = h.clock.Now()
h.fs = newPosixTestServer(t)
h.fs.posixLocks = posixlock.NewManagerWithClock(h.clock.Now)
h.keys.Store([2]string{scopeTestKey, ""})
sc := newFilerGrpcScope(scopeConfig{
verificationKeys: func() (security.SigningKey, security.SigningKey) {
keys := h.keys.Load().([2]string)
return security.SigningKey(keys[0]), security.SigningKey(keys[1])
},
leeway: func() time.Duration { return leeway },
}, h.fs)
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer(sc.ServerOptions()...)
filer_pb.RegisterSeaweedFilerServer(srv, h.fs)
go func() { _ = srv.Serve(lis) }()
t.Cleanup(func() { srv.Stop(); _ = lis.Close() })
h.addr = lis.Addr().String()
return h
}
// at moves the lock manager's clock to d after the harness start.
func (h *posixOwnershipHarness) at(d time.Duration) {
h.clock.mu.Lock()
defer h.clock.mu.Unlock()
h.clock.now = h.start.Add(d)
}
func (h *posixOwnershipHarness) client(token string) filer_pb.SeaweedFilerClient {
h.t.Helper()
conn, err := grpc.NewClient("passthrough:///"+h.addr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(scopeToken(token)))
if err != nil {
h.t.Fatal(err)
}
h.t.Cleanup(func() { _ = conn.Close() })
return filer_pb.NewSeaweedFilerClient(conn)
}
func (h *posixOwnershipHarness) call(c filer_pb.SeaweedFilerClient, key string, op filer_pb.PosixLockOp, lk *filer_pb.PosixLockRange, held ...*filer_pb.PosixLockRange) (*filer_pb.PosixLockResponse, error) {
return c.PosixLock(scopeCtx(h.t), &filer_pb.PosixLockRequest{Key: key, Op: op, Lock: lk, Locks: held})
}
func (h *posixOwnershipHarness) must(c filer_pb.SeaweedFilerClient, key string, op filer_pb.PosixLockOp, lk *filer_pb.PosixLockRange, held ...*filer_pb.PosixLockRange) *filer_pb.PosixLockResponse {
h.t.Helper()
resp, err := h.call(c, key, op, lk, held...)
if err != nil {
h.t.Fatalf("PosixLock %v: %v", op, err)
}
return resp
}
func (h *posixOwnershipHarness) held(key string) []posixlock.Range {
return h.fs.posixLocks.Snapshot()[key]
}
// grantable reports whether a fresh scoped holder could take lk's range now.
func (h *posixOwnershipHarness) grantable(key string, flock bool) bool {
h.t.Helper()
probe := h.client(scopedToken("newcomer", time.Hour, []string{"/locks"}, nil))
resp := h.must(probe, key, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 50, 51, 9, flock))
return !resp.GetHasConflict()
}
func expectPosixCode(t *testing.T, what string, err error, code codes.Code) {
t.Helper()
if status.Code(err) != code {
t.Fatalf("%s: got %v, want %v", what, err, code)
}
}
func TestScopedPosixLockSurvivesReplayOfItsDisclosedIdentity(t *testing.T) {
intruders := []struct {
name string
token func() string
}{
{name: "another scoped token", token: func() string { return scopedToken("intruder", time.Hour, []string{"/locks"}, nil) }},
{name: "tokenless", token: func() string { return "" }},
{name: "unscoped token", token: unscopedToken},
}
attacks := []struct {
name string
op filer_pb.PosixLockOp
lock func(known *filer_pb.PosixLockRange) *filer_pb.PosixLockRange
held bool
}{
{name: "partial unlock", op: filer_pb.PosixLockOp_UNLOCK, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange {
return pbLock(10, 20, posixlock.Unlock, k.Sid, k.Owner, 8, k.IsFlock)
}},
{name: "release posix owner", op: filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { return k }},
{name: "release flock owner", op: filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange { return k }},
{name: "bare keepalive", op: filer_pb.PosixLockOp_KEEP_ALIVE, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange {
return &filer_pb.PosixLockRange{Sid: k.Sid}
}},
{name: "reassertion", op: filer_pb.PosixLockOp_KEEP_ALIVE, held: true, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange {
return &filer_pb.PosixLockRange{Sid: k.Sid}
}},
{name: "try lock", op: filer_pb.PosixLockOp_TRY_LOCK, lock: func(k *filer_pb.PosixLockRange) *filer_pb.PosixLockRange {
return pbLock(0, 99, posixlock.Write, k.Sid, k.Owner, 8, k.IsFlock)
}},
}
for _, flock := range []bool{false, true} {
for _, intruder := range intruders {
for _, attack := range attacks {
name := map[bool]string{false: "fcntl", true: "flock"}[flock] + "/" + intruder.name + "/" + attack.name
t.Run(name, func(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
if !h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock)).Granted {
t.Fatal("holder's acquisition refused")
}
before := h.held(posixOwnershipKey)
c := h.client(intruder.token())
query := pbLock(0, 99, posixlock.Write, 3, 4, 8, flock)
known := h.must(c, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, query).GetConflict()
if known.GetSid() != 1 || known.GetOwner() != 2 || known.GetPid() != 7 {
t.Fatalf("GET_LK should disclose the holder, got %+v", known)
}
h.at(10 * time.Second)
var held []*filer_pb.PosixLockRange
if attack.held {
held = []*filer_pb.PosixLockRange{pbLock(0, 99, posixlock.Write, known.Sid, known.Owner, 8, flock)}
}
resp := h.must(c, posixOwnershipKey, attack.op, attack.lock(known), held...)
if resp.GetGranted() {
t.Fatal("the holder's identity must not grant another caller its lock")
}
if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) {
t.Fatalf("holder's locks changed:\n got %+v\nwant %+v", got, before)
}
if !h.must(c, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, known.Sid, known.Owner, 8, flock)).GetHasConflict() {
t.Fatal("the disclosed identity must still conflict for another caller")
}
// The intruder renewed nothing: the holder's lease still ends 15s
// after its acquisition.
h.at(15*time.Second - time.Nanosecond)
if h.grantable(posixOwnershipKey, flock) {
t.Fatal("holder's lease must last until its deadline")
}
h.at(15 * time.Second)
if !h.grantable(posixOwnershipKey, flock) {
t.Fatal("holder's lease was extended by another caller")
}
})
}
}
}
}
func TestScopedPosixLockHolderUnlocksReleasesAndRenewsItsOwnLocks(t *testing.T) {
for _, flock := range []bool{false, true} {
t.Run(map[bool]string{false: "fcntl", true: "flock"}[flock], func(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock))
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(10, 20, posixlock.Unlock, 1, 2, 7, flock))
if got := h.held(posixOwnershipKey); len(got) != 2 || got[0].End != 9 || got[1].Start != 21 {
t.Fatalf("partial unlock should split the holder's range, got %+v", got)
}
release := filer_pb.PosixLockOp_RELEASE_POSIX_OWNER
if flock {
release = filer_pb.PosixLockOp_RELEASE_FLOCK_OWNER
}
h.must(holder, posixOwnershipKey, release, pbLock(0, 0, posixlock.Unlock, 1, 2, 7, flock))
if got := h.held(posixOwnershipKey); len(got) != 0 {
t.Fatalf("owner release should drop the holder's locks, got %+v", got)
}
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock))
h.at(10 * time.Second)
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1})
h.at(20 * time.Second)
if h.grantable(posixOwnershipKey, flock) {
t.Fatal("a bare keepalive should renew the holder's lease")
}
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, flock))
h.at(35*time.Second - time.Nanosecond)
if h.grantable(posixOwnershipKey, flock) {
t.Fatal("a reassertion should renew the holder's lease")
}
h.at(35 * time.Second)
if !h.grantable(posixOwnershipKey, flock) {
t.Fatal("the lease should end 15s after the last renewal")
}
})
}
}
func TestScopedPosixLockLeaseEndsAtTokenExpiryPlusLeeway(t *testing.T) {
const leeway = 2 * time.Second
h := newPosixOwnershipHarness(t, leeway)
exp := time.Now().Add(time.Hour).Truncate(time.Second)
h.start = exp.Add(-5 * time.Second)
h.at(0)
holder := h.client(signedScopeClaims(t, scopeTestKey, security.SeaweedFilerClaims{
AllowedPrefixes: []string{"/locks"},
RegisteredClaims: jwt.RegisteredClaims{ID: "holder", ExpiresAt: jwt.NewNumericDate(exp)},
}))
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
h.at(time.Second)
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1})
h.at(5*time.Second + leeway - time.Nanosecond)
if h.grantable(posixOwnershipKey, false) {
t.Fatal("the lease should last until the token's expiry plus leeway")
}
h.at(5*time.Second + leeway)
if !h.grantable(posixOwnershipKey, false) {
t.Fatal("a renewal must not extend the lease past the token's expiry plus leeway")
}
}
func TestScopedPosixLockRenewalWithNarrowerGrantLeavesOtherKeysToExpire(t *testing.T) {
keyA := scopePosixLockKeyPrefix + "/locks/a"
keyB := scopePosixLockKeyPrefix + "/locks/b"
for _, reassert := range []bool{false, true} {
t.Run(map[bool]string{false: "bare keepalive", true: "reassertion"}[reassert], func(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
wide := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(wide, keyA, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
h.must(wide, keyB, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
h.at(10 * time.Second)
narrow := h.client(scopedToken("holder", time.Hour, []string{"/locks/a"}, nil))
var held []*filer_pb.PosixLockRange
if reassert {
held = []*filer_pb.PosixLockRange{pbLock(0, 99, posixlock.Write, 1, 2, 7, false)}
}
h.must(narrow, keyA, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, held...)
_, err := h.call(narrow, keyB, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1})
expectPosixCode(t, "bare keepalive outside the renewed grant", err, codes.PermissionDenied)
_, err = h.call(narrow, keyB, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
expectPosixCode(t, "reassertion outside the renewed grant", err, codes.PermissionDenied)
h.at(15 * time.Second)
if !h.grantable(keyB, false) {
t.Fatal("key b keeps only its previous deadline")
}
if h.grantable(keyA, false) {
t.Fatal("key a was renewed under the narrower grant")
}
h.at(25 * time.Second)
if !h.grantable(keyA, false) {
t.Fatal("key a's lease ends 15s after its renewal")
}
})
}
}
func TestScopeGrantFingerprintIgnoresOrderAndRepetitionOnly(t *testing.T) {
base := []scopeGrant{{path: "/a", readWrite: true}, {path: "/b"}}
same := [][]scopeGrant{
{{path: "/b"}, {path: "/a", readWrite: true}},
{{path: "/a", readWrite: true}, {path: "/b"}, {path: "/a", readWrite: true}},
}
different := [][]scopeGrant{
{{path: "/a", readWrite: true}},
{{path: "/a"}, {path: "/b"}},
{{path: "/a", readWrite: true}, {path: "/b", readWrite: true}},
{{path: "/a", readWrite: true}, {path: "/b/c"}},
{{path: "/a", readWrite: true}, {path: "/b"}, {path: "/b", readWrite: true}},
nil,
}
want := scopeGrantFingerprint(base)
for _, g := range same {
if got := scopeGrantFingerprint(g); got != want {
t.Errorf("%+v should match %+v", g, base)
}
}
for _, g := range different {
if got := scopeGrantFingerprint(g); got == want {
t.Errorf("%+v should not match %+v", g, base)
}
}
}
// A mount renews its keys one keepalive at a time; with many keys a round can
// outlast the lease, so a keepalive renews all of the session's keys taken
// under the same grants, not only the key it names.
func TestScopedPosixLockKeepaliveRenewsTheSessionsKeysUnderTheSameGrants(t *testing.T) {
const keys = 128
key := func(i int) string { return fmt.Sprintf("%s/locks/f%d", scopePosixLockKeyPrefix, i) }
for _, reassert := range []bool{false, true} {
t.Run(map[bool]string{false: "bare keepalive", true: "reassertion"}[reassert], func(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
holder := h.client(scopedToken("holder", time.Hour, []string{"/locks", "/other"}, nil))
for i := 0; i < keys; i++ {
if !h.must(holder, key(i), filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).Granted {
t.Fatalf("key %d refused", i)
}
}
otherSid := scopePosixLockKeyPrefix + "/locks/other-sid"
h.must(holder, otherSid, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 3, 2, 7, false))
// Same grants in another order and a reused id, as a remount sends them.
h.at(10 * time.Second)
remount := h.client(scopedToken("holder", time.Hour, []string{"/other", "/locks", "/locks"}, nil))
var held []*filer_pb.PosixLockRange
if reassert {
held = []*filer_pb.PosixLockRange{pbLock(0, 99, posixlock.Write, 1, 2, 7, false)}
}
h.must(remount, key(0), filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, held...)
probe := h.client(scopedToken("newcomer", time.Hour, []string{"/locks"}, nil))
grantable := func(k string) bool {
return !h.must(probe, k, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 50, 51, 9, false)).GetHasConflict()
}
h.at(25*time.Second - time.Nanosecond)
for i := 0; i < keys; i++ {
if grantable(key(i)) {
t.Fatalf("key %d lapsed although its session renewed under the same grants", i)
}
}
if !grantable(otherSid) {
t.Fatal("another session's lock was renewed")
}
h.at(25 * time.Second)
for i := 0; i < keys; i++ {
if !grantable(key(i)) {
t.Fatalf("key %d outlived the renewed lease", i)
}
}
})
}
}
func TestScopedPosixLockTokenWithNewIdCannotAdoptPreviousLocks(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
old := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(old, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
before := h.held(posixOwnershipKey)
h.at(10 * time.Second)
renewed := h.client(scopedToken("holder-renewed", time.Hour, []string{"/locks"}, nil))
h.must(renewed, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
h.must(renewed, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(0, 99, posixlock.Unlock, 1, 2, 7, false))
if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) {
t.Fatalf("a new token id adopted or released the previous locks: %+v", got)
}
h.at(15 * time.Second)
if !h.must(renewed, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).Granted {
t.Fatal("after expiry the renewed token should reacquire cleanly")
}
}
func TestScopedPosixLockReassertionReportsALostLock(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
if resp := h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)); resp.HasConflict {
t.Fatalf("the holder's own re-assertion reported a loss: %+v", resp.Conflict)
}
// The holder's lease lapses and another token takes the range.
h.at(16 * time.Second)
other := h.client(scopedToken("other", time.Hour, []string{"/locks"}, nil))
if !h.must(other, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 49, posixlock.Write, 3, 4, 9, false)).Granted {
t.Fatal("the lapsed range should be grantable")
}
resp := h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
if !resp.HasConflict || resp.Conflict.GetPid() != 9 || resp.Conflict.GetEnd() != 49 {
t.Fatalf("re-assertion of a lock another session holds should report it, got %+v", resp)
}
}
// Ownership is per token id: tokens sharing an id, such as a remount reusing
// its credential, act for the same holder, even under a fresh sid.
func TestScopedPosixLockTokensSharingAnIdShareItsLocks(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
first := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(first, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
remount := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
if h.must(remount, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 5, 2, 8, false)).Granted {
t.Fatal("a fresh sid is a different owner and must conflict")
}
h.must(remount, posixOwnershipKey, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, pbLock(0, 0, posixlock.Unlock, 1, 2, 8, false))
if got := h.held(posixOwnershipKey); len(got) != 0 {
t.Fatalf("a token with the same id controls the holder's locks, got %+v", got)
}
}
func TestScopedPosixLockGetLkReportsConflictWithoutTransferringOwnership(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(10, 50, posixlock.Write, 1, 2, 7, false))
if h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).GetHasConflict() {
t.Fatal("the holder must not conflict with itself")
}
reader := h.client(scopedToken("reader", time.Hour, nil, []string{"/locks"}))
got := h.must(reader, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Read, 1, 2, 9, false)).GetConflict()
want := pbLock(10, 50, posixlock.Write, 1, 2, 7, false)
if got.GetStart() != want.Start || got.GetEnd() != want.End || got.GetType() != want.Type || got.GetSid() != want.Sid || got.GetOwner() != want.Owner || got.GetPid() != want.Pid {
t.Fatalf("GET_LK with the holder's identity should report the holder, got %+v", got)
}
// A peer's cooling probe carries no principal, so it also sees the conflict.
probe, err := h.fs.PosixLock(context.Background(), &filer_pb.PosixLockRequest{
Key: posixOwnershipKey, IsMoved: true, CoolingProbe: true, Op: filer_pb.PosixLockOp_GET_LK,
Lock: pbLock(0, 99, posixlock.Write, 1, 2, 7, false),
})
if err != nil || !probe.GetHasConflict() {
t.Fatalf("a cooling probe must report the scoped lock: %+v, %v", probe, err)
}
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(0, 99, posixlock.Unlock, 1, 2, 7, false))
if got := h.held(posixOwnershipKey); len(got) != 0 {
t.Fatalf("queries must not transfer ownership away from the holder: %+v", got)
}
}
func TestScopedPosixLockRefusedRequestsLeaveStateUnchanged(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
holder := h.client(scopedToken("holder", time.Hour, []string{"/locks"}, nil))
h.must(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
before := h.held(posixOwnershipKey)
h.at(10 * time.Second)
valid := pbLock(0, 99, posixlock.Write, 1, 2, 7, false)
_, err := h.call(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, valid, pbLock(200, 299, posixlock.Unlock, 1, 2, 7, false))
expectPosixCode(t, "reassertion with an unlock range", err, codes.InvalidArgument)
_, err = h.call(holder, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, valid, pbLock(300, 200, posixlock.Write, 1, 2, 7, false))
expectPosixCode(t, "reassertion with an inverted range", err, codes.InvalidArgument)
_, err = h.call(holder, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(200, 299, posixlock.Unlock, 1, 2, 7, false))
expectPosixCode(t, "try lock with an unlock range", err, codes.InvalidArgument)
expired := h.client(signedScopeClaims(t, scopeTestKey, security.SeaweedFilerClaims{
AllowedPrefixes: []string{"/locks"},
RegisteredClaims: jwt.RegisteredClaims{ID: "holder", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute))},
}))
_, err = h.call(expired, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1}, valid)
expectPosixCode(t, "keepalive with an expired token", err, codes.Unauthenticated)
readOnly := h.client(scopedToken("holder", time.Hour, nil, []string{"/locks"}))
_, err = h.call(readOnly, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1})
expectPosixCode(t, "keepalive with a read-only grant", err, codes.PermissionDenied)
if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) {
t.Fatalf("a refused request changed the holder's locks: %+v", got)
}
h.at(15 * time.Second)
if !h.grantable(posixOwnershipKey, false) {
t.Fatal("a refused request must not renew the lease")
}
}
func TestUnscopedPosixLocksKeepTheirBehaviour(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
tokenless := h.client("")
unscoped := h.client(unscopedToken())
scoped := h.client(scopedToken("scoped", time.Hour, []string{"/locks"}, nil))
h.must(tokenless, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
// Unscoped callers share one namespace in which sid and owner identify the
// lock, as before.
if h.must(unscoped, posixOwnershipKey, filer_pb.PosixLockOp_GET_LK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).GetHasConflict() {
t.Fatal("an unscoped caller naming the owner should not conflict with it")
}
h.must(unscoped, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(10, 20, posixlock.Unlock, 1, 2, 7, false))
if got := h.held(posixOwnershipKey); len(got) != 2 {
t.Fatalf("an unscoped caller should still split an unscoped lock, got %+v", got)
}
before := h.held(posixOwnershipKey)
// A scoped token's verified id never matches an unscoped lock.
h.must(scoped, posixOwnershipKey, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, pbLock(0, 0, posixlock.Unlock, 1, 2, 7, false))
if h.must(scoped, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false)).Granted {
t.Fatal("a scoped token must not take over an unscoped lock")
}
if got := h.held(posixOwnershipKey); !reflect.DeepEqual(got, before) {
t.Fatalf("a scoped token changed an unscoped lock: %+v", got)
}
// Unscoped sessions are leased only once they renew, as a whole.
h.at(time.Hour)
if reaped := h.fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) != 0 {
t.Fatalf("a never-renewed unscoped session must not be reaped, got %v", reaped)
}
h.must(scoped, posixOwnershipKey, filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1})
h.at(time.Hour + posixLockSessionTTL)
if reaped := h.fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) != 0 {
t.Fatalf("a scoped keepalive must not lease an unscoped session, got %v", reaped)
}
h.must(tokenless, scopePosixLockKeyPrefix+"/elsewhere", filer_pb.PosixLockOp_KEEP_ALIVE, &filer_pb.PosixLockRange{Sid: 1})
h.at(2*time.Hour + posixLockSessionTTL)
if reaped := h.fs.posixLocks.ReapExpired(posixLockSessionTTL); len(reaped) != 1 || reaped[0] != 1 {
t.Fatalf("a renewed unscoped session should be reaped after the ttl, got %v", reaped)
}
if got := h.held(posixOwnershipKey); len(got) != 0 {
t.Fatalf("the reaped unscoped session's locks should be gone, got %+v", got)
}
}
func TestScopedPosixLockOwnerSurvivesSigningKeyRotation(t *testing.T) {
h := newPosixOwnershipHarness(t, 0)
claims := func() security.SeaweedFilerClaims {
return security.SeaweedFilerClaims{
AllowedPrefixes: []string{"/locks"},
RegisteredClaims: jwt.RegisteredClaims{ID: "holder", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))},
}
}
before := h.client(signedScopeClaims(t, scopeTestKey, claims()))
h.must(before, posixOwnershipKey, filer_pb.PosixLockOp_TRY_LOCK, pbLock(0, 99, posixlock.Write, 1, 2, 7, false))
const rotated = "rotated-scope-test-key"
h.keys.Store([2]string{rotated, scopeTestKey})
h.must(before, posixOwnershipKey, filer_pb.PosixLockOp_UNLOCK, pbLock(10, 20, posixlock.Unlock, 1, 2, 7, false))
after := h.client(signedScopeClaims(t, rotated, claims()))
h.must(after, posixOwnershipKey, filer_pb.PosixLockOp_RELEASE_POSIX_OWNER, pbLock(0, 0, posixlock.Unlock, 1, 2, 7, false))
if got := h.held(posixOwnershipKey); len(got) != 0 {
t.Fatalf("the token id, not the signing key, owns the lock; got %+v", got)
}
}
+5 -3
View File
@@ -98,9 +98,10 @@ func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream file
sentSnapshot := false
var listErr error
for limit > 0 {
var hasEntries bool
// entries this page handed over, the hidden ones included
var seen int
lastFileName, listErr = fs.filer.StreamListDirectoryEntries(stream.Context(), util.FullPath(req.Directory), lastFileName, includeLastFile, int64(paginationLimit), req.Prefix, "", "", func(entry *filer.Entry) (bool, error) {
hasEntries = true
seen++
if scopeHideListEntry(stream.Context(), req.Directory, entry.Name()) {
return true, nil
}
@@ -141,7 +142,8 @@ func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream file
if err != nil {
return err
}
if !hasEntries {
// a store hands over a full page while the directory has names left
if seen < paginationLimit {
break
}
+4 -3
View File
@@ -166,8 +166,8 @@ func canonicalETag(etag string) (value string, weak bool) {
// storedEntryETag mirrors the S3 gateway's ETag precedence — the stored
// Seaweed ETag extended attribute, then the remote ETag while the entry still
// holds the remote bytes, then Md5, then the chunk hash (an empty object has
// no ETag) — so conditional comparisons match what the gateway computes,
// holds the remote bytes, then Md5, then the MD5 of inline content, then the
// chunk hash — so conditional comparisons match what the gateway computes,
// without coupling the filer to S3 request handling.
func storedEntryETag(entry *filer.Entry) string {
if v, ok := entry.Extended[s3_constants.ExtETagKey]; ok && len(v) > 0 {
@@ -182,7 +182,8 @@ func storedEntryETag(entry *filer.Entry) string {
return fmt.Sprintf("%x", entry.Md5)
}
if len(entry.GetChunks()) == 0 {
return ""
etag, _ := filer.ETagOfInlineContent(entry.ToProtoEntry())
return etag
}
return normalizeETag(filer.ETagChunks(entry.GetChunks()))
}
@@ -301,9 +301,30 @@ func TestStoredEntryETag(t *testing.T) {
if got := storedEntryETag(remoteStale); got != "ab" {
t.Errorf("stale remote size falls to md5: got %q", got)
}
if got := storedEntryETag(&filer.Entry{}); got != "" {
if got := storedEntryETag(&filer.Entry{}); got != "d41d8cd98f00b204e9800998ecf8427e" {
t.Errorf("empty entry: got %q", got)
}
inline := &filer.Entry{Attr: filer.Attr{FileSize: 5}, Content: []byte("hello")}
if got := storedEntryETag(inline); got != "5d41402abc4b2a76b9719d911017c592" {
t.Errorf("inline content: got %q", got)
}
if got := storedEntryETag(&filer.Entry{Attr: filer.Attr{FileSize: 4096}}); got != "" {
t.Errorf("hole only: got %q", got)
}
}
// A mount writes an empty file with no MD5 and no chunks; If-Match with the
// ETag the gateway answers for it (the MD5 of nothing) must hold.
func TestETagMatchOnEntryWithoutChunks(t *testing.T) {
empty := &filer.Entry{FullPath: "/buckets/b/empty"}
match := one(&filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{`"d41d8cd98f00b204e9800998ecf8427e"`}})
if !writeConditionSatisfied(match, empty) {
t.Error("If-Match with the MD5 of nothing must hold for an empty file")
}
noneMatch := one(&filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etags: []string{`"d41d8cd98f00b204e9800998ecf8427e"`}})
if writeConditionSatisfied(noneMatch, empty) {
t.Error("If-None-Match with the MD5 of nothing must fail for an empty file")
}
}
// The CreateEntry handler enforces the precondition atomically: a matching
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more