Compare commits

...
Author SHA1 Message Date
Chris Lu 9dbd847bc3 Merge branch 'filer-postgres-shared-connection' into filer-postgres-flat 2026-12-01 21:59:56 -08:00
Chris Lu e5a2db4455 Merge branch 'filer-sql-row-key' into filer-postgres-shared-connection 2026-12-01 21:59:55 -08:00
Chris LuandClaude Opus 5.5 6146aa0813 filer/postgres: keep the nameExpr doc comment on nameExpr
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:56:14 -08:00
Chris LuandClaude Opus 5.5 ae3c3fad42 filer/postgres: postgres_flat shares the generator's tableIdent
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 21:21:09 -08:00
Chris Lu bebc8a7aac Merge branch 'filer-sql-row-key' into filer-postgres-shared-connection 2026-12-01 21:21:02 -08:00
Chris Lu 9bbc0faee5 Merge branch 'filer-postgres-shared-connection' into filer-postgres-flat 2026-12-01 21:21:02 -08:00
Chris LuandClaude Opus 5.5 102dae663f filer/postgres: escape the table name inside its quotes
A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 21:20:36 -08:00
Chris LuandClaude Opus 5.5 e0fef0bae8 filer/postgres: postgres_flat escapes the table name inside its quotes
A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one, but the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 20:20:34 -08:00
Chris LuandClaude Opus 5.5 2fddcae20e filer/postgres_flat: name a missing filemeta table instead of a foreign layout
With createTable = false and no filemeta table, the layout check said the
table had no path column and blamed a postgres2 layout. Report the missing
table and the key-value table that also has to be created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:58:17 -08:00
Chris LuandClaude Opus 5.5 737b633ec3 filer/sql: test the arguments each generator binds
Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:58:06 -08:00
Chris LuandClaude Opus 5.5 6df73344ca filer: register postgres_flat and add it to the filer.toml scaffold
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:40:04 -08:00
Chris LuandClaude Opus 5.5 cb1356f7f1 filer: postgres_flat store
Entries are keyed by their full path, the object key inside a bucket's
table; buckets get tables of their own as in postgres2. Key-value
records keep the postgres2 layout in filemeta_kv. The store refuses a
filemeta table of another layout, so it needs a schema of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:38:39 -08:00
Chris LuandClaude Opus 5.5 cba6549067 filer/postgres: SQL generator keyed by the full path
Rows have path as their primary key; a (directory, name) unique
constraint serves the directory listings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:38:39 -08:00
Chris LuandClaude Opus 5.5 a341909a81 filer/sql: key-value records may live in a table of their own
A store whose entry tables have another layout keeps its key-value
records in KvTable, written by KvSqlGenerator; its scans then read only
entries and need not tell the records apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:37:10 -08:00
Chris LuandClaude Opus 5.5 19573691ca filer/postgres: postgres and postgres2 share their connection setup
ReadConnection reads the settings and their defaults, Connection.Open
opens the store's pools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:35:16 -08:00
Chris LuandClaude Opus 5.5 69d88eb385 filer/sql: scan pages take the row key of the last row as their cursor
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:59 -08:00
Chris LuandClaude Opus 5.5 cb9f2095c9 filer/postgres: build the connection string with pgxutil.BuildDSN
The credential store already does; it quotes values per libpq, so a
password or certificate path with spaces or quotes no longer breaks the
connection string. The OpenPGXDB alias has no callers left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:59 -08:00
Chris LuandClaude Opus 5.5 34e0271181 filer/sql: batch lookup takes row keys and matches rows by name and directory
A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:59 -08:00
Chris LuandClaude Opus 5.5 38aa347c35 filer/sql: generators bind the arguments of directory statements
Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:58 -08:00
Chris LuandClaude Opus 5.5 4ae00a4728 filer/sql: generators bind the arguments of row statements
Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:58 -08:00
Chris LuandClaude Opus 5.5 88fb3c60eb ci: give the go test job Postgres and MySQL services
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:54 -08:00
Chris LuandClaude Opus 5.5 6c6cd81b89 filer: run postgres2 and mysql2 through the conformance suite
RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:34:54 -08:00
Chris LuandClaude Opus 5.5 e67a7b3752 filer/store_test: conformance suite for filer stores
Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-12-01 16:32:27 -08:00
d715c4e28f mount: buffer a write in memory when the swap file cannot take it (#13205)
* mount: buffer a write in memory when the swap file cannot take it

The dirty pages of a random write, or of more files than the memory budget
holds, go to a swap file under -cacheDirWrite (by default -cacheDir). On a
full cache disk the swap file cannot be created, or a write into it fails,
and the FUSE write failed with EIO (#12655; before it the mount panicked or
acknowledged a write it had not kept). The data was still in hand.

Such a chunk now stays in memory. A chunk whose swap write fails is sealed
with what it holds, so its upload keeps that, and the data goes into a
chunk in memory. The file then keeps chunks in memory for a 10s backoff
before it tries its swap file again. The sealed chunk uploads through the
swap read-back of #13198: if its earlier bytes cannot be read back either,
the flush fails, while the data written again into memory still uploads.

Memory stays bounded, as the sequential path bounds it: past 8 writable
chunks in the file, or past the shared memory-chunk ceiling, the file seals
a chunk before it creates another. Sealing waits for an upload slot, so a
writer that outpaces its uploads slows down instead of filling memory.

The #12655 tests made a write fail through an unusable swap directory. They
now make the dirty pages refuse the write directly, and a new test checks
that an unusable swap directory no longer fails it. A pipeline test covers
a sealed chunk whose swap file can no longer be read.

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

* mount: move a refused swap chunk into memory instead of sealing it

When the swap file refused a write, the first commit sealed the swap chunk
with what it held and wrote the data again into a new chunk in memory at
the same index. Two chunks at one index fail in two ways:

- A disk that takes part of an overwrite, as a full copy-on-write disk can,
  leaves the swap chunk with the new first half and the old second half.
  Its upload joins the two under the overwrite's timestamp, and the memory
  chunk uploads the new bytes under the same timestamp. Equal timestamps
  resolve to the chunk the entry lists last, so when the swap upload
  finished last the old bytes came back.
- Sealing the memory chunk while the swap chunk was still uploading
  replaced the swap chunk in the sealed slot. Until its upload finished,
  reads of the bytes only it held found nothing.

Now the swap chunk's ranges are read back into the new memory chunk, each
under its own timestamp, before the write goes in. The swap chunk then gives
back its slot without an upload, so the index keeps one chunk. When the swap
file cannot be read back either, or memory holds the shared ceiling of
chunks, the write stores only what the swap file took and reports a short
write, as master does.

Memory now stays under the shared ceiling of memory chunks. Before, a file
with no chunk of its own to seal allocated a new chunk past the ceiling
anyway, so memory grew with the number of open files writing sparse
chunks. Now that write fails. A file that has a chunk seals it to make room
for the new one, as before. The per-file bound is also checked again after
each seal, since a seal releases the lock.

refusingDirtyPages moves to a test file built on every platform, because
the copy range test also uses it on FreeBSD.

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

* mount: seal a memory chunk at the shared ceiling and recheck both bounds

At the shared ceiling, a file made room for a new chunk in memory by
sealing any one of its writable chunks. A swap chunk left by a refused
write frees no memory when it uploads, so memory went past the ceiling by
one chunk for each file in that state. At the ceiling a file now seals
one of its memory chunks, and if it has none the write fails.

Sealing releases the lock, and other writers may create chunks meanwhile.
The per-file bound was checked again after a seal made for it, but not
after a seal made for the shared ceiling. One loop now checks both bounds
again after every seal.

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

* mount: drop an empty swap chunk the swap file refused at the shared ceiling

At the shared ceiling, a swap chunk created for a write that the swap file
then refuses cannot move into memory. It was left in place, holding
nothing. Such chunks count against the file's bound, but nothing can seal
an empty chunk, so after enough refused writes a later write found nothing
to seal and created a chunk past the bound anyway. The empty chunk is now
dropped, giving back its slot and its write budget. A write that still
finds nothing to seal at the bound fails instead of going past it.

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

* mount: seal a memory chunk of the file before moving a refused swap chunk at the ceiling

At the shared memory ceiling a new chunk seals one of the file's memory
chunks and carries on, but a swap chunk whose write the swap file refused
failed the write instead. That is the first write after every backoff on
a full cache disk, and every write into an existing swap chunk.

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

* mount: keep the per-file bound when a refused swap chunk moves into memory

A file may hold more swap chunks than swapRefusedWritableChunks. When the
swap file refuses a write into a chunk created past that count, moving it
into memory left the file over the bound with every chunk in memory.
Seal another chunk of the file first, as a new chunk does.

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

* mount: write again when a refused swap chunk is sealed during a seal

Moving a refused swap chunk into memory may first seal another chunk,
which releases the lock. If another writer or the flusher sealed the
swap chunk meanwhile, the write failed although a new chunk could take
it. Write into the chunk now at the index instead.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 16:01:52 -08:00
Chris LuandClaude Opus 5.5 44b016b991 helm: run the S3 gateway's message queue broker with grpc.msg_broker TLS (#13240)
* helm: pass the S3 gateway's message queue broker port

Every S3 gateway now runs a message queue broker on 17777. s3.mqBrokerPort and filer.s3.mqBrokerPort set the port for the standalone gateway and the filer's, and allInOne.s3.mqBrokerPort falls back to s3.mqBrokerPort when null. A port of 0 renders the off flag, since leaving the flag out would let weed start the broker on its default. The all-in-one inherits through a helper that tells null from 0, which default cannot.

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

* helm: admit the message queue broker port in the NetworkPolicy

Clients and other brokers learn a broker's address from the master and dial the pod directly, so a Service does not help them. Under a default-deny namespace the policy has to admit the port on the s3, filer and all-in-one pods that run a broker, or publishing and inter-broker replication stall.

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

* helm: list the message queue broker port on the S3 pods and Services

The s3, filer and all-in-one pods declare a swfs-mq-broker containerPort when they run a broker, and their Services carry it the way they carry the Iceberg and Lance ports. Brokers are reached by pod IP, so this is for visibility and for anything that addresses the port by name.

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

* helm: document the S3 gateway's message queue broker port

Describe the three port values, that 0 turns the broker off, and that clients reach brokers by pod IP, so under the NetworkPolicy anything outside the release needs its own ingress rule. The chart version is left alone; it moves with the release commits.

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

* helm: leave the broker port flag out when it is weed's default

17777 is already the binary's default and the broker is on by default, so rendering -mq.broker.port=17777 only breaks a release pinned to an image that predates the broker flags. The port flag now appears only for a non-default port and the off flag only for 0; the containerPort, Service port and NetworkPolicy entry still follow the configured port.

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

* helm: give the gateway brokers mTLS through grpc.msg_broker

weed starts the broker beside an S3 gateway on its own only when grpc.msg_broker has a cert and key. With enableSecurity the chart now writes that section with the internal client certificate grpc.s3 already uses, so the brokers serve and dial each other with mutual TLS against the grpc.ca the chart sets, and every pod running a gateway already mounts both.

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

* helm: choose the gateway broker with mqBroker auto, true or false

weed now starts the broker beside an S3 gateway unflagged only when grpc.msg_broker TLS is configured. s3.mqBroker, filer.s3.mqBroker and allInOne.s3.mqBroker (null inherits s3's) pick it: auto passes no flag and so runs it under enableSecurity, true passes -mq.broker=true (-s3.mq.broker=true on the filer) and runs it without TLS when security is off, false passes the off flag. One helper decides the flags and whether the broker runs for all three, and the containerPort, Service ports and NetworkPolicy entry now appear only when it does.

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

* helm: document mqBroker and the broker's TLS default

The gateway broker no longer runs everywhere: describe auto, true and false, that auto means enableSecurity and its mTLS, that true without security serves any client that reaches the port, and that the ports only appear when the broker runs.

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

* helm: test the gateway broker's flags, ports and TLS section

Render s3, filer.s3 and allInOne across auto with and without security, true, false, port 0 and a custom port, plus allInOne.s3 inheriting and overriding the s3 values. Each case checks the broker and port flags together with the containerPort, Service port and NetworkPolicy entry, so a broker that runs with its port blocked fails. Also check that [grpc.msg_broker] is written only with enableSecurity, and that an unknown mqBroker value fails the render.

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

* helm: keep the broker port off the Services

Brokers register with the master under the pod address, and other brokers and publishers find them there and dial the pod, never a Service. The swfs-mq-broker Service port only made a LoadBalancer or NodePort s3, filer or all-in-one Service publish the broker outside the cluster, in plaintext with mqBroker true and no security. Drop it; the containerPort and NetworkPolicy entry stay, and the test now fails if any Service carries the broker port.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:49:06 -08:00
Chris LuandClaude Opus 5.5 3ea924d39f filer: take every log fence from the event stamp sequence (#13239)
* filer: take the log fence without registering an in-flight stamp

LogFenceTsNs stamped and released at once, so each fence briefly sat in
the in-flight registry, where a concurrent claim could be capped below it,
and took the registry mutex twice. Draw the fence from the same sequence
under one lock acquisition without registering it. Lookups are about to
take one per read.

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

* filer: fence CreateEntry and UpdateEntry from the event stamp sequence

Both stamped their pre-write fence from the raw wall clock, so after a
backwards clock step the fence could sit below events the acknowledged
state already reflects, including the previous write's event on the same
key. A mount that versions a no-op ack by that fence would then accept an
older event over it. Take the fence from the same sequence the events use,
so it lands above every earlier event and below the write's own.

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

* filer: fence a remote-object cache commit from the event stamp sequence

CacheRemoteObjectToLocalCluster stamped its commit fence from the raw wall
clock under the path lock. After a backwards clock step that fence fell
below events the cached entry already reflects, the same as the old
CreateEntry and UpdateEntry fences. Take it from the event stamp sequence.

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

* filer: fence lookups from the event stamp sequence

fencedFindEntry, behind LookupDirectoryEntry and LookupDirectoryEntries,
stamped its read fence from the raw wall clock under the shared path lock.
After a backwards clock step the fence fell below events the returned
entry already reflects, so a client versioning the entry by it could take
an older event as newer. Draw it from the event stamp sequence instead.

The fence registers nothing in flight, so it never caps flush or delivery
claims; it costs one short critical section on the stamp registry's mutex
per lookup.

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

* filer: keep the stamp sequence above renumbered log positions

The meta log buffer renumbers an event appended out of stamp order past
the last position it holds, and that position is what subscribers see.
Concurrent writers append in whatever order their notify work finishes,
and with the wall clock behind the sequence every renumbered position
lands past the last stamp, so a later fence could sit below an event the
fenced state already reflects. Feed each delivered position back into the
sequence stamps and fences draw from.

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

* filer: draw a lookup's fence after the read

FindEntry can log an event of its own on the path it reads: importing a
remote object under a mount creates the entry, and an expired entry is
deleted. Both stamp above a fence drawn before the read, while the
returned state reflects them. Draw the fence after the read with the
shared path lock still held; a locked writer on the path cannot land in
between.

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

* filer: draw the remote cache commit's fence after its re-read

The re-read can import the object from the remote and log that event; an
entry changed during the download is returned with this fence, which has to
cover the import.

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

* filer: take the exclusive path lock for a lookup that writes

Fenced lookups share the path lock, and FindEntry can write under it: it
deletes an expired S3 object and imports an object from a remote mount,
logging an event either way. A lookup that read the old state just before
could then draw its fence above that event and return the old state, so a
client skipped the event as already reflected.

A fenced lookup now reads with FindEntry reporting such a write instead
of making it, and redoes the read under the exclusive path lock when it
does. The shared lock is released first, so nothing holding it waits on
the exclusive one.

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

* filer: escalate a fenced lookup only when the remote has the object

Refusing the lazy fetch before the remote stat sent every fenced lookup that
missed under a remote mount to the exclusive lock, so concurrent lookups of
one missing key ran their stats one after another instead of sharing one.
A lookup that may not write now stats in a flight of its own and asks for
the exclusive lock only when there is an object to import.

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

* filer: require the live object from the first lookup in the expiry race test

The fence check was skipped when the first lookup errored or found
nothing, so a run that took either path passed without checking
anything. The store hands that lookup its copy before the hook expires
the object, so it always returns the live object; require that, then
compare its fence against the delete.

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

* filer: release the shared remote stat only after every lookup joined it

The test let the stat sleep and assumed all eight lookups joined within
that window, so a lookup scheduled late could start a second, correct flight
and fail the count. The stat now waits on a gate the test opens once the
other seven lookups wait on the in-flight call.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:37:35 -08:00
Chris LuandClaude Opus 5.5 185cefc652 filer: keep the server digest tests passing under fips140=only (#13243)
GODEBUG=fips140=only refuses MD5, and the filer then digests with SHA-256
cut to MD5's size. Tests that compared stored or reported digests against
crypto/md5 or hard-coded MD5 hex panicked or failed there; they now
compute the expected digest with util.Md5, which follows the process mode.
Tests that exercise a client's Content-Md5, which only exists with MD5,
are skipped under fips140=only as the digest test already is.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:36:21 -08:00
0d3f81b771 volume(rs): refuse short JWT keys and skip Content-MD5 under fips.mode strict (#13206)
* volume(rs): refuse short JWT keys and skip Content-MD5 under fips.mode strict

Under fips.mode = strict the Rust volume server now does what the Go
volume server does under GODEBUG=fips140=only:

- At startup it exits when a JWT key in security.toml (any of the eleven
  jwt.signing* and jwt.filer_signing* settings Go checks) is shorter than
  the 14 characters FIPS 140 needs for HMAC keys, naming each one. Outside
  strict mode it warns about each such key but the previous ones.
- On SIGHUP, short current keys keep the keys in effect, and a short
  previous key is dropped, as in Go's Guard.UpdateSigningKeys.
- An upload's Content-MD5 is kept as the client sent it, unchecked, since
  strict mode computes no MD5.

The key rule and its messages live in seaweed-common's jwt_keys, so the
worker can use the same one.

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

* ci: run the fips140only cells in fips.mode strict, check strict refusals

The fips140only cells of the S3 digest matrix set WEED_FIPS_MODE=strict
beside GODEBUG=fips140=only, so the Rust volume server runs in the same
mode as the Go processes. A new job, test/s3/digest_matrix/negative_config.sh,
checks that master, filer and both volume servers refuse a 10-byte JWT key
at startup, that both volume servers keep a mismatched Content-MD5
unchecked, and that S3 answers a request signed with an 8-character secret
with an error.

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

* test: check the strict-mode Content-MD5 rule against both volume servers

TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS starts the volume cluster
under GODEBUG=fips140=only and WEED_FIPS_MODE=strict and checks that an
upload with a mismatched Content-MD5 is stored with the client's value. It
sits in test/volume_server/http, so it runs against the Go volume server and,
with VOLUME_SERVER_IMPL=rust, against the Rust one. The same check leaves
negative_config.sh, which keeps the startup refusals.

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

* volume(rs): say which keys the strict-mode checks cover and what they do

The doc comments of the startup check, the reload rule and the jwt_keys
helpers now say which keys they check and what happens in each mode.

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

* volume(rs): an empty WEED_ variable leaves the security.toml value in place

env_string returned an empty variable as a value, so WEED_JWT_SIGNING_KEY=
replaced the key from security.toml with an empty one: the volume server
then checked no JWTs, and under fips.mode strict a short file key was not
refused, while Go's volume server exits with the same files. Go's viper
ignores empty variables; env_string now does the same for every WEED_
override.

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

* volume(rs): read security.toml with the TOML parser

The line reader missed quoted key names, multiline strings, dotted keys,
inline tables and spaced or quoted table headers, all of which Go's viper
reads, so a short JWT key written that way escaped the strict-mode check
and was not used at all. Settings are now looked up in the parsed table,
case-insensitively as viper does. A file that is not valid TOML is still
read line by line, as before.

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

* volume(rs): prefer the longest literal security.toml key, as viper does

Viper looks a dotted setting up longest name first, so a quoted
"jwt.filer_signing.key" key, at the top or under [jwt], wins over the
nested [jwt.filer_signing] key. The volume server read only the nested
one, so a short literal key passed the strict-mode check here while the
Go servers refused it.

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

* volume(rs): resolve security.toml key case collisions as viper does

Viper lowercases every key of a config file, and when two spellings
collide (key and KEY, or [jwt] and [JWT]) the one that is not lowercase
wins. The volume server matched names case-insensitively but took the
exact spelling first, so a short KEY next to a compliant key passed the
strict-mode check here while the Go servers refused it. The parsed table
is now lowercased the same way before any lookup.

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

* volume(rs): read an array or table security.toml setting as unset

Viper's GetString reads an array or a table as "", so the Go servers
skip a jwt key written as key = ["x"]. The volume server read its TOML
text instead, used it as the key and refused strict-mode startup over
it. fips.mode is still read as text: Go refuses a mode that is not a
string, and so does this server.

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

* volume(rs): keep each lenient security.toml line under its full name

A security.toml that is not valid TOML is read line by line, and those
lines went into nested tables, so a later scalar such as signing = "x"
under [jwt] replaced the [jwt.signing] table and erased its key. The
line reader ignored such lines before, and a SIGHUP reload of that file
would have installed an empty write key. Each line now goes in under its
full dotted name, which the longest-name lookup finds first.

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

* volume(rs): take the FIPS mode from the read that gives the JWT keys

Startup read security.toml once for the JWT keys and again for
fips.mode, so a file replaced between the two reads could pair the keys
of one version with the mode of the other and refuse to start over keys
that version never ran in strict mode with. The mode now comes from the
same parse as the keys; a file that exists but was not read is still an
error.

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

* volume(rs): read a float security.toml setting as Go's GetString does

GetString formats a float with the shortest digits and no exponent, so
key = 1234567890123.0 is a 13-byte key to the Go servers. The volume
server kept the TOML spelling with its .0 and measured 15 bytes, which
passed the strict-mode check the Go servers refuse.

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

* volume(rs): skip array-of-tables sections in a lenient security.toml

A file that is not valid TOML is read line by line, and lines under a
[[jwt.signing]] header went in under the same names as [jwt.signing],
so an empty key there replaced the real one, and a SIGHUP reload would
install it. The line reader now skips such sections up to the next
ordinary header, as the earlier reader did.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 15:33:31 -08:00
Chris LuandClaude Opus 5.5 04bbf1ae0f filer: keep the default broker off the debug port (#13242)
weed filer -s3 checked the broker port against the filer, metrics,
read-only, WebDAV, IAM and SFTP ports but not -debug.port, which the
debug server binds before the broker starts. weed server already
includes it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:33:00 -08:00
Chris LuandClaude Opus 5.5 52afabbf1b mq: avoid a deadlock when retiring a partition with a full flush queue (#13225)
* mq: let partition retirement drain a full flush queue outside broker locks

* log_buffer: queue the final flush from ShutdownLogBuffer itself

Every ShutdownLogBuffer caller already waits afterwards with WaitForShutdown
or IsAllFlushed, so queueing the final flush in the background changes no
caller's outcome and lets every caller holding a lock a flush callback needs
avoid the full-queue deadlock, without a second shutdown entry point.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:32:00 -08:00
Chris LuandClaude Opus 5.5 45458336e1 s3: run a message queue broker beside every S3 gateway (#13235)
* mq broker: let an embedding command own the broker's start failure and shutdown

startQueueServer now returns an error when the broker cannot start instead
of exiting, binds its port before creating the broker so one that cannot
serve never registers with the master, and stops when an optional
shutdownCtx is cancelled. Profiling setup moves to weed mq.broker, since an
embedded broker read the standalone command's profile flags. weed mq.broker
and weed server -mq.broker still exit on a start failure.

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

* s3: run a message queue broker beside the gateway by default

weed s3 now starts a broker on -mq.broker.port (17777) once it has reached
its filer, using the masters and filer group the filer reports. The broker
is its own gRPC server: it binds the gateway's -ip.bind, advertises the
address the gateway registers with the master, and joins the cluster like
any other broker. It stops with the gateway. A broker that cannot start,
say because the port is taken, is logged and the gateway keeps serving.
-mq.broker=false turns it off.

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

* server: start the message queue broker with the S3 gateway

weed server -s3 now runs a broker beside its gateway, started by the
gateway once it reaches the filer. -mq.broker=false leaves it out. An
explicit -mq.broker or -mq.agent still starts the broker on its own, and
then the gateway does not start a second one. Only that explicit broker
exits the server when it cannot start; the one that comes with -s3 is
logged, so a host already running a broker on the port keeps its gateway.

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

* mini: run the message queue broker beside the S3 gateway

weed mini now starts a broker with its S3 gateway on -mq.broker.port
(17777, below the Linux ephemeral range), binding and advertising mini's
-ip.bind and -ip like the other services. The port joins mini's port
layout, so a taken port moves to the next free one unless it was given
explicitly. The broker stops with the gateway, before the filer it
flushes to. -mq.broker=false or -s3=false leaves it out.

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

* filer: start the message queue broker with the S3 gateway

weed filer -s3 now runs a broker beside its gateway on -s3.mq.broker.port
(17777), the same way weed server -s3 does: it binds and advertises where
the gateway does, takes the filer's -dataCenter and -rack, stops with the
gateway, and a broker that cannot start is logged while the gateway keeps
serving. -s3.mq.broker=false leaves it out.

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

* mini: list the message queue broker when it is running

The S3 gateway now binds its broker's port before it starts serving, as it
does for the Iceberg and Lance listeners, and records whether the bind
worked. Once mini sees the S3 port answer, the result is final: the
progress board shows the broker ready or failed, and the welcome banner
lists its address only when it bound. With -mq.broker=false or -s3=false
neither shows it.

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

* s3: keep the default broker off the gateway's own ports

The broker binds before the gateway binds its ports, so a gateway started
with -port=17777, -port.grpc=17777 or -port=7777 (gRPC port 17777) lost
its port to the default broker and exited. weed s3, weed server -s3 and
weed filer -s3 now compare the broker port with the gateway's HTTP,
HTTPS, gRPC, Iceberg, Lance and metrics ports first. A default broker
port that clashes skips the broker with a warning; a broker port given
on the command line that clashes is an error.

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

* mini: reserve explicitly set gRPC ports before placing other ports

Mini only kept derived gRPC ports free while it placed the other
services, so the broker's default port could take an explicit
-s3.port.grpc=17777 and push the S3 gRPC server to another port. An
explicit gRPC port is now reserved too: the default broker moves off it,
and an explicit broker port on it is rejected.

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

* server: keep the default broker off the ports of the servers it starts

With -volume.port=7777 the volume gRPC port is 17777, the default broker
port. The volume server binds its gRPC port only after a master answers,
so the broker could take it first and the whole process exited.

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

* mini: keep an explicit gRPC reservation when a derived one moves

When the filer's HTTP port was taken and moved, dropping its old derived
gRPC port also dropped an explicit -s3.port.grpc on the same port, so an
explicit -mq.broker.port could share it.

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

* server: bind the broker beside S3 where the gateway binds

With -ip.bind=0.0.0.0 -s3.ip.bind=127.0.0.1 the broker that comes with
the gateway listened on every interface. It now takes the gateway's bind
and advertised address, as under weed s3 and weed filer -s3.

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

* server: keep the default broker off the volume public port

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

* mq broker: report a bad TLS config instead of exiting

The embedded broker loaded grpc.msg_broker TLS through LoadClientTLS and
LoadServerTLS, which exit on a bad config, so a cert without a key or
without grpc.ca took the whole S3 gateway down. The broker now loads TLS
before binding through the error-returning loaders, exported from the
security package as TryLoadClientTLS and TryLoadServerTLS, and returns
the error like any other start failure: the gateway logs it and keeps
serving, while weed mq.broker and weed server -mq.broker still exit.

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

* s3: start the gateway's broker by default only with broker TLS

Without grpc.msg_broker TLS the broker accepts any peer, so the broker
beside weed s3, weed server -s3 and weed filer -s3 now starts on its own
only when grpc.msg_broker has a cert and key in security.toml. Otherwise
it stays off and the gateway logs one line saying so and that
-mq.broker=true (-s3.mq.broker=true for the filer) runs it without TLS.
An explicit true starts it either way and an explicit false keeps it
off. weed mini, a single-process dev setup, keeps its broker on.

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

* filer: keep the default broker off the ports of the servers it starts

weed filer -s3 checked the broker port only against the gateway's ports,
so with -webdav -webdav.port=17777 the broker could bind 17777 first and
WebDAV then took the whole filer down. The check now also covers the
filer's own HTTP, gRPC and read-only ports, its metrics port, and the
WebDAV, IAM and SFTP ports when those run, as weed server does. A
default broker port that clashes skips the broker with a warning; a
clashing -s3.mq.broker.port is an error before the servers start.

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

* server: keep the default broker off the filer read-only and debug ports

The port check beside -s3 left out -filer.port.public and, with -debug,
-debug.port, so a broker on 17777 could still take a port the filer or
the debug server binds. Both are now in the list. WebDAV, SFTP and IAM
were already covered when enabled.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:53:36 -08:00
Chris LuandClaude Opus 5.5 6b2e22950a s3: bucket notification configuration API and target registry (#13236)
* s3: add the bucket notification target registry

Notification destinations are defined by the operator in
/etc/s3/notification/targets.json and referred to by name from bucket
configurations, so a bucket owner cannot make the server connect anywhere
new. The registry parses and validates that file: unique names that fit in
an ARN segment and an MQ topic name, known types (topic and webhook now,
kafka, aws_sqs, google_pub_sub and pubsub accepted for later), the fields
each type needs, and no unknown keys. A target serves only the buckets its
allowed_buckets globs match, and none when the list is empty. Parse errors
never carry credential values.

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

* s3api: hot-reload the notification target registry

Every gateway reads /etc/s3/notification/targets.json at startup and
reloads it from the /etc metadata subscription it already runs for the IAM
and circuit breaker files. A write reloads it, a delete or rename away
empties it, and a file that does not parse leaves the previous registry in
place so a bad edit does not cut every bucket off its destinations.

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

* s3: parse and validate bucket notification configurations

The full PutBucketNotificationConfiguration document is parsed: topic,
queue and cloud function configurations with their Id, destination ARN,
events and key filter. Event names are checked against the AWS list,
wildcards and names for things that never happen here included, plus the
multipart and retention events this server emits. A filter takes at most
one prefix and one suffix rule, a document at most 100 configurations, and
overlapping rules are allowed. EventBridge stays NotImplemented.

A destination resolves by the last segment of its ARN to a target, which
must exist, be enabled and allow the bucket; the error does not say which
of those failed. A rule without an Id gets one derived from its content, so
every gateway reports the same configurationId for it.

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

* s3: match an event against a bucket's notification rules

Configuration.Match takes an event name such as s3:ObjectCreated:Put and
an object key and returns each rule that covers them, with its
configurationId and target, in configuration order. Category wildcards
cover every event in the category, prefix and suffix are case-sensitive and
checked independently, and an event that several rules cover matches each
of them, as AWS delivers one record per rule. Publishing calls this; it is
a pure function of the stored configuration.

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

* s3api: store bucket notification configurations

PutBucketNotificationConfiguration used to accept only an empty document
and answer NotImplemented for any destination. It now parses the full
document, checks every destination against the target registry for this
bucket, and stores the XML exactly as sent in one Extended key on the
bucket entry through updateBucketConfig, which patches that key alone on
the bucket's owner filer. An empty document removes the key. GET returns
the stored bytes unchanged, so tools comparing ARNs see no diff, and the
bucket config cache carries the parsed rules for publishing to match.

x-amz-skip-destination-validation is parsed and must be true or false. It
only skips the test event, which publishing will send; the registry check
always runs.

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

* s3notification: reject content after the configuration's root element

The stored document is served back unchanged by GET, so anything after the
root other than whitespace, comments or processing instructions is refused.

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

* s3notification: reject unknown elements inside rules and filters

A misspelled Filter, S3Key, FilterRule or Value was dropped by decoding and
left an unfiltered rule; it is now MalformedXML like an unknown root child.

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

* s3notification: URL-decode prefix and suffix filter values

AWS has special characters in filter values percent-encoded and a space
written as +, so reports+2026/ selects reports 2026/a. A value that is not
valid encoding is still matched as written.

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

* s3api: refuse a notification targets file stored in chunks

Only inline content is read, so a targets.json kept in chunks (written by a
mount, for one) read as an empty registry and dropped every target. It is
now refused with a warning and the loaded registry stays.

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

* s3notification: refuse overlapping rules as AWS does

AWS answers InvalidArgument ("Configuration is ambiguously defined") when two
rules share an event type and both their prefixes and suffixes overlap, so an
event for a key matches at most one rule. Such configurations were accepted
and matched every rule.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:45:21 -08:00
Chris LuandClaude Opus 5.5 6a6208e42f mq: a leader-only partition gains a follower, and cold partitions are purged (#13232)
* mq balancer: start a new generation when a partition's follower changes

EnsureAssignmentsToActiveBrokers gave a leader-only partition a follower
once a second broker was live, and replaced a lost follower, but kept the
epoch. A leader starts replicating only when it takes the fence, so a
loaded leader never saw the new follower: its copy at the same epoch was
never retired, and the partition stayed unreplicated, acking from memory,
until something reloaded it. Any change of the pair now bumps the epoch,
so the leader retires its copy after the last flush and reloads under the
new generation with a replicator to the new follower. Re-spelling the same
broker's address still keeps the epoch, so an unchanged pair is not
churned.

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

* mq broker: hand a repaired assignment's new generation to its leader

When the balancer repaired a topic's assignments it only saved
topic.conf. A leader learned of a new generation only when a new publish
or subscribe stream asked for the partition after its own cached
topic.conf expired, so a loaded partition kept serving the old
generation, without the follower it had just been given, for as long as
its clients stayed connected. Once the repair is saved, the balancer now
sends every assignment whose epoch moved to its leader, which retires
the old copy after its last flush and reloads under the new fence,
replicating to the new follower. The handoff runs outside topicConfLock,
since the leader may wait for that flush.

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

* mq balancer: repair every topic's assignments once a broker joins

The balancer repaired a topic's assignments only when a lookup missed
its cached topic.conf. A partition placed while its leader was the only
broker kept no follower after a second broker joined for as long as its
clients stayed connected and never looked it up again. The balancer now
counts brokers joining it and, once settled, repairs every stored topic
after a join, handing any new generation to its leader. A sweep that
fails is retried on the next tick; one that finds nothing to change
saves nothing, so a reconnect does not churn partitions. A repair that
saves topic.conf also drops the balancer's cached copy, which lookups
would otherwise keep answering with the old pair.

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

* mq broker: purge a partition past retention when its leader loads it

Files past a topic's retention were deleted only by the periodic purge,
which visits partitions that are loaded when it runs. A partition loaded
for a short read or write and unloaded once idle could miss every pass,
keeping its expired files. A leader now purges a partition as soon as it
has loaded it, under the fence it has just taken and after seeding its
offsets, so every load deletes what has expired. The purge runs once the
partition is registered, outside the broker's access lock.

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

* mq balancer: load partitions whose files are past retention

A partition that nothing publishes to or reads from is never loaded, so
neither the periodic purge nor a purge on load ever reached it, and a
cold topic kept its expired files indefinitely. Every purge interval the
balancer now lists each topic with retention, works out per partition
what a purge would delete, and hands only the partitions with something
to delete to their leaders. The leader's load purges them under the
fence it takes, so deletes stay fenced. A partition with nothing to
delete, such as one holding only its newest file, is not loaded, so
cold partitions are not churned.

The planning half of purgeExpiredLogFiles moves into expiredLogFiles,
which the purge and the balancer share.

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

* mq balancer: resend a new generation until its leader takes it

After a repair saved a new generation, the balancer told the leader once
and only logged a failure. The repair loop still counted the join as
done, and later sweeps found nothing to change, so a leader whose
publish stream kept its old partition went on acking without the
follower it had been given. Saved generations are now kept as pending,
one per partition with a newer one replacing an older, and the repair
loop hands each due one to its leader, backing off after each refusal,
until the leader takes it or topic.conf has moved past it. A join counts
as repaired only once nothing is pending. Sending runs in the repair
loop, off topicConfLock, which a save now wakes.

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

* mq balancer: hand pending generations to leaders in parallel under one deadline

The repair loop handed pending generations over one at a time, each
with its own 30 second timeout, so a broker that stopped answering held
the loop for that long per partition it led: with a hundred of them,
healthy leaders and later joins waited most of an hour. A pass now reads
each topic.conf once, groups the generations still current by leader
and topic into one request each, and sends up to eight leaders at once
under a single deadline for the whole pass. A leader that does not
answer delays only its own generations, which keep their backoff, and
the pass returns once the deadline passes.

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

* mq balancer: key a pending generation by the partition's full identity

Pending generations were keyed by topic and range alone. A topic
repartitioned away from a range and back gets a new partition for that
range, with a new creation time and epochs starting over, so a pending
generation of the old partition at a higher epoch made the new one look
older and it was never queued. The key now includes the ring size and
creation time, so epochs are compared only within one partition; the old
entry is dropped as superseded when it next comes due.

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

* mq balancer: hand over generations a previous balancer left undelivered

Pending generations live only in the balancer's memory. A balancer that
saved a new generation and stopped before its leader took it lost it:
the next balancer's sweep found topic.conf already repaired, recorded
the join as done, and a leader whose clients kept its old copy served
that generation without its new follower indefinitely. Once settled
under a new lease, the balancer now queues the current generation of
every partition a leader reports loaded and hands them over through the
same batched delivery, so joins are not done until those are taken too.
A leader already on that generation keeps its copy, as an assignment at
the epoch it holds is a no-op, and an unloaded partition is skipped
since it reads topic.conf when it loads.

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

* filer_client: track a filer's backoff atomically

Every call through one FilerClientAccessor records the filer's health,
and those calls run concurrently, but the backoff deadline was a plain
time.Time read and written without synchronization. The broker now reads
topic.conf from background purges and repairs while serving requests
through the same accessor, which the race detector caught. The deadline
is now an atomic Unix-nanosecond value, and the failure time it was
stored beside, which nothing read, is dropped.

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

* mq balancer: keep generations pending when the pass ends before sending them

A batch still waiting for a sender when the pass deadline passed took
the cancellation branch with its error still nil, so its generations
were dropped as delivered although nothing was sent, and their leaders
kept serving the old generation. Such a batch now fails with the pass's
deadline and keeps its backoff, like a batch whose send timed out.

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

* mq balancer: give each leader one sender, not each of its topics

The limit on concurrent sends applied to per-topic batches, so a stalled
leader with as many due topics as there are senders took every slot and
a healthy leader waited out the pass deadline. A pass now groups due
generations by leader; each leader takes one sender and sends its topics
in turn, so a stalled leader holds only its own slot, and its topics not
reached before the deadline stay pending.

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

* filer_client: keep backing off a filer that has failed many times

The backoff doubled with a shift of the failure count, which wraps once
a filer has failed 64 times in a row, so its backoff dropped to nothing
and it was retried on every call. The doubling now stops at 16 seconds
and the backoff stays at 30 seconds after that.

* mq balancer: requeue each broker's held generations once its stats arrive

A new balancer requeued the generations of loaded partitions once per
lease, from whatever stats it had at that moment. A leader that had
connected but not yet sent its first stats looked as if it held
nothing, and since the scan never ran again under that lease, a
generation an earlier balancer saved but never handed over stayed
undelivered. The balancer now records which brokers have reported and,
on each pass, scans the brokers whose first stats arrived since the
last scan under the current lease, queuing their held partitions'
current generations for the same batched delivery.

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

* mq balancer: scan each broker connection, judged by the stats it reported

The handoff scan took the reported brokers' addresses, then looked each
one's stats up again while matching partitions, and marked the address
scanned. A broker that disconnected in between was looked up as holding
nothing yet still marked scanned, so when it reconnected under the same
lease it was never scanned again and a generation it never took stayed
undelivered. The scan now judges each broker by the stats it was
listed with and records connections, not addresses, as scanned; a
reconnect brings new stats and is scanned again.

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

* mq balancer: register each broker connection separately

AddBroker reused the stats already registered under a broker's address,
and a stream's cleanup removed whatever was registered under it. A
broker that reconnected before its old stream ended shared that stream's
stats, and the old stream's cleanup then dropped it from the live set
while the new stream kept reporting, so the balancer treated a live
broker as gone, and the handoff scan, which already counted that stats
object as scanned, skipped the reconnect. Each connection now registers
fresh stats, and its cleanup removes the broker only while those are
still the registered ones.

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

* mq broker: record an assignment only on a connected broker's stats

After handing a partition to its leader, the balancer recorded the
assignment on the leader's stats and, when the leader had none, created
and registered stats for it. A leader not connected to the balancer, as
one still reconnecting or one that only answered the assignment, was
thereby added to the live set without a connection whose cleanup would
ever remove it, and assignments could then pick a broker the balancer
could not see. The assignment is now recorded only when the leader's
connection has registered it.

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

* mq balancer: sweep topics from a listing that reports its failures

The repair sweep, the handoff scan and the retention scan took their
topics from ListTopics, which serves what it can: a failed namespace
listing, a failed topic listing or a failed topic.conf lookup is only
logged. A sweep could therefore see some topics, or none, and still
succeed, recording a join as repaired with topics never looked at.
ListTopics' filer scan is now listStoredTopics, which lists all it can
and reports every failure. The repair sweep and the handoff scan fail
on it, so the join stays pending until a sweep lists every topic, while
an empty listing that succeeded is still complete. The retention scan
purges what was listed and logs the rest. ListTopics keeps serving
partial results to its gRPC callers and only logs the failure.

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

* mq broker: list every namespace and topic, not the first thousand

The topic listing asked the filer for at most 1000 namespaces and at
most 1000 topics per namespace and never asked again, so anything past
the first thousand was missing from ListTopics, never repaired after a
broker joined, never handed over by a new balancer, and never purged
past retention. Both listings now ask for everything, which the filer
pages through itself, as the partition offset scan already does.

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

* mq balancer: forget the scan record of a broker connection that ended

The handoff scan remembered every broker connection it had scanned
until the balancer lease changed. Each reconnect is a new connection,
so a long-running balancer kept one record, holding that connection's
stats, for every reconnect of every broker. Each pass now drops the
records of connections no longer reported; a broker that reconnects
brings new stats and is scanned again either way.

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

* mq broker: give the stored-topic listing a deadline

The shared topic listing ran under the broker's long-lived context, so
a filer that accepted a listing and stopped answering held the repair
loop and the retention sweep indefinitely; ListTopics used to give its
scan two seconds. Each listing now gives up after 30 seconds and
returns the error, so the scan is retried on a later pass.

* mq balancer: give a retention hand-over a deadline

A leader that took the hand-over of a partition past retention and never
answered held the balancer's retention loop on it, so later topics and the
next tick never ran.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:35:34 -08:00
Chris LuandClaude Opus 5.5 a1f3f9aaa1 filer: return the commit stamp from ObjectTransaction (#13234)
* filer: add log_ts_ns to ObjectTransactionResponse

CreateEntry and UpdateEntry return the filer log position stamped under
the path lock; a conditional write through ObjectTransaction had no such
field. Add it as field 4 so callers can order one key's commits the same
way regardless of which RPC applied them.

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

* filer: return the commit's log position from ObjectTransaction

A committed transaction now stamps log_ts_ns under its lock_key lock after
its last mutation, the same wall-clock source CreateEntry and UpdateEntry
use. All mutations of one transaction sit between that stamp and the next
writer's, so one stamp orders the transaction against every other write
of the key. A refused or failed transaction leaves it 0, and a replayed
request returns the stamp recorded with its first outcome. A non-owner
forwards the owner's response unchanged.

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

* filer: stamp ObjectTransaction's log_ts_ns from the meta-log clock

The wall clock can step back between two transactions on one key, or sit
below stamps already bumped past it, giving a later transaction a smaller
stamp than an earlier one or than its own event. Take the response stamp
from the same monotonic allocator the events use, released at once.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:22:45 -08:00
Chris LuandClaude Opus 5.5 42a39099e0 mq broker: keep one request id across filers for a topic.conf save (#13237)
A save that applied but lost its answer was retried on the next filer under
a new request id, refused as changed by its own write, and redone from the
saved topic.conf: a balance move then found the target already leading and
failed after saving. The same id lets the owner replay the recorded outcome.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:19:51 -08:00
5213f4c1b0 worker(rs): write in the filer's digest and send a CRC32C with each upload (#13221)
* worker(rs): write ETags and chunk digests in the filer's digest

The worker's Lance store (weed-worker, and weed-vector, which links it)
wrote MD5 chunk ETags, MD5 object digests and MD5 multipart ETags whatever
the filer's digest (#12913), so a cluster on -digest=sha256 held MD5
digests for every file the worker wrote. It now reads the digest the filer
reports and writes in it, as the Go writers do: SHA-256 cut to 16 bytes
under sha256.

A filer that reports no digest leaves the worker in its own mode, sha256
under fips.mode strict and md5 otherwise, with Go's warning; under strict
mode a filer using md5 is refused, as the Go clients refuse it under
GODEBUG=fips140=only.

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

* worker(rs): send the CRC32C of each upload to the volume server

The worker uploaded chunks with no checksum header, so a volume server
could not tell a chunk damaged in transit from a good one. Each upload now
carries X-Seaweed-Content-Crc32c (#12999) over the bytes it sends, as Go's
uploader does; volume servers check it before storing the chunk, and those
that predate the header ignore it.

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

* worker(rs): read the whole upload request in the CRC32C header test

The test's server read the request once, so a request TCP split before the
checksum header failed the test although the client sent it. It now reads
up to the end of the head, fails on a connection closed before it, drains
the body by its Content-Length, and matches the header name in any case.

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

* worker(rs): digest a chunk's ETag before the volume encryption

Go's uploader records the caller's digest of the bytes it hands to the
volume encryption as the chunk ETag; the worker digested the ciphertext,
so under cipher its chunk ETags and the multipart ETags derived from them
differed from the gateway's.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 14:17:49 -08:00
ec1032d642 filer.remote.sync: a source chunk gone for good no longer wedges the write-back (#13220)
* filer.remote.sync: a source chunk gone for good no longer wedges the write-back

An entry whose chunk the volume servers answer 404 for, even with
readDeleted=true, can never be uploaded: the bytes no longer exist in the
cluster. A volume lost with its disk leaves such entries behind (for
example a filer restored from a metadata backup onto a new volume server
while some chunks had not been written back yet). filer.remote.sync
retried the create event forever, every ~2 s, and since a failing event
holds the directory's processed watermark, no later change under the
mount was ever written back again. We hit this in production: one photo's
chunk answered 404 for hours and more than 11,000 later changes waited
behind it.

Now, once the filer confirms the entry is still the one the event
described (the existing supersession check), the upload ends with
errSourceGone when:

- every location answered 404 for sourceGoneGrace (5 min) over
  sourceGoneMinAnswers (3) attempts in a row, or
- the master cannot locate the chunk's volume at all ("failed to locate",
  the whole volume lost with its disk) for sourceGoneLookupGrace (30 min,
  the filer deletion retry's figure for "volume not found").

It logs one ERROR line naming the path, the chunk's fid and the
destination, with a per-process count, and every caller treats the event
as handled so the offset advances. A path found gone is remembered with
its fid (bounded to 10,000), so later events of the same entry are skipped
at once; any other outcome (success, superseded, another error, a failed
supersession lookup) forgets it and starts the grace again, so a volume
server that has not loaded its volume yet, or a stale location, is not
mistaken for lost data.

Only the source decides. The upload body is wrapped in a recorder that
keeps the first error the chunk reader returned, because remote clients
wrap a body read failure in their own errors (the AWS SDK's RequestError
has no Unwrap). The recorder forwards ReadAt and Seek, so s3manager keeps
reading parts in place. A 404, 5xx, timeout or any other error from the
remote itself never reaches the recorder and keeps retrying as before.

A rename of an entry that was written back now deletes the old key only
after the new one is written: when the entry's local data is gone, the old
key keeps the last remote copy (logged) instead of being deleted before an
upload that can never succeed. The gateway's rename path, which deletes
first, does not acknowledge errSourceGone and keeps failing visibly.

util/http:
- GetAuthenticated (the encrypted chunk read) reports a 404 as ErrNotFound,
  as the unencrypted read paths already do, with the same error text;
  readEncryptedUrl wraps with %w instead of %v and treats a 404 as
  retryable, like the plain read, so it tries the other locations.
- A chunk read is ErrNotFound only when no location of the pass failed
  differently (NotFoundEverywhere): a 404 from one replica while another is
  down, answers 5xx or is throttled does not mean the chunk is gone. This
  is applied once in hedgedChunkPass (both RetriedFetchChunkData paths) and
  in the manifest's retriedStreamFetchChunkData loop.

Tests:
- filer_remote_sync_gone_test.go: a plain and an encrypted chunk served 404
  by a test volume server end in errSourceGone on the third attempt and are
  counted once; a remote that answers 404 with readable chunks never does;
  the tracker's grace, answer count, reset, fid change and remembered path;
  the lookup-miss grace; ReaderAt kept by the recorder; a rename keeps the
  old key when the entry is gone and deletes it after the write otherwise.
- TestGetAuthenticatedNotFound; TestRetriedFetchChunkDataNotFoundEverywhere
  (plain direct, plain stream, encrypted; a 404 and a 503 in either order
  is not ErrNotFound).
- Mutation checks: each fails with readEncryptedUrl back on %v, with the
  write error classified instead of the body's read error, with
  NotFoundEverywhere dropped from hedgedChunkPass, with the old key deleted
  first, and with the recorder hiding ReadAt.
- go vet and go test of weed/util/http, weed/command, weed/filer and
  weed/replication/... pass; weed/util/http also with -race.

* filer.remote.sync: renames keep the old key until the new one holds the content; gone is per entry; missing volumes opt-in

- A sighting is counted per entry content (the sorted chunk file ids),
  not per failing chunk. An uploader reads the parts of a ReaderAt body in
  parallel, so the chunk that fails first changes between attempts; keyed
  on it, the grace restarted every time and a large file missing several
  chunks held the offset forever. The tracker's `seen` map is bounded, and
  the log names the first chunk "and N more" instead of every fid.
- On every rename the old key is deleted only after the new one holds the
  content: also when the event's old entry carries no stamp (an upload
  whose stamp a rename in between refused leaves an unstamped copy), and
  in the superseded branch, where the old key is what uploadCurrentEntry
  copies a remote-only entry from. uploadCurrentEntry reports when the
  current entry's data is gone, and the old key stays then. A multipart or
  system path whose old key cannot be deleted no longer skips the stamp.
- A volume the master cannot locate counts only with
  -sourceGoneVolumeMissing=<duration> (default 0: never): a volume server
  that is down or in maintenance looks the same, and an entry written off
  is not retried. It suits a deployment whose master and volume server run
  as one process.
- filer.remote.gateway's rename writes the new key first, deletes the old
  object after, and keeps it when the source data is gone.

Tests: TestRetriedWriteFileSourceGoneAcrossChunks (two lost chunks read in
turn), TestSupersededRenameUploadsCurrentEntry "uncached between the check
and the upload" and "current entry's chunks gone: the old key stays",
TestRenameOfGoneEntryKeepsTheOldKey "old entry unstamped",
TestSourceGoneGraceFor (lookup miss off by default, on with the flag);
each fails with its fix undone. The test remote's DeleteFile removes the
object, as a real remote does.

* filer.remote.sync: evidence kinds apart, a gone entry counted once, the copy owns its source's cleanup; gateway keeps the old object on a superseded rename

- Lookup misses and 404s no longer share one run of sightings
  (sightingKey = content + grace): with -sourceGoneVolumeMissing set, a few
  minutes of "failed to locate" followed by one 404 met the 404 grace with
  the misses' start and answers.
- observe reports whether this call found the entry gone; a replayed event
  of an entry already gone is skipped without another log line or count.
- A superseded rename whose current entry is remote-only leaves the old key
  to completeRemoteOnlyRename, which removes its source only while it is
  the object the stamp describes; an unconditional delete after it could
  remove a replacement.
- filer.remote.gateway: a superseded rename keeps the old object (logged)
  instead of deleting it before the superseding event has written the new
  key.

Tests: TestSourceGoneTrackerCountsOnceAndKeepsEvidenceApart,
TestSupersededRenameUploadsCurrentEntry "the old key replaced during the
copy"; each fails with its fix undone. The gateway change has no test of its
own (its rename path needs a reachable filer).

* filer.remote.sync: drop -sourceGoneVolumeMissing, a lookup miss keeps retrying

A volume the master cannot locate looks the same whether it was lost or
its server is down, so no default can write such an entry off safely, and
a flag for the one-process layout is not worth carrying. Only a 404 from
every location counts as gone; a lookup miss retries as before.

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

* filer.remote.gateway: a superseded rename settles its old object

A rename the filer has moved past kept the renamed-from object for good,
so every rename followed by a delete or a rewrite before the gateway
reached it left an orphan on the remote. Settle it the way
filer.remote.sync's uploadCurrentEntry does: copy from it when the entry
has become remote-only, and otherwise delete it, since it no longer holds
the entry's content.

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

* filer.remote.sync, filer.remote.gateway: a superseded rename copied from a later rename's source settles its own old key

When the entry became remote-only through another rename onto it, the copy
reads that rename's source and removes it, and nothing read or removed the
event's own old key any more. Delete it then, in both commands.

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

* filer.remote.gateway: reset cached remote clients after the superseded-rename test

A cached client kept the previous run's recorder, so the test failed under
-count above one.

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-12-01 14:15:37 -08:00
Chris LuandClaude Opus 5.5 3363f4a318 mq: disk and parquet reads stop when asked, resume inside earlier files, and order new stamps after stored ones (#13230)
* mq logstore: stop a disk read when the callback is done

GenLogOnDiskReadFunc ignored the isDone the per-entry callback returned, so it
kept fetching and delivering every later entry, chunk and file, and the merged
read then went on into the parquet files. The chunked offset read and the query
scanner's close path both return true and expect the read to stop. The reader
now stops at that entry, skips the remaining chunks and files, and returns done
with a position just past the entry: the next offset for an offset read, its
time for a timestamp read. The merged read returns there instead of reading
parquet.

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

* mq logstore: stop a parquet read when the callback is done

The parquet reader also ignored the callback's isDone and delivered every
remaining row of every compacted file, and the merged read cleared any done it
reported. It now stops at that row and skips the remaining files, which it
lists before reading instead of reading inside the listing. Its done now means
only that the callback asked to stop, so the merged read passes it on; the
no-op readers and a file starting at or after stopTsNs no longer report done,
which the merged read used to clear anyway.

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

* mq logstore: read parquet files named before a timestamp resume

A parquet file is named after its first source log, and that log can start
seconds before rows the file holds, so listing parquet files from the resume
second skipped a file named earlier that still held later rows. The reader now
keeps the same sparse logFileIndex the log reader uses and lists from the last
mark before which every file ends before the resume time, deciding each file
by its ts_max.

Rows are not in time order once windows flushed across a reload are compacted
together, so stopping at the first row past stopTsNs dropped later rows still
inside it. Each row is now kept or skipped on its own, and the returned
position is the latest row delivered rather than the last row looked at.

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

* query: take MIN and MAX of _ts from the files' recorded time range

MIN and MAX of _ts without column statistics were computed from file names,
which are only the start second of a file's first source log: MIN rounded down
to that second and MAX was the start of the latest file rather than its last
row. Each file's stats already carry ts_min and ts_max as MinTimestampNs and
MaxTimestampNs, so those are used when set, and names only for files that
record no range.

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

* mq broker: stamp a loaded partition's messages after the newest stored one

Within one LogBuffer timestamps only increase, but a new buffer starts LastTsNs
at 0, so a leader whose clock is behind the previous leader's stamped new
messages earlier than what was already stored, and a subscriber resuming by
timestamp from the last stored message dropped them. OffsetRange now also
records the newest ts_max of the partition's log and parquet files, and loading
a partition seeds LastTsNs with it, so the buffer bumps new messages past it.

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

* mq logstore: read parquet rows at the stop time

The log reader treats stopTsNs as inclusive, delivering an entry at it and
reading a file whose first entry is at it, but the parquet reader stopped at a
row equal to it and skipped a file starting at it, so the same bounded read
returned that message from a log file and dropped it once compacted. Both
checks are now inclusive.

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

* mq logstore: drop a debug print from the disk read

A disk read bounded by stopTsNs printed the stop time and the first entry past
it to stdout on every such read. It was a leftover debug line.

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

* mq logstore: start an offset read of parquet files at the offset

An offset read of the parquet files delivered every row from the first one on,
and the stateless fetch fills a disk chunk with a callback that stops after a
chunk's worth of entries outside it. Now that the reader honors that stop, a
fetch at 1000 from a partition stored only in parquet stopped after rows 0-999
and returned nothing. An offset read now skips files whose recorded range ends
below the offset or that record none, reads the rest in offset order, and skips
rows below the offset before they reach the callback. It returns the offset
after the last row delivered, not a timestamp position.

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

* mq logstore: read parquet files first in a merged offset read

The merged read took the live log files first and, now that it honors the
callback's done, returned without reading parquet when the callback stopped.
The stateless fetch stops after a chunk's worth of entries outside the chunk it
fills, so with offsets 0-999 only in parquet and 1000-1999 in log files, a fetch
at 0 stopped on the log files' entries and never reached parquet.

Compaction turns the oldest windows into parquet, so an offset read now takes
the parquet files first and the log files after: the lower offsets arrive
first, and since each source skips what lies below its start, a bounded caller
only stops on entries past what it wants. Compaction leaves a parquet file's
source logs in place until retention removes them, so the log files are read
from the offset after the last one parquet delivered, and each offset is
delivered once. Timestamp reads keep their order.

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

* mq logstore: serve merged offset reads from log files where they exist

A merged offset read took parquet first and the log files from the offset after
the last row parquet delivered. Compaction keeps a parquet file's source logs
until retention removes them and drops messages with no key or no data, so that
skipped those messages although their logs were still there, and delivered
compacted rows in place of the messages as written.

The log reader now lists its files before reading them, and an offset read
finds the lowest offset the listed log files record. Parquet serves only the
offsets from the requested one up to that, and the log files everything from
there, so each offset is read once and from a log file whenever one holds it.

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

* mq logstore: read schemaless parquet rows back as their published bytes

Compaction stores a schemaless message's bytes in the _value column, but the
parquet reader handed out the whole row marshaled as a RecordValue, with _key,
_ts_ns and _offset wrapped around it, so a consumer reading compacted offsets
got different bytes than it would from the log files, and the query engine
showed that wrapping as the value. A schemaless topic's rows now carry the
_value bytes as Data; schematized topics keep the marshaled row.

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

* mq logstore: fail a read that needs parquet when its reader cannot be set up

A topic whose schema cannot be laid out as parquet left the parquet
reader nil, and a merged read that reached parquet called it and
panicked. Such a read now returns the setup error; skipping the parquet
rows silently would hide stored messages.

* mq logstore: a stopped log read returns the last delivered time

A later-named log file can hold earlier messages, so the latest time a
stopped read delivered can be past one it never reached.

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

* mq logstore: compact a group's rows in offset order

Source logs list by name, which sorts out of offset order under clock
skew, so a compacted file could hold offsets 2,3,0,1. An offset read
delivers a file's rows as stored and then reports a next offset past
ones it never delivered.

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

* mq: floor a reload's stamps by the newest legacy log file name

Log files record ts_max only since this release, so after an upgrade a
reload saw no newest time and seeded the stamps at zero. A log file that
records no times is named by its first message, so its second still
bounds the newest stored time.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:14:02 -08:00
Chris LuandClaude Opus 5.5 e84c3f9ada mount, filer: a content change clears the stored content MD5 (#13238)
* mount: a content change clears the stored content MD5

Attributes.Md5 is the whole content's MD5: the S3 and WebDAV ETags and
WebDAV's oc:checksums report it. A write, a size change, a grown
fallocate, an O_TRUNC open or a copy_file_range into the file kept it, so
those reported the old content's MD5 and an ETag that did not change.

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

* filer: AppendToEntry clears the stored content MD5

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

* mount: copy_file_range clears the MD5 once it buffers bytes

A cancelled copy or a later read error returned before the clear, leaving
the bytes already buffered under the old MD5.

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

* filer: an empty AppendToEntry keeps the content MD5

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:22:56 -08:00
484e16e30c webdav: keep X-OC-Mtime and report oc:checksums (#13226)
* webdav: keep X-OC-Mtime and report oc:checksums

ownCloud and Nextcloud sync clients, and rclone's webdav backend in those
vendor modes, send a file's modification time in X-OC-Mtime and read its
hash from the oc:checksums property. Without them every upload gets the
upload time as mtime and clients can only compare sizes, so syncs re-upload
unchanged files.

- PUT stores X-OC-Mtime (Unix seconds, fractions dropped) as the entry's
  mtime, at create and at commit, and answers "X-OC-Mtime: accepted"
- a file created and written front to back stores its content MD5; any
  other write clears it, so no stale MD5 outlives a partial rewrite
- PROPFIND reports oc:checksums ("MD5:<hex>") for files whose MD5 is known;
  PROPPATCH is still refused

Checked with rclone (vendor=owncloud): sync keeps mtimes, md5sum matches
local files, including an 8-chunk file.

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

* webdav: only report an inline MD5 for whole inline content; test commits

- contentMd5 hashes inline content only when it is the whole file
  (filer.ETagOfInlineContent): content next to chunks, or shorter than the
  file size, is only part of it and must not be advertised as its checksum
- test a PUT that crosses a buffer flush end to end: the committed entry
  carries the X-OC-Mtime and the MD5 of the whole body
- test that writing into an existing file clears its stored MD5

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

* webdav: ignore a NaN X-OC-Mtime

int64 of NaN is implementation-specific (the most negative value on amd64,
the largest on riscv64), so a NaN header could store an arbitrary mtime.

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

* webdav: group the oc test imports

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 13:16:48 -08:00
Chris LuandClaude Opus 5.5 c8cd1a7d77 volume: refuse a batch delete while a replica is offline (#12311)
* volume: refuse a batch delete while a replica is offline

BatchDelete now applies the replica check the HTTP delete path already
uses: when the master lists fewer replicas than the volume's copy count,
the delete is refused with 503 instead of applied to the replicas that
remain. The caller retries, so the replica that was offline still gets
the delete once it returns.

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

* filer: retry deletes refused for an offline replica

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

* volume(rust): refuse a batch delete while a replica is offline

Mirrors the Go volume server: batch_delete checks that the master lists
every replica of a replicated volume before deleting, and answers 503
with the replica count error otherwise.

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

* filer: move exhausted deletion retries to dead letter queues

A deletion that still fails after the backed-off retries is no longer
dropped. It moves to a dead letter queue retried after 24 hours, then to a
second one retried after 48 hours, and is dropped only if that fails too.
The id stays in the durable deletion ledger the whole time, so a restart
replays it instead of losing it.

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

* volume: report a low-disk volume as read-only but deletable

A volume is read-only while its disk is low on space, but it still
applies deletes; only noWriteOrDelete refuses them. The heartbeat set
readOnlyCanDelete from the operator mark alone, so the master listed a
low-disk replica as refusing deletes and the replica count check
rejected every delete on its volumes, on the healthy replicas too.

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

* volume(rust): report a low-disk volume as read-only but deletable

Mirrors the Go heartbeat: readOnlyCanDelete is set whenever the volume
is read-only without no_write_or_delete, which includes low disk space.

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

* filer: retry deletes a low-disk replica could not record

A low-disk volume now counts as deletable, but appending the tombstone
can still fail with no space left on device. Treat that as retryable so
the deletion stays queued instead of being dropped after the other
replicas applied it.

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

* master: keep under-replicated volumes out of empty-volume cleanup

The cleanup only looked at the copies the master lists. With a replica
offline the listed copies can be empty and quiet while the missing one
still holds data, and deleting them would leave that copy as the only
one when it returns. Low-disk replicas now report readOnlyCanDelete and
pass the eligibility check, which made this reachable for more volumes.

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

* master: finish a partly deleted empty volume in the next sweep

When one copy's VolumeDelete succeeded and another failed, the vid was
left with fewer copies than its replica placement, so every later sweep
skipped it as under-replicated and the empty copy kept its slot. The vid
now stays marked deleting after a partial delete, and the next sweep
finishes it. The mark is cleared once the vid is gone or stops being an
empty, quiet candidate.

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

* master: keep the cleanup mark while a survivor is only read-only

A partly deleted empty volume lost its deleting mark when the next sweep
found a surviving copy read-only. Later sweeps then skipped the vid as
under-replicated, so the empty copy kept its slot after it became
deletable again. Only a copy that gained data or was written recently
clears the mark now; a read-only or missing copy just postpones the
cleanup.

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

* shell: delete an empty volume only when every copy is empty

volume.deleteEmpty judged each copy on its own, so it removed an empty
copy while another copy still held data or was offline, leaving that
one as the volume's only copy. Low-disk copies now report
readOnlyCanDelete and passed the check as well. Apply the master
sweep's rule: every copy is listed and every copy is empty.

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

* shell: name the copies a partial empty-volume delete leaves behind

Once some copies of a volume are deleted, a rerun of volume.deleteEmpty
skips the rest as under-replicated, and the shell keeps no state to
finish them. Log each copy whose delete failed with the volume.delete
command that removes it once it is empty.

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

* shell: keep the gRPC port in the printed volume.delete command

ServerAddress.String() drops a custom gRPC port, so the printed -node
would dial the HTTP port plus 10000. Print the full address.

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

* filer: let manifest retries pass through the dead letter queues

The manifest retry queue reuses DeletionRetryQueue, so a manifest that
does not resolve now waits through both dead letter queues before it is
deleted alone.

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

* volume(rust): look up a batch delete's replicas over the master's gRPC port

lookup_volume now dials the master's gRPC port, as Go's LookupVolumeIds
does; the replica check and its test follow.

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

* volume: let a batch delete through on a volume grown degraded

A volume the master grew with fewer copies than its placement reports
min_writable_copies in the lookup. Go's replica check already uses it;
Rust now does too, so deletes on such a volume are not refused forever.

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

* volume, shell: let volume.merge write deletes into its merged copy

volume.merge marks the source copies read-only and writes the merged
records, deletes included, into a temporary copy that replaces them. The
batch delete replica check counts only the temporary copy there and
refused every delete, so the merge stopped at its first tombstone.
BatchDeleteRequest.skip_replica_check lets a caller that updates the
other copies itself skip the check; volume.merge sets it.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:14:33 -08:00
Chris LuandClaude Opus 5.5 25b9278d60 mq: conditional topic.conf saves, bounded topic.conf I/O, and mq.balance moves that save their assignment (#13231)
* mq broker: give up topic.conf filer calls with the caller's context

The topic.conf read and save helpers took no context, so a filer that took
the call and never answered kept the balancer inside topicConfLock for good,
and every ConfigureTopic, lookup repair and EndPartitionGeneration queued
behind it on a plain mutex. reportGenerationEnded's per-attempt deadline
could not bound any of it. The helpers now take a context, the RPC paths pass
their request context, and topicConfLock is a one-slot semaphore whose wait
ends with the caller's context. Calls made while holding it are also bounded
by topicConfTimeout, so a caller without a deadline cannot hold it forever.

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

* mq broker: save topic.conf only if it is still what was read

Every topic.conf update is a read-modify-write on the balancer, but the save
was unconditional, so a balancer whose lease ran out between its read and its
save wrote its stale assignments over a successor's newer epoch. topicConfLock
only orders writers within one broker. A failed read in ConfigureTopic could
also recreate an existing topic from scratch.

The read now returns the topic.conf entry, and the save is an ObjectTransaction
requiring that entry unchanged, or the file still absent for a new topic. A
refused save is redone from a fresh read a few times, so a report for an epoch
a successor already ended finds it moved on, and then gives up with
Unavailable for the caller to retry.

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

* mq broker: save mq.balance moves to topic.conf before assigning them

A balance move only told the target to load the partition and the source to
drain it. It never touched topic.conf, so lookups kept sending publishers to
the source, and since partitions are fenced by epoch the target was asked to
lead at epoch 0 and refused before anything moved.

The balancer now runs the move itself: it saves the target as leader at the
next epoch through the conditional topic.conf save, tells the source about the
new epoch so it retires its copy, flushing what it holds under its own fence
and sealing it, and then assigns the target, which takes the fence at the new
epoch. A follower that becomes the leader swaps places with the old leader.

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

* mq broker: keep a retiring leader's fence renewed until it seals

A leader told of a newer epoch, as a balance move's source is, retires its
copy by shutting it down and waiting for its last flush before sealing the
fence, but it did not renew the fence meanwhile. A flush outlasting
fenceSealWait left an aged unsealed fence the new leader could take, and the
pending flush then failed its fence check and dropped acknowledged messages.
The fence is now renewed for as long as the flush takes. Loaders retiring the
same copy at once share one renewal, which the first to return stops before
any seal, so no renewal lands on a sealed fence.

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

* mq broker: save a configure's assignment repair with its update

ConfigureTopic saved the repair of assignments on dead brokers on its own,
then saved the requested schema or retention change against the entry it had
read before that repair. The second save was always refused, so the update
went round a full reread, and a resize first drained brokers for nothing. The
repair is now applied in memory and saved together with the requested change
in one conditional save. A resize replaces the assignments anyway, so it no
longer saves a repair first.

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

* mq broker: report a balance move the target refused

assignTopicPartitionsToBrokers logged each broker that refused its assignment
and returned nil, so mq.balance reported success for a move whose target never
took the partition, after topic.conf had already moved and the source had
retired its copy. It now returns the refusals, and BalanceTopics passes them
to its caller. The saved move stands: a retry assigns the target again, and
the target also loads the partition on first use. ConfigureTopic keeps
logging a refused assignment of a topic it has saved, as before.

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

* mq broker: give up a topic.conf cache miss with the caller's context

getTopicConfFromCache waited for topicConfLock and read the filer under
context.Background(), so a lookup whose caller had already given up stayed
queued behind whatever held the lock and then did up to topicConfTimeout of
filer work for nobody. It now takes the caller's context, which LookupTopicBrokers
and the retention purge pass along and the partition loaders pass as
Background; cache hits are unchanged. A waiter whose context has already ended
no longer takes a free lock either, since a select with both cases ready picks
one at random.

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

* mq broker: require exactly one moved partition in the balance tests

The move tests took the last partition led by the target as the moved
one, so a move that handed both partitions to the target would pass.
They now fail unless exactly one partition moved.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:03:20 -08:00
40bb214b3f s3api: store a re-copied multipart part as a new attempt so the earlier copy's data is freed (#13216)
* s3api: replace a re-copied multipart part in place so the old part's data is deleted

UploadPartCopy into a part number that already held a part removed the
old part entry with isDeleteData=false and then wrote the new one. The
filer deletes the chunks an entry replaced only when it overwrites that
entry, as UploadPart does, so the old part's chunks were left on the
volume servers with no entry referencing them, for every retried or
repeated copy of a part. The same applied to an empty-range copy.

The part entry is now written over the existing one: the filer deletes
the chunks the new entry does not hold, and the part is never missing
between the two writes.

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

* s3api: store each UploadPartCopy as a new attempt of the part instead of replacing it

Replacing a copied part in place deletes the replaced part's chunks while
the upload is open. A CompleteMultipartUpload that listed the part before
the replacement builds the object from those chunks and can commit it
after they are deleted. UploadPart never replaces a part: each upload is
a new attempt with its own name (genPartUploadPath).

copyPartLocation now names each copy the same way, and nothing is replaced
or deleted when a part is copied again. Completion already uses the latest
attempt of each part number and frees the data of the others after it
commits, and abort frees them all, so the earlier copy's data is still
reclaimed, without a window against a completion in progress.

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

* s3api: trim the UploadPartCopy attempt comments

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 12:32:11 -08:00
Chris LuandClaude Opus 5.5 0872953b81 mount: resolve NFS file handles across a weed mount restart (-nfsExport) (#13020)
* mount: persist a created file's entry at create time under -nfsExport

A file created over NFS gets a handle at create time. With creation
deferred to flush, a mount that stops before the flush leaves no entry for
the next mount to resolve that handle to.

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

* mount: resolve NFS file handles of files an earlier mount had open

With -nfsExport, the mount records on the filer the path of each file it
has open, keyed by inode, and drops the record a minute after the last
close. A "." lookup on a node id the mount does not know reads that
record, so the NFS server can reopen its files after the mount restarts or
another mount takes over. A failed read answers EIO rather than ESTALE.

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

* mount: record NFS handles at open, not on every path refresh

A writeback close flushes after the last release, and the flush refreshes
the handle's path. Recording there renewed the record of a file no longer
open, so it was never removed. Opens and creates now record, and a path
refresh only moves an existing record.

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

* mount: leave writeback creates deferred under -nfsExport

With writeback caching an eager create runs as an async filer RPC that an
unlink does not wait for, so a quick create+unlink could bring the name
back. Writeback mounts already accept losing unflushed files on a crash.

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

* mount: retain a recorded handle path only once it matches the file

A path read from the filer record was retained before the lookup checked
it, so a stale one kept answering ESTALE without reading the record again.
It is now retained right before LookupHandle, and never over a forgotten
inode or path the table already holds.

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

* mount: count NFS handle opens, keep other mounts' records, retry writes

A reopen that attached a new handle before the close registered its
release left a removal pending for an open file; opens are now counted.
Records carry the writing mount's signature, so a delayed removal leaves
a record another mount wrote since. A failed write is retried while the
inode's state is unchanged, and the put runs under the attempt context.

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

* mount: keep one NFS handle registration per mount in an inode's record

Two mounts with the same file open shared one record, so the one that
closed last removed the path the other still had open. Each mount now
replaces or drops only its own registration, and a lookup uses the newest.

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

* mount: name a mount's NFS handle registrations by host and mount directory

A restarted mount drew a new random signature, so it never replaced or
removed the registrations its predecessor left for files it had open.

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

* mount: take turns on an NFS handle record through the lock manager under -dlm

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

* mount: retry an NFS handle record update when its lock is not granted

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

* mount: renew an NFS handle record's lock for the whole update

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

* mount: resolve an NFS handle record to the newest path under the mount root

Another mount rooted elsewhere could hold the newest registration of a
hard-linked inode, hiding this mount's own valid path.

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

* mount: register an NFS handle at the path the mount knows now

A rename could move the inode after an opener read its path but before
the new handle was registered, so the record kept the old path; a stale
opener could also move an existing record back.

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

* mount: keep no NFS handle records with -filer.tokenFile

The filer refuses KvGet and KvPut to scoped tokens, so the records would
only fail: log at startup instead, and keep the in-process handle support.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:31:17 -08:00
f9157933f0 volume: refuse a write the local volume already rejects before forwarding it to the replicas (#13214)
* volume: refuse a write the local volume already rejects before the replica fan-out

ReplicatedWrite runs the local needle write and the replica fan-out
concurrently. When the local volume is read-only (noWriteOrDelete or
noWriteCanDelete), unavailable, or on a disk below -minFreeSpace, the
local leg fails, but the replicas have already stored the needle. The
client writes to a new file id, so the replica copy is referenced by
nothing, and the copies of the volume differ in file count and size
until volume.fsck purges it.

Ask the volume whether it accepts writes (Volume.CheckWritable, the
same check Store.WriteVolumeNeedle applies first) before the fan-out
starts, and fail the request without contacting the replicas. The error,
its metrics and the ErrorWriteRefused rule are those of a failed local
write. A type=replicate request, and a write with no local copy, are
unchanged.

A volume that turns read-only after the check, during the write, still
leaves a replica copy.

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

* volume: observe a write refused before the fan-out in the local write histogram

The local write that the up-front refusal replaces observed the refusal in
the WriteToLocalDisk request histogram next to the error counter. Observe
it there too, so a refused write is counted as before. The replication
metrics do not record it, since it no longer reaches the replicas.

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

* volume(rs): refuse a write the local volume already rejects before forwarding it to the replicas

Mirror the Go up-front check: when the local volume refuses writes, the
replicated upload fails with the local refusal and never spawns the
replica fan-out, so no replica keeps a needle nothing references.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 12:03:04 -08:00
Chris LuandClaude Opus 5.5 f65234685a filer.sync: check the stream bottleneck test by peak jobs in flight (#13233)
TestConcurrencyIneffectiveOnStreamBottleneck compared the wall-clock
rates of separate runs at concurrency 32 and 512 and failed on a loaded
32-bit runner when one run took 1.6x longer than the other. The ratio
measured runner load, not the processor.

Record the most jobs that ran at once instead. While it stays below the
smallest limit, the limit never holds back an event, which is why a
larger -concurrency cannot help a stream-limited sync.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:01:24 -08:00
MapleWhiteZZZandMapleWhiteZZZ 76cae100de filer: leave the manifests an update keeps unread when finding its garbage (#13224)
MinusChunks finds the chunks an update drops by resolving every manifest of
the old entry and of the new one. A manifest both entries list is the same
needle on both sides: all it holds is held by both, so none of it can be
dropped, yet it was read from a volume server twice on every update. A file
whose older chunks are folded into manifests paid that on each chmod, utimes,
setxattr and append.

Manifests listed on both sides are now taken out of both lists before the
others are resolved. They are read only when something else the old entry
holds might still be held through one of them, and then subtracted, so the
result is the one resolving everything gives. An attribute change or an
append that keeps the manifests reads none of them, and a kept manifest
that cannot be read no longer fails an update that drops nothing.

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
2026-12-01 12:00:31 -08:00
Yip LeoandClaude Opus 5.5 0b0f54381d s3api: list every entry of the upload directory when completing a multipart upload (#13219)
prepareMultipartCompletionState read the upload directory with one
listing of MaxS3MultipartParts+1 entries and ignored whether more
remained. The directory holds one entry per attempt of a part, as each
UploadPart gets its own name, so an upload with many parts and some
retries can hold more, and the parts that sort after the first page were
never found: completion answered InvalidPart for parts that exist. The
cleanup listing of an already committed completion was capped the same
way.

listUploadEntries lists the directory page by page until the listing
reports its last entry, and both listings use it. The completion test
filer now pages like the filer, which its map-order listing had hidden.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:59:35 -08:00
Yip LeoandClaude Opus 5.5 e8fef6bdfd mount: fail a read of dirty pages that cannot be read back from the swap file (#13215)
Dirty pages that weed mount buffers in the swap file (non-sequential
writes, or when the memory chunks run out) also serve reads until they
upload. SwapFileChunk.ReadDataAt logged a read error and stopped,
returning only how far it had read; UploadPipeline.MaybeReadDataAt and
DirtyPages.ReadDirtyDataAt passed that offset up. The mount read path
then served the rest of the range from the stored chunks or from zeros,
and the read returned OK. A read error on the cache disk, or a swap file
truncated by an outside cleanup, is enough: the application reads back
bytes it was told were written and gets other bytes, with no error
anywhere. This is the read-side twin of #13198, which made the upload
of those bytes fail.

PageChunk.ReadDataAt, UploadPipeline.MaybeReadDataAt and
DirtyPages.ReadDirtyDataAt now return an error besides the offset. A
swap chunk that cannot read back an interval overlapping the requested
range returns it, wrapping the new ErrDirtyDataUnreadable and the read
error (a short read is io.ErrUnexpectedEOF). Intervals outside the range
are not read, so a read that does not touch the lost bytes still
succeeds. MemChunk cannot fail. The read handler and copy_file_range
turn the error into EIO. Read does not refresh the filer entry and retry
for this error, since the entry has no say over bytes that only exist in
the swap file.

A failed read does not mark the handle failed. Reads of other ranges and
writes keep working, and the upload path already records the failure
when it cannot read the same bytes, so flush, fsync and close return EIO.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:58:05 -08:00
30d7f484aa s3api: delete the chunks a failed CopyObject or UploadPartCopy wrote (#13217)
* s3api: delete the chunks a failed CopyObject or UploadPartCopy wrote

A copy writes new needles for the destination before any entry
references them. copyChunks and copyChunksForRange returned on the
first failed chunk without waiting for the copies still running, and
nothing deleted the chunks already written. The running copies went on
to write needles after the request was over; the written ones were never
referenced. The same happened when the copy succeeded and the later
write of the entry failed or a destination precondition refused it, and
in the per-chunk loops of the SSE copy paths.

The concurrent copies now go through copyChunksConcurrently: no further
copy is started after a failure, every started copy is waited for, and
the chunks the others wrote are deleted with deleteOrphanedChunks. The
sequential SSE loops delete what they wrote when they fail part-way. A
chunk a failed copy returned is not kept anywhere, so nothing is left
for volume.fsck.

CopyObject and UploadPartCopy delete the copied chunks when a
precondition or the lock refuses the write, or when the write of the
entry fails and no filer holds an entry at that path that references
them: a failed write can have committed (the answer lost), and chunks
deleted under a stored entry would break the object. An answer the
lookups cannot settle keeps the chunks. Chunks the source entry also
holds (the SSE-KMS same-key rotation hands them back) are never deleted.

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

* s3api: keep a failed copy's chunks when any entry exists at the destination

After a failed write of the destination entry, the copied chunks were
deleted when the first entry the lookup found did not hold them. That
entry can be an older one on one filer while the copy's own entry
committed on another, for example a part written to a filer the routing
failed over to, so the delete could reclaim chunks a stored entry holds.

Delete them only when no filer holds an entry at the path and every filer
answered, as putToFiler does. A copy that fails over an existing object
therefore still leaves its chunks.

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

* s3api: keep a copy's chunks when its failed write may still commit

A write of the destination entry that fails without the filer's answer
(a transport failure, a timeout or a cancel) can still be running on the
filer. A lookup that finds no entry then proves nothing: the write can
commit after it, and an entry would reference the chunks the cleanup
deleted.

Keep the copied chunks after such a failure without a lookup; these are
the errors filerErrorToS3Error keeps retryable for the same reason. The
lookup now runs only after the filer answered the write with an error.

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

* s3api: keep a copy's chunks whenever its write of the entry fails

A failed write of the destination entry can have committed with its
answer lost, or still commit: after a transport failure, or when a
failover replay that another filer refused hides an ambiguous first
attempt. A lookup cannot tell these apart, and chunks deleted under a
stored entry break the object, which is worse than the leak.

CopyObject and UploadPartCopy therefore keep the copied chunks when the
write fails. They still delete them when the lock or a precondition
refuses the write, or the old part cannot be removed, before any entry
write is attempted.

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

* s3api: size the copy-owned chunk set without adding slice lengths

CodeQL flags the summed capacity hint as a possible allocation overflow;
the map grows as needed anyway.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 11:57:00 -08:00
Chris LuandClaude Opus 5.5 3809cfe4cf mq: fetched messages carry their log offset (#13229)
* mq: carry the log offset on fetched messages

FetchMessage answers with DataMessages that have no offset, so a client
can only number them by position from its start offset. That is wrong as
soon as the stored range has a hole or an entry the log cannot place.
DataMessage gains an optional offset; presence tells a broker that sets
it apart from one that predates it.

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

* mq broker: send each fetched message's log offset

FetchMessage dropped the offset of every log entry it read, leaving clients to number the messages by position. Each DataMessage now carries its LogEntry offset, including -1 for an entry the log could not place.

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

* mq/kafka: number fetched records by the broker's offsets

The gateway numbered the records of a fetch as start offset plus position, and moved the next fetch past them by count. A hole in the stored range, such as offsets 10, 11 and 13, put record 13 at 12 and fetched it again at 13. Records now take the offset the broker sends, the batch offset deltas and the next offset follow those offsets, and an entry the broker reports at -1 is left out rather than given a guessed offset. A broker that sends no offsets is still numbered from the start offset.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:51:08 -08:00
Chris Lu abd2587f9e s3api: send user metadata headers in lowercase (#13228)
GET/HEAD returned user metadata as X-Amz-Meta-<key>. AWS sends
x-amz-meta-<key>, and older aws-sdk-kotlin releases match the prefix
case-sensitively, so they saw no metadata at all. Airbyte's S3
destination reads ab-generation-id that way at the end of an Overwrite
sync, treats a missing id as generation 0, and deleted the files it had
just written.
2026-12-01 11:36:58 -08:00
Chris LuandClaude Opus 5.5 d6dee41f00 ec: do not place shards on a volume server in maintenance mode (#13227)
* master: report a volume server's maintenance mode in DataNodeInfo

Planners that work from VolumeList had no way to tell a volume server in
maintenance mode from any other, so they kept choosing it as a target.

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

* admin: give a volume server in maintenance mode no free capacity

It refuses new data, so EC encode and balance planning must not pick it as
a destination; it stays listed so it can still be a source.

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

* ec_balance: never move shards to a volume server in maintenance mode

It refuses every shard copy, and right after an evacuate it is the emptiest
server, so the planner kept targeting it.

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

* shell: count no free EC shard slots on a volume server in maintenance mode

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

* ec: report the volume server's error when it refuses a shard upload

A refused ReceiveFile ends the stream, so Send returns only io.EOF and the
job logged "failed to send file content: EOF" instead of the reason.

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

* ec: test that a refused shard upload reports the server's error

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

* shell: never plan EC shard moves onto a volume server in maintenance mode

Zero free slots alone did not keep it out: a shard the planner moves off
the node credits a slot back, and a later move could take it.

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

* ec: test that ReceiveFileSendError reports a refusal in the response's Error field

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

* ec_balance: move the maintenance-target test to the end of the file

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:06:18 -08:00
76aa922d06 shell: let fs.du print subdirectory totals and list directories in parallel (#13212)
* shell: let fs.du print subdirectory totals and list directories in parallel

fs.du prints one total and walks the tree one directory at a time. Finding
where the data of a large bucket sits takes one fs.du per directory, each a
full walk, and every listing waits on the filer and its store in turn.

-depth N also prints the total of each directory down to N levels below the
given one, like du -d N. Directories come in du's order: each one after the
directories below it, siblings by name, and the given directory's total
last, as before. One walk now gives the whole breakdown.

-concurrency N lists up to N directories at a time. A subdirectory gets a
goroutine of its own while the limit allows one and is walked in place
otherwise, so memory grows with depth and concurrency, not with the number
of directories. filer_pb.TraverseBfs is not used because it remembers every
directory it visits and queues whole levels: on a tree of 200k directories
it held 49 MB more live heap than this walk at the same speed, and weed
shell often runs in a small container. A directory's listing is complete
before its subdirectories are walked, so no listing stream stays open while
a subtree is walked.

A directory that cannot be listed used to drop out of the totals silently.
It is still left out, but the command now fails at the end with the number
of such directories and the first of them. fs.du took its last argument as
the path, or the current directory when that argument started with a dash,
so "fs.du /dir -depth=1" would have walked the current directory. Flags now
go before the path, and anything else is an error. With a prefix
(fs.du /dir/name_prefix) and no -depth, the directories the prefix matches
are no longer walked, because nothing below them is printed.

The defaults, -depth=0 and -concurrency=1, print what fs.du printed before.

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

* shell: fs.du walks a page of subdirectories before listing the next one

fs.du collected the names of all subdirectories of a directory before it
walked any of them, so a directory with millions of subdirectories held
millions of names. It now lists 1024 entries at a time and walks the
subdirectories of a page before it asks for the next page. A directory
holds at most one page of names, and still no listing stream stays open
while its subdirectories are walked. On one directory with 200k
subdirectories the walk holds 0.5 MB of live heap with -concurrency=1 and
2.5 MB with -concurrency=5.

When a page of a listing fails, the pages before it still count and the
failed page is dropped. The help and the error said that such a directory
was left out of the totals; they now say that the totals are incomplete.
When the given directory itself cannot be listed, fs.du cancels the walks
under way and waits for them before it returns the error.

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

* shell: fs.du tests refuse a listing the way a failing filer store does

An Unavailable without details makes pb close the shared connection, so the
listings running beside the refused one failed with "the client connection
is closing" and the error named another directory (6 of 30 runs with -race).
A store error reaches the client as Unknown and leaves the connection up.

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

* shell: fs.du lists directories in parallel without a -concurrency flag

The walk prints the same totals in the same order at any concurrency, so
there is nothing for a user to choose: list up to DefaultMaxParallelization
directories at a time, like the other shell commands that fan out.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 11:01:37 -08:00
Chris LuandClaude Opus 5.5 13d9f3b104 mini: run weed-vector and weed-worker by default, continuing without either if missing (#13207)
* mini: start weed-worker with the vector engine

With -vector, mini now also starts weed-worker, the Lance maintenance
worker that builds vector and metadata indexes, finding it the way it
finds weed-vector: beside weed, then on PATH. -vector.worker=false leaves
it out and -vector.worker.binary names another binary.

The Lance Namespace trusts the worker only by a token derived from
jwt.filer_signing.key. A cluster with that key hands it to the worker
through security.toml as before. Without one, mini makes a key for the
run, gives it to the worker in its environment, and lets the namespace
accept it while no cluster key is set. The filer and the other services
are unaffected, so unauthenticated filer writes keep working.

* mini: run the vector engine by default, without failing when it is missing

-vector now defaults to true, so a plain weed mini starts weed-vector and
weed-worker whenever they are installed. Both binaries are looked up
before ports are reserved; one that is not found is logged and left out,
and mini runs without it. A vector engine that fails to start is logged
the same way instead of shutting mini down. -vector=false still leaves
vector search out.

* mini: clear the vector state a previous in-process run prepared

prepareMiniVector returned early without clearing the paths and key an
earlier run in the same process had set, so a rerun with
-vector.worker=false still started that run's weed-worker.

* mini: pass the [grpc.worker] certificates to weed-worker

weed-worker takes its admin TLS only from --tls-ca, --tls-cert and
--tls-key, not from security.toml, so behind an admin secured with
[grpc.admin] the worker mini started dialed in plaintext and never
connected. Mini now passes the certificates its Go workers dial admin
with, chosen as security.LoadClientTLS chooses them.

* mini: find weed-worker without new flags

Drop -vector.worker and -vector.worker.binary. weed-worker is looked up
beside weed, then beside the weed-vector mini starts (so an explicit
-vector.binary also locates it), then on PATH; -vector=false leaves both
out.

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

* docker/s3vectors: keep mini from starting a second engine and worker

The demo runs weed-vector and weed-worker in their own containers. With
-vector on by default, mini in an image that ships both binaries would
start another engine and worker beside them.

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

* mini: look for weed-worker beside a relative -vector.binary

filepath.Join drops the "." of ./weed-vector, so the sibling candidate
became a bare name and LookPath searched PATH instead. Resolve the
directory first.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:58:00 -08:00
Yip LeoandClaude Opus 5.5 82a435c468 mount: list a directory from the filer when the cache disk cannot hold it (#13204)
* mount: list a directory from the filer when the cache disk cannot hold it

A listing builds the directory into the mount's local metadata cache, a
leveldb store under -cacheDir, and serves it from there. Once that disk is
full the build fails at its first write, and the listing failed with it:
readdir returned EIO for every directory the mount had not cached, and for
one whose cached listing a refused event had just dropped (#13141). Files
could still be opened, read and written; only listing them broke.

A build the store refuses now reports a LocalStoreError, and the listing
reads the directory through from the filer, the way it already does for a
directory too large to cache. Builds then wait out a 10s backoff instead of
re-listing a directory from the filer only to fail at its first insert
again; once the disk has room the next build caches the directory. While
the store refuses, at most 4 listings per mount read through at once, so a
burst of them reaches the filer spread out rather than all together.

The hand-over from a walk served from the cache to one read through from
the filer resumed at the request's offset, so the entries the cached walk
had just put in the same reply were sent again and the client listed them
twice. A directory found too large partway through a walk took that path
rarely; a full cache disk takes it on every request. The direct walk now
resumes past the entries already in the reply.

Lookups needed no change: in a directory the cache does not hold, a lookup
already asks the filer for the one entry.

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

* mount: list unflushed creates and every page when reading a directory through

Listings read through from the filer are now the common path on a full
cache disk. This fixes three gaps in them:

- A file created on this mount is not on the filer until its first flush.
  Until then the local store holds a placeholder for it, which a rebuild
  keeps. A cached listing showed such a file; a listing read through from
  the filer left it out. The read-through now merges in, page by page and
  in name order, the children the local store keeps for a rebuild
  (MetaCache.LocalOnlyChildren, which asks the same pinnedChildFn as the
  rebuild's wipe). Each page takes the ones after its start and up to its
  last name; the last page takes every one past its start. A name the
  filer also has by now is listed once. Directories too large to cache
  read through the same way, so they get the fix as well.
- The filer applies the page limit before the loader leaves out the root's
  hidden system entries (etc, topics). A full page that held one came back
  short, and the listing ended there. The end of the directory is now read
  from the number of entries the filer sent. If a failover reruns a page,
  the loader starts its entries and that count over.
- A walk served from the cache also hands over to the filer when
  refreshing a stale section would list too many entries
  (ErrRefreshRangeTooLarge). That hand-over still resumed at the request's
  offset, so it sent again the entries already in the reply. It now
  resumes where the cached walk reached, like the other hand-over.

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

* mount: keep the rest of a read-through page on the directory handle

A page listed from the filer went onto the directory handle only up to the
entry the reply had no room for. The next request listed the filer again
from there and merged the unflushed creates again, so with small replies
each filer page was listed, and the local store scanned, once per reply.
Now the whole page goes onto the handle, and later requests take what is
left from it, as they do from the cache. The unflushed creates are also
looked up without decoding chunk lists.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:57:29 -08:00
a2a7a589bb filer: keep the content out of S3 config parse errors (#13202)
* filer: keep the content out of S3 config parse errors

protojson's errors quote the token they reject, and in these files that
can be a secret key or KMS key material, so a config that didn't parse
could log part of a key. The error now gives the line and column, the
field's type and name for a value of the wrong type, or says the file
ends early. Syntax errors come from encoding/json, which gives an offset
instead of a quote, so protojson's text is only read for valid JSON.

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

* filer: keep codespell from flagging a parse error test case

Codespell reads `tru` in `{"é": tru#` as a misspelling. `nul#` fails at
the same column.

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

* credential: run the store interface tests on the memory store

The tests took the first registered store, which depends on package
init order: once filer_etc registered first they ran against a filer
that is not there.

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

* credential: keep the content out of static S3 config file parse errors

LoadS3ConfigFile parsed the -s3.config file with protojson directly, so
the filer logged a rejected token such as a secret key. It now uses
ParseS3ConfigurationFromBytes like the other readers of that file.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 10:56:25 -08:00
19204293c2 filer: always range-fetch a chunk too big for the reader budget (#13201)
* filer: always range-fetch a chunk too big for the reader budget

A whole chunk view bigger than the reader cache budget only fell back to
a range fetch in random mode. A sequential read, or a read across a
chunk boundary, took the whole-chunk path and failed with "chunk buffer
needs N bytes, exceeding reader cache budget". Prefetch also started
such chunks, which took a slot in the cache and then failed.

readsRange now decides for both read paths, and a chunk that can't fit
the budget is always a range fetch. Prefetch skips it.

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

* filer: test that prefetch skips a chunk over the reader budget

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 10:55:20 -08:00
Chris LuandClaude Opus 5.5 f9c08ad379 docker: keep resolv.conf readable after dropping to the seaweed user (#13213)
* docker: make resolv.conf and hosts readable before dropping to the seaweed user

A Docker daemon running with a restrictive umask writes the container's
/etc/resolv.conf and /etc/hosts as 0600. The entrypoint then drops to the
seaweed user, which cannot read them, so Go's resolver falls back to
localhost:53 and every peer lookup fails with connection refused, while
nslookup through docker exec (root) still resolves.

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

* docker: warn when resolv.conf stays unreadable to the server user

The entrypoint cannot fix the mode when the file is mounted read-only,
under a user namespace, or when the container starts as a non-root user,
so say why peer lookups are about to fail.

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

* docker: warn about an unreadable /etc/hosts too

Names defined only there stop resolving the same way, and resolv.conf
may be readable while hosts is not.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:53:45 -08:00
Chris LuandClaude Opus 5.5 3beca7d956 mq: resume inside the file holding the resume point, and start offset reads near the offset (#13209)
* mq logstore: resume a timestamp read inside the file that holds the resume point

A disk read by timestamp listed the partition from the file named after the
resume second and dropped every earlier name, so the file that started before
that second but still held messages after the resume point was skipped and
its remaining messages were never delivered. The reader now keeps a sparse
index of the partition's log file names, starts listing at the last mark
before the resume second, and reads the last file starting before that
second along with every later one; its entries up to the resume point are
already filtered by timestamp. This covers names with and without the offset
suffix.

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

* mq logstore: read a log file's offset range in one place

The disk reader decoded offset_min and offset_max inline in three places, by
string literal rather than the mq constants. A single logFileOffsets helper
now reads both, so the reader and the offset index added next agree on what a
file records. No behavior change: the flush writes both attributes together.

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

* mq logstore: start an offset read at the indexed file holding the offset

A disk read by offset listed the whole partition directory on every call and
filtered the files by their offset ranges, so a lagging consumer paid for the
partition's entire history on each read. The reader's sparse index of log
file names now also keeps each mark's first offset, and an offset read lists
from the last mark starting at or before its offset; offsets grow with names,
so no earlier file can hold it. The index is extended by every listing past
the last name it has seen, so after the first read a call lists at most one
stride of files before its own plus the files after it. When no mark with an
offset range is at or before the offset, as with files that record none, the
read still lists from the first file.

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

* mq broker: never name a log file before the newest one in its partition

A log file is named by its window's start second, taken from the writing
broker's clock. A new leader whose clock is behind the previous one's wrote
windows whose names sorted before older files holding lower offsets, so names
no longer followed offsets. An offset read listing from an indexed file then
skipped the new windows, and a read starting below such a file passed over it
without notice; no reader-side check can see a file that sorts before where
it starts listing. The partition fence now carries the newest log file time:
the leader seeds it from the listing it already pages to continue the
partition's offsets, which now also reports the newest log file name, legacy
names included and compacted files, the fence and directories excluded. Each
flush names its window no earlier than that time and advances it. Files
sharing a second still sort by their min offset suffix. Timestamp reads
resuming past the old leader's names now list such windows too, though
entries timestamped before the resume point are still filtered out by
timestamp.

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

* mq: bound a log file by its first message time, not its name

Now that a window can be named after a later second than its messages to
keep names in offset order, the disk reader's stop filter, which dropped
every file whose name second was after the stop time, missed windows whose
messages were inside a time-bounded read. A flush now records the window's
first message timestamp on the log file as ts_min, the attribute parquet
files already carry, and the stop filter compares that when present. Files
without it were written before names could be moved later, so their name
still bounds them.

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

* mq logstore: read every offset candidate, not a binary-searched suffix

An offset read binary-searched its candidate files by offset range and
dropped those before the hit, assuming name order matched offset order. A
directory written under clock skew holds a file that sorts before files with
lower offsets, and the search skipped it even on a full listing. The listing
already drops files whose range ends before the offset, so in an ordered
directory the search removed nothing but offset-less legacy files, which are
filtered per entry anyway. The search is gone.

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

* mq logstore: list from the start once a partition's names leave offset order

An offset read lists from the indexed file starting at or before its offset,
which is right only while names sort in offset order. Directories written
under clock skew before log file names were kept ordered hold files sorting
before files with lower offsets, and a read listing from a later mark passed
over them. The index now remembers the highest offset it has seen in name
order, and once a file starts below it the partition is unordered and every
offset read lists from the first file, as before the index existed.

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

* mq broker: name a takeover's file no earlier than the newest one stored

A follower taking over named its file by its first entry's time, so a
follower whose clock is behind its lost leader's wrote a name sorting
before files holding lower offsets. It now takes the newest stored name
from the listing it already reads for the high-water mark and names
its file no earlier, as a leader's flush does.

* mq: resume a timestamp read in every earlier file holding later messages

A timestamp read kept only the last file sorting before the resume second,
assuming names bound message times. A window named no earlier than the
newest stored file can sort after a file it does not follow in time: a slow
leader's window of older messages took that last place and the file before
it, still holding messages after the resume point, was never read. A flush,
and a follower's takeover write, now also record the window's last message
time as ts_max, the attribute parquet files carry. Of the files sorting
before the resume second, every one whose last message is at or after the
resume time is read; files without it were named by their first message
and keep the old rule.

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

* mq logstore: return the latest time a timestamp read delivered

A timestamp read returned the last processed file's last message time as
its position, and each chunk's result replaced the file's. Files are read in
name order, and a slow leader's window can sort after a file holding later
messages, so the position went back and the next read delivered those later
messages again; a trailing chunk that delivered nothing also reset a file's
time to zero. The position is now the highest time delivered across chunks
and files.

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

* mq logstore: deliver an offset read's files in offset order

An offset read processed its candidate files in name order. In a partition
written under clock skew a file sorts before files with lower offsets, so
its entries were delivered first, and a reader taking only the first few
entries, as the chunked offset read does, got the wrong ones. The files that
record an offset range are now read in order of their first offset, each in
a place one of them held, so files without a range keep their position. In
an ordered partition this changes nothing.

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

* mq logstore: list a timestamp resume from the start once a name was clamped

A timestamp resume listed from the index's last mark before the resume
second. Once a window is named later than its first message to keep names in
offset order, many such windows can share one clamped second, and the marks
among them sorted after an earlier file still holding messages past the
resume point, so that file was never listed and never reached the check of
its last message time. The index now notes a file whose name is later than
its first message, and from then on a timestamp resume lists from the first
file. Partitions without such a name keep using the index.

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

* mq logstore: start a timestamp resume at a mark bounded by message times

A timestamp resume listed from the index's last mark sorting before the
resume second, falling back to the first file once a clamped name was seen.
That still assumed names bound earlier files' messages: windows whose
messages overlap within one second, none of them clamped, could push a mark
past an earlier file holding messages after the resume point, and the resume
skipped it. Each mark now records the latest message time of every file
sorting before it, from ts_max, or for a file without it the end of the next
file's start second, since such files were named by their first message and
ended before the next began. A resume starts at the last mark whose earlier
files all end before the resume time, so the files it skips hold nothing it
still has to deliver, whatever the names or clocks. The clamped-name flag is
gone.

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

* mq logstore: leave an older file unbounded when the next name was clamped

A file without a recorded last message time was bounded by the end of the
next file's start second, on the reasoning that it ended before the next
began. When the next file is a slower leader's window clamped into that
second, its name says nothing about when its messages, or the older file's,
end; the older file was bounded too early, a later mark qualified, and a
resume past it skipped its remaining messages. The next file now bounds it
only when its name is not later than its first message; otherwise the older
file stays unbounded, no mark after it qualifies, and a resume lists from
before it.

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

* mq logstore: fetch by offset through the log buffer over out-of-order names

The out-of-order name tests drove the disk reader directly. A fetch
goes through the log buffer's disk chunk on top of it, so this reads a
few offsets at a time through ReadMessagesAtOffset over a partition
whose names sort out of offset order, and checks each fetch returns
its own offsets.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:52:54 -08:00
Chris LuandClaude Opus 5.5 746cae3895 mq: enforce topic retention (#13210)
* log_buffer: find a fetched offset in a disk chunk by its offset

A stateless read caches disk reads in chunks aligned to 1000 offsets and
picked the requested message by its distance from the aligned start. A
chunk read from disk begins at the first offset stored at or above that
start, so once the partition's oldest files are gone the chunk begins
later and the read returned messages from further on, under the
requested offsets. The message is now found by its offset, and the next
offset follows the last message returned.

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

* mq broker: start a loaded partition's log at its earliest stored offset

A loaded partition reported its earliest offset as 0 and its log start as
the start of its memory, so neither said where the stored data begins. The
log buffer now keeps the earliest offset still stored: a leader seeds it
from the offset ranges on its files when it loads, it only moves up, and
the partition's offset info and log start report it. A stateless read
below it fails with ErrOffsetOutOfRange instead of being answered from a
later file under the requested offsets.

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

* mq broker: purge a partition's files past its topic's retention

A topic's retention was stored but never applied, so a topic that is not
re-partitioned kept every flushed file. Every five minutes the broker now
purges each partition it leads whose topic has retention enabled. It
deletes the oldest run of files whose newest message is older than the
retention, stopping at the first file still retained so the stored
offsets stay contiguous, and always keeps the file with the highest
offset, which a later load continues offsets from. A log file is judged
by when it was flushed and a parquet file by its newest row; a parquet
file is deleted together with its source log files. The partition's log
start is raised before the deletes, and each delete is a transaction
conditioned on the partition's fence token, so a leader that lost its
fence deletes nothing.

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

* mq/kafka: map an unknown broker error to UNKNOWN_SERVER_ERROR (-1)

The gateway's error table gave UNKNOWN_SERVER_ERROR the code 1, which
Kafka uses for OFFSET_OUT_OF_RANGE, and the broker's table carried the
same value for its unknown and publisher-not-found errors. Today the
mapped code only reaches error text, but a fetch path that answers
OFFSET_OUT_OF_RANGE by its Kafka code would make every unknown broker
failure reset a consumer. The code is now -1. The gateway only tests
these codes against 0 and against specific codes, and the cached
assignment is still dropped on the broker's own code 1, so nothing
treated 1 as success or depended on it.

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

* mq: answer a fetch below retention with OFFSET_OUT_OF_RANGE

A read below the earliest retained offset failed like any other read, so
FetchMessage reported a storage error and the gateway answered
KAFKA_STORAGE_ERROR, which a consumer retries at the same offset forever
once retention has purged it. FetchMessage now answers
ErrOffsetOutOfRange with its own broker code, the earliest retained
offset as LogStartOffset, and the requested offset as NextOffset. The
gateway carries it as ErrOffsetOutOfRange and answers the partition with
OFFSET_OUT_OF_RANGE, so the consumer applies auto.offset.reset; a reset
to earliest asks ListOffsets, which reports the retained start through
the leader's range info.

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

* log_buffer: keep a disk chunk's entries in offset order

A disk read filled its 1000-offset chunk with the first 1000 entries
in the order the files listed, and the lookup searches the chunk by
offset. Files whose names sort out of offset order deliver entries out
of order, so the chunk held the wrong offsets and was cached that way.
It now keeps only the chunk's offsets, wherever they come, and sorts
them before caching.

* mq broker: purge a partition's files in offset order

The purge walked a partition's files in name order and stopped at the
first one still retained. Names sort by the start of a window, which can
be earlier than older files' after a reload, so a file holding higher
offsets could be purged ahead of a retained one below it, leaving a hole.
The walk now goes by each file's first offset, taking a parquet file that
records none from its first source, and by name among equals.

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

* mq broker: round a log file's flush time up to bound its messages

A log file without a recorded newest timestamp is judged by its Mtime,
which the filer keeps in whole seconds, so a file flushed later in the
cutoff's second looked older than messages it may hold. The purge now
takes the end of that second as the bound. A recorded newest timestamp
is still used as is.

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

* log_buffer: keep one entry per offset in a disk chunk

A disk read goes through a partition's log files and then its parquet
files, and a parquet file holds the same offsets as the log files it was
compacted from, so a chunk could take an offset twice and a fetch
returned the duplicate as the next message. The chunk now keeps the
first entry for each offset.

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

* log_buffer: reread a cached disk chunk that lacks the fetched offset

A disk chunk can be cached while its later offsets are still in memory.
Once those are flushed and memory moves on, a fetch past the cached part
hit the cache, found nothing, and returned no messages until the chunk
was evicted. A cached chunk that does not hold the fetched offset is now
dropped and read from disk again.

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

* mq/logstore: record a parquet file's offset range from its sources

The compactor took a parquet file's offset range from its entries'
offsets above 0 and recorded it only when the lowest was above 0, so a
file compacted from a partition's first window recorded no range, and one
whose entries started at 0 would have claimed to start at 1. The range
now comes from the source log files' recorded ranges, including one that
starts at offset 0, and is left out unless every source records one.

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

* mq: keep the earliest offset at or below files that record no range

The earliest stored offset was the lowest offset any file records, so a
file that records none, such as a parquet file compacted from a
partition's first window or a log file flushed without a range, was left
out. A reload or a purge could then start the log above offsets a read
can still return, and ListOffsets for the earliest offset left them out.
OffsetRange now takes the whole entry and keeps the earliest offset at 0
while a log or parquet file records no range, except a parquet file whose
listed sources are all present, as their ranges cover it.

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

* mq broker: keep a partition whose files cannot all be placed by offset

The purge ordered a data file that records no offsets, and whose
sources give none, as if it held the lowest, so an expired one could
be deleted while a retained file below its offsets stayed, leaving a
hole. A partition holding such a file is now left alone; only files
written before offsets were recorded lack them.

* mq broker: purge a parquet file only when each of its sources has expired

The purge deleted every source of an expired parquet file along with it,
judging the whole group by the parquet file's newest timestamp. Message
timestamps are not ordered across reloads, so a parquet file can hold an
expired source next to one still retained, and the retained one went
early. A parquet group is now purged only when the parquet file and each
source in it are past the cutoff on their own; otherwise the walk stops
there.

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

* mq/logstore: record a parquet file's lowest and highest timestamps

The compactor recorded a parquet file's timestamp range from its first
and last rows. Message timestamps are not ordered across reloads, so the
last row need not be the newest, and the recorded ts_max could sit below
messages the file holds, making it look older to the retention purge and
to readers that skip files by time. It now records the lowest and
highest timestamps over all rows.

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

* mq/logstore: keep each compacted row's offset in the _offset column

The compaction schema had no _offset column, so a schematized row's
offset was dropped and a schemaless row never carried one, while the
parquet reader expects the column and a fetch places rows by offset. The
compactor now adds the column when the schema lacks it and fills it for
every row, schemaless ones included, when the source files record their
offsets; otherwise it is left null.

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

* mq/logstore: read a parquet file by its own columns and mark unknown offsets

The parquet reader always expected an _offset column and read rows by
column position, so a file compacted before the column existed was read
out of alignment and panicked with an index out of range. A row with no
real offset also read back as offset 0, so a disk chunk, which keeps one
entry per offset, collapsed such rows into one. The reader now uses the
_offset column only when the file has it, trusts it only when the file
records its offset range, and reports any other row with offset -1,
which keeps it out of reads by offset.

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

* mq broker: keep a purge group that reaches past the first retained offset

A parquet file is purged with its sources as one group, and the sources
need not be contiguous: an expired parquet file could list expired files
on both sides of a retained one, so purging the group left a hole above
the retained file. A group now goes only when every offset it and its
sources cover lies below the first offset left behind; the walk keeps the
first group that does not, and the ones after it. A log file whose
offsets a retained parquet file also starts at now stays until that
parquet file goes.

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

* mq/logstore: give compaction test fixtures file ids no other fixture uses

The parquet reader caches chunks in a package-wide cache keyed by file
id, and each compaction fixture numbered its file ids from 1, so one
fixture could read another's cached bytes; with -count=3 a test read a
parquet file from an earlier run and failed. File ids are now numbered
across all fixtures.

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

* mq/logstore: compact legacy log files apart from ones that record offsets

A compaction group could hold a legacy log file without an offset range
next to files that record one, and a parquet file keeps its rows'
offsets only when every source records them, so the ranged rows lost
their offsets and could no longer be fetched by offset. Groups now split
where a file's having an offset range differs from the group's.

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

* mq broker: treat a parquet file's end as unknown when a source is gone

A parquet file that records no offset range took its last offset from
the sources still present, so one whose later source was already gone
looked as if it ended below a retained file and was purged, though it
may hold that source's offsets above the retained one. A gone or
unranged source now leaves the end unknown, and the group stays.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:18:45 -08:00
Chris Lu d63c225d78 mq: replicate each partition to a follower and hand it to a new pair when one is lost (#13203)
* mq: carry offsets, epoch and heartbeats on the follow stream

The follow stream sent the publisher's raw message, so the follower
could not keep the leader's offsets, and nothing named the generation
or told a quiet leader from a dead one. The stream now carries log
entries with their offsets, the epoch and leader in its init,
heartbeats, and the flushed offset; acks report the follower's offset.
EndPartitionGeneration lets a broker of a broken pair report it to the
balancer.

* mq broker: hand a partition's fence between generations

A fence could only be taken by the next leader, at once. A pair that
breaks needs more: the survivor must keep persisting what it holds
before a new leader writes, and a follower must be able to take the
fence from a leader it lost. The holder can now renew the fence,
which tells a new leader it is still persisting, and seal it when it
is done; a new leader takes an earlier generation's fence once it is
sealed or left unrenewed for 30 seconds. Within one generation the
fence moves only from the leader to its follower, and a sealed one
stays sealed.

Sealing writes a new token, so a follower that read the fence before
the seal cannot take it over after; a plain renewal keeps the token,
so flushes under way still match. A stale leader that reloads seals
its old fence once its last flush lands, so the reload does not wait.

* mq broker: ack a publish once the follower holds it

The leader acked a publish as soon as it was in its own memory, sent
the follower the raw message without its offset, learned its follower
only from the publisher's init message (which the Kafka gateway never
sets), and wrote to one follower stream from every publisher at once.

The leader now takes its follower from the partition's assignment when
it loads the partition and streams each entry, with its offset, from
one sender goroutine in offset order; a publish is acked once the
follower acks that offset. Heartbeats and a 5 second silence limit
tell a lost follower from a quiet one, and a broken pair answers the
publisher GENERATION_ENDED. The follower holds the entries the leader
has not stored yet, drops them as flush notices arrive, and the leader
closes the stream gracefully once it has stored everything, when the
partition unloads. A partition with no follower acks from memory as
before.

* mq: give a partition whose pair broke a new pair

Nothing reassigned a partition whose leader or follower was lost while
the other half lived on: the balancer only replaced brokers that had
left its broker set, and only on its own schedule. A broker of a
broken pair now reports the epoch with EndPartitionGeneration, and the
balancer assigns a new pair and the next epoch, preferring brokers
outside the old pair. A report for an epoch that already moved on is
ignored, so both halves can report, and reassignments are serialized.

* mq broker: a leader that loses its follower stores what it holds and ends the generation

When the follower stream broke, the leader kept serving alone, acking
from memory again. A broken pair now ends the generation on the leader:
it stops taking publishes, renews its fence so a new leader waits,
stores everything it holds under that fence, seals it, and reports the
epoch so the balancer assigns a new pair. A follower that cannot be
reached when the partition loads ends the generation the same way.

* mq broker: a follower takes over from a leader it lost

When the follow stream broke, the follower dropped what it held, so
entries the leader had acked but not stored were gone with it. The
follower now moves the fence from the lost leader to itself, unless
the leader sealed it first, reads what is already stored, stores the
entries above that, seals the fence and reports the generation ended.
The leader acks only what the follower holds, so every acked entry is
stored once, and a leader still writing is fenced out.

* mq broker: reload topic.conf when the balancer names this broker leader

A broker made leader by a reassignment could still hold the previous
topic.conf in its 30 second cache, so it either found no assignment
for itself or tried to take the fence with the old epoch, and refused
publishes until the cache expired. A publish that finds either now
drops the cached config and loads the partition again.

* mq broker: stop routing subscriptions through the follower

A subscription dialed the follower named in its init and advanced its
committed position only while that follower stream existed, so a
partition without a follower never saved a consumer position, and a
dead follower failed every subscription. The leader now tracks the
position itself and saves it when the subscriber leaves.

* mq broker: tell a partition's leader its follower when assigning it

The balancer created a topic's partitions on their leaders with only
the partition and epoch, so a partition made that way never knew its
follower and acked from memory. It now sends the whole assignment. Only
the named leader creates the partition; the follower learns of it from
the leader's follow stream, so the old forward of the leader's request
to the follower, which would have made the follower take the fence
too, is gone.

* mq broker: report an ended generation until a settled balancer takes it

A broker reported a broken pair once. When the lost broker was also
the balancer, the report failed and the partition stayed at a sealed
epoch nobody would serve. The report is now retried with backoff until
a balancer takes it, and a balancer takes reports only after its settle
window, so the new pair is picked from every live broker rather than
the few that reconnected first.

* mq: describe the replicated pair in the failover notes

* mq broker: break a pair whose follower stopped reading

The follower's silence was checked in the loop that sends to it, so
once a send blocked on a follower that stopped reading but kept its
connection, nothing checked again and publishers waited on acks that
never came. The check now runs on its own and cancels the stream.

* mq broker: a follower that cannot ack its leader takes over

An ack that failed to send ended the follow stream with an error and
dropped the follower's entries, though they may include messages the
leader had already acked to publishers. A failed ack now takes over
the partition, as a broken receive does.

* mq broker: retry a takeover through filer errors

A follower taking over gave up on the first failed fence or offset
read, dropping the entries its lost leader had not stored, which may
be the only copy left. It now retries until the fence has moved on or
the broker stops.

* mq broker: keep the fence renewed while a survivor persists

A leader that lost its follower renewed its fence once before
storing what it held, and a follower taking over not at all after
moving the fence, so a store that ran past 30 seconds let a new
leader take the unsealed fence, refusing the survivor's write and
dropping what it held. Both now renew every 10 seconds until they
seal.

* mq broker: leave the follower its copy when a retiring leader dropped a flush

A retiring leader closed its follow stream gracefully once its buffer
shut down, which tells the follower everything is stored, but a flush
that failed until shutdown is dropped. With the filer unavailable both
copies of acked messages went. The stream is now closed only when the
flushed offset reached the last one assigned; otherwise it is broken,
so the follower takes over and stores its copy.

* mq broker: order every topic.conf read-modify-write on the balancer

Only the generation handoff held a lock around its read and save of
topic.conf, so a concurrent ConfigureTopic or assignment refresh that
read the old assignments could save them back over the new pair,
after the reporter had been told the generation was taken. All of
them now take the same lock.

* mq broker: stamp a fence write when it lands, not when it was first tried

A fence write took its mtime before retrying, so a renewal that
landed after a long run of store errors was already older than the
seal wait, and a new leader could take the fence from a survivor
still persisting. Each attempt now stamps the time it is sent.

* mq broker: watch a leader's follower only once its partition is listed

The lost-follower watch started before the partition was registered,
so a pair that broke in that gap ended its generation while the
partition could not be removed, and the partition was then registered
and served after its fence was sealed. Both load paths now start the
watch after registering it.

* mq/kafka: answer a produce on an ended generation with NOT_LEADER_OR_FOLLOWER

A partition whose pair broke answers publishes with GenerationEnded
while the balancer hands it to a new pair, which the gateway mapped
to UNKNOWN_SERVER_ERROR: it kept the session and Kafka clients did not
refresh their metadata. It now maps to NOT_LEADER_OR_FOLLOWER, so the
gateway drops the session and clients look the leader up again.

* mq broker: take a stale fence only if its holder has not renewed it since

A new leader judged an earlier generation's unsealed fence stale by
its mtime, then wrote under the token alone. A renewal keeps the token
and moves only the mtime, so a holder that renewed in between, still
persisting what it held, lost the fence and the write that followed.
Taking a fence judged stale now requires the entry as it was read.

* mq broker: bound the seal when a leader cannot reach its follower

A leader whose replica failed to start sealed its fence and reported
the generation under the broker's access lock with no deadline, and a
fence write retries until it lands, so a filer that kept failing held
every partition operation on the broker. The seal now gives up after
the fence take timeout and the generation is reported regardless.

* mq broker: bound each report of an ended generation

A generation report called the balancer with no deadline, so a
balancer that accepted the call and stopped answering held the retry
loop and the partition stayed unassigned. Each attempt now gives up
after 30 seconds and is retried; a repeat after a save that landed
finds the epoch moved on and returns without writing.
2026-12-01 00:56:20 -08:00
Chris LuandClaude Opus 5.5 5c5e282787 mq: a failed fetch keeps the requested offset (#13208)
* mq broker: keep the fetch offset when a read fails

FetchMessage answered any read error with NextOffset set to the log
buffer's start offset and error code 2, which the broker error table
defines as topic-not-found. That start offset is the earliest offset
still in memory, or 0 before the buffer has taken a message, so a client
that followed NextOffset either rewound to the start of the partition or
skipped every offset that lives on disk. A failed read is now reported
as a storage error, mapped to Kafka's retriable KAFKA_STORAGE_ERROR, with
NextOffset left at the requested offset. Offsets below the buffer are
served from disk, so a read error is never out of range.

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

* mq/kafka: retry a failed broker fetch at the same offset

FetchMessagesStateless treated a broker error with code 2 as "offset too
old" whenever the fetch offset was below the response's LogStartOffset,
and silently refetched from LogStartOffset. Brokers sent code 2 for every
read error, and LogStartOffset is only the earliest offset in the
broker's memory, so a failed disk read made the gateway skip everything
stored on disk. The skipped records were then handed to the fetch path
as if they started at the requested offset. Any broker error is now
returned, and the fetch path retries at the offset it asked for.

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

* mq broker: keep the fetch offset when the partition cannot be loaded

FetchMessage answered a partition it could not load with an empty NextOffset, which reads as offset 0, so a client following NextOffset after a failed lookup or a topic.conf miss would rewind to the start of the partition. The response now carries the requested offset, as the read error path does.

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

* mq/kafka: answer unreadable records with KAFKA_STORAGE_ERROR

A broker storage error reached the Kafka fetch path as a plain error. FetchMultipleBatches dropped it, readRecords dropped the fallback's error too, and the partition was answered with no records and error code 0, which a consumer cannot tell from having caught up. The broker code now travels as ErrKafkaStorageError through FetchMessagesStateless and GetStoredRecords, FetchMultipleBatches returns an error that comes before any batch, readRecords returns the error when it found no records, and the partition is answered with KAFKA_STORAGE_ERROR so the client retries at the same offset.

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

* mq/kafka: require the fetch read-error test to reach the broker

TestFetchMessagesStatelessReadErrorKeepsOffset only checked that no fetch went to another offset, so it also passed when the request failed before reaching FetchMessage. It now requires exactly one fetch at offset 10 and an error carrying the broker's read failure, a storage error for code 56.

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

* mq/kafka: keep a storage error when the fallback read also fails

When the batch read failed with a storage error and the fallback read
then failed another way, readRecords returned only the fallback's
error, which maps to no error code, so the fetch answered an empty
success instead of KAFKA_STORAGE_ERROR. Both errors are now kept.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:47:09 -08:00
29c9e9df04 mq: fix races and a deadlock in the subscriber market (#13200)
* mq: fix races and a deadlock in the subscriber market

The balance loop reads consumerInstances, partition slots and each
consumer's AssignedPartitions without m.mu, while subscriber gRPC
streams mutate them under that mutex: a concurrent map read and map
write that the Go runtime turns into a fatal error, killing the
broker.

balanceRequestChan is unbuffered and sent to under m.mu; when the
balance loop finishes a pass and calls Status() (which takes m.mu),
the sender and the loop deadlock and the consumer group freezes.

adjustBusyConsumers indexes AssignedPartitions with a count derived
from a load that includes inflight assigns, which can exceed the
slice length and panic.

Take m.mu around doBalanceLoad, coalesce balance requests through a
buffered non-blocking send, cap the unassign count at the assigned
slice length, update MaxPartitionCount under the lock, and wait for
the balance loop to exit before closing AdjustmentChan.

Add market_concurrent_test.go: consumer churn across balance ticks
with concurrent adjustment confirms, and a minimal repro of the
index-out-of-range panic. Verified with go test -race.

* mq: send market adjustments outside the lock

Address review of the subscriber market concurrency fix.

doBalanceLoad now collects adjustments under m.mu and the balance loop
sends them after releasing it, selecting on stopChan so shutdown can
interrupt a send blocked on a full AdjustmentChan. Holding m.mu across
the blocking send could freeze the group: a stalled subscriber fills
AdjustmentChan, and RemoveSubscriber cannot take m.mu to remove it.

AddSubscriber registers the instance before applying the incoming
MaxPartitionCount, so the setter no longer no-ops for overlapping joins
that reuse an instance not yet in the market.

Add TestMarketBalanceDoesNotHoldLockWhileSending: fill AdjustmentChan
with no reader and check RemoveConsumerInstance still completes while
the loop is blocked sending.

* mq: apply consumer limit atomically and stamp adjustments at send

Address re-review of the subscriber market concurrency fix.

Register the instance and apply the incoming MaxPartitionCount in one
operation under m.mu (AddConsumerInstanceWithLimit), so overlapping
joins that reuse an instance id keep the latest limit on the instance
the market tracks. The previous add-then-set pair left a window where
the limit could land on an untracked or stale instance.

Stamp each adjustment when it is published, not when it is created.
The loop sends after releasing m.mu, so a send blocked on a full
AdjustmentChan could otherwise age the unsent tail past the inflight
TTL; the next pass would expire it and reassign its partition.

Make TestMarketUnassignWithInflightAssigns deterministic: receive the
first pass's six assigns, stop the loop, then call adjustBusyConsumers
directly and assert it unassigns nothing from a consumer that holds no
confirmed partition.

* mq: rebalance after raising a tracked consumer's limit

Address re-review of the subscriber market concurrency fix.

When a join reuses an already-tracked instance id,
AddConsumerInstanceWithLimit updates that instance's MaxPartitionCount
but returned without requesting a balance. The ticker only acts on a
pending request, and the previous one may have already drained, so a
rejoin that raises the limit left the extra capacity idle until some
other event happened to request balancing.

Request a balance in that branch too, so raising a tracked consumer's
limit takes effect on the next pass.

* mq: reconsider capacity on expiry and guard unassign by owner

Address re-review of the subscriber market concurrency fix.

Expire inflight adjustments on every tick, not only when a balance
pass is pending. A confirmed adjustment can linger in inflight until
its TTL and double-count a consumer's load, so a pass triggered by a
raised limit could see the consumer as full and assign nothing. When
expiry frees that capacity, request a pass so the freed or raised
capacity is reconsidered instead of staying idle.

Guard the unassign confirmation by owner. ConfirmAdjustment now passes
the acknowledging consumer into unassignPartitionSlot, which releases
the partition only when it is still assigned to that consumer. A late
or duplicate unassign ack can no longer clear a partition that was
reassigned to a new owner.

* mq: drop confirmed adjustments from inflight load accounting

A confirmed adjustment stayed in inflightAdjustments until its TTL,
so a partition already in AssignedPartitions was counted twice in the
load. An expiry-triggered pass then saw a healthy consumer as over the
average and unassigned its partitions, restarting subscribers that
were already fine.

Remove an adjustment from inflight as soon as it is acknowledged,
under m.mu, and take m.mu for the TTL sweep so the two cannot race.
Expiry now only retries genuinely unconfirmed adjustments. Also skip
unassigning from a busy consumer when no peer has room to accept the
freed partition.

* mq: scope the market fix back to races and the deadlock

The expiry-triggered rebalance and the confirmed-adjustment removal
added in the last two commits chased a pre-existing load-accounting
behavior: a confirmed adjustment lingers in inflight until its TTL and
is counted twice. That is upstream behavior outside this PR's scope,
and triggering passes on it churned healthy partitions.

Restore the focused fix: the balance-loop data race, the balance-request
send deadlock, the inflight unassign panic, the limit write under the
lock, and the shutdown close-versus-send race. Load accounting is left
as upstream has it.

* mq: fold AddConsumerInstanceWithLimit into AddConsumerInstance

AddConsumerInstance now takes the partition limit and applies it under
m.mu, updating the tracked instance when the id is already registered.
The broker was its only production caller.

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

* mq: wait for the adjustment buffer to fill before the lock test

A fixed sleep let RemoveConsumerInstance run before the balance loop
blocked on a full AdjustmentChan, so the test could pass without
exercising a blocked send.

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-12-01 00:19:07 -08:00
e9fa5802e1 volume: keep a low-disk location read-only until free space is back by a margin (#13199)
* volume: keep a low-disk location read-only until free space is back by a margin

The volume server checks each disk location once a minute and sets the
location's low-disk flag from that reading alone. A disk whose free
space hovers at -minFreeSpace (writes use space, deletes and vacuum give
a little back) flips the flag on and off, and every volume on the
location with it. The master hears each flip in a heartbeat, so it keeps
assigning writes to volumes that are about to turn read-only, and the
write fails with a read-only error. Nothing smooths this: the volume
reads the location's flag directly, and the master's volume layout takes
the heartbeat's read-only bit as it comes (its recovery delay and size
band apply to full volumes, not to read-only ones).

A location that went low now stays low until its free space is 1% of the
disk above the limit, for a percentage limit and a byte limit alike
(MinFreeSpace.IsLowFrom). Going low is unchanged. The margin is a
constant, not a flag: what flips a disk at the limit within one check is
a vacuum, a volume copy or the writes of one minute, each about one
volume (30 GB by default) at most. 1% of a multi-TB disk is about that
much, so a swing of that size does not clear the state, while an
ordinary cleanup of a few volumes does. The disk check runs on one
goroutine per location and is the only writer of the flag, so the
previous verdict it reads cannot change under it; readers only load it.

Every consumer of the flag (heartbeat max volume counts, read-only
flags, volume allocation, EC shard placement) reads the same flag, so
they all see the held state. The live checks of volume copy and
preallocation, which read the disk instead of the flag, only ever refuse
more than the flag does.

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

* volume: do not remember a low verdict from a reading without space values

When statfs fails or times out before any good reading is cached, the
disk status has All, Free and PercentFree at 0, and MinFreeSpace.IsLow
calls that low. With the hysteresis, that verdict was remembered, so a
later good reading between the limit and limit+1% kept the location
read-only, where it used to clear it: a disk whose first check timed out
stayed read-only until its free space cleared the margin.

A reading without space values (All is 0) is now judged by IsLow alone,
as before, and does not change the remembered verdict, which lives in
its own atomic field that only readings with space values update. A
failed reading between two good ones leaves the held verdict as it was.

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

* volume(rs): keep a low-disk location read-only until free space is back by a margin

Mirror Go's MinFreeSpace.IsLowFrom: once a location goes low it stays low
until free space is 1% of the disk above the limit, for percentage and
byte limits alike. A failed statfs reading (total 0) already leaves the
flag untouched.

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

* volume: trim the low-disk hysteresis comments

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

* volume(rs): test the low-disk hysteresis with fixed readings

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 00:17:29 -08:00
Chris LuandClaude Opus 5.5 43556b3a3c mq: publishers re-look up and resend when a partition's leader changes (#13195)
* mq client: dial brokers with the publisher's dial option

The publisher dialed every broker with insecure credentials, and the
per-partition connection added the configured option on top of them, so
a publisher could not reach a broker that requires TLS. That connection
was also never closed. PublisherConfiguration now takes the dial option,
insecure only when none is given, the agent passes its own, and the
partition connection is closed when its publish job ends.

* mq client: resend unacked messages when a partition's publish stream fails

A publisher sent each message once and kept no record of it. Acks were
only logged, a broker error on the stream was written to a field nobody
read, and the scheduler's wait loop broke out of its select instead of
the loop, so after the first stream failure it never looked the
partitions up again. Losing a partition leader silently dropped every
unacked message and stopped that partition for good.

Each partition now keeps its queue and the messages it sent but has not
had acked across streams. When a stream fails, or the broker answers
with an error or error code, the job ends, the scheduler looks the
topic up again with a short backoff, and the replacement stream resends
the unacked messages in order before draining the queue. Acks remove
messages up to the acked timestamp, so timestamps are made strictly
increasing per publisher. A partition holds at most 1024 queued or
unacked messages, and Publish blocks beyond that instead of growing
without bound. FinishPublish and Shutdown stop the input, Publish then
fails, and Shutdown returns once everything queued is acked.

* mq client: bound how long a closed publisher keeps resending

Once its input is closed, a publisher kept retrying a partition until
every message was acked, so Shutdown never returned while no broker
could take the partition, and a publisher that was only finished kept
looking the topic up forever. Resending now stops a minute after
FinishPublish or Shutdown, the open streams are cancelled, and Shutdown
reports how many messages were left unacknowledged.

* mq/kafka: replace a publish session whose call failed or was cancelled

PublishRecord ran Send and Recv in goroutines and returned when the
request context ended, leaving them on the stream. A leftover Recv then
took the ack meant for the next call on that partition, so acks and
offsets drifted apart, and a session whose stream had failed or whose
broker answered with an error stayed cached until the topic was
deleted. A call that fails, is cancelled, or gets an error response now
drops its session and cancels the stream, so the next call opens a
fresh one. PublishRecordValue shares the same path.

* mq/kafka: publish to the partition's current leader

The gateway opened every publish stream on the one broker it was
configured with, and a broker answers a publish for a partition it does
not lead with not-leader, so with more than one broker most partitions
could not be produced to, and none could after its leader moved. The
gateway now opens the stream on the leader named by the partition
lookup it already caches. A not-leader or connection failure drops the
session and the cached lookup and comes back as ErrNotLeaderOrFollower,
so the next attempt finds the new leader.

* mq/kafka: answer a produce that lost its partition leader with NOT_LEADER_OR_FOLLOWER

Every failed produce went back to the client as UNKNOWN_SERVER_ERROR,
which Kafka clients do not retry, so a partition leader change surfaced
as failed sends. A publish that failed because the leader moved or
could not be reached now answers NOT_LEADER_OR_FOLLOWER, and the client
refreshes its metadata and sends again.

* mq client: let the flush timeout cancel a stalled partition lookup

A lookup after a stream failure used context.Background, so a broker
that accepted LookupTopicBrokers and never answered kept the scheduler
inside it after the flush timeout, and Shutdown never returned. Lookups
now run under a context cancelled when the publisher stops, and each
broker attempt is bounded so a stalled one does not hold up the next.

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

* mq client: stop each test publisher and release held acks on cancel

A test that never shut its publisher down left the scheduler retrying
lookups against the stopped fake broker for the rest of the package run,
and a fake ack worker held on the gate could not exit when its stream
was cancelled.

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

* mq client: do not restart a partition whose stream finished during the switch

A re-lookup that moved a partition's leader cancelled its stream and
waited for it, then started a new one. If that stream had just finished
cleanly, the replacement ran for a job already counted as done, and the
scheduler could exit with it still running.

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

* mq client: count only data messages as unacknowledged at Shutdown

The count added the in-flight list and the queue length, so the close
marker FinishPublish queues counted as a lost message: an empty
publisher whose marker went unacked reported one unacknowledged message.
Every data message holds a slot until it is acked, so the slots are the
count.

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

* mq/kafka: let a produce's deadline bound opening its publish stream

Opening a session ran under the gateway's own context and waited for the
leader's hello, so a leader that took the init and never answered held
the produce, and every produce to that partition queued on the creation
lock, past their deadlines. Setup now also ends when the caller's
context does, without invalidating the assignment for a caller timeout,
and the stream outlives the call once open. A call whose context ended
while it waited for a dropped session no longer opens another one.

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

* mq/kafka: cancel the held publish only once the broker holds its data

The test cancelled on a 200 ms timer. A slow session setup let that
deadline pass before the data went out, leaving the first stream open
for the next call, which then waited on the held ack.

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

* mq/kafka: fetch and read offsets from the partition's leader

Produces go to the leader, but fetches and the high water mark and log
start offset reads still went to the gateway's own broker, which answers
partition not found for a partition it does not lead. Reads now use the
leader the assignment lookup returns, as the publish path does.

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

* mq agent: report unacknowledged messages when a publish session closes

ClosePublishSession returned success right after FinishPublish, which
only queues the close marker, so a message the brokers never acked was
lost without an error. The close now waits for Shutdown, which returns
once everything is acked or reports what was not after the flush
timeout, and no longer holds the session map lock while it waits.

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

* mq/kafka: look the leader up again after a read it cannot serve

Reads used the cached assignment until its TTL, so after a leader died or
gave the partition up, every fetch for the next 30 seconds went to it.
A connection failure or a partition-not-found answer from the leader now
drops the cached assignment, unless the caller's own context ended.

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

* mq client: leave a Publish still waiting to enqueue out of the Shutdown count

Publish takes a slot before it checks that the input is open, so a
Publish paused between the two still held its slot when Shutdown
counted, and Shutdown reported a message the caller was then told was
rejected. Each job now counts the data messages it accepted and has not
had acked.

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

* mq/kafka: cancel the silent-leader publish once its hello is withheld

The test cancelled on a 200 ms timer, which could fire before the call
opened a stream; the retry then opened the withheld stream with no
deadline and hung the suite. It now cancels once the fixture holds the
hello and bounds the retry.

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

* mq: retain the original publisher payload for replay

* mq agent: flush accepted records when the publish stream closes

* mq client: isolate bootstrap RPCs by publisher credentials

* mq/kafka: honor publish cancellation during lookup and partition waits

* mq/kafka: read a partition's offset range from its leader

GetHighWaterMark and GetEarliestOffset asked the gateway's configured
broker, which answers from its own log buffer. Publishes now go to the
partition's leader, so a non-leader gateway broker reported a high water
mark that missed the leader's unflushed records. Send the range query to
the leader and drop the cached assignment when that broker fails.

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

* mq agent client: bound the wait for the agent to finish a session

CloseSession waited in Recv until the agent answered EOF. An agent
blocked enqueueing to a partition whose broker stopped acknowledging
never reads the close, so it never starts its bounded flush and the
close hung. After two minutes, cancel the stream: the agent then stops
accepting and flushes, and the close reports the timeout.

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

* mq agent: wait for both closers to reach the flush in the close test

The duplicate-close test slept 100 ms to let the second close start. A
late goroutine then found the session already removed and the test
failed. Wait until both closers are inside finishPublisher instead.

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

* mq: answer a partition's offset range only from its leader

A broker answered GetPartitionRangeInfo from its offset manager even
after the partition moved away, so the gateway kept reading the old
leader's range until its assignment cache expired. The broker now checks
ownership the way FetchMessage does, and the gateway drops the cached
assignment when the range request fails.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:34:45 -08:00
github-actions[bot] 29eebd7bb2 docs: regenerate star history chart 2026-12-01 07:21:20 +00:00
Yip LeoandClaude Opus 5.5 e3e3bacf10 mount: read an open file's extended attributes under its entry lock (#13194)
* mount: read an open file's extended attributes under its entry lock

getxattr and listxattr on an open file read the Extended map of the
handle's live entry with no lock, while setxattr and removexattr change
that map in place. Go ends the process on a concurrent map read and
write, so weed mount exits with "fatal error: concurrent map read and
map write" (GetXAttr) or "concurrent map iteration and map write"
(ListXAttr), and every file open on the mount returns ENOTCONN. The
kernel asks for security.capability on each write(), so a program that
writes a file while another process sets or removes its attributes
reaches this.

The entry's own lock, LockedEntry.RWMutex, is the one every other
writer of the handle's entry takes: truncate to zero, the metadata
merges of a flush, SetEntry and the acknowledged-attribute retention.
setxattr and removexattr changed the map under the handle lock and
entryLock only. They now also take the entry lock, in the documented
order after those two, and re-read the handle's entry under it, as
SetAttr does, in case SetEntry swapped it. GetXAttr and ListXAttr read
the handle's current entry under the entry's read lock and copy what
they return before releasing it. The read lock is a leaf: it waits for
no other lock and does not wait for the handle lock, so a getxattr is
not held up by a write in progress.

TestXAttrReadsAgainstSetAndRemoveOnOpenFile and
TestXAttrReadsAgainstTruncateToZeroOnOpenFile abort the test binary with
the fatal errors above without the change, and all three race tests
report data races under -race.

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

* mount: remove the attributes the xattr race test sets

The writer of TestXAttrReadsAgainstSetAndRemoveOnOpenFile set even
keys and removed odd ones, so every RemoveXAttr found no key and
returned ENOATTR before deleting anything. Each name is now set and
then removed, and both calls must succeed. With RemoveXAttr's entry
lock taken out, -race reports its delete against GetXAttr's read.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:13:23 -08:00
Chris LuandClaude Opus 5.5 24951dbfe7 mq: one offset assigner per partition, continued from disk (#13191)
* mq: assign publish offsets inside the partition's log buffer

A publish took its offset from the offset manager under one lock and
appended it to the log buffer under another, so two publishers on one
partition could append offsets out of order. The buffer now assigns the
offset under its own lock when the entry asks for one, and an entry
that already carries an offset moves the buffer's next offset past it
instead of bumping it by one.

* mq: give the entry that rolls a window over to the new window

Both append paths widened the window's offset range before checking
for a rollover. The sealed window then claimed the entry that started
the next one, and the new window's range started without it, so a
window holding only that entry was flushed as offsets 0..0 and readers
skipped it. The range is now widened after the rollover.

* mq: seed a partition's offsets from all of its own files

A loading partition continued its offsets from the highest offset
recorded on disk, but the scan listed without a limit, so the filer
returned only its default page (1000 entries under weed server and
mini) and offsets below the real maximum were handed out again. It also
read the newest version directory rather than the partition's own, and
a filer error left the partition counting from 0.

The broker and the Kafka gateway now share mq.ReadOffsetRange, which
lists every file, the broker reads the partition's own directory, and
a partition whose stored offsets cannot be read is not loaded, so the
publish fails and is retried.

* mq: reload a partition only after its retired copy has flushed

Idle cleanup and a drain retire a partition and return while its last
flush is still queued. A publish right behind them created a new copy,
which read the stored offsets before that flush landed and handed out
its offsets again. Loading a partition now waits for a retired copy of
the same range, outside the broker's access lock that the flush takes.

* mq broker: report a partition's high water mark from its buffer

The range reported to the Kafka gateway took the larger of the offset
manager's count and the buffer's, so it followed the manager's
checkpoint rather than what the partition had assigned. It now comes
from the loaded partition's buffer, which assigns the offsets, or from
the ranges stored on disk when this broker has not loaded the partition.

* mq: drop the offset manager's assignment, checkpoint and subscription code

Publish offsets now come from each partition's log buffer and its high
water mark from that buffer or the stored ranges, so the separate
assigner, its checkpoint.offset writer and the offset subscription
layer built on it have no callers left. Only consumer-group positions
remain in BrokerOffsetManager. Existing checkpoint.offset files are left
alone; readers already skip them.

* mq broker: recheck a retiring partition under the lock when assigning

AssignTopicPartitions waited for a retiring copy before taking the
access lock, so a drain in between could retire the partition and the
assignment then seeded a replacement before that flush landed. The
check now runs under the lock, which is released only to wait.

* mq topic: mark a partition retiring before it leaves the list

RemoveLocalPartition took the partition out of the active list before
recording it as retiring, so a replacement loaded in between saw
neither and read the stored offsets before the last flush landed. The
partition is now recorded as retiring first.

* mq topic: gate the retired-flush test on a channel instead of a sleep

The test relied on a 200ms flush delay to observe the partition as
pending, which a paused test goroutine could outlast.

* mq topic: remove a partition by its instance under one lock

RemoveLocalPartition looked the partition up, marked it retiring and then
removed by range in separate steps. A second remover of the same copy could
take out a replacement loaded in between, leaving it neither listed nor
retiring, and a removal that found nothing still left a stale retiring entry.
Callers now pass the copy they hold; it is marked retiring and taken out of
the list under the partition lock, and only if it is still listed.

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

* mq broker: look a partition up once per assignment pass

The retirement wait checked one lookup and the load used a second one, so
idle cleanup retiring the partition between them let the assignment load a
replacement from stored offsets before the retired copy's last flush landed.
The wait and the load now use the same lookup.

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

* mq broker: let a cancelled assignment leave the retirement wait

AssignTopicPartitions waited for a retired copy's last flush without watching
its request, so while that flush kept failing a cancelled call still held its
handler. WaitRetired now takes a context and returns its error, leaving the
retirement pending; the publish and subscribe loader keeps waiting as before.

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

* mq topic: share one flush signal per retirement

A cancelled WaitRetired left its goroutine blocked on the retired
buffer's flush, so repeated cancelled assignments piled up goroutines
until that flush finished. The retirement now owns one channel, closed
after its last flush, and every waiter selects on it.

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

* mq broker: load the assigned generation for any request of its range

Subscribe and fetch pass the partition from the request, and the loader
built the local partition from it after matching only the range. A stale
or zero generation then scanned a directory the broker was not assigned,
found no offsets, and registered a partition that restarted at zero over
stored data. The loader now takes the assignment's partition.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:29:27 -08:00
Yip LeoandClaude Opus 5.5 de76148f54 mount: fail the flush when dirty pages cannot be read back from the swap file (#13198)
* mount: fail the flush when dirty pages cannot be read back from the swap file

Dirty pages that weed mount buffers in the swap file (non-sequential
writes, or when the memory chunks run out) are read back when they
upload. SwapFileChunk.SaveContent ignored the error of that read: an
interval it could not read in full was uploaded short, or not at all,
and flush, fsync and close still succeeded. The writes the application
had been told succeeded became a hole in the stored file, with no error
anywhere. A read error on the cache disk, or a swap file truncated by an
outside cleanup, is enough.

SaveContent now hands the upload a reader that fails with the read
error. The upload fails like any other failed chunk upload: the handle
records it, rejects further writes, and flush, fsync and close return
EIO without publishing the entry. The remaining intervals of that chunk
are not saved, since the handle cannot flush cleanly. The chunk, its
write budget and its swap slot are released as before.

The test in weed/mount cuts the swap file after the write was
acknowledged: on master fsync returns OK and the filer is never told.
The pipeline tests cover a closed and a truncated swap file, and a swap
file cut inside the second of two intervals.

SwapFileChunk.ReadDataAt, which serves reads of pages not yet uploaded,
still logs a read error and returns what it has read so far; that is
left for a follow-up since it needs an error path through the read side.

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

* mount: require a failed fsync to leave the filer entry unchanged

TestFsyncFailsWhenSwapFileCannotBeReadBack accepted any filer entry
backed by stored bytes that left out the lost range, so an entry
published with the readable interval (the original 256 bytes plus the
"A" write) would also have passed. It now records the filer's entry
before the writes and requires the same entry and the same 256 bytes
after the failed fsync.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:55:31 -08:00
Yip LeoandClaude Opus 5.5 265b3aae0f mount: take the two handle locks of CopyFileRange in one order (#13197)
CopyFileRange locked the destination handle exclusively and then the
source handle shared. Two copy_file_range calls in opposite directions
between the same pair of files (A to B and B to A, which coreutils cp
issues by default) each held their destination and waited for their
source, and neither could go on. Every operation that needs either
handle's lock then waits behind them: reads, writes, flush, release,
and the invalidation of the handle by a metadata event. The processes
using the two files hang until the mount is restarted.

The two locks are now taken in ascending FileHandleId order, whichever
of the two handles is the destination; the destination is still locked
exclusive and the source shared. A copy whose source and destination are
the same handle takes the one lock exclusive, as before. CopyFileRange
is the only place that holds the fhLockTable locks of two handles at
once, which the nested lock order comment in filehandle.go now says.

The test queues the first copy behind a handle lock held by the test and
starts the opposite copy while it waits; the lock order is the only
thing that lets both finish. It fails on master with both copies parked
in the lock queue.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:54:37 -08:00
Chris LuandClaude Opus 5.5 9cea13b9fc mq broker: fenced flushes, one file per window (#13192)
* mq: number partition leaderships with an epoch

A partition assignment named its leader but nothing told one leadership
from the next, so a broker that lost a partition could not be told apart
from the one that replaced it. BrokerPartitionAssignment now carries an
epoch that the balancer bumps whenever it picks a different leader,
including the first leader of a new partition, so a fresh allocation starts
at epoch 1. Follower changes and re-spelled addresses of the same leader
keep the epoch.

* mq broker: take a partition fence before leading a partition

Nothing stopped a broker that had lost a partition from writing to it, so
two brokers flushing one partition overwrote each other's files. Each
partition directory now holds a .fence entry naming its writer and the
assignment epoch. A broker generating a partition as leader reads the fence
and rewrites it with one filer ObjectTransaction, routed to the fence's
owner filer and conditioned on the fence being absent or unchanged since
the read, before it reads the partition's existing offsets. A fence stored
at a higher epoch or sealed is refused, and the partition is not served
when the fence cannot be taken. The broker keeps the fence entry as stored
so later writes can present it. Topic configuration now passes each
assignment's epoch to the broker it assigns.

* mq broker: flush each window to its own fenced file

A flush uploaded a chunk on every attempt and appended it to the chunk list
of the file named by the window's start second with an unconditional
CreateEntry. A lost response duplicated the window, every retry orphaned
the previous chunk, and two brokers writing one partition overwrote each
other's chunk lists. Each window now becomes a new file named by its start
second and its first offset, uploaded once and written with one filer
ObjectTransaction conditioned on the partition fence the broker holds. Only
the transaction is retried, under a single request id, so a replay cannot
apply twice. buffer_start now records the window's first offset instead of
the next-offset counter. A failed fence condition means another broker
took the partition: the window is dropped, later windows drop without an
upload, and the publish path answers not-leader so publishers move on.

The follower's stream-end write of its leftover windows now goes through
the same fenced writer, which refuses it because a follower holds no
fence. That write only ever produced offset-less duplicates of what the
leader flushed, so the follower now drops those windows.

* mq: read flushed windows named with an offset suffix

Flushed windows are now named by start second and first offset, which the
readers did not expect. The disk reader dropped every file whose name
sorted after the stop second, which a window starting in that very second
now does, and log compaction parsed the whole name as a time and skipped
the new files. Both now look only at the start-second part, so files with
either naming are read. The partition fence that sorts first in a listing
is skipped by the disk reader and the query engine's live-log scans, and
topic truncation keeps it.

* mq broker: retry a recorded flush failure under a new request id

The filer records a failed mutation under its request id and replays it for
two minutes, so retrying the same id stalled the partition's flush. Putting
the same window entry again is harmless, so a recorded failure now retries
under a fresh id; a lost response still retries under the same one.

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

* mq broker: hold the partition fence by a token, not a read-back entry

Taking the fence read the written entry back through the broker's filer,
which may lag the fence's owner filer; a successful take then looked lost
and the new leader did not load. The fence entry now carries a fresh token
as its etag, and later writes require that etag on the owner, so nothing
is read back.

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

* mq broker: bound the fence take's filer calls

A partition is loaded under accessLock, and the fence take's lookups and
transaction had no deadline, so a filer that accepted a call and never
answered held every partition operation on the broker. A take that runs
out of time leaves the partition unserved for a later attempt.

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

* mq: name compacted files and skip compacted windows by their source logs

Now that several windows can start in one second, compaction named
every output after its first message's second, so groups starting in
the same second overwrote each other, and it skipped any window whose
start second was not after the newest compacted row, so a later window
in that second was never compacted. A parquet file is now named after
its first source log, which is unique, and a window is skipped when a
parquet file lists it as a source; the start-second rule remains only
for windows named by their second alone.

* mq broker: reload a partition whose fence another broker took

A partition that lost its fence stayed registered until its last
client left, and both partition load paths reused it, so a broker made
leader again at a newer epoch kept answering not-leader, or wrote
until its next flush was refused. A fenced partition is now dropped
and the partition loaded again under the current assignment's epoch.

* mq broker: reload a partition held under an older epoch

A copy whose fence was taken is reloaded only once a refused flush marks
it lost. Until then a broker made leader again at a newer epoch kept the
copy and accepted publishes that the next flush dropped against the other
broker's fence. A copy whose fence epoch is older than the assignment's is
now reloaded too. Its last flush lands under its own fence before the
reload reads the stored offsets.

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

* mq: start a new compaction group only after the current one has a file

A first log file larger than the group size left an empty first group, and
naming a parquet file after its group's first log then indexed past the end.

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

* mq: remove a partition by its instance, not its range

A publisher or subscriber of a copy that was replaced removed the partition
by range on its way out, which shut down the replacement instead. Removal
now takes the copy itself and leaves a copy that has replaced it.

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

* mq broker: keep a stale copy registered until its last flush lands

A reload removed the stale copy and then waited for its last flush without
accessLock. A concurrent lookup or assignment found no copy, took the new
fence first, and the pending flush was refused and its window dropped. The
copy is now shut down where it is registered, so every loader finds it and
waits for the same flush, and it is removed only afterwards.

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

* mq broker: refuse an assignment once a reload waited out a shutdown start

The stopping check ran before the stale-copy reload, which releases
accessLock while the copy flushes. A Shutdown starting then left the retired
copy in place and the assignment reported success for it.

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

* mq broker: bound the concurrent reload test's waits

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

* mq: describe fenced writes and the follower loss window in the failover notes

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

* mq broker: release the upload gate when the reload test times out

A first upload starting just after the deadline check stayed blocked on the
gate, so the test server's Close waited on it and cleanup hung.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:52:47 -08:00
Chris LuandClaude Opus 5.5 d4910b70cf s3api: classify the GetPart part key in the route-key test (#13193)
s3api: classify the GetPart part key as an uploadId modifier

The GetPart route added a `part` query key that TestRouteQueryKeysAreClassified
did not know, failing the s3api tests on master. `part` only narrows an
uploadId request from ListParts to GetPart, like partNumber does for
UploadPart, so it must not count toward the ambiguity guard: counting it
would reject every `?part&uploadId` request.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:47:33 -08:00
Chris LuandClaude Opus 5.5 139c1d6d04 mq broker: survive startup, non-balancer brokers, and restarts (#13181)
* mq broker: turn a panic in an RPC into an error

The broker's gRPC servers had no recovery, so a nil dereference in any
handler took the whole process down. Once the broker runs inside
another server, that process is the host.

* mq broker: guard the filer set

The master's peer updates and the startup peer listing both write the
filers map and currentFiler from different goroutines, and every filer
call reads currentFiler. Two writers on the map at startup is a fatal
concurrent map write.

* mq broker: answer balancer requests before the balancer lock exists

The balancer lock is created only once the broker has found a filer,
while the gRPC server already serves. Every lookup, configure, publish
and balance request dereferenced it, so an early request crashed the
broker. Those requests now answer Unavailable until a balancer is
elected.

Ownership is the lock's unexpired lease instead of the owner name it
last saw, so a broker whose renewals have failed stops acting as
balancer once the lease runs out. A lapsed lease can still name this
broker, so proxying refuses to send a request to itself.

* mq broker: follow the filer lock ring

The balancer lock client was seeded with the first filer the broker
found and never given the ring, so it kept dialing that filer after it
left and no broker could become balancer. The broker now takes the
master's lock ring updates the way S3 gateways and mounts do, and the
master sends brokers the ring snapshot on connect.

* mq: never pick a partition's leader as its follower

pickBrokersExcluded ignored the leader it was told to exclude. With one
broker, the first assignment repair made that broker its own follower,
and it then replicated every publish to itself.

A dead follower that has no replacement is now dropped and counted as a
change, so the cleared name is saved; picking the leader had hidden
that.

* mq: keep a partition's leader unless a live broker replaces it

The repair cleared the leader of any partition whose leader it did not
see, even with no broker to take over, and the cleared assignment was
cached. With an empty broker set every leader went blank. A leader now
moves only to a live broker, the only live follower is promoted when it
is all that is left, and a follower that names its own leader is
replaced.

* mq broker: only a settled balancer repairs assignments

Every broker repaired topic assignments on a cache miss, but only the
balancer tracks which brokers are live. Any other broker saw an empty
set, cleared the topic's leaders, and could not load a partition it
did own, so a publish to it dereferenced a nil partition.

A newly elected balancer also waits 30 seconds, long enough for every
broker to notice the change and reconnect, before it treats a broker
it has not heard from as gone.

* mq broker: refuse a publish for a partition not assigned here

When the balancer named this broker as leader but its own copy of the
topic config did not, the partition lookup returned nil and the
publish dereferenced it. It now answers not-leader, and the publisher
looks the partition up again.

* mq broker: compare the publish leader as an address

The leader check built "ip:port" with Sprintf and compared strings,
while broker addresses are joined with JoinHostPort. On IPv6 the
brackets never matched and every publish was refused as not-leader.

* mq broker: flush partitions on stop

The broker had no Stop. Its loops ran on context.Background, and the
standalone command registered nothing for SIGTERM, so every restart
dropped the publishes still in the open flush window.

Stop now cancels the broker's loops, releases the balancer lock, and
waits until every partition has flushed. The command calls it on
interrupt before stopping its gRPC servers. The startup peer listing,
which blocked the constructor until a master answered, now runs in the
background with the balancer election.

* mq topic: flush partitions added or retired while stopping

Shutdown took one snapshot of the partition list, so a partition a
publish created after the snapshot was never flushed, and one that idle
cleanup had just retired was not waited on. Adding a partition now
fails once Shutdown starts, Shutdown waits out an idle cleanup pass in
progress, and every retired partition is waited on until its last
flush.

* mq broker: release the balancer lock once on stop

Stop and the balancer election could both release the lock when a stop
landed just as the lock was published, and a second LiveLock.Stop
closes its channel again and panics. Each path now takes the lock out
with Swap, so only one releases it.

* mq broker: forget the buffered ring version on a master change

Before the balancer lock client exists, the broker keeps the last ring
it got. A master change then reset nothing, so the client attached with
the old master's version and refused the new master's lower one.

* mq broker: restart the settle window when the balancer lease is regained

The window started when the lock owner's name changed. A balancer that
lost a renewal and got the lease back still had the same name, so it
skipped the wait and could repair assignments before brokers
reconnected. The window now counts from the first sight of the lease's
generation, which changes on every fresh acquisition and stays put on
renewal.

* mq broker: expire configs cached while the balancer settles

A balancer reading a topic during its settle window skipped the repair
and then cached the config for the full 30 seconds, so a dead leader
was served well past the window. Those entries now expire at the
settle deadline.

* mq topic: wait for drained partitions on shutdown

A partition removed by a drain or by its last client leaving was shut
down but not tracked, so a stop right after a resize could exit before
its final flush. Every removal now retires the partition through the
manager, and Shutdown waits on the set of retiring partitions instead
of a WaitGroup that a late removal could Add to while Wait ran.

* mq broker: update the settle window's lease and start together

The lease generation and its start were two atomics written one after
the other, so a concurrent reader could pair a regained lease's new
generation with the old start and see the window as already over. They
are now read and written under one lock.

* mq broker: refuse an assignment while stopping

A partition assigned after shutdown started was shut down, but the
handler still answered success, so the balancer recorded an assignment
this broker never installed. It now answers Unavailable.

* mq topic: signal a subscriber to stop only once

Shutdown leaves partitions registered, so a drain that arrives while the
broker flushes shuts the same partition down again, and closing a still
registered subscriber's stop channel a second time panicked.

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

* mq broker: bound flush retries once stopping

Stop waits for every partition's last flush, and a flush retried a failing
write forever, so a broker whose filer or volumes were unreachable never
exited on SIGTERM. In weed server it also held back the filer and volume
shutdown hooks, which run after it. Like the filer's metadata log, a flush
now gives up 15s into Stop and drops the window instead.

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

* mq.broker: flush before closing the localhost listener too

The localhost server's stop hook was registered after the broker's, so it
ran first and cut loopback clients before the partitions flushed.

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

* mq topic: gofmt local_manager.go

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

* mq broker: end a shutdown flush stalled in a filer call

The shutdown budget was checked only after a failed append returned, and
the entry lookup and update ran under context.Background(), so a filer
that accepted the call and never answered still held Stop open. Flushes
now append under a context that Stop cancels once the budget runs out,
as the filer does for its metadata log. Every window after a dropped one
then drops too, so a later success cannot advance the watermark or tell
the follower to discard a window that never reached the filer.

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

* mq topic: leave a partition to Shutdown once it starts

RemoveLocalPartition detached a partition before registering it as
retiring, so a Shutdown snapshot taken in between missed it and returned
before its last flush. Once Shutdown starts, removal now reports false and
the partition stays registered for Shutdown to retire, as idle cleanup
already does.

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

* mq broker: refuse an assignment for a hosted partition while stopping

Only a new partition was refused once Shutdown started. A partition the
broker already hosted stays registered after Shutdown retires it, so its
assignment was acknowledged although the broker no longer serves it. Both
paths now answer Unavailable.

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

* mq broker: expire a settling balancer's config from when it was validated

The expiry was computed when the config was cached. A lookup that skipped
validation just before the settle deadline and cached the config just after
it kept the unrepaired assignments for the full TTL. The expiry now counts
from the time of validation, so such a config expires at the deadline.

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

* mq broker: stop waiting on an upload once the flush budget ends

Cancelling the flush context ended retries and the filer metadata calls,
but not a volume assignment or upload already in flight. Those ran on
their own timeouts and retries, so a filer or volume server that never
answered held Stop past the budget, for minutes in the worst case. The
upload now runs on its own copy of the window, and the flush stops
waiting for it when the context ends.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:21:23 -08:00
394e9d247e mount: keep assignment proofs until the filer stores their chunks (#13186)
* operation: return the assignment proof of an upload

A filer serving a scoped token returns an assignment proof with
AssignVolume and stores a new chunk in an entry only when the request
presents that proof in chunk_auth. UploadWithRetry dropped it, so a
client had no way to commit the chunks it uploaded.

UploadResult.AssignAuth now carries the proof of the assignment the data
was finally stored under. A proof from an assignment the upload abandoned
after a failed attempt is never returned. The field is not serialized and
stays empty when the filer sends none, so existing callers are unchanged.

* mount: keep assignment proofs until the filer stores their chunks

A mount with a scoped filer token was refused whenever it wrote new
chunks: the filer asks for the assignment proof of every chunk the stored
entry does not hold, and the mount never kept it.

The mount now keeps the proof of every chunk it uploads and attaches the
proofs of the chunks a request names to each create, update and append
it sends, over the mutation stream and over unary calls, on every
attempt. A proof is released only once a filer acknowledged an entry that
names the chunk, or a manifest that holds it. A failed, refused or timed
out commit releases nothing, since it may have been stored: the retry
still carries the proof, and a filer ignores proofs for chunks it holds.
Proofs are stateless, so a commit retried on another filer of the cluster
is accepted there.

The store is bounded. When it is full an upload waits for commits to make
room before it is assigned a file id, and fails after a minute instead of
evicting a proof a pending commit still needs. Only proofs well past their
expiry, which a filer refuses anyway, are dropped to make room.

Without a filer token the mount keeps no store: its requests and chunk
lists are as before. A token without path grants is given no proofs, so
nothing is attached either.

* mount: keep chunk lists flat with a filer token file

A filer serving a scoped token stores no new chunk in an entry that holds
manifests, so once a mount folded a file's small chunks into a manifest,
every later write to that file was refused. A mount with a filer token now
keeps chunk lists flat; mounts without one fold as before.

* mount: test the unscoped-token path with a signed token

GenJwtForFilerScope returns an empty token when it is given no path
grants, so both cases of TestUnscopedMountRequestsCarryNoProofs ran a
tokenless mount. Sign an unscoped filer token instead and check that it
is not empty, so the test covers a mount holding a token the filer issues
no proofs for.

* mount: fold chunk lists unless the filer scopes the mount's token

A mount with -filer.tokenFile kept every chunk list flat, also when the
token is an unscoped one the filer issues no proofs for. Such a mount
stopped folding chunks into manifests, so its small-chunk runs were never
folded and, on FoundationDB, a file past about 1000 chunks no longer fit
its entry. Keep lists flat only while the current token has path grants
or a method list, which the filer scopes; fold as before otherwise.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:18:29 -08:00
aeca7a9a8a master: keep writes available when the replica placement cannot be satisfied (#13178)
* master: keep writes available when the replica placement cannot be satisfied

With a placement such as 200 on exactly three data centers, losing one data
center stops all writes: every volume misses a copy and leaves the writable
list, and volume growth cannot find three data centers.

Add master.replication.degraded_growth_min_copies (0 = off). When the
topology no longer has enough data centers, racks or servers for a placement,
the master grows volumes with fewer copies, never below that number. A lack
of free space never triggers it.

These volumes keep the requested placement in their super block and are
writable while the master flags them as degraded; lookups report the copies
they need, so volume servers accept writes to them. Once the topology can
hold the placement again the flag is cleared: they turn read-only until
volume.fix.replication adds the missing copies. The flag is in memory only,
so a master restart has the same safe effect.

Refs #13177

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

* master: tighten degraded volume growth after review

- A degraded volume is writable only with exactly the copies it was grown
  with: losing one turns it read-only, so a copy that comes back has missed
  no write, and it is not writable before all its copies are registered.
- Use the first relaxed placement the topology can hold and stop there when
  it lacks free slots, so full disks never drop more copies.
- Try every relaxed placement, ordered by copies, then data centers, then
  racks (011 can fall back to 010, not only 001).
- Data nodes in maintenance mode do not count when checking the topology.

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

* master: tie degraded writability to the original servers

- A degraded volume is writable only on exactly the servers it was grown
  on: a replacement copy no longer stands in for a missing original one.
- Lookups report the degraded copy count only in that exact state, so a
  volume server never relaxes its check when the layout would not.
- When a relaxed placement fails to find slots, try the other placements
  with as many copies (for example in the requested data center) before
  giving up, still never dropping copies for lack of space.

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

* seaweed-volume: copy min_writable_copies into the master.proto copy

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

* seaweed-volume: let a degraded volume replicate with the master's min_writable_copies

Mirrors getRemoteReplications: lookup_volume also returns the lookup's
min_writable_copies, and do_replicated_request uses it instead of the
placement's copy count when it is lower.

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

* seaweed-volume: test the degraded replicated write through the admin router

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

* master: grow degraded volumes without a setting

Degraded growth no longer needs master.replication.degraded_growth_min_copies:
it always applies when the topology cannot hold a placement, never below two
copies. Lookups skip the degraded scan until a volume was grown degraded.

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

* master: leave refused servers out of the degraded slot search

findDegradedSlots cleared option.refused, so a retry could pick the server
that just refused the allocation. Search without the refused servers first
and fall back to them only when nothing else fits, as findAndGrow does.

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

* master: document that a degraded volume losing every copy stays read-only

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

* admin: warn about under-replicated and misplaced volumes on the dashboard

The dashboard health line now counts the volumes volume.fix.replication would
repair, using the same placement checks, so volumes grown degraded while a
data center is down show up until they are repaired.

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

* master: spread degraded copies over racks and servers when data centers are missing

A 200 volume with a single data center left found no degraded placement:
only per-dimension reductions were tried, and 100 needs two data centers.
Try every placement with fewer copies and no more data centers, so the
remaining copies go to other racks or servers.

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

* master: report min_writable_copies only for the locations it is returned with

LookupVolume read the locations and the degraded minimum in two steps, so
a replica set change in between could pair the minimum with locations it
does not hold for. Count the minimum only when the returned locations are
exactly the servers the volume was grown on.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 16:05:54 -08:00
Chris LuandClaude Opus 5.5 5815d13881 mount: keep in-place updates at a listed entry's commit stamp (follow-up to #13152) (#13189)
* mount: keep an entry whose in-place update is already reflected

A listed entry carries its own commit stamp, so the update event that made
it arrives at exactly that stamp. The removal half passed the strict check
while the write half was fenced, and the entry was deleted and tombstoned.
An in-place update is one change: when its write is fenced, so is the
removal of the same path.

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

* mount: report a cached entry's own commit as its version

FindEntry still versioned a listed entry at the listing floor, below the
commit it carries. An open handle compares invalidations against that
version, so a delayed event the cache fenced out could still replace the
handle's content with the older state.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:05:41 -08:00
Chris Lu 501cf6b760 mq: read a recorded offset range that ends at offset 0 (#13190)
The broker and the Kafka gateway each scanned a partition's files for
the high water mark and counted a maximum only when it was above 0, so
a partition holding one message still read as empty. Both now share
mq.OffsetRange, which tracks whether a range was found apart from its
value.
2026-11-30 16:01:39 -08:00
4830ae5e96 feat: set GOMEMLIMIT from cgroup memory limit via automemlimit (#13188)
* feat: set GOMEMLIMIT from cgroup memory limit via automemlimit

* weed: set the memory limit before dispatch and report it through glog

The blank import ran memlimit.Set in an init with slog.Default, so every
weed command, including weed version and weed shell, wrote to stderr
outside glog, and macOS and Windows printed "failed to set GOMEMLIMIT:
cgroups is not supported" each time. Call memlimit.Set before running the
command instead, and log the resulting limit or a bad AUTOMEMLIMIT value
next to the transparent huge page line of long-running commands.

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

* mount: log the -memoryLimitMB override and document the automatic limit

weed mount now starts with 90% of the cgroup memory limit unless GOMEMLIMIT
is set, so -memoryLimitMB=0 no longer means unlimited inside a container.
Say so in the flag help and log the override, which replaces the limit the
startup line reported.

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

---------

Co-authored-by: Rajesh Kannapalli <rajesh.kannapalli@broadcom.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:45:12 -08:00
Song Bian 54f0c7ca5b fix(filer): clip chunk group reads at EOF (#13182) 2026-11-30 15:43:10 -08:00
Song Bian 81b83b155f fix(mq): copy flush buffers before queuing follower data (#13183)
* fix(mq): copy flush buffers before queuing follower data

* fix(buffered_queue): release references after dequeue
2026-11-30 15:33:06 -08:00
df2fa630c1 mount: fence events below a cached entry's own commit stamp (#13152)
A listing snapshot capped at the peers' delivery watermark can trail
entries already in the store. A delayed event older than the listed
version then rolled the entry back, e.g. a completed file to its empty
create, until the newer event arrived. A live entry now counts as
versioned at least at its CommitTsNs.

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:28:08 -08:00
0d09c87281 fix(master): handle capacity changes during volume placement (#13185)
* fix(master): handle capacity changes during volume placement

* topology: test capacity changes during placement deterministically

The maintenance-toggling loops ran for seconds and could pass without
reaching either guard. Drain the secondary rack or data center right
before its slot draw, and feed PickNodesByWeight a node whose reported
capacity changes between reads. Each case fails on the code before the
fix.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:27:12 -08:00
d807dbfcbc fix(s3): preserve logical part layouts on multipart completion (#13184)
* fix(s3): preserve logical part layouts on multipart completion

* s3api: accept a multipart part that is entirely a hole

UploadPartCopy of a range that overlaps no source chunk stores a part
with no chunks but a non-zero size. Completion rejected any chunkless
non-last part as empty, so the upload failed with InvalidPart even
though the part copy succeeded. Reject only parts whose logical size is
zero; the all-hole part now completes as zeros at its position.

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

* s3api: refuse a multipart completion made only of holes

When every completed part is a hole, the object gets a positive size
and no chunks, and GET answers it with InternalError as a data
integrity failure. Reject that completion with InvalidPart instead of
committing an object that cannot be read. Uploads that mix hole-only
parts with data parts still complete.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:14:20 -08:00
Chris LuandClaude Opus 5.5 480a1baa20 s3api: GetPart, reading parts of in-progress and completed multipart uploads (#13174)
* s3api: GetPart reads one part of a multipart upload

GET /key?part&partNumber=N&uploadId=X serves the latest attempt of an
open upload's part, or the bytes that part became in the object a
completed upload assembled, including a version that is no longer
latest. x-amz-multipart-upload-status says which. A Range counts
within the part, and a whole part answers 200 even though a completed
part is served as a range of the object.

The route sits ahead of ListParts and claims any ?part request, so a
missing partNumber is InvalidArgument rather than a listing, and the
request resolves to s3:GetObject, not the ListParts grant.

* s3api: reading an open upload's part needs s3:GetIncompleteUpload

AWS gates GetPart on an upload that has not completed behind
s3:GetIncompleteUpload on top of s3:GetObject, so a plain read grant
does not start exposing data its writer has not committed yet. The
action is its own legacy grant too; Read alone does not carry it, Admin
does. A completed upload's part needs only the read grant, plus
s3:GetObjectVersion when it lives in a version.

* s3api: a GetPart request carrying ?uploads is not a multipart listing

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

* s3api: GetPart answers a completed empty part with an empty 200

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:09:19 -08:00
Song BianandMaster ac2efbac01 fix(buffered_queue): synchronize enqueue with input closure (#13168)
Check isClosed while holding the queue mutex so the check and insertion are atomic with respect to CloseInput. This prevents a producer from successfully enqueueing after a consumer has exited a closed, empty queue.

Add concurrent enqueue, close, and drain coverage with a bounded wait, plus checks for both sequential close orderings. The concurrent regression reproduces the original data race and stranded item under the race detector.

Co-authored-by: Master <Master@node0.8m510.lpad-pg0.utah.cloudlab.us>
2026-11-30 13:48:52 -08:00
Chris Lu 10381075f3 mq: record the offset range of a partition's first window (#13180)
The flush wrote offset_min/offset_max only when minOffset > 0, using 0
as "no range given". A partition's first window starts at offset 0, so
its file never got a range. A restarted broker derives the high water
mark from those ranges, so a partition whose data was all in its first
file read as empty.
2026-11-30 13:39:52 -08:00
Chris Lu 51d591e060 cluster: read a LiveLock's owner atomically (#13179)
The renewal goroutine rewrites the owner on every attempt while other
goroutines read it through LockOwner. The MQ broker reads it on every
request it proxies to the balancer.
2026-11-30 13:38:41 -08:00
411 changed files with 33051 additions and 7996 deletions

No files matched your search

+24
View File
@@ -125,6 +125,28 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
mysql:
image: mysql:8.4
env:
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
options: >-
--health-cmd "mysqladmin ping -uroot -proot"
--health-interval 10s
--health-timeout 5s
--health-retries 10
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
@@ -136,6 +158,8 @@ jobs:
- name: Test
env:
RUN_REDIS_TESTS: "1"
RUN_POSTGRES_TESTS: "1"
RUN_MYSQL_TESTS: "1"
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
test-32bit:
+37 -2
View File
@@ -4,8 +4,11 @@ name: "S3 digest and FIPS matrix"
# signing on, so the sha256 digest and GODEBUG=fips140=only stay working:
# md5 GODEBUG=fips140=off, the default digest
# sha256 GODEBUG=fips140=on with the filer's -digest=sha256
# fips140only GODEBUG=fips140=only, built with GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster.
# fips140only GODEBUG=fips140=only and WEED_FIPS_MODE=strict, built with
# GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster. The
# negative-config job checks what strict mode refuses at startup
# (test/s3/digest_matrix/negative_config.sh).
on:
push:
@@ -115,6 +118,38 @@ jobs:
retention-days: 1
path: digest-matrix-binaries.tar
negative-config:
name: Strict FIPS mode refusals
needs: build
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
- name: Restore binaries
run: |
tar xf digest-matrix-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
- name: Short keys refused
env:
WEED: ${{ github.workspace }}/weed/weed
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
WORK_DIR: /tmp/negative-config
run: bash test/s3/digest_matrix/negative_config.sh
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: negative-config-logs
path: /tmp/negative-config/**/*.log
retention-days: 3
suites:
name: S3 suites (${{ matrix.digest }}, ${{ matrix.volume }} volume server)
needs: build
@@ -73,6 +73,13 @@ jobs:
echo "=== Running S3 Prefix Object Tests ==="
go test -v -timeout=180s -run TestS3PrefixObjectKeys ./...
- name: Run S3 GetPart Tests
timeout-minutes: 15
working-directory: test/s3/normal
run: |
set -x
go test -v -timeout=180s -run TestS3GetPart ./...
- name: Run IAM Integration Tests
timeout-minutes: 15
working-directory: test/s3/normal
+14
View File
@@ -37,10 +37,24 @@ if [ "$(id -u)" = "0" ]; then
fi
fi
# A restrictive Docker daemon umask can leave these 0600, and the resolver
# then falls back to a nameserver on localhost once privileges are dropped.
for f in /etc/resolv.conf /etc/hosts; do
if [ -f "$f" ] && ! su-exec seaweed test -r "$f"; then
chmod a+r "$f" 2>/dev/null
fi
done
# Use su-exec to drop privileges and run as seaweed user
exec su-exec seaweed "$0" "$@"
fi
for f in /etc/resolv.conf /etc/hosts; do
if [ -f "$f" ] && [ ! -r "$f" ]; then
echo "Warning: $f is not readable by uid $(id -u), so host name lookups may fail. Make it world-readable (0644)." >&2
fi
done
isArgPassed() {
# Match both `-flag` and `--flag` (and their `=value` forms): the Go fla9
# library accepts both, and users may pick either form on the CLI.
+9 -7
View File
@@ -30,10 +30,12 @@ Override `SEAWEEDFS_IMAGE` to test a newer image. With metrics-enabled engines,
append `--metrics-port=9329 --metrics-ip=0.0.0.0` to the vector command and scrape
`vector:9329/metrics` inside the Compose network.
A native development setup can use `weed mini -vector -vectorBucket=embeddings`
with `weed-vector` beside `weed` or on PATH. `-vector.binary` selects an explicit
binary, and `-vector.metricsPort=9329` enables HTTP readiness and metrics on a
compatible engine. The child inherits the cluster's configuration directory and
stops with mini. Run `weed-worker` separately for ANN maintenance. `weed shell`
provides `s3vectors -operation <Operation> -file request.json` for the same API
operations using trusted cluster credentials.
A native development setup can use `weed mini -vectorBucket=embeddings`. Mini
starts `weed-vector` and the `weed-worker` maintenance worker when it finds them
beside `weed` or on PATH, and logs and continues without one it cannot find.
`-vector.binary` selects an explicit engine binary, and `weed-worker` is also
looked up beside it. `-vector=false` leaves both out, and
`-vector.metricsPort=9329` enables HTTP readiness and metrics on a compatible
engine. The children inherit the cluster's configuration directory and stop with
mini. `weed shell` provides `s3vectors -operation <Operation> -file
request.json` for the same API operations using trusted cluster credentials.
+1 -1
View File
@@ -1,7 +1,7 @@
services:
seaweedfs:
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE -vector=false
environment: &environment
WEED_JWT_FILER_SIGNING_KEY: vector-demo-cluster-key
AWS_ACCESS_KEY_ID: vector-demo
+2
View File
@@ -12,6 +12,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Jille/raft-grpc-transport v1.6.1
github.com/KimMachineGun/automemlimit v1.0.2
github.com/Shopify/sarama v1.38.1
github.com/ThreeDotsLabs/watermill v1.5.3
github.com/a-h/templ v0.3.1100
@@ -378,6 +379,7 @@ require (
github.com/parquet-go/bitpack v1.1.1 // indirect
github.com/parquet-go/jsonlite v1.5.7 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
+4
View File
@@ -85,6 +85,8 @@ github.com/IBM/go-sdk-core/v5 v5.23.1 h1:fxLusCG+GlGY1SM7BYAAiiSFhzKUs5zqs0P8knD
github.com/IBM/go-sdk-core/v5 v5.23.1/go.mod h1:yO+OQpByKDLTvpEcsFFexgzpeR8eRfCFWAYzxkAu4bk=
github.com/Jille/raft-grpc-transport v1.6.1 h1:gN3sjapb+fVbiebS7AfQQgbV2ecTOI7ur7NPPC7Mhoc=
github.com/Jille/raft-grpc-transport v1.6.1/go.mod h1:HbOjEdu/yzCJ/mjTF6wEOJNbAUpHfU2UOA2hVD4CNFg=
github.com/KimMachineGun/automemlimit v1.0.2 h1:DkORkhuzrwT2/b35xz8zLd7cJ6Hu2ESRGBY8HKUFIYk=
github.com/KimMachineGun/automemlimit v1.0.2/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0=
github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g=
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd h1:nzE1YQBdx1bq9IlZinHa+HVffy+NmVRoKr+wHN8fpLE=
@@ -964,6 +966,8 @@ github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMP
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
+12
View File
@@ -267,6 +267,18 @@ filer:
enabled: true
```
### Message queue broker
An S3 gateway can run a message queue broker beside it, on gRPC port 17777 by default. `s3.mqBroker`, `filer.s3.mqBroker` and `allInOne.s3.mqBroker` choose it:
- `auto` (the default) runs it only with `global.seaweedfs.enableSecurity`, where the chart gives it mutual TLS through `[grpc.msg_broker]` in security.toml.
- `true` runs it either way. Without `enableSecurity` it then accepts any client that can reach the port.
- `false` never runs it.
`s3.mqBrokerPort`, `filer.s3.mqBrokerPort` and `allInOne.s3.mqBrokerPort` set the port, and 0 also turns the broker off. The `allInOne.s3` values inherit the `s3` ones when null. The container port and NetworkPolicy entry appear only when the broker runs.
Brokers register with the master under the pod IP, and clients and other brokers find them there and dial that address, so the port is deliberately left off the Services; a LoadBalancer or NodePort Service would only publish it outside the cluster. With `networkPolicy.enabled` the chart admits the port from the release's own pods; publishers and subscribers elsewhere need an `extraIngress` rule for it.
### Enabling Authentication to S3
To enable authentication for S3, you have two options:
@@ -274,6 +274,9 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
-sftp \
@@ -406,6 +409,10 @@ spec:
- containerPort: {{ $httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
- containerPort: {{ .Values.allInOne.sftp.port | default .Values.sftp.port }}
@@ -296,6 +296,9 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
-master={{ include "seaweedfs.masterServerArg" . }} \
{{- range .Values.filer.extraArgs }}
@@ -363,6 +366,10 @@ spec:
- containerPort: {{ .Values.filer.s3.httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- $jwt := (.Values.global.seaweedfs.securityConfig).jwtSigning | default dict }}
{{- $isJwtEnabled := or $jwt.filerWrite $jwt.filerRead }}
@@ -179,6 +179,9 @@ spec:
{{- end }}
{{- /* rendered even when 0: an if would drop the flag and weed would serve its default */}}
-port.lance={{ .Values.s3.lancePort | default 0 }} \
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).args }}
{{ . }} \
{{- end }}
{{- range .Values.s3.extraArgs }}
{{ . }} \
{{- end }}
@@ -233,6 +236,10 @@ spec:
- containerPort: {{ .Values.s3.lancePort }}
name: swfs-lance
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- if .Values.s3.metricsPort }}
- containerPort: {{ .Values.s3.metricsPort }}
name: metrics
@@ -283,6 +283,55 @@ true
{{- end -}}
{{- end -}}
{{/*
The message queue broker beside an S3 gateway, for (list $ "s3"|"filer"|"allInOne"),
as JSON: "args" are its flags and "port" the port it serves, 0 when it cannot run.
Unflagged, weed starts it only with grpc.msg_broker TLS, which enableSecurity
writes, and on 17777; defaults are left out so images without these flags start.
allInOne.s3 inherits s3's mqBroker and mqBrokerPort when null.
*/}}
{{- define "seaweedfs.mqBroker" -}}
{{- $root := index . 0 -}}
{{- $component := index . 1 -}}
{{- $prefix := "" -}}
{{- $name := "s3.mqBroker" -}}
{{- $mode := $root.Values.s3.mqBroker -}}
{{- $port := $root.Values.s3.mqBrokerPort -}}
{{- if eq $component "filer" -}}
{{- $prefix = "s3." -}}
{{- $name = "filer.s3.mqBroker" -}}
{{- $mode = $root.Values.filer.s3.mqBroker -}}
{{- $port = $root.Values.filer.s3.mqBrokerPort -}}
{{- else if eq $component "allInOne" -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBroker) -}}
{{- $name = "allInOne.s3.mqBroker" -}}
{{- $mode = $root.Values.allInOne.s3.mqBroker -}}
{{- end -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBrokerPort) -}}
{{- $port = $root.Values.allInOne.s3.mqBrokerPort -}}
{{- end -}}
{{- end -}}
{{- $mode = ternary "auto" (toString $mode | lower) (kindIs "invalid" $mode) -}}
{{- if not (has $mode (list "auto" "true" "false")) -}}
{{- fail (printf "%s must be auto, true or false, not %q" $name $mode) -}}
{{- end -}}
{{- $port = int ($port | default 0) -}}
{{- $runs := false -}}
{{- if and (gt $port 0) (or (eq $mode "true") (and (eq $mode "auto") $root.Values.global.seaweedfs.enableSecurity)) -}}
{{- $runs = true -}}
{{- end -}}
{{- $args := list -}}
{{- if or (eq $mode "false") (eq $port 0) -}}
{{- $args = append $args (printf "-%smq.broker=false" $prefix) -}}
{{- else if eq $mode "true" -}}
{{- $args = append $args (printf "-%smq.broker=true" $prefix) -}}
{{- end -}}
{{- if and $runs (ne $port 17777) -}}
{{- $args = append $args (printf "-%smq.broker.port=%d" $prefix $port) -}}
{{- end -}}
{{- dict "args" (join " " $args) "port" (ternary $port 0 $runs) | toJson -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -26,6 +26,9 @@
{{- if and $https (gt (int $https) 0) }}
{{- $ports = append $ports $https }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "allInOne") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
{{- $ports = append $ports (.Values.allInOne.sftp.port | default .Values.sftp.port) }}
@@ -62,6 +65,9 @@
{{- if and .Values.filer.s3.httpsPort (gt (int .Values.filer.s3.httpsPort) 0) }}
{{- $ports = append $ports .Values.filer.s3.httpsPort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "filer") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- $targets = append $targets (dict "component" "filer" "ports" $ports) }}
{{- end }}
@@ -76,6 +82,9 @@
{{- if .Values.s3.lancePort }}
{{- $ports = append $ports .Values.s3.lancePort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "s3") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- if .Values.s3.metricsPort }}
{{- $ports = append $ports .Values.s3.metricsPort }}
{{- end }}
@@ -120,6 +120,14 @@ stringData:
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
{{- /* The broker beside each S3 gateway serves with this identity and
dials other brokers with it; weed starts that broker only when this
section has a cert and key. Same internal client cert as grpc.s3, which
every pod running a gateway already mounts. */}}
[grpc.msg_broker]
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
# use this for any place needs a grpc client
# i.e., "weed backup|benchmark|filer.copy|filer.replicate|mount|s3|upload"
[grpc.client]
@@ -0,0 +1,199 @@
package tests
import (
"fmt"
"os/exec"
"strings"
"testing"
)
const security = "global.seaweedfs.enableSecurity=true"
type brokerGateway struct {
name string
settings []string
kind string
object string
prefix string
broker string
port string
}
var brokerGateways = []brokerGateway{
{"s3", []string{"s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-s3", "", "s3.mqBroker", "s3.mqBrokerPort"},
{"filer.s3", []string{"filer.s3.enabled=true"}, "StatefulSet", "vector-test-seaweedfs-filer", "s3.", "filer.s3.mqBroker", "filer.s3.mqBrokerPort"},
{"allInOne", []string{"allInOne.enabled=true", "allInOne.s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-all-in-one", "", "allInOne.s3.mqBroker", "allInOne.s3.mqBrokerPort"},
}
func firstContainer(workload map[string]interface{}) map[string]interface{} {
return workload["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"].([]interface{})[0].(map[string]interface{})
}
// brokerFlags returns the broker flags of the workload's first container.
func brokerFlags(workload map[string]interface{}) []string {
container := firstContainer(workload)
var words []string
for _, key := range []string{"command", "args"} {
if list, ok := container[key].([]interface{}); ok {
for _, word := range list {
words = append(words, strings.Fields(word.(string))...)
}
}
}
var flags []string
for _, word := range words {
if strings.Contains(word, "mq.broker") {
flags = append(flags, word)
}
}
return flags
}
func namedPort(ports []interface{}, name, field string) int {
for _, port := range ports {
if p := port.(map[string]interface{}); p["name"] == name {
return p[field].(int)
}
}
return 0
}
func policyAllows(policy map[string]interface{}, want int) bool {
rules, _ := policy["spec"].(map[string]interface{})["ingress"].([]interface{})
for _, rule := range rules {
ports, _ := rule.(map[string]interface{})["ports"].([]interface{})
for _, port := range ports {
if port.(map[string]interface{})["port"] == want {
return true
}
}
}
return false
}
// checkBroker asserts the flags, that the broker port is declared and
// admitted exactly when the broker runs, so a broker that runs with its port
// blocked fails, and that no Service ever carries it.
func checkBroker(t *testing.T, gateway brokerGateway, label string, settings []string, wantFlags []string, wantPort int) {
t.Helper()
_, documents := render(t, append(append([]string{"networkPolicy.enabled=true"}, gateway.settings...), settings...)...)
label = fmt.Sprintf("%s %s", gateway.name, label)
workload := findDocument(documents, gateway.kind, gateway.object)
if workload == nil {
t.Fatalf("%s: no %s %s", label, gateway.kind, gateway.object)
}
if got := brokerFlags(workload); strings.Join(got, " ") != strings.Join(wantFlags, " ") {
t.Errorf("%s: broker flags %q, want %q", label, got, wantFlags)
}
containerPorts, _ := firstContainer(workload)["ports"].([]interface{})
if got := namedPort(containerPorts, "swfs-mq-broker", "containerPort"); got != wantPort {
t.Errorf("%s: containerPort %d, want %d", label, got, wantPort)
}
// Clients find brokers through the master and dial the pod, so a Service
// port would only publish the broker through a LoadBalancer or NodePort.
for _, document := range documents {
if document["kind"] != "Service" {
continue
}
for _, port := range document["spec"].(map[string]interface{})["ports"].([]interface{}) {
p := port.(map[string]interface{})
if p["name"] == "swfs-mq-broker" || p["port"] == 17777 || p["targetPort"] == 17777 || (wantPort != 0 && (p["port"] == wantPort || p["targetPort"] == wantPort)) {
t.Errorf("%s: Service %v carries the broker port: %v", label, document["metadata"].(map[string]interface{})["name"], p)
}
}
}
policy := findDocument(documents, "NetworkPolicy", gateway.object)
if policy == nil {
t.Fatalf("%s: no NetworkPolicy %s", label, gateway.object)
}
if wantPort != 0 && !policyAllows(policy, wantPort) {
t.Errorf("%s: NetworkPolicy does not admit broker port %d", label, wantPort)
}
for _, port := range []int{17777, 18887} {
if port != wantPort && policyAllows(policy, port) {
t.Errorf("%s: NetworkPolicy admits %d with no broker on it", label, port)
}
}
}
func TestMqBrokerModes(t *testing.T) {
for _, gateway := range brokerGateways {
on := "-" + gateway.prefix + "mq.broker=true"
off := "-" + gateway.prefix + "mq.broker=false"
port := "-" + gateway.prefix + "mq.broker.port=18887"
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"auto without security", nil, nil, 0},
{"auto with security", []string{security}, nil, 17777},
{"auto with security, custom port", []string{security, gateway.port + "=18887"}, []string{port}, 18887},
{"auto without security, custom port", []string{gateway.port + "=18887"}, nil, 0},
{"true", []string{gateway.broker + "=true"}, []string{on}, 17777},
{"true, custom port", []string{gateway.broker + "=true", gateway.port + "=18887"}, []string{on, port}, 18887},
{"false with security", []string{security, gateway.broker + "=false"}, []string{off}, 0},
{"true, port 0", []string{gateway.broker + "=true", gateway.port + "=0"}, []string{off}, 0},
}
for _, c := range cases {
checkBroker(t, gateway, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
}
func TestMqBrokerAllInOneInherits(t *testing.T) {
allInOne := brokerGateways[2]
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"null inherits s3.mqBroker=true", []string{"s3.mqBroker=true"}, []string{"-mq.broker=true"}, 17777},
{"null inherits s3.mqBroker=false", []string{security, "s3.mqBroker=false"}, []string{"-mq.broker=false"}, 0},
{"explicit auto overrides s3.mqBroker=false", []string{security, "s3.mqBroker=false", "allInOne.s3.mqBroker=auto"}, nil, 17777},
{"null inherits s3.mqBrokerPort", []string{security, "s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
{"explicit port overrides s3.mqBrokerPort=0", []string{security, "s3.mqBrokerPort=0", "allInOne.s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
}
for _, c := range cases {
checkBroker(t, allInOne, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
func TestMqBrokerTLSOnlyWithSecurity(t *testing.T) {
for _, secured := range []bool{false, true} {
// filer JWT signing writes security.toml without enableSecurity
settings := []string{"s3.enabled=true", "global.seaweedfs.securityConfig.jwtSigning.filerWrite=true"}
if secured {
settings = append(settings, security)
}
_, documents := render(t, settings...)
secret := findDocument(documents, "Secret", "vector-test-seaweedfs-security-config")
if secret == nil {
t.Fatalf("security %v: no security config Secret", secured)
}
toml := secret["stringData"].(map[string]interface{})["security.toml"].(string)
section := "[grpc.msg_broker]\ncert = \"/usr/local/share/ca-certificates/client/tls.crt\"\nkey = \"/usr/local/share/ca-certificates/client/tls.key\""
if got := strings.Contains(toml, section); got != secured {
t.Errorf("security %v: [grpc.msg_broker] with the client cert present = %v\n%s", secured, got, toml)
}
if !secured && strings.Contains(toml, "[grpc.msg_broker]") {
t.Errorf("[grpc.msg_broker] written without enableSecurity")
}
}
}
func TestMqBrokerRejectsUnknownValue(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
output, err := exec.Command("helm", "template", "test", "..", "--set", "s3.enabled=true", "--set", "s3.mqBroker=yes").CombinedOutput()
if err == nil || !strings.Contains(string(output), `s3.mqBroker must be auto, true or false, not "yes"`) {
t.Fatalf("s3.mqBroker=yes accepted: %v %s", err, output)
}
}
+12
View File
@@ -1096,6 +1096,9 @@ filer:
port: 8333
# add additional https port
httpsPort: 0
# Message queue broker beside the gateway, see s3.mqBroker
mqBroker: auto
mqBrokerPort: 17777
# Suffix of the host name, {bucket}.{domainName}
domainName: ""
# Seconds the gateway keeps serving after SIGTERM while its health checks
@@ -1186,6 +1189,13 @@ s3:
# Lance Namespace port; weed serves 9101 by default, 0 disables it
# (and the worker's Lance container)
lancePort: 9101
# Message queue broker beside the gateway: auto runs it only with
# global.seaweedfs.enableSecurity, which gives it mTLS; true runs it either
# way, without TLS when security is off; false never does.
mqBroker: auto
# Its gRPC port, 0 turns it off. Clients and other brokers find the broker
# through the master and dial the pod IP, so no Service carries this port.
mqBrokerPort: 17777
loggingOverrideLevel: null
# enable user & permission to s3 (need to inject to all services)
enableAuth: false
@@ -2060,6 +2070,8 @@ allInOne:
enabled: false # Whether to enable S3 gateway
port: null # S3 gateway port (null inherits from s3.port)
httpsPort: null # S3 gateway HTTPS port (null inherits from s3.httpsPort)
mqBroker: null # Message queue broker: auto, true or false (null inherits from s3.mqBroker)
mqBrokerPort: null # Message queue broker gRPC port (null inherits from s3.mqBrokerPort, 0 turns the broker off)
domainName: null # Suffix of the host name (null inherits from s3.domainName)
enableAuth: false # Enable user & permission to S3
# Set to the name of an existing kubernetes Secret with the s3 json config file
+1056 -1060
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

+169
View File
@@ -0,0 +1,169 @@
//! JWT signing keys under [`FipsMode::Strict`].
//!
//! FIPS 140 needs HMAC keys of at least 112 bits, and Go's `crypto/hmac`
//! panics on a shorter one under `GODEBUG=fips140=only`, so every Go process
//! refuses to start when a JWT key in security.toml is shorter
//! (`weed/util/fips140_keys.go`). The Rust binaries take `fips.mode = strict`
//! to mean the same and apply the same rule with the same wording, so one
//! security.toml gets the same answer from a Go and a Rust server.
use crate::fips::FipsMode;
/// The shortest HMAC key FIPS 140 allows: 112 bits.
pub const MIN_HMAC_KEY_BYTES: usize = 14;
/// The wiki section on switching JWT signing keys without downtime.
pub const JWT_SIGNING_KEYS_WIKI: &str =
"https://github.com/seaweedfs/seaweedfs/wiki/Cryptography-and-FIPS-Compliance#jwt-signing-keys";
/// Every security.toml setting that keys an HS256 JWT, in the order Go checks
/// them. Go refuses a short one at startup in any process that reads the file.
pub const JWT_KEY_SETTINGS: [&str; 11] = [
"jwt.signing.key",
"jwt.signing.previous_key",
"jwt.signing.read.key",
"jwt.signing.read.previous_key",
"jwt.filer_signing.key",
"jwt.filer_signing.previous_key",
"jwt.filer_signing.read.key",
"jwt.filer_signing.read.previous_key",
"jwt.filer_signing.grpc_key",
"jwt.filer_signing.grpc_previous_key",
"jwt.filer_signing.subscribe.key",
];
/// Whether `key` is shorter than the FIPS mode allows (14 characters when
/// strict).
pub fn is_short(mode: FipsMode, key: &[u8]) -> bool {
mode == FipsMode::Strict && !key.is_empty() && key.len() < MIN_HMAC_KEY_BYTES
}
/// Go's `CheckFips140HmacKeys`: under strict mode, one message naming each
/// setting in `keys` whose key is too short, with its length; otherwise `None`.
pub fn short_keys(mode: FipsMode, keys: &[(&str, &[u8])]) -> Option<String> {
let short: Vec<String> = keys
.iter()
.filter(|(_, key)| is_short(mode, key))
.map(|(setting, key)| format!("{} ({} characters)", setting, key.len()))
.collect();
match short.as_slice() {
[] => None,
[one] => Some(format!(
"{} is shorter than the {} characters FIPS 140 needs for HMAC keys",
one, MIN_HMAC_KEY_BYTES
)),
[rest @ .., last] => Some(format!(
"{} and {} are shorter than the {} characters FIPS 140 needs for HMAC keys",
rest.join(", "),
last,
MIN_HMAC_KEY_BYTES
)),
}
}
/// The error a server logs before it exits at startup over the short keys in
/// `file`; `short` is the message from [`short_keys`].
pub fn startup_refusal(file: &str, short: &str) -> String {
format!(
"{}: this process runs with fips.mode strict, and stops because {}; replace them on every server that uses them, with or without downtime, see {}",
file, short, JWT_SIGNING_KEYS_WIKI
)
}
/// Go's `shortJwtKeyWarning`: a warning that the key (other than a previous
/// key) of `setting` in `file` is too short for strict mode, asking for a
/// longer one while the short one still works.
pub fn short_key_warning(mode: FipsMode, file: &str, setting: &str, key: &[u8]) -> Option<String> {
if mode == FipsMode::Strict
|| key.is_empty()
|| key.len() >= MIN_HMAC_KEY_BYTES
|| setting.ends_with("previous_key")
{
return None;
}
Some(format!(
"{}: this process does not run with fips.mode strict, so {} works, but under fips.mode strict this server would not start: the key is shorter than the {} characters FIPS 140 needs for HMAC keys (it has {}); to replace it on every server that uses it without downtime, see {}",
file,
setting,
MIN_HMAC_KEY_BYTES,
key.len(),
JWT_SIGNING_KEYS_WIKI
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_keys_only_under_strict() {
let keys: [(&str, &[u8]); 1] = [("jwt.signing.key", b"0123456789")];
assert_eq!(short_keys(FipsMode::On, &keys), None);
assert_eq!(short_keys(FipsMode::Off, &keys), None);
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) is shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn short_keys_names_every_short_key_and_skips_unset_and_long_ones() {
let keys: [(&str, &[u8]); 4] = [
("jwt.signing.key", b"0123456789"),
("jwt.signing.read.key", b""),
("jwt.filer_signing.key", b"01234567890123"),
("jwt.filer_signing.subscribe.key", b"01234567"),
];
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) and jwt.filer_signing.subscribe.key (8 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
let three: [(&str, &[u8]); 3] = [("a", b"1"), ("b", b"12"), ("c", b"123")];
assert_eq!(
short_keys(FipsMode::Strict, &three).as_deref(),
Some(
"a (1 characters), b (2 characters) and c (3 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn warning_outside_strict_except_for_previous_keys() {
assert!(short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b"0123456789")
.unwrap()
.starts_with("s.toml: this process does not run with fips.mode strict, so jwt.signing.key works"));
assert!(
short_key_warning(FipsMode::On, "s.toml", "jwt.signing.key", b"0123456789").is_some()
);
assert_eq!(
short_key_warning(FipsMode::Strict, "s.toml", "jwt.signing.key", b"0123456789"),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.previous_key",
b"0123456789"
),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.key",
b"01234567890123"
),
None
);
assert_eq!(
short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b""),
None
);
}
}
+3 -1
View File
@@ -8,9 +8,11 @@
//! rustls provider, which only works if every binary installs the same one.
//! The security.toml search path joined them for the same reason: an operator
//! mounts the file once and every binary has to look where `weed` looks.
//! The FIPS mode joined them because it decides that provider.
//! The FIPS mode joined them because it decides that provider, and the JWT key
//! rule for strict mode because every binary that reads the keys applies it.
pub mod address;
pub mod fips;
pub mod jwt_keys;
pub mod security_config;
pub mod tls;
+2
View File
@@ -6332,7 +6332,9 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
"bytes",
"crc32c",
"log",
"prost",
"protoc-bin-vendored",
+4
View File
@@ -289,6 +289,9 @@ message LookupVolumeResponse {
repeated Location locations = 2;
string error = 3;
string auth = 4;
// > 0 when the volume was grown degraded: a write needs this many
// writable copies instead of its replica placement's copy count.
uint32 min_writable_copies = 5;
}
repeated VolumeIdLocation volume_id_locations = 1;
}
@@ -438,6 +441,7 @@ message DataNodeInfo {
uint32 grpc_port = 3;
int64 last_heartbeat_ns = 5;
string address = 4; // ip:port for connecting to the volume server
bool maintenance = 6; // the volume server refuses new data while set
}
message RackInfo {
string id = 1;
+1
View File
@@ -148,6 +148,7 @@ message BatchDeleteRequest {
repeated string file_ids = 1;
bool skip_cookie_check = 2;
bool fsync = 3;
bool skip_replica_check = 4; // the caller updates the other copies itself
}
message BatchDeleteResponse {
+521 -151
View File
@@ -31,8 +31,12 @@ fn parse_common_names(value: &str) -> Vec<String> {
.collect()
}
/// The value of the WEED_ variable `key`, or `None` when it is unset or empty:
/// Go's viper ignores an empty variable, so the setting keeps its file value.
fn env_string(env: EnvLookup<'_>, key: &str) -> Option<String> {
env(key).and_then(|value| value.into_string().ok())
env(key)
.and_then(|value| value.into_string().ok())
.filter(|value| !value.is_empty())
}
/// SeaweedFS Volume Server (Rust implementation)
@@ -188,7 +192,7 @@ pub struct Cli {
pub min_free_space_percent: String,
/// 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.
/// Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.
#[arg(long = "minFreeSpace", default_value = "")]
pub min_free_space: String,
@@ -337,6 +341,13 @@ pub struct VolumeServerConfig {
pub tls_policy: TlsPolicy,
/// Path to security.toml — stored for SIGHUP reload.
pub security_file: String,
/// The security.toml the settings came from, for messages that name it.
pub security_file_name: String,
/// Every JWT key setting, from `SecurityConfig::jwt_keys`, for the strict
/// mode check at startup.
pub jwt_keys: Vec<(&'static str, Vec<u8>)>,
/// The FIPS mode, from the same read of security.toml as `jwt_keys`.
pub fips_setting: Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError>,
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
/// (allows loopback / link-local / metadata hosts).
pub allow_untrusted_remote_endpoints: bool,
@@ -374,6 +385,27 @@ impl MinFreeSpace {
}
}
/// Go's util.MinFreeSpaceReleaseMarginPercent.
pub const RELEASE_MARGIN_PERCENT: u64 = 1;
/// Mirrors Go's MinFreeSpace.IsLowFrom: a location that was low stays low
/// until free space is RELEASE_MARGIN_PERCENT of the disk above the limit.
pub fn is_low_from(&self, was_low: bool, free_bytes: u64, total_bytes: u64) -> bool {
let low = self.is_low(free_bytes, total_bytes);
if !was_low || low {
return low;
}
match self {
MinFreeSpace::Percent(pct) => {
free_bytes as f64 / total_bytes as f64 * 100.0
< *pct + Self::RELEASE_MARGIN_PERCENT as f64
}
MinFreeSpace::Bytes(min) => {
free_bytes < min.saturating_add(total_bytes / 100 * Self::RELEASE_MARGIN_PERCENT)
}
}
}
/// Free bytes above the floor; mirrors Go's MinFreeSpace.AvailableSpace.
pub fn available_space(&self, free_bytes: u64, total_bytes: u64) -> u64 {
let floor = match self {
@@ -953,6 +985,7 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
// Parse security config from TOML file
let sec = parse_security_config_with_env(&cli.security_file, env);
let fips_setting = resolve_fips_setting_with_env(&cli.security_file, &sec, env);
// Parse whitelist: merge CLI --whiteList with guard.white_list from security.toml
let mut white_list: Vec<String> = cli
@@ -1009,6 +1042,9 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
debug: cli.debug,
debug_port: cli.debug_port,
ui_enabled: sec.jwt_signing_key.is_empty() || sec.access_ui,
security_file_name: sec.file_name(),
jwt_keys: sec.jwt_keys(),
fips_setting,
jwt_signing_key: sec.jwt_signing_key,
jwt_signing_expires_seconds: sec.jwt_signing_expires,
jwt_previous_signing_key: sec.jwt_previous_signing_key,
@@ -1040,6 +1076,12 @@ fn default_volume_dir() -> String {
std::env::temp_dir().to_string_lossy().into_owned()
}
/// The WEED_ variable that overrides `setting`, as Go's viper names it:
/// `jwt.filer_signing.key` is `WEED_JWT_FILER_SIGNING_KEY`.
fn env_name(setting: &str) -> String {
format!("WEED_{}", setting.to_uppercase().replace('.', "_"))
}
/// Parsed security configuration from security.toml.
#[derive(Debug, Default)]
pub struct SecurityConfig {
@@ -1068,6 +1110,12 @@ pub struct SecurityConfig {
pub access_ui: bool,
/// The file was read; otherwise only defaults and WEED_ overrides are set.
pub file_read: bool,
/// The file the settings came from, for messages that name it.
pub file_used: Option<PathBuf>,
/// The `jwt.filer_signing*` keys, by setting. The volume server does not
/// use them; they are read so strict mode refuses a short one, as every Go
/// process that reads the same security.toml does.
pub filer_jwt_keys: Vec<(&'static str, Vec<u8>)>,
/// IPs from [guard] white_list in security.toml
pub guard_white_list: Vec<String>,
/// `[fips] mode` as the file sets it, read like every other key here;
@@ -1075,6 +1123,48 @@ pub struct SecurityConfig {
pub fips_mode: Option<String>,
}
impl SecurityConfig {
/// Sets the `jwt.filer_signing*` key `setting` to `value`, replacing an
/// earlier value as a later line or a WEED_ variable does in Go.
fn set_filer_jwt_key(&mut self, setting: &'static str, value: &str) {
self.filer_jwt_keys.retain(|(s, _)| *s != setting);
self.filer_jwt_keys
.push((setting, value.as_bytes().to_vec()));
}
/// Every JWT key setting the file and the WEED_ variables set, in the
/// order of `seaweed_common::jwt_keys::JWT_KEY_SETTINGS`; an unset key is
/// empty.
pub fn jwt_keys(&self) -> Vec<(&'static str, Vec<u8>)> {
seaweed_common::jwt_keys::JWT_KEY_SETTINGS
.iter()
.map(|&setting| {
let key = match setting {
"jwt.signing.key" => self.jwt_signing_key.clone(),
"jwt.signing.previous_key" => self.jwt_previous_signing_key.clone(),
"jwt.signing.read.key" => self.jwt_read_signing_key.clone(),
"jwt.signing.read.previous_key" => self.jwt_previous_read_signing_key.clone(),
_ => self
.filer_jwt_keys
.iter()
.find(|(s, _)| *s == setting)
.map(|(_, key)| key.clone())
.unwrap_or_default(),
};
(setting, key)
})
.collect()
}
/// The name messages give the file: its path, or "security.toml" when no
/// file was read, as Go does.
pub fn file_name(&self) -> String {
self.file_used
.as_ref()
.map_or_else(|| "security.toml".to_string(), |p| p.display().to_string())
}
}
/// Parse a security.toml file to extract JWT signing keys and TLS configuration.
/// Format:
/// ```toml
@@ -1133,129 +1223,62 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
}
};
let mut cfg = SecurityConfig::default();
let table = lowercase_keys(
content
.parse::<toml::Table>()
.unwrap_or_else(|_| lenient_toml_table(&content)),
);
let setting = |name: &str| toml_setting(&table, name);
let text = |name: &str| setting(name).unwrap_or_default();
let flag = |name: &str| text(name).parse().unwrap_or(false);
let expires =
|name: &str, default: i64| setting(name).map_or(0, |v| v.parse().unwrap_or(default));
#[derive(PartialEq)]
enum Section {
None,
JwtSigning,
JwtSigningRead,
HttpsClient,
Grpc,
HttpsVolume,
GrpcVolume,
Tls,
Guard,
Access,
Fips,
}
let mut section = Section::None;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
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;
}
if let Some((key, value)) = trimmed.split_once('=') {
let key = key.trim();
let value: &str = &toml_value_text(value);
match section {
Section::JwtSigningRead => match key {
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_read_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_read_signing_expires = value.parse().unwrap_or(60)
}
_ => {}
},
Section::JwtSigning => match key {
"key" => cfg.jwt_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_signing_expires = value.parse().unwrap_or(10)
}
_ => {}
},
Section::HttpsClient => match key {
"enabled" => cfg.https_client_enabled = value.parse().unwrap_or(false),
"cert" => cfg.https_client_cert_file = value.to_string(),
"key" => cfg.https_client_key_file = value.to_string(),
"ca" => cfg.https_client_ca_file = value.to_string(),
_ => {}
},
Section::Grpc => match key {
"ca" => cfg.grpc_ca_file = value.to_string(),
"allowed_wildcard_domain" => {
cfg.grpc_allowed_wildcard_domain = value.to_string()
}
"health_check_commonNames" => {
cfg.grpc_health_check_common_names = parse_common_names(value)
}
_ => {}
},
Section::HttpsVolume => match key {
"cert" => cfg.https_cert_file = value.to_string(),
"key" => cfg.https_key_file = value.to_string(),
"ca" => cfg.https_ca_file = value.to_string(),
_ => {}
},
Section::GrpcVolume => match key {
"cert" => cfg.grpc_cert_file = value.to_string(),
"key" => cfg.grpc_key_file = value.to_string(),
"client_cert" => cfg.grpc_client_cert_file = value.to_string(),
"client_key" => cfg.grpc_client_key_file = value.to_string(),
// Go only reads CA from [grpc], not [grpc.volume]
"allowed_commonNames" => {
cfg.grpc_volume_allowed_common_names =
value.split(',').map(|name| name.to_string()).collect();
}
_ => {}
},
Section::Tls => match key {
"min_version" => cfg.tls_policy.min_version = value.to_string(),
"max_version" => cfg.tls_policy.max_version = value.to_string(),
"cipher_suites" => cfg.tls_policy.cipher_suites = value.to_string(),
_ => {}
},
Section::Guard => {
if key == "white_list" {
cfg.guard_white_list = value
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
Section::Access => {
if key == "ui" {
cfg.access_ui = value.parse().unwrap_or(false)
}
}
Section::Fips => {
if key == "mode" {
cfg.fips_mode = Some(value.to_string())
}
}
Section::None => {}
}
let mut cfg = SecurityConfig {
jwt_signing_key: text("jwt.signing.key").into_bytes(),
jwt_previous_signing_key: text("jwt.signing.previous_key").into_bytes(),
jwt_signing_expires: expires("jwt.signing.expires_after_seconds", 10),
jwt_read_signing_key: text("jwt.signing.read.key").into_bytes(),
jwt_previous_read_signing_key: text("jwt.signing.read.previous_key").into_bytes(),
jwt_read_signing_expires: expires("jwt.signing.read.expires_after_seconds", 60),
https_client_enabled: flag("https.client.enabled"),
https_client_cert_file: text("https.client.cert"),
https_client_key_file: text("https.client.key"),
https_client_ca_file: text("https.client.ca"),
grpc_ca_file: text("grpc.ca"),
grpc_allowed_wildcard_domain: text("grpc.allowed_wildcard_domain"),
grpc_health_check_common_names: parse_common_names(&text("grpc.health_check_commonNames")),
https_cert_file: text("https.volume.cert"),
https_key_file: text("https.volume.key"),
https_ca_file: text("https.volume.ca"),
grpc_cert_file: text("grpc.volume.cert"),
grpc_key_file: text("grpc.volume.key"),
grpc_client_cert_file: text("grpc.volume.client_cert"),
grpc_client_key_file: text("grpc.volume.client_key"),
// Go only reads CA from [grpc], not [grpc.volume]
grpc_volume_allowed_common_names: setting("grpc.volume.allowed_commonNames")
.map(|names| names.split(',').map(String::from).collect())
.unwrap_or_default(),
tls_policy: TlsPolicy {
min_version: text("tls.min_version"),
max_version: text("tls.max_version"),
cipher_suites: text("tls.cipher_suites"),
},
guard_white_list: text("guard.white_list")
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
access_ui: flag("access.ui"),
fips_mode: toml_entry(&table, &["fips", "mode"]).map(toml_text),
..SecurityConfig::default()
};
for name in seaweed_common::jwt_keys::JWT_KEY_SETTINGS
.iter()
.filter(|name| name.starts_with("jwt.filer_signing"))
{
if let Some(key) = setting(name) {
cfg.set_filer_jwt_key(name, &key);
}
}
@@ -1273,6 +1296,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
// e.g. WEED_JWT_SIGNING_KEY overrides [jwt.signing] key
apply_env_overrides(&mut cfg, env);
cfg.file_read = true;
cfg.file_used = Some(config_path);
cfg
}
@@ -1291,6 +1315,95 @@ fn section_header(trimmed: &str) -> Option<&str> {
Some(header.trim_end())
}
/// The value of the dotted `setting` in `table`, a table from
/// `lowercase_keys`, as Go's viper GetString reads it: a value that is not a
/// string reads as its TOML text, and an array or a table as unset.
fn toml_setting(table: &toml::Table, setting: &str) -> Option<String> {
let setting = setting.to_lowercase();
let path: Vec<&str> = setting.split('.').collect();
match toml_entry(table, &path)? {
toml::Value::Array(_) | toml::Value::Table(_) => None,
value => Some(toml_text(value)),
}
}
fn toml_text(value: &toml::Value) -> String {
match value {
toml::Value::String(text) => text.clone(),
toml::Value::Float(number) => number.to_string(),
other => other.to_string(),
}
}
/// The value at `path` in `table`. As in viper, the longest run of leading
/// parts that is itself a key wins (`"jwt.signing.key" = ...` over
/// `[jwt.signing] key`), and a shorter run is tried when the rest of the path
/// is not under it.
fn toml_entry<'a>(table: &'a toml::Table, path: &[&str]) -> Option<&'a toml::Value> {
(1..=path.len()).rev().find_map(|n| {
let value = table.get(&path[..n].join("."))?;
match (&path[n..], value) {
([], value) => Some(value),
(rest, toml::Value::Table(next)) => toml_entry(next, rest),
_ => None,
}
})
}
/// `table` with every key lowercased, as viper holds a config file. When two
/// spellings of a key collide, the one that is not lowercase wins, as it does
/// in viper.
fn lowercase_keys(table: toml::Table) -> toml::Table {
let mut lowered = toml::Table::new();
for (key, value) in table {
let value = match value {
toml::Value::Table(nested) => toml::Value::Table(lowercase_keys(nested)),
other => other,
};
let lower = key.to_lowercase();
if key != lower || !lowered.contains_key(&lower) {
lowered.insert(lower, value);
}
}
lowered
}
/// The `key = value` lines of a file that is not valid TOML, each under its
/// full dotted name (`jwt.signing.key`), so no line can replace the table
/// another line's value is in. Go's viper skips such a file; this server keeps
/// reading what it can from it, one line at a time.
fn lenient_toml_table(content: &str) -> toml::Table {
let mut table = toml::Table::new();
let mut section = String::new();
let mut in_array_of_tables = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if let Some(header) = section_header(trimmed) {
in_array_of_tables = header.starts_with("[[");
section = header
.trim_start_matches('[')
.trim_end_matches(']')
.split('.')
.map(|part| format!("{}.", part.trim()))
.collect();
continue;
}
if in_array_of_tables {
continue;
}
if let Some((key, value)) = trimmed.split_once('=') {
table.insert(
format!("{section}{}", key.trim()),
toml::Value::String(toml_value_text(value)),
);
}
}
table
}
/// 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.
@@ -1306,31 +1419,22 @@ fn toml_value_text(raw: &str) -> String {
}
/// The FIPS mode this volume server runs in: `WEED_FIPS_MODE`, else
/// `fips.mode` in the security.toml `--securityFile` names or the search
/// finds, read by the same loader as the JWT keys, else off. A file that
/// exists but cannot be read is an error, since it may set the mode.
pub fn resolve_fips_setting(
security_file: &str,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(security_file, &process_env)
}
/// `fips.mode` in `parsed`, the security.toml `--securityFile` names or the
/// search finds, else off. A file that exists but was not read is an error,
/// since it may set the mode.
fn resolve_fips_setting_with_env(
security_file: &str,
parsed: &SecurityConfig,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
let path = resolve_security_config_path(security_file, env).filter(|p| p.exists());
let path = parsed
.file_used
.clone()
.or_else(|| resolve_security_config_path(security_file, env).filter(|p| p.exists()));
let Some(path) = path else {
return seaweed_common::fips::resolve(None, None, env);
};
if let Err(e) = std::fs::read_to_string(&path) {
return Err(seaweed_common::fips::FipsModeError::File {
path,
reason: e.to_string(),
});
}
let parsed = parse_security_config_with_env(&path.to_string_lossy(), env);
fips_setting_from_parsed(path, &parsed, env)
fips_setting_from_parsed(path, parsed, env)
}
/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env`
@@ -1365,6 +1469,13 @@ fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBu
/// Apply WEED_ environment variable overrides to a SecurityConfig.
/// Matches Go's Viper convention: WEED_ prefix, uppercase, dots replaced with underscores.
fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
for setting in seaweed_common::jwt_keys::JWT_KEY_SETTINGS {
if setting.starts_with("jwt.filer_signing") {
if let Some(v) = env_string(env, &env_name(setting)) {
cfg.set_filer_jwt_key(setting, &v);
}
}
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_KEY") {
cfg.jwt_signing_key = v.into_bytes();
}
@@ -1717,6 +1828,46 @@ mod tests {
}
}
#[test]
fn test_min_free_space_is_low_from_holds_until_margin() {
let pct = MinFreeSpace::Percent(7.0);
let total = 10_000u64;
for (was_low, free, want) in [
(false, 699, true),
(false, 702, false),
(true, 702, true),
(true, 799, true),
(true, 800, false),
(false, 799, false),
] {
assert_eq!(
pct.is_low_from(was_low, free, total),
want,
"percent was_low={was_low} free={free}"
);
}
let gib = 1u64 << 30;
let bytes = MinFreeSpace::Bytes(70 * gib);
let total = 1000 * gib;
for (was_low, free, want) in [
(false, 70 * gib - 1, true),
(false, 70 * gib, false),
(true, 70 * gib + 1, true),
(true, 80 * gib - 1, true),
(true, 80 * gib, false),
] {
assert_eq!(
bytes.is_low_from(was_low, free, total),
want,
"bytes was_low={was_low} free={free}"
);
}
let near_max = MinFreeSpace::Bytes(u64::MAX - 1);
assert!(near_max.is_low_from(true, u64::MAX - 1, u64::MAX));
}
#[test]
fn test_parse_min_free_spaces_percent() {
let result = parse_min_free_spaces("", "1").unwrap();
@@ -1943,6 +2094,58 @@ mod tests {
}
}
#[test]
fn test_jwt_keys_include_the_filer_keys_and_their_env_overrides() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "volume-write"
previous_key = "volume-write-old"
[jwt.signing.read]
key = "volume-read"
[jwt.filer_signing]
key = "filer-write"
grpc_key = "filer-grpc"
[jwt.filer_signing.read]
previous_key = "filer-read-old"
[jwt.filer_signing.subscribe]
key = "filer-subscribe"
"#,
)
.unwrap();
let path = tmp.path().to_str().unwrap();
let env = fake_env(&[("WEED_JWT_FILER_SIGNING_KEY", "filer-write-env")]);
let cfg = parse_security_config_with_env(path, &env);
let keys: Vec<(&str, String)> = cfg
.jwt_keys()
.into_iter()
.map(|(setting, key)| (setting, String::from_utf8(key).unwrap()))
.collect();
let want = [
("jwt.signing.key", "volume-write"),
("jwt.signing.previous_key", "volume-write-old"),
("jwt.signing.read.key", "volume-read"),
("jwt.signing.read.previous_key", ""),
("jwt.filer_signing.key", "filer-write-env"),
("jwt.filer_signing.previous_key", ""),
("jwt.filer_signing.read.key", ""),
("jwt.filer_signing.read.previous_key", "filer-read-old"),
("jwt.filer_signing.grpc_key", "filer-grpc"),
("jwt.filer_signing.grpc_previous_key", ""),
("jwt.filer_signing.subscribe.key", "filer-subscribe"),
];
let want: Vec<(&str, String)> = want.iter().map(|(s, k)| (*s, k.to_string())).collect();
assert_eq!(keys, want);
assert_eq!(cfg.file_name(), path);
assert_eq!(SecurityConfig::default().file_name(), "security.toml");
}
#[test]
fn test_parse_security_config_access_ui() {
let tmp = tempfile::NamedTempFile::new().unwrap();
@@ -2262,6 +2465,39 @@ cipher_suites = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_empty_env_override_keeps_the_file_value() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "file-write"
[jwt.filer_signing]
key = "file-filer"
[grpc]
ca = "/file/ca.pem"
"#,
)
.unwrap();
let env = fake_env(&[
("WEED_JWT_SIGNING_KEY", ""),
("WEED_JWT_FILER_SIGNING_KEY", ""),
("WEED_GRPC_CA", ""),
]);
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &env);
assert_eq!(cfg.jwt_signing_key, b"file-write");
assert_eq!(cfg.grpc_ca_file, "/file/ca.pem");
let filer_key = cfg
.jwt_keys()
.into_iter()
.find(|(setting, _)| *setting == "jwt.filer_signing.key")
.map(|(_, key)| key);
assert_eq!(filer_key.as_deref(), Some(&b"file-filer"[..]));
}
#[test]
fn test_previous_signing_keys_from_file_and_env() {
let tmp = tempfile::NamedTempFile::new().unwrap();
@@ -2313,16 +2549,16 @@ previous_key = "read-old"
std::fs::write(tmp.path(), "[fips]\nmode = \"on\"\n").unwrap();
let path = tmp.path().to_str().unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
let env = fake_env(&[("WEED_FIPS_MODE", "strict")]);
let setting = resolve_fips_setting_with_env(path, &env).unwrap();
let setting = fips_setting_of(path, &env).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
let env = fake_env(&[("WEED_FIPS_MODE", "only")]);
assert!(resolve_fips_setting_with_env(path, &env).is_err());
assert!(fips_setting_of(path, &env).is_err());
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Off);
}
@@ -2336,11 +2572,34 @@ previous_key = "read-old"
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"unquoted-secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
std::fs::write(tmp.path(), "[fips]\nmode = [\"strict\"]\n").unwrap();
assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err());
assert!(fips_setting_of(path, &fake_env(&[])).is_err());
}
#[test]
fn test_lenient_file_keeps_a_key_a_later_line_would_shadow() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[jwt]\nsigning = \"x\"\n\
[jwt.signing.key]\nx = unquoted\n";
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
}
#[test]
fn test_lenient_file_skips_array_of_tables_sections() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[[jwt.signing]]\nkey = \"\"\n\
[fips]\nmode = \"on\"\n";
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
}
#[test]
@@ -2357,23 +2616,134 @@ previous_key = "read-old"
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();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
}
#[test]
fn test_security_config_reads_the_toml_forms_go_reads() {
for text in [
"[jwt.signing]\n\"key\" = \"0123456789\"\n\
[jwt.filer_signing]\n'key' = \"0123456789\"\n[fips]\n\"mode\" = \"on\"\n",
"[jwt.signing]\nkey = \"\"\"\n0123456789\"\"\"\n\
[jwt.filer_signing]\nkey = '''\n0123456789'''\n[fips]\nmode = \"on\"\n",
"jwt.signing.key = \"0123456789\"\njwt.filer_signing.key = \"0123456789\"\n\
fips.mode = \"on\"\n",
"[jwt]\nsigning = { key = \"0123456789\" }\nfiler_signing = { key = \"0123456789\" }\n\
[fips]\nmode = \"on\"\n",
"[ \"jwt\" . signing ]\nKey = \"0123456789\"\n[jwt.\"filer_signing\"]\nKEY = \"0123456789\"\n\
[FIPS]\nMode = \"on\"\n",
] {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), text).unwrap();
assert!(
text.parse::<toml::Table>().is_ok(),
"TOML, as Go reads it: {text}"
);
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
let keys = cfg.jwt_keys();
for setting in ["jwt.signing.key", "jwt.filer_signing.key"] {
let key = keys
.iter()
.find(|(s, _)| *s == setting)
.map(|(_, k)| k.as_slice());
assert_eq!(key, Some(&b"0123456789"[..]), "{setting} in {text}");
}
assert_eq!(cfg.fips_mode.as_deref(), Some("on"), "{text}");
}
}
fn fips_setting_of(
path: &str,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(path, &parse_security_config_with_env(path, env), env)
}
#[test]
fn test_fips_mode_comes_from_the_read_the_jwt_keys_come_from() {
use seaweed_common::fips::FipsMode;
let tmp = tempfile::NamedTempFile::new().unwrap();
let path = tmp.path().to_str().unwrap();
std::fs::write(tmp.path(), "[fips]\nmode = \"strict\"\n").unwrap();
let parsed = parse_security_config_with_env(path, &fake_env(&[]));
std::fs::write(tmp.path(), "[fips]\nmode = \"off\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &parsed, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
}
/// The value Go's viper GetString reads for `jwt.filer_signing.key` from
/// security.toml `text`, as this server reads it.
fn filer_jwt_key(text: &str) -> Vec<u8> {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_ok(), "TOML: {text}");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
cfg.jwt_keys()
.into_iter()
.find(|(s, _)| *s == "jwt.filer_signing.key")
.map(|(_, k)| k)
.unwrap()
}
#[test]
fn test_security_config_prefers_the_longest_literal_key_as_go_does() {
let nested = "[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n";
for literal in [
"\"jwt.filer_signing.key\" = \"short\"\n",
"[jwt]\n\"filer_signing.key\" = \"short\"\n",
] {
assert_eq!(filer_jwt_key(&format!("{literal}{nested}")), b"short");
}
assert_eq!(
filer_jwt_key(&format!("\"jwt.filer_signing\" = \"x\"\n{nested}")),
b"0123456789abcdef"
);
}
#[test]
fn test_security_config_resolves_key_case_collisions_as_go_does() {
for text in [
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\nKEY = \"short\"\n",
"[jwt.filer_signing]\nKEY = \"short\"\nkey = \"0123456789abcdef\"\n",
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n[JWT.filer_signing]\nkey = \"short\"\n",
] {
assert_eq!(filer_jwt_key(text), b"short", "{text}");
}
assert_eq!(
filer_jwt_key("[JWT.Filer_Signing]\nKey = \"0123456789abcdef\"\n"),
b"0123456789abcdef"
);
}
#[test]
fn test_security_config_reads_a_non_string_jwt_key_as_go_does() {
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = [\"x\"]\n"), b"");
assert_eq!(filer_jwt_key("[jwt.filer_signing.key]\nx = \"y\"\n"), b"");
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = 1234\n"), b"1234");
}
#[test]
fn test_security_config_reads_a_float_jwt_key_as_go_does() {
let key = filer_jwt_key("[jwt.filer_signing]\nkey = 1234567890123.0\n");
assert_eq!(key, b"1234567890123");
let key = filer_jwt_key("[jwt.filer_signing]\nkey = \"1234567890123.0\"\n");
assert_eq!(key, b"1234567890123.0");
}
#[test]
fn test_fips_mode_refuses_a_security_file_it_cannot_read() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"[fips]\nmode = \"on\"\n\xff\xfe\n").unwrap();
let path = tmp.path().to_str().unwrap();
let err = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap_err();
let err = fips_setting_of(path, &fake_env(&[])).unwrap_err();
assert!(
err.to_string()
.contains("cannot tell whether it sets fips.mode"),
"{err}"
);
let missing = format!("{path}.missing");
let setting = resolve_fips_setting_with_env(&missing, &fake_env(&[])).unwrap();
let setting = fips_setting_of(&missing, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off);
}
+32 -3
View File
@@ -57,7 +57,8 @@ fn main() {
.init();
let config = config::parse_cli();
install_crypto_provider_for_fips_mode(&config.security_file);
install_crypto_provider_for_fips_mode(&config);
check_jwt_keys_for_fips_mode(&config);
seaweed_volume::server::server_stats::init_process_start();
#[cfg(unix)]
let cpu_profile = match CpuProfileSession::start(&config) {
@@ -105,8 +106,10 @@ fn main() {
/// Resolves the FIPS mode from `fips.mode` or `WEED_FIPS_MODE`, logs it and
/// installs the matching rustls provider before anything builds TLS; exits
/// when the value is unknown.
fn install_crypto_provider_for_fips_mode(security_file: &str) {
let installed = config::resolve_fips_setting(security_file)
fn install_crypto_provider_for_fips_mode(config: &config::VolumeServerConfig) {
let installed = config
.fips_setting
.clone()
.map_err(|e| e.to_string())
.and_then(|setting| {
seaweed_common::tls::install_process_provider(setting.mode)
@@ -126,6 +129,32 @@ fn install_crypto_provider_for_fips_mode(security_file: &str) {
}
}
/// Checks the JWT HMAC signing keys from security.toml and their WEED_
/// variables for a length of at least 14 characters, as FIPS 140 requires.
/// Under `fips.mode = strict`, if any of them is shorter, it logs an error
/// naming each such setting and its length and exits the server with status 1.
/// In any other mode the server starts, and each such key except a
/// `previous_key` gets a warning that strict mode would refuse it.
fn check_jwt_keys_for_fips_mode(config: &config::VolumeServerConfig) {
use seaweed_common::jwt_keys;
let mode = seaweed_common::fips::process_mode();
let file = &config.security_file_name;
for (setting, key) in &config.jwt_keys {
if let Some(warning) = jwt_keys::short_key_warning(mode, file, setting, key) {
warn!("{}", warning);
}
}
let keys: Vec<(&str, &[u8])> = config
.jwt_keys
.iter()
.map(|(setting, key)| (*setting, key.as_slice()))
.collect();
if let Some(short) = jwt_keys::short_keys(mode, &keys) {
error!("{}", jwt_keys::startup_refusal(file, &short));
std::process::exit(1);
}
}
/// Mirrors Go's rejectHttpsDowngrade: a redirect must not downgrade a request
/// carrying data and auth headers from https to plaintext.
fn redirect_is_https_downgrade(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
+116 -2
View File
@@ -12,6 +12,8 @@ use std::net::IpAddr;
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use seaweed_common::fips::FipsMode;
use seaweed_common::jwt_keys;
use serde::{Deserialize, Serialize};
// ============================================================================
@@ -184,6 +186,21 @@ pub struct Guard {
is_write_active: bool,
}
/// Go's `usablePreviousKey`: under strict mode, a previous key shorter than 14
/// characters is dropped with an error naming it (`name`), and the reload goes
/// ahead without it.
fn usable_previous_key(mode: FipsMode, name: &str, key: SigningKey) -> SigningKey {
if jwt_keys::is_short(mode, &key.0) {
tracing::error!(
"JWT reload: ignoring the {}, which is shorter than the {} characters FIPS 140 needs for HMAC keys; the new keys are in effect",
name,
jwt_keys::MIN_HMAC_KEY_BYTES
);
return SigningKey(vec![]);
}
key
}
impl Guard {
pub fn new(
whitelist: &[String],
@@ -238,7 +255,10 @@ impl Guard {
/// Refresh the JWT signing keys and their expirations in place so operators
/// can rotate keys via SIGHUP without restarting the process. Mirrors Go's
/// `Guard::UpdateSigningKeys`: it swaps the fields and recomputes
/// `is_write_active`.
/// `is_write_active`. Under `fips.mode = strict`, a new write or read key
/// shorter than 14 characters keeps the keys as they were, logs an error and
/// returns false; a short previous key is dropped with an error and the
/// other keys take effect.
pub fn update_signing_keys(
&mut self,
signing_key: SigningKey,
@@ -247,7 +267,42 @@ impl Guard {
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) {
) -> bool {
self.update_signing_keys_in_mode(
seaweed_common::fips::process_mode(),
signing_key,
expires_after_sec,
read_signing_key,
read_expires_after_sec,
previous_signing_key,
previous_read_signing_key,
)
}
/// [`Guard::update_signing_keys`] for the FIPS mode `mode`.
#[allow(clippy::too_many_arguments)]
fn update_signing_keys_in_mode(
&mut self,
mode: FipsMode,
signing_key: SigningKey,
expires_after_sec: i64,
read_signing_key: SigningKey,
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) -> bool {
let current: [(&str, &[u8]); 2] = [
("signing key", &signing_key.0),
("read signing key", &read_signing_key.0),
];
if let Some(short) = jwt_keys::short_keys(mode, &current) {
tracing::error!("JWT reload: keeping the keys in effect, because {}", short);
return false;
}
let previous_signing_key =
usable_previous_key(mode, "previous signing key", previous_signing_key);
let previous_read_signing_key =
usable_previous_key(mode, "previous read signing key", previous_read_signing_key);
self.signing_key = signing_key;
self.expires_after_sec = expires_after_sec;
self.read_signing_key = read_signing_key;
@@ -257,6 +312,7 @@ impl Guard {
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
true
}
/// Whether any write-side control is configured: a non-empty whitelist or a
@@ -688,6 +744,64 @@ mod tests {
assert!(!accepts(&guard, "read-old", false));
}
#[test]
fn test_strict_reload_keeps_keys_when_a_current_key_is_short() {
let mut guard = Guard::new(
&[],
SigningKey::from_string("write-key-long-enough"),
10,
SigningKey::from_string("read-key-long-enough"),
60,
);
for (write, read) in [
("0123456789", "read-key-replaced-ok"),
("write-key-replaced-ok", "short"),
] {
assert!(!guard.update_signing_keys_in_mode(
FipsMode::Strict,
SigningKey::from_string(write),
11,
SigningKey::from_string(read),
61,
SigningKey(vec![]),
SigningKey(vec![]),
));
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
assert_eq!(guard.read_signing_key.0, b"read-key-long-enough");
assert_eq!(guard.expires_after_sec, 10);
}
assert!(guard.update_signing_keys_in_mode(
FipsMode::On,
SigningKey::from_string("0123456789"),
11,
SigningKey(vec![]),
61,
SigningKey(vec![]),
SigningKey(vec![]),
));
assert_eq!(guard.signing_key.0, b"0123456789");
}
#[test]
fn test_strict_reload_drops_a_short_previous_key() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(guard.update_signing_keys_in_mode(
FipsMode::Strict,
SigningKey::from_string("write-key-long-enough"),
10,
SigningKey::from_string("read-key-long-enough"),
60,
SigningKey::from_string("old-short"),
SigningKey::from_string("old-read-key-long-enough"),
));
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
assert!(guard.previous_signing_key.is_empty());
assert_eq!(
guard.previous_read_signing_key.0,
b"old-read-key-long-enough"
);
}
#[test]
fn test_update_signing_keys_toggles_write_active() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
+6
View File
@@ -457,6 +457,12 @@ mod tests {
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
security_file_name: String::new(),
jwt_keys: Vec::new(),
fips_setting: Ok(seaweed_common::fips::Setting {
mode: Default::default(),
source: None,
}),
}
}
+140
View File
@@ -1141,6 +1141,8 @@ impl VolumeServer for VolumeGrpcService {
self.state.check_maintenance()?;
let req = request.into_inner();
let mut results = Vec::new();
let mut replica_errs: std::collections::HashMap<u32, Result<(), String>> =
std::collections::HashMap::new();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -1162,6 +1164,23 @@ impl VolumeServer for VolumeGrpcService {
}
};
let vid = file_id.volume_id.0;
if !req.skip_replica_check && !replica_errs.contains_key(&vid) {
let checked =
crate::server::handlers::check_delete_replicas(&self.state, vid).await;
replica_errs.insert(vid, checked);
}
if let Some(Err(e)) = replica_errs.get(&vid) {
results.push(volume_server_pb::DeleteResult {
file_id: fid_str.clone(),
status: 503,
error: e.clone(),
size: 0,
version: 0,
});
continue;
}
let mut n = Needle {
id: file_id.key,
cookie: file_id.cookie,
@@ -15032,6 +15051,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -15051,6 +15071,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: true,
fsync: false,
skip_replica_check: false,
}))
.await
.expect_err("a server in maintenance mode must refuse a batch delete");
@@ -15102,6 +15123,120 @@ mod tests {
);
}
/// Go's TestBatchDelete_WaitsForEveryReplica: a replica the master no
/// longer lists would miss the delete, so the delete waits for it.
#[tokio::test]
async fn test_batch_delete_waits_for_every_replica() {
let (service, _tmp) = make_local_service_with_volume("", None);
{
let mut store = service.state.store.write().unwrap();
store
.add_volume(
VolumeId(2),
DiskType::HardDrive,
&VolumeSpec {
replica_placement: Some(
crate::storage::super_block::ReplicaPlacement::from_string("001")
.unwrap(),
),
..Default::default()
},
)
.unwrap();
let mut n = Needle {
id: NeedleId(1),
cookie: Cookie(0x3344),
data: b"hello".to_vec(),
data_size: 5,
..Needle::default()
};
store
.write_volume_needle(VolumeId(2), &mut n, false)
.unwrap();
for id in [2, 3] {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(0x3344),
data: b"hello".to_vec(),
data_size: 5,
..Needle::default()
};
store
.write_volume_needle(VolumeId(2), &mut n, false)
.unwrap();
}
}
let urls = Arc::new(std::sync::Mutex::new(vec!["127.0.0.1:1"]));
let min_writable_copies = Arc::new(std::sync::atomic::AtomicU32::new(0));
*service.state.current_master_url.write().await =
crate::server::handlers::tests::spawn_lookup_master({
let urls = urls.clone();
let min_writable_copies = min_writable_copies.clone();
move |vid| {
let locations = urls
.lock()
.unwrap()
.iter()
.map(|url| master_pb::Location {
url: url.to_string(),
..Default::default()
})
.collect();
let mut answer =
crate::server::handlers::tests::lookup_answer(vid, locations, "");
answer.volume_id_locations[0].min_writable_copies =
min_writable_copies.load(std::sync::atomic::Ordering::SeqCst);
Ok(answer)
}
})
.await;
let service = &service;
let delete = |id: u64| async move {
let fid = needle::FileId::new(VolumeId(2), NeedleId(id), Cookie(0x3344)).to_string();
let resp = service
.batch_delete(Request::new(volume_server_pb::BatchDeleteRequest {
file_ids: vec![fid],
skip_cookie_check: true,
fsync: false,
skip_replica_check: id == 3,
}))
.await
.unwrap()
.into_inner();
assert_eq!(resp.results.len(), 1, "{:?}", resp.results);
(resp.results[0].status, resp.results[0].error.clone())
};
let (status, error) = delete(1).await;
assert_eq!(status, 503, "{error}");
assert!(error.contains("replication copy count"), "{error}");
{
let store = service.state.store.read().unwrap();
let (_, v) = store.find_volume(VolumeId(2)).unwrap();
let mut n = Needle {
id: NeedleId(1),
..Needle::default()
};
v.read_needle(&mut n)
.expect("needle deleted while a replica was offline");
}
let (status, error) = delete(3).await;
assert_eq!(status, 202, "a delete skipping the replica check: {error}");
urls.lock().unwrap().push("127.0.0.2:8080");
let (status, error) = delete(1).await;
assert_eq!(status, 202, "{error}");
// a volume grown degraded is complete with the copies the master asks for
urls.lock().unwrap().pop();
min_writable_copies.store(1, std::sync::atomic::Ordering::SeqCst);
let (status, error) = delete(2).await;
assert_eq!(status, 202, "{error}");
}
/// Go's TestBatchDeleteFsyncsOnlyWhenAsked.
#[tokio::test]
async fn test_batch_delete_fsyncs_only_when_asked() {
@@ -15133,6 +15268,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: true,
fsync,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -16320,6 +16456,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: false,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -16403,6 +16540,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: false,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -17525,6 +17663,7 @@ mod tests {
file_ids: vec!["1,b00003344".to_string()],
skip_cookie_check: false,
fsync: false,
skip_replica_check: false,
})
};
@@ -17575,6 +17714,7 @@ mod tests {
file_ids: vec!["2,b00003344".to_string()],
skip_cookie_check,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
+161 -30
View File
@@ -577,12 +577,13 @@ async fn master_lookup_once(
/// Look up volume locations over the master's gRPC port, like Go's
/// operation.LookupVolumeIds: the master's HTTP port need not speak the
/// `[https.client]` scheme.
/// `[https.client]` scheme. Also returns the master's min_writable_copies
/// (0 unless the volume was grown degraded).
async fn lookup_volume(
tls: Option<&OutgoingGrpcTlsConfig>,
master_url: &str,
volume_id: u32,
) -> Result<Vec<VolumeLocation>, String> {
) -> Result<(Vec<VolumeLocation>, u32), String> {
let grpc_addr = parse_grpc_address(master_url)?;
let cached = MASTER_LOOKUP_CHANNEL
.lock()
@@ -618,15 +619,17 @@ async fn lookup_volume(
}
};
let mut locations = Vec::new();
let mut min_writable_copies = 0;
for found in resp.volume_id_locations {
// Mirror Go: a per-volume error in an answered lookup (e.g. a missing
// volume) means "no locations"; only a failed call is an error.
if !found.error.is_empty() {
tracing::debug!("volume {} lookup: {}", volume_id, found.error);
}
min_writable_copies = min_writable_copies.max(found.min_writable_copies);
locations.extend(found.locations.into_iter().map(VolumeLocation::from));
}
Ok(locations)
Ok((locations, min_writable_copies))
}
fn grpc_address_for_location(location: &VolumeLocation) -> Result<String, String> {
@@ -678,7 +681,7 @@ async fn batch_delete_file_ids(
let locations = if let Some(locations) = lookup_cache.get(&volume_id) {
locations.clone()
} else {
let locations = lookup_volume(
let (locations, _) = lookup_volume(
state.outgoing_grpc_tls.as_ref(),
&state.current_master().await,
volume_id,
@@ -719,6 +722,7 @@ async fn batch_delete_file_ids(
file_ids: batch.clone(),
skip_cookie_check: true,
fsync: false,
skip_replica_check: false,
})
.await
.map_err(|e| format!("batch delete {}: {}", grpc_addr, e))?
@@ -740,6 +744,47 @@ async fn batch_delete_file_ids(
Ok(())
}
/// Mirrors Go's checkDeleteReplicas: refuses a delete the master cannot route
/// to every replica, as the HTTP delete path does, so an offline replica does
/// not keep the needle once it returns.
pub(crate) async fn check_delete_replicas(
state: &VolumeServerState,
vid: u32,
) -> Result<(), String> {
let copy_count = {
let store = state.store.read().unwrap();
match store.find_volume(VolumeId(vid)) {
Some((_, v)) => v.super_block().replica_placement.get_copy_count() as u32,
None => return Ok(()),
}
};
if copy_count <= 1 {
return Ok(());
}
let (locations, min_writable_copies) = lookup_volume(
state.outgoing_grpc_tls.as_ref(),
&state.current_master().await,
vid,
)
.await
.map_err(|e| format!("replicating lookup failed for {}: {}", vid, e))?;
let copy_count = match min_writable_copies {
n if n > 0 && n < copy_count => n,
_ => copy_count,
};
let deletable = locations
.iter()
.filter(|loc| !loc.read_only || loc.read_only_can_delete)
.count();
if deletable < copy_count as usize {
return Err(format!(
"replication locations [{}] is less than volume {} replication copy count [{}]",
deletable, vid, copy_count
));
}
Ok(())
}
/// `query` with the fields named in `overrides` replaced by their values.
fn override_query_fields(
query: &str,
@@ -828,7 +873,7 @@ async fn do_replicated_request(
body: Option<bytes::Bytes>,
replica_jwt: Option<&ReplicaJwt>,
) -> Result<(), String> {
let locations = lookup_volume(
let (locations, min_writable_copies) = lookup_volume(
state.outgoing_grpc_tls.as_ref(),
&state.current_master().await,
vid,
@@ -839,9 +884,15 @@ async fn do_replicated_request(
let copy_count = {
let store = state.store.read().unwrap();
store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| {
v.super_block().replica_placement.get_copy_count()
v.super_block().replica_placement.get_copy_count() as u32
})
};
// A degraded volume is writable with fewer copies, like Go's
// getRemoteReplications.
let copy_count = match min_writable_copies {
n if n > 0 && n < copy_count => n,
_ => copy_count,
};
let allow_delete = method == axum::http::Method::DELETE;
let eligible_locations: Vec<_> = locations
.into_iter()
@@ -1009,7 +1060,7 @@ async fn proxy_or_redirect_to_target(
)
.await
{
Ok(locs) => locs,
Ok((locs, _)) => locs,
Err(e) => {
tracing::warn!("volume lookup failed for {}: {}", vid.0, e);
// Go: master lookup failure is 500 in proxy mode, 404 for redirect
@@ -3266,12 +3317,14 @@ pub async fn post_handler(
let original_data_size = uncompressed_data.len() as u32;
// Only compute and validate Content-MD5 when the client provided one
// (Go only computes MD5 when Content-MD5 header/field is present)
// (Go only computes MD5 when Content-MD5 header/field is present).
// Under fips.mode strict no MD5 is computed: the client's value is kept
// unchecked, as Go does under GODEBUG=fips140=only.
let content_md5 = content_md5.or(parsed_content_md5);
let original_content_md5 = if content_md5.is_some() {
Some(compute_md5_base64(&uncompressed_data))
} else {
None
let original_content_md5 = match &content_md5 {
Some(expected) if strict_fips_mode() => Some(expected.clone()),
Some(_) => Some(compute_md5_base64(&uncompressed_data)),
None => None,
};
if let (Some(expected_md5), Some(actual_md5)) = (&content_md5, &original_content_md5)
&& expected_md5 != actual_md5
@@ -3500,10 +3553,19 @@ pub async fn post_handler(
.is_some_and(|(_, v)| v.super_block().replica_placement.get_copy_count() > 1)
};
// A local volume that already refuses writes is refused before the
// fan-out, so no replica keeps a needle nothing references.
let local_refusal = if needs_replication {
let vol = state.store.read().unwrap().writable_volume(vid);
vol.and_then(|v| v.check_writable()).err()
} else {
None
};
// The fan-out runs concurrently with the local needle write, like Go's
// ReplicatedWrite: replicas get the stored bytes with their compression
// state, so they keep it instead of re-deriving it. The ack waits for both.
let replication = if needs_replication {
let replication = if needs_replication && local_refusal.is_none() {
let state_clone = state.clone();
let path_clone = path.clone();
let query_clone = match replica_jwt {
@@ -3576,12 +3638,14 @@ pub async fn post_handler(
None
};
let (write_result, refused_before_append) =
match write_upload_needle(&state, vid, n, fsync).await {
let (write_result, refused_before_append) = match local_refusal {
Some(refused) => (Err(refused), true),
None => match write_upload_needle(&state, vid, n, fsync).await {
Ok(Ok(written)) => (Ok(written), false),
Ok(Err(refused)) => (Err(refused), true),
Err(error) => (Err(error), false),
};
},
};
// No leader-known gate: when the lookup cannot run, the write must fail
// rather than be acknowledged on fewer copies than required. The local
@@ -4927,7 +4991,7 @@ async fn read_remote_chunk_needle(
fid: &str,
how: RemoteRead,
) -> Result<ChunkBytes, String> {
let locations = lookup_volume(
let (locations, _) = lookup_volume(
state.outgoing_grpc_tls.as_ref(),
&state.current_master().await,
vid.0,
@@ -5315,6 +5379,12 @@ fn check_content_crc32c(expected: &str, data: &[u8]) -> Result<(), String> {
Ok(())
}
/// Whether this process runs under `fips.mode = strict`, where it computes no
/// MD5.
fn strict_fips_mode() -> bool {
seaweed_common::fips::process_mode() == seaweed_common::fips::FipsMode::Strict
}
fn compute_md5_base64(data: &[u8]) -> String {
use base64::Engine;
use md5::{Digest, Md5};
@@ -5427,7 +5497,7 @@ fn parse_content_disposition_filename(value: &str) -> Option<String> {
// ============================================================================
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
/// A replica that reads the forward and never answers. Each request's
@@ -5485,6 +5555,67 @@ mod tests {
}
}
/// A volume grown degraded keeps its placement's copy count in the super
/// block; the master's min_writable_copies lets it write with fewer.
#[tokio::test]
async fn http_replicated_write_uses_the_master_min_writable_copies() {
use crate::storage::super_block::ReplicaPlacement;
use tower::ServiceExt;
let app = axum::Router::new().fallback(|| async { StatusCode::CREATED });
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let peer = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
for (min_writable_copies, written) in [(0, false), (2, true), (3, false)] {
let tmp = tempfile::TempDir::new().unwrap();
let mut state = volume_test_state(&tmp);
Arc::get_mut(&mut state).unwrap().self_url = "127.0.0.1:8080".to_string();
state
.store
.read()
.unwrap()
.find_volume(VolumeId(1))
.unwrap()
.1
.set_replica_placement(ReplicaPlacement::from_string("200").unwrap())
.unwrap();
*state.current_master_url.write().await = spawn_lookup_master(move |vid| {
let location = |url: String| master_pb::Location {
url,
..Default::default()
};
let mut answer = lookup_answer(
vid,
vec![
location("127.0.0.1:8080".to_string()),
location(peer.to_string()),
],
"",
);
answer.volume_id_locations[0].min_writable_copies = min_writable_copies;
Ok(answer)
})
.await;
let response = super::super::volume_server::build_admin_router(state)
.oneshot(
Request::builder()
.method(Method::POST)
.uri(format!("/1,{:x}{TEST_COOKIE:08x}", 0x6e7a_0c04u64))
.body(Body::from("x"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status() == StatusCode::CREATED,
written,
"{min_writable_copies}: {}",
response.status()
);
}
}
/// A write forward carries a JWT signed for it, not the incoming one, which
/// can expire while the body streams in.
#[tokio::test]
@@ -6351,7 +6482,7 @@ mod tests {
/// Serve `answer` as the master's gRPC LookupVolume. The returned address
/// carries an unused HTTP port, so a lookup over HTTP would fail.
async fn spawn_lookup_master(
pub(crate) async fn spawn_lookup_master(
answer: impl Fn(&str) -> Result<master_pb::LookupVolumeResponse, tonic::Status>
+ Send
+ Sync
@@ -6367,7 +6498,7 @@ mod tests {
format!("127.0.0.1:1.{}", port)
}
fn lookup_answer(
pub(crate) fn lookup_answer(
volume_id: &str,
locations: Vec<master_pb::Location>,
error: &str,
@@ -6420,7 +6551,7 @@ mod tests {
.await;
for _ in 0..2 {
let locations = super::lookup_volume(None, &master_url, 31)
let (locations, _) = super::lookup_volume(None, &master_url, 31)
.await
.expect("lookup over the master's gRPC port");
assert_eq!(locations.len(), 1);
@@ -6471,7 +6602,7 @@ mod tests {
})
.await;
let locations = super::lookup_volume(None, &master_url, 7)
let (locations, _) = super::lookup_volume(None, &master_url, 7)
.await
.expect("missing volume is not a lookup failure");
assert!(locations.is_empty());
@@ -9599,7 +9730,7 @@ mod tests {
}
#[tokio::test]
async fn http_local_refusal_after_replica_append_is_not_marked() {
async fn http_replicated_write_refusal_is_not_marked() {
for local_read_only in [true, false] {
use crate::storage::super_block::ReplicaPlacement;
use tower::ServiceExt;
@@ -9672,18 +9803,18 @@ mod tests {
}
);
assert!(response.headers().get("x-seaweed-write-outcome").is_none());
let (refused, written) = if local_read_only {
(&volume, &peer_volume)
} else {
(&peer_volume, &volume)
};
assert_eq!(refused.dat_file_size().unwrap(), before);
assert_eq!(peer_volume.dat_file_size().unwrap(), before);
if local_read_only {
assert_eq!(volume.dat_file_size().unwrap(), before);
peer_server.abort();
continue;
}
let mut stored = Needle {
id: NeedleId(id),
cookie: Cookie(TEST_COOKIE),
..Needle::default()
};
written.read_needle(&mut stored).unwrap();
volume.read_needle(&mut stored).unwrap();
assert_eq!(stored.data, payload);
peer_server.abort();
}
+40 -2
View File
@@ -1413,6 +1413,7 @@ fn build_heartbeat_with_ec_status(
}
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
let (read_only, read_only_can_delete) = vol.reported_read_only();
let volume_message = master_pb::VolumeInformationMessage {
id: vol.id.0,
size: volume_size,
@@ -1420,8 +1421,8 @@ fn build_heartbeat_with_ec_status(
file_count: vol.file_count() as u64,
delete_count: vol.deleted_count() as u64,
deleted_byte_count: vol.deleted_size(),
read_only: vol.is_read_only(),
read_only_can_delete: vol.is_no_write_can_delete(),
read_only,
read_only_can_delete,
replica_placement: vol.super_block().replica_placement.to_byte() as u32,
version: vol.super_block().version.0 as u32,
ttl: vol.super_block().ttl.to_u32(),
@@ -1868,6 +1869,43 @@ mod tests {
);
}
#[test]
fn test_build_heartbeat_low_disk_volume_reports_can_delete() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
3,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
vec![],
)
.unwrap();
store
.add_volume(VolumeId(7), DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
store.locations[0]
.is_disk_space_low
.store(true, std::sync::atomic::Ordering::Relaxed);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert!(heartbeat.volumes[0].read_only);
assert!(heartbeat.volumes[0].read_only_can_delete);
store
.find_volume(VolumeId(7))
.unwrap()
.1
.set_no_write_or_delete(true);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert!(heartbeat.volumes[0].read_only);
assert!(!heartbeat.volumes[0].read_only_can_delete);
}
#[test]
fn test_build_heartbeat_marks_empty_store_as_has_no_volumes() {
let temp_dir = tempfile::tempdir().unwrap();
+6
View File
@@ -177,6 +177,12 @@ mod tests {
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
security_file_name: String::new(),
jwt_keys: Vec::new(),
fips_setting: Ok(seaweed_common::fips::Setting {
mode: Default::default(),
source: None,
}),
}
}
+44 -2
View File
@@ -905,6 +905,15 @@ impl DiskLocation {
unused
}
/// Mirrors Go's DiskLocation.updateDiskSpaceLow for a reading with space
/// values.
fn update_disk_space_low(&self, free: u64, total: u64) -> bool {
let was_low = self.is_disk_space_low.load(Ordering::Relaxed);
let is_low = self.min_free_space.is_low_from(was_low, free, total);
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
is_low
}
/// Check disk space against min_free_space and update is_disk_space_low.
pub fn check_disk_space(&self) {
let (total, free) = get_disk_stats(&self.directory);
@@ -912,8 +921,7 @@ impl DiskLocation {
return;
}
let used = total.saturating_sub(free);
let is_low = self.min_free_space.is_low(free, total);
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
self.update_disk_space_low(free, total);
// Go's DiskLocation.AvailableSpace counts only free space above the
// -volume.minFreeSpace floor, so space checks stay above it too.
self.available_space.store(
@@ -1701,6 +1709,40 @@ mod tests {
assert_eq!(loc.available_space.load(Ordering::Relaxed), 0);
}
// Mirrors Go's TestDiskSpaceLowStaysUntilFreeSpaceIsClearlyBack: a
// location that went low stays low until free space clears the margin.
#[test]
fn test_disk_space_low_stays_until_free_space_is_clearly_back() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = DiskLocation::new(
dir,
dir,
0,
DiskType::HardDrive,
MinFreeSpace::Percent(7.0),
Vec::new(),
)
.unwrap();
let total = 10_000u64;
for (free, want) in [
(699, true),
(702, true),
(698, true),
(760, true),
(800, false),
(702, false),
(699, true),
] {
assert_eq!(
loc.update_disk_space_low(free, total),
want,
"free {free} of {total}"
);
assert_eq!(loc.is_disk_space_low.load(Ordering::Relaxed), want);
}
}
// Mirrors Go's CheckDiskSpace pending subtraction: an in-flight copy's
// charge stays out of the cache across a probe, so another copy cannot
// re-spend the headroom the live reading still shows as free.
+8 -1
View File
@@ -3403,7 +3403,7 @@ impl Volume {
Ok(Some(offset))
}
fn check_writable(&self) -> Result<(), VolumeError> {
pub(crate) fn check_writable(&self) -> Result<(), VolumeError> {
if self.is_closed() {
return Err(VolumeError::NotFound);
}
@@ -4229,6 +4229,13 @@ impl Volume {
self.no_write_flags().1
}
/// What the master is told: low disk space still lets deletes through,
/// only no_write_or_delete refuses them. Mirrors Go's reportedReadOnly.
pub fn reported_read_only(&self) -> (bool, bool) {
let (read_only, no_write_or_delete, _, _) = self.read_only_reasons();
(read_only, read_only && !no_write_or_delete)
}
pub fn last_compact_revision(&self) -> u16 {
self.io.read().unwrap().last_compact_revision
}
+2
View File
@@ -6357,7 +6357,9 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
"bytes",
"crc32c",
"log",
"prost",
"protoc-bin-vendored",
+107
View File
@@ -0,0 +1,107 @@
//! The digest a cluster writes ETags and chunk digests in.
//!
//! The filer decides it (`weed filer -digest`) and reports it in its
//! configuration; every writer follows it, so a cluster holds one kind of
//! digest (Go's `util.AdoptFilerDigest`). Under sha256 a digest keeps MD5's
//! 16 bytes but is SHA-256 cut to that size.
use std::fmt;
use anyhow::{Result, bail};
use md5::{Digest as _, Md5};
use seaweed_common::fips::FipsMode;
use sha2::Sha256;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ContentDigest {
#[default]
Md5,
Sha256,
}
impl ContentDigest {
/// The digest to write into `filer`, which reports `reported`: the filer's
/// own, or, from a filer that reports none, sha256 under strict mode and
/// md5 otherwise. Under strict mode a filer using md5 is refused, as the Go
/// clients refuse it under `GODEBUG=fips140=only`.
pub fn for_filer(filer: &str, reported: &str, mode: FipsMode) -> Result<Self> {
let strict = mode == FipsMode::Strict;
match reported {
"sha256" => Ok(Self::Sha256),
"md5" if strict => {
bail!("filer {filer} uses digest md5, which needs MD5; fips.mode strict refuses it")
}
"md5" => Ok(Self::Md5),
"" => {
let own = if strict { Self::Sha256 } else { Self::Md5 };
tracing::warn!(
"filer {filer} does not report its digest; writing {own} digests as this process's fips.mode implies"
);
Ok(own)
}
other => bail!("filer {filer} reports digest {other:?}; want md5 or sha256"),
}
}
/// The digest of `data`: its MD5, or its SHA-256 cut to MD5's 16 bytes.
pub fn sum(self, data: &[u8]) -> [u8; 16] {
match self {
Self::Md5 => Md5::digest(data).into(),
Self::Sha256 => {
let full = Sha256::digest(data);
let mut cut = [0u8; 16];
cut.copy_from_slice(&full[..16]);
cut
}
}
}
}
impl fmt::Display for ContentDigest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Md5 => "md5",
Self::Sha256 => "sha256",
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn follows_the_filer_and_refuses_md5_under_strict_mode() {
let pick = |reported, mode| ContentDigest::for_filer("f:18888", reported, mode);
assert_eq!(
pick("sha256", FipsMode::Off).unwrap(),
ContentDigest::Sha256
);
assert_eq!(pick("md5", FipsMode::On).unwrap(), ContentDigest::Md5);
assert_eq!(pick("", FipsMode::Off).unwrap(), ContentDigest::Md5);
assert_eq!(pick("", FipsMode::Strict).unwrap(), ContentDigest::Sha256);
assert_eq!(
pick("sha256", FipsMode::Strict).unwrap(),
ContentDigest::Sha256
);
assert!(
pick("md5", FipsMode::Strict)
.unwrap_err()
.to_string()
.contains("fips.mode strict")
);
assert!(pick("sha512", FipsMode::Off).is_err());
}
#[test]
fn sha256_digests_keep_md5s_length() {
assert_eq!(
hex::encode(ContentDigest::Md5.sum(b"bar")),
"37b51d194a7513e45b56f6524f2d51f2"
);
assert_eq!(
hex::encode(ContentDigest::Sha256.sum(b"bar")),
"fcde2b2edba56bf408601fb721fe9b5c"
);
}
}
+94 -17
View File
@@ -13,6 +13,7 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::digest::ContentDigest;
use anyhow::{Context, bail};
use base64::prelude::{BASE64_STANDARD, Engine};
use bytes::Bytes;
@@ -21,7 +22,6 @@ use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use lance::io::WrappingObjectStore;
use md5::{Digest, Md5};
use object_store::path::Path;
use object_store::{Attribute, Attributes, PutMode, UploadPart};
use object_store::{
@@ -349,13 +349,9 @@ impl Source for Filers {
data: Bytes,
) -> anyhow::Result<FileChunk> {
let name = path.rsplit('/').next().unwrap_or(path).to_string();
let digest = BASE64_STANDARD.encode(Md5::digest(&data));
let mut chunk = self
.writer
self.writer
.upload_assigned_chunk_bytes(assignment, &name, offset as i64, data)
.await?;
chunk.e_tag = digest;
Ok(chunk)
.await
}
async fn create(&self, dir: &str, entry: Entry, exclusive: bool) -> anyhow::Result<()> {
@@ -436,6 +432,9 @@ struct Shared {
chunk_size: usize,
/// Chunks are encrypted for the volume servers, as the cluster asks.
cipher: bool,
/// The digest ETags and chunk digests are written in, as the filer reports
/// it.
digest: ContentDigest,
/// The filer group, which prefixes a bucket's collection as the gateway
/// names it.
filer_group: String,
@@ -530,6 +529,11 @@ impl DirectReads {
Box::pin(async move { c.get_configuration().await })
})
.await?;
let digest = ContentDigest::for_filer(
&conn.filers.join(","),
&config.digest,
seaweed_common::fips::process_mode(),
)?;
let kek_file = filers
.lookup(KEK_PATH.0, KEK_PATH.1)
.await
@@ -546,6 +550,7 @@ impl DirectReads {
let shared = Arc::get_mut(&mut reads.shared).expect("just created");
shared.chunk_size = chunk_size;
shared.cipher = config.cipher;
shared.digest = digest;
shared.filer_group = if conn.filer_group.is_empty() {
config.filer_group.clone()
} else {
@@ -568,6 +573,7 @@ impl DirectReads {
keys,
chunk_size: DEFAULT_CHUNK_SIZE,
cipher: false,
digest: ContentDigest::default(),
filer_group: String::new(),
objects: moka::sync::Cache::builder()
.max_capacity(OBJECT_CACHE_ENTRIES)
@@ -779,8 +785,8 @@ fn bare_directory(entry: &Entry) -> bool {
/// The object's ETag as the gateway reports it: its stored S3 ETag, else the
/// remote ETag while the entry holds the remote bytes, else the entry's md5,
/// else derived from the chunks', quoted.
fn etag(entry: &Entry) -> Option<String> {
/// else derived from the chunks' in the cluster's `digest`, quoted.
fn etag(entry: &Entry, digest: ContentDigest) -> Option<String> {
let quoted = |etag: String| {
if etag.starts_with('"') {
etag
@@ -828,7 +834,7 @@ fn etag(entry: &Entry) -> Option<String> {
[] => None,
[one] => Some(quoted(hex::encode(one))),
many => {
let joined = Md5::digest(many.concat());
let joined = digest.sum(&many.concat());
Some(quoted(format!("{}-{}", hex::encode(joined), many.len())))
}
}
@@ -968,7 +974,7 @@ impl DirectStore {
.map_err(generic)?;
Ok(Arc::new(Object {
size: file_size(&entry, &chunks),
etag: etag(&entry),
etag: etag(&entry, self.reads.digest),
entry,
chunks,
decoder,
@@ -1009,7 +1015,7 @@ impl DirectStore {
)
.unwrap_or_default(),
size: entry_size(entry),
e_tag: etag(entry),
e_tag: etag(entry, self.reads.digest),
version: None,
}
}
@@ -1107,7 +1113,7 @@ impl ObjectStore for DirectStore {
};
let upload = Upload::start(self.clone(), location.clone(), &opts.attributes)?;
let data: Bytes = payload.into();
let md5 = Md5::digest(&data);
let md5 = self.reads.digest.sum(&data);
if let Err(err) = upload.put(data).await {
if let Err(discard) = upload.discard_all().await {
tracing::warn!("{location}: discarding after a failed upload: {discard:#}");
@@ -1275,9 +1281,14 @@ impl fmt::Debug for Upload {
impl Upload {
fn start(store: DirectStore, location: Path, attributes: &Attributes) -> Result<Self> {
let path = store.filer_path(&location);
let encoder = EntryEncoder::new(store.reads.keys.clone(), store.sse_s3, store.reads.cipher)
.with_context(|| format!("encoding {path}"))
.map_err(generic)?;
let encoder = EntryEncoder::new(
store.reads.keys.clone(),
store.sse_s3,
store.reads.cipher,
store.reads.digest,
)
.with_context(|| format!("encoding {path}"))
.map_err(generic)?;
let collection = match store.reads.filer_group.as_str() {
"" => String::new(),
group => format!("{group}_{}", store.bucket),
@@ -1345,6 +1356,7 @@ impl Upload {
}
};
chunk.size = size;
chunk.e_tag = encoded.e_tag;
chunk.cipher_key = encoded.cipher_key;
chunk.sse_type = encoded.sse_type;
chunk.sse_metadata = encoded.sse_metadata;
@@ -1405,7 +1417,7 @@ impl Upload {
}
let attributes = self.encoder.attributes().map_err(generic)?;
entry.extended.extend(attributes);
let e_tag = etag(&entry);
let e_tag = etag(&entry, self.store.reads.digest);
let created = self.store.reads.source.create(dir, entry, exclusive).await;
if let Err(err) = created {
// A create the filer took and never answered may still be applied,
@@ -1672,6 +1684,7 @@ impl VolumeTransport for JwtTransport {
mod tests {
use super::*;
use futures::TryStreamExt;
use md5::{Digest, Md5};
use object_store::ObjectStoreExt;
use object_store::memory::InMemory;
use std::collections::HashMap;
@@ -2667,6 +2680,64 @@ mod tests {
assert_eq!(got, Bytes::from_static(b"again"));
}
/// A store writing through `fake` into a cluster whose digest is `digest`,
/// with 4096-byte chunks.
fn writing_store_in(fake: Arc<Fake>, digest: ContentDigest) -> Arc<dyn ObjectStore> {
let mut reads = DirectReads::new(fake, "", no_keys());
{
let shared = Arc::get_mut(&mut reads.shared).unwrap();
shared.chunk_size = 4096;
shared.digest = digest;
}
reads
.encrypting(false)
.wrap("s3$vb", Arc::new(InMemory::new()))
}
/// In a sha256 cluster the entry's digest, its chunks' ETags and a
/// multipart ETag are SHA-256 cut to 16 bytes, as Go's writers write them.
#[tokio::test]
async fn writes_follow_a_sha256_digest() {
let fake = Arc::new(Fake::default());
let store = writing_store_in(fake.clone(), ContentDigest::Sha256);
let sum = |data: &[u8]| ContentDigest::Sha256.sum(data);
let body = Bytes::from(vec![9u8; 5000]);
let path = Path::from("vector/idx/_versions/1.manifest");
let result = store
.put_opts(&path, body.clone().into(), PutMode::Create.into())
.await
.unwrap();
let whole = hex::encode(sum(&body));
assert_eq!(
result.e_tag.as_deref(),
Some(format!("\"{whole}\"").as_str())
);
let entry = entry_of(&fake, "vector/idx/_versions/1.manifest");
assert_eq!(hex::encode(&entry.attributes.as_ref().unwrap().md5), whole);
let tags: Vec<String> = entry.chunks.iter().map(|c| c.e_tag.clone()).collect();
let want: Vec<String> = [&body[..4096], &body[4096..]]
.iter()
.map(|piece| BASE64_STANDARD.encode(sum(piece)))
.collect();
assert_eq!(tags, want);
let mut upload = store
.put_multipart(&Path::from("vector/idx/data/ef.lance"))
.await
.unwrap();
let parts = [vec![1u8; 3000], vec![2u8; 1000]];
for part in &parts {
upload
.put_part(Bytes::from(part.clone()).into())
.await
.unwrap();
}
let result = upload.complete().await.unwrap();
let digests: Vec<u8> = parts.iter().flat_map(|p| sum(p)).collect();
let want = format!("\"{}-2\"", hex::encode(sum(&digests)));
assert_eq!(result.e_tag.as_deref(), Some(want.as_str()));
}
/// A multipart upload's parts become chunks in order, its ETag derives
/// from them as the gateway's does, and an abort leaves no needle behind.
#[tokio::test]
@@ -2743,6 +2814,12 @@ mod tests {
let plain =
&body[chunk.offset as usize..chunk.offset as usize + chunk.size as usize];
assert_ne!(needle, plain, "cipher {cipher} sse {sse_s3}");
// The ETag digests the bytes before the volume encryption.
if !cipher {
assert_eq!(chunk.e_tag, BASE64_STANDARD.encode(Md5::digest(needle)));
} else if !sse_s3 {
assert_eq!(chunk.e_tag, BASE64_STANDARD.encode(Md5::digest(plain)));
}
assert_eq!(!chunk.cipher_key.is_empty(), cipher);
assert_eq!(chunk.sse_type == SSE_S3_TYPE, sse_s3);
}
+1
View File
@@ -13,6 +13,7 @@ pub mod admin_cluster;
pub mod catalog;
pub mod cluster;
pub mod dataset;
pub mod digest;
pub mod direct_read;
pub mod drop_guard;
pub mod grpc_tls;
+15 -1
View File
@@ -20,6 +20,8 @@ use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use sw_client::ChunkDecoder;
use crate::digest::ContentDigest;
use sw_client::filer_pb::{Entry, FileChunk};
type Aes256Ctr = ctr::Ctr128BE<aes::Aes256>;
@@ -332,6 +334,9 @@ impl ObjectKey {
/// records about them.
pub struct EncodedChunk {
pub data: Vec<u8>,
/// The chunk's ETag: the digest of its bytes before the volume encryption,
/// as Go's uploader records it under cipher.
pub e_tag: String,
pub cipher_key: Vec<u8>,
pub sse_type: i32,
pub sse_metadata: Vec<u8>,
@@ -348,6 +353,7 @@ pub struct EntryEncoder {
keys: Arc<SseS3Keys>,
object: Option<(ObjectKey, String)>,
cipher: bool,
digest: ContentDigest,
}
fn key_id() -> String {
@@ -355,7 +361,12 @@ fn key_id() -> String {
}
impl EntryEncoder {
pub fn new(keys: Arc<SseS3Keys>, sse_s3: bool, cipher: bool) -> Result<Self> {
pub fn new(
keys: Arc<SseS3Keys>,
sse_s3: bool,
cipher: bool,
digest: ContentDigest,
) -> Result<Self> {
let object = if sse_s3 {
if !keys.configured() {
bail!(
@@ -370,6 +381,7 @@ impl EntryEncoder {
keys,
object,
cipher,
digest,
})
}
@@ -390,6 +402,7 @@ impl EntryEncoder {
}
None => (0, Vec::new()),
};
let e_tag = BASE64_STANDARD.encode(self.digest.sum(&data));
let (data, cipher_key) = if self.cipher {
encrypt_chunk(&data)
} else {
@@ -397,6 +410,7 @@ impl EntryEncoder {
};
Ok(EncodedChunk {
data,
e_tag,
cipher_key,
sse_type,
sse_metadata,
@@ -11,7 +11,10 @@ name = "sw_client"
[dependencies]
anyhow.workspace = true
async-trait.workspace = true
base64 = "0.22"
bytes = "1"
# The checksum each upload carries for the volume server to check.
crc32c = "0.6"
log = "0.4"
prost.workspace = true
# System roots for volume servers behind public CAs, as Go's http client.
@@ -323,6 +323,9 @@ pub struct FilerConfig {
pub version: String,
pub cluster_id: String,
pub filer_group: String,
/// The digest the cluster writes ETags and chunk digests in, "md5" or
/// "sha256"; empty from a filer that predates the setting.
pub digest: String,
}
impl From<GetFilerConfigurationResponse> for FilerConfig {
@@ -337,6 +340,7 @@ impl From<GetFilerConfigurationResponse> for FilerConfig {
version: r.version,
cluster_id: r.cluster_id,
filer_group: r.filer_group,
digest: r.digest,
}
}
}
@@ -524,6 +524,17 @@ impl VolumeTransport for HttpTransport {
}
}
/// The header in which an upload carries the CRC32C of its bytes, which the
/// volume server checks before storing them (Go's needle.ContentCrc32cHeader).
pub const CONTENT_CRC32C_HEADER: &str = "X-Seaweed-Content-Crc32c";
/// The [`CONTENT_CRC32C_HEADER`] value for `data`: the base64 of its CRC32C,
/// big-endian, as Go's needle.ContentCrc32c writes it.
pub fn content_crc32c(data: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(crc32c::crc32c(data).to_be_bytes())
}
impl HttpTransport {
async fn upload(
&self,
@@ -539,6 +550,7 @@ impl HttpTransport {
url.push_str("?fsync=true");
}
let size = data.len() as u64;
let crc32c = content_crc32c(&data);
let part = reqwest::multipart::Part::stream_with_length(data, size)
.file_name(filename.to_string());
let form = reqwest::multipart::Form::new().part("file", part);
@@ -546,6 +558,7 @@ impl HttpTransport {
.http
.post(&url)
.timeout(self.write_timeout)
.header(CONTENT_CRC32C_HEADER, crc32c)
.multipart(form);
if !auth.is_empty() {
req = req.header(AUTHORIZATION, format!("BEARER {auth}"));
@@ -967,6 +980,68 @@ AAAA
);
}
/// Reads one HTTP request from `socket`, however TCP splits it: the head up
/// to its blank line, then as many body bytes as its Content-Length says.
/// Returns the head.
async fn read_request_head_and_body(socket: &mut tokio::net::TcpStream) -> String {
let mut request = Vec::new();
let mut buf = [0u8; 4096];
let head_end = loop {
if let Some(at) = request.windows(4).position(|w| w == b"\r\n\r\n") {
break at + 4;
}
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed inside the request head");
request.extend_from_slice(&buf[..n]);
};
let head = String::from_utf8_lossy(&request[..head_end]).to_string();
let body_len: usize = head
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse().ok())?
})
.unwrap_or(0);
while request.len() < head_end + body_len {
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed inside the request body");
request.extend_from_slice(&buf[..n]);
}
head
}
/// An upload carries the CRC32C of its bytes for the volume server to
/// check, in the form Go writes it.
#[tokio::test]
async fn upload_carries_the_crc32c_of_its_bytes() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let head = read_request_head_and_body(&mut socket).await;
socket
.write_all(
b"HTTP/1.1 201 Created\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await
.unwrap();
head.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case(CONTENT_CRC32C_HEADER)
.then(|| value.trim().to_string())
})
.unwrap_or_default()
});
HttpTransport::new()
.write(&address, "7,abc", "", "k", Bytes::from_static(b"hello"))
.await
.unwrap();
assert_eq!(server.await.unwrap(), content_crc32c(b"hello"));
assert_eq!(content_crc32c(b"hello"), "mnG7TA==");
}
/// A write that never reached the server (connection refused) is a plain
/// error, not an ambiguous commit.
#[tokio::test]
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Checks what strict FIPS mode refuses, in the Go components
# (GODEBUG=fips140=only) and the Rust volume server (WEED_FIPS_MODE=strict).
# Go's crypto/hmac refuses keys shorter than 112 bits (14 bytes) in that mode,
# so a component must refuse such a key at startup instead of failing (or
# panicking) on the first request that needs it.
#
# master, filer, volume (Go), volume (Rust): started alone with a 10-byte
# jwt.signing.key; each must exit non-zero within 20 s naming the mode.
# s3: a fips140=only cluster with valid JWT keys and an identity whose
# 8-character secret makes a SigV4 signing key under 14 bytes; a request
# signed with it must get an S3 error answer, not a dropped connection.
#
# Prints one line per component and exits non-zero if any check fails.
# WEED, WEED_VOLUME, WORK_DIR binaries and scratch dir
set -uo pipefail
WEED=${WEED:-weed}
WEED_VOLUME=${WEED_VOLUME:-weed-volume}
WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-negative-config}
export GODEBUG=fips140=only WEED_FIPS_MODE=strict
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR/short" "$WORK_DIR/valid"
printf '[jwt.signing]\nkey = "0123456789"\n' > "$WORK_DIR/short/security.toml"
printf '[jwt.signing]\nkey = "%s"\n' "$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')" \
> "$WORK_DIR/valid/security.toml"
failures=0
# expect_refusal starts a component with the short key and reports whether it
# exited non-zero within 20 s naming the mode in its log: fips140=only for Go,
# fips.mode strict for Rust.
expect_refusal() {
local name=$1; shift
local log="$WORK_DIR/$name.log"
(cd "$WORK_DIR/short" && exec "$@") > "$log" 2>&1 &
local pid=$! status=
for _ in $(seq 1 20); do
if ! kill -0 "$pid" 2>/dev/null; then wait "$pid"; status=$?; break; fi
sleep 1
done
if [ -z "$status" ]; then
kill -KILL "$pid" 2>/dev/null; wait "$pid" 2>/dev/null
echo "FAIL $name: still running after 20 s with a 10-byte jwt.signing.key"
failures=$((failures + 1))
elif [ "$status" -ne 0 ] && grep -q -E 'fips140=only|fips\.mode strict' "$log"; then
echo "ok $name: refused at startup (exit $status)"
else
echo "FAIL $name: exited $status without naming the FIPS mode; log tail:"
tail -5 "$log" | sed 's/^/ /'
failures=$((failures + 1))
fi
}
mkdir -p "$WORK_DIR/m" "$WORK_DIR/f" "$WORK_DIR/vg" "$WORK_DIR/vr"
expect_refusal master "$WEED" master -port=19333 -mdir="$WORK_DIR/m" -peers=none
expect_refusal filer "$WEED" filer -master=127.0.0.1:19333 -port=18888 -defaultStoreDir="$WORK_DIR/f"
expect_refusal volume-go "$WEED" volume -master=127.0.0.1:19333 -port=18080 -dir="$WORK_DIR/vg"
expect_refusal volume-rust "$WEED_VOLUME" --master 127.0.0.1:19333 --port 18081 --port.grpc 28081 \
--dir "$WORK_DIR/vr" --securityFile "$WORK_DIR/short/security.toml"
cat > "$WORK_DIR/valid/s3.json" <<'EOF'
{"identities":[{"name":"short","credentials":[{"accessKey":"shortsecretkey01","secretKey":"abcd1234"}],"actions":["Admin"]}]}
EOF
mkdir -p "$WORK_DIR/s"
(cd "$WORK_DIR/valid" && exec "$WEED" server -filer -s3 -ip=127.0.0.1 -dir="$WORK_DIR/s" \
-master.port=29333 -volume.port=28080 -filer.port=28888 -s3.port=28000 -master.peers=none \
-s3.config="$WORK_DIR/valid/s3.json") > "$WORK_DIR/s3.log" 2>&1 &
server_pid=$!
for _ in $(seq 1 60); do curl -s -o /dev/null http://127.0.0.1:28000/ && break; sleep 1; done
code=$(curl -s -o "$WORK_DIR/s3.body" -w '%{http_code}' --aws-sigv4 "aws:amz:us-east-1:s3" \
--user shortsecretkey01:abcd1234 http://127.0.0.1:28000/)
curl_status=$?
if [ "$curl_status" -eq 0 ] && [ "${code:0:1}" = 4 ]; then
echo "ok s3: an 8-character secret gets HTTP $code ($(grep -o '<Code>[^<]*' "$WORK_DIR/s3.body" | cut -c7-))"
else
echo "FAIL s3: an 8-character secret got curl exit $curl_status, HTTP $code (a dropped connection is a panic in the request)"
failures=$((failures + 1))
fi
kill -TERM "$server_pid" 2>/dev/null; wait "$server_pid" 2>/dev/null
exit $((failures > 0))
+4 -2
View File
@@ -4,7 +4,9 @@
# $WORK_DIR/pids, so `xargs kill < "$WORK_DIR/pids"` stops the cell.
#
# DIGEST_MODE md5 (GODEBUG=fips140=off), sha256 (fips140=on with the
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only)
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only
# and WEED_FIPS_MODE=strict, which the Rust volume server
# takes its mode from and the Go processes check)
# VOLUME_SERVER go (weed server's own volume server) or rust (weed-volume)
# WEED, WEED_VOLUME, WORK_DIR, S3_CONFIG binaries, scratch dir, identities
#
@@ -22,7 +24,7 @@ WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-digest-matrix}
case "$DIGEST_MODE" in
md5) export GODEBUG=fips140=off; digest_flag=() ;;
sha256) export GODEBUG=fips140=on; digest_flag=(-filer.digest=sha256) ;;
fips140only) export GODEBUG=fips140=only; digest_flag=() ;;
fips140only) export GODEBUG=fips140=only WEED_FIPS_MODE=strict; digest_flag=() ;;
*) echo "unknown DIGEST_MODE $DIGEST_MODE" >&2; exit 2 ;;
esac
case "$VOLUME_SERVER" in
+352
View File
@@ -0,0 +1,352 @@
package example
import (
"bytes"
"encoding/base64"
"encoding/xml"
"fmt"
"hash/crc32"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// getPart issues GetPart, which the SDK this suite pins predates, as a signed
// raw request.
func getPart(t *testing.T, cluster *TestCluster, creds *credentials.Credentials, bucket, key, uploadID string, partNumber int, header http.Header) (*http.Response, []byte) {
t.Helper()
query := url.Values{}
query.Set("part", "")
query.Set("partNumber", fmt.Sprint(partNumber))
query.Set("uploadId", uploadID)
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/%s?%s", cluster.s3Endpoint, bucket, key, query.Encode()), nil)
require.NoError(t, err)
for k, v := range header {
req.Header[k] = v
}
_, err = v4.NewSigner(creds).Sign(req, nil, "s3", testRegion, time.Now())
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
return resp, body
}
func errorCode(t *testing.T, body []byte) string {
t.Helper()
var e struct{ Code string }
require.NoError(t, xml.Unmarshal(body, &e), string(body))
return e.Code
}
func TestS3GetPart(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
cluster, err := startMiniCluster(t)
require.NoError(t, err)
defer cluster.Stop()
client := cluster.s3Client
admin := client.Config.Credentials
bucket := createTestBucket(t, cluster, "test-get-part-")
key := "media/clip.bin"
part1 := bytes.Repeat([]byte("a"), 5*1024*1024)
part1Retry := bytes.Repeat([]byte("c"), 5*1024*1024)
part2 := []byte("the last part, short")
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
require.NoError(t, err)
uploadID := aws.StringValue(created.UploadId)
upload := func(n int64, data []byte) *s3.UploadPartOutput {
out, err := client.UploadPart(&s3.UploadPartInput{
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
PartNumber: aws.Int64(n), Body: bytes.NewReader(data),
})
require.NoError(t, err)
return out
}
upload(1, part1)
retried := upload(1, part1Retry)
uploaded2 := upload(2, part2)
t.Run("open upload serves the latest attempt", func(t *testing.T) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
assert.Equal(t, "IN_PROGRESS", resp.Header.Get("x-amz-multipart-upload-status"))
assert.Equal(t, aws.StringValue(retried.ETag), resp.Header.Get("ETag"))
assert.Empty(t, resp.Header.Get("Content-Range"))
assert.True(t, bytes.Equal(part1Retry, body), "part 1 body is not the retried attempt")
})
t.Run("open upload range counts within the part", func(t *testing.T) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=4-7"}})
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
assert.Equal(t, fmt.Sprintf("bytes 4-7/%d", len(part2)), resp.Header.Get("Content-Range"))
assert.Equal(t, string(part2[4:8]), string(body))
})
t.Run("missing part", func(t *testing.T) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
assert.Equal(t, "NoSuchPart", errorCode(t, body))
})
t.Run("sse request header is rejected", func(t *testing.T) {
resp, _ := getPart(t, cluster, admin, bucket, key, uploadID, 1, http.Header{"X-Amz-Server-Side-Encryption": {"AES256"}})
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
t.Run("open part returns its checksum when asked", func(t *testing.T) {
data := []byte("checksummed part")
sum := crc32.ChecksumIEEE(data)
want := base64.StdEncoding.EncodeToString([]byte{byte(sum >> 24), byte(sum >> 16), byte(sum >> 8), byte(sum)})
_, err := client.UploadPart(&s3.UploadPartInput{
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
PartNumber: aws.Int64(5), Body: bytes.NewReader(data), ChecksumCRC32: aws.String(want),
})
require.NoError(t, err)
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 5, http.Header{"X-Amz-Checksum-Mode": {"ENABLED"}})
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
assert.Equal(t, want, resp.Header.Get("x-amz-checksum-crc32"))
})
t.Run("ListParts still answers without ?part", func(t *testing.T) {
parts, err := client.ListParts(&s3.ListPartsInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID)})
require.NoError(t, err)
require.Len(t, parts.Parts, 3)
})
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{
{PartNumber: aws.Int64(1), ETag: retried.ETag},
{PartNumber: aws.Int64(2), ETag: uploaded2.ETag},
}},
})
require.NoError(t, err)
t.Run("completed upload serves the part from the object", func(t *testing.T) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, nil)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
assert.Equal(t, aws.StringValue(uploaded2.ETag), resp.Header.Get("ETag"))
assert.Empty(t, resp.Header.Get("Content-Range"))
assert.Equal(t, string(part2), string(body))
})
t.Run("completed upload range counts within the part", func(t *testing.T) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=-4"}})
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
n := len(part2)
assert.Equal(t, fmt.Sprintf("bytes %d-%d/%d", n-4, n-1, n), resp.Header.Get("Content-Range"))
assert.Equal(t, string(part2[n-4:]), string(body))
})
t.Run("completed upload has no such part", func(t *testing.T) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
assert.Equal(t, "NoSuchPart", errorCode(t, body))
})
t.Run("completed upload in a version that is no longer latest", func(t *testing.T) {
vbucket := createTestBucket(t, cluster, "test-get-part-versioned-")
_, err := client.PutBucketVersioning(&s3.PutBucketVersioningInput{
Bucket: aws.String(vbucket), VersioningConfiguration: &s3.VersioningConfiguration{Status: aws.String("Enabled")},
})
require.NoError(t, err)
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(vbucket), Key: aws.String(key)})
require.NoError(t, err)
out, err := client.UploadPart(&s3.UploadPartInput{
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
PartNumber: aws.Int64(1), Body: bytes.NewReader(part2),
})
require.NoError(t, err)
done, err := client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: out.ETag}}},
})
require.NoError(t, err)
_, err = client.PutObject(&s3.PutObjectInput{Bucket: aws.String(vbucket), Key: aws.String(key), Body: strings.NewReader("newer")})
require.NoError(t, err)
resp, body := getPart(t, cluster, admin, vbucket, key, aws.StringValue(created.UploadId), 1, nil)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
assert.Equal(t, aws.StringValue(done.VersionId), resp.Header.Get("x-amz-version-id"))
assert.Equal(t, string(part2), string(body))
})
t.Run("completed empty part", func(t *testing.T) {
emptyKey := "media/empty-tail.bin"
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(emptyKey)})
require.NoError(t, err)
var parts []*s3.CompletedPart
for n, data := range [][]byte{part1, nil} {
out, err := client.UploadPart(&s3.UploadPartInput{
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
PartNumber: aws.Int64(int64(n + 1)), Body: bytes.NewReader(data),
})
require.NoError(t, err)
parts = append(parts, &s3.CompletedPart{PartNumber: aws.Int64(int64(n + 1)), ETag: out.ETag})
}
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{Parts: parts},
})
require.NoError(t, err)
resp, body := getPart(t, cluster, admin, bucket, emptyKey, aws.StringValue(created.UploadId), 2, nil)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
assert.Equal(t, aws.StringValue(parts[1].ETag), resp.Header.Get("ETag"))
assert.Empty(t, body)
})
t.Run("aborted upload", func(t *testing.T) {
other, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
require.NoError(t, err)
_, err = client.AbortMultipartUpload(&s3.AbortMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: other.UploadId})
require.NoError(t, err)
resp, body := getPart(t, cluster, admin, bucket, key, aws.StringValue(other.UploadId), 1, nil)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
assert.Equal(t, "NoSuchUpload", errorCode(t, body))
})
}
// TestS3GetPartIncompleteUploadGrant checks that reading a part of an open
// upload needs s3:GetIncompleteUpload on top of s3:GetObject, while a
// completed upload's part needs only the read grant.
func TestS3GetPartIncompleteUploadGrant(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
cluster, err := startMiniCluster(t)
require.NoError(t, err)
defer cluster.Stop()
client := cluster.s3Client
bucket := createTestBucket(t, cluster, "test-get-part-grant-")
openKey, doneKey := "open.bin", "done.bin"
start := func(key string) (string, *s3.UploadPartOutput) {
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
require.NoError(t, err)
part, err := client.UploadPart(&s3.UploadPartInput{
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
PartNumber: aws.Int64(1), Body: strings.NewReader("only part"),
})
require.NoError(t, err)
return aws.StringValue(created.UploadId), part
}
openID, _ := start(openKey)
doneID, donePart := start(doneKey)
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(doneKey), UploadId: aws.String(doneID),
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: donePart.ETag}}},
})
require.NoError(t, err)
sess, err := session.NewSession(client.Config.Copy())
require.NoError(t, err)
iamClient := iam.New(sess)
userName := "getpart-reader"
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
require.NoError(t, err)
key, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)})
require.NoError(t, err)
reader := credentials.NewStaticCredentials(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "")
grant := func(actions ...string) {
policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["%s"],"Resource":["arn:aws:s3:::%s/*"]}]}`, strings.Join(actions, `","`), bucket)
_, err := iamClient.PutUserPolicy(&iam.PutUserPolicyInput{UserName: aws.String(userName), PolicyName: aws.String("reader"), PolicyDocument: aws.String(policy)})
require.NoError(t, err)
}
expectStatus := func(t *testing.T, key, uploadID string, want int) {
t.Helper()
require.Eventually(t, func() bool {
resp, _ := getPart(t, cluster, reader, bucket, key, uploadID, 1, nil)
return resp.StatusCode == want
}, 10*time.Second, 200*time.Millisecond)
}
grant("s3:GetObject")
t.Run("read grant alone reads a completed part", func(t *testing.T) {
expectStatus(t, doneKey, doneID, http.StatusOK)
})
t.Run("read grant alone cannot read an open part", func(t *testing.T) {
expectStatus(t, openKey, openID, http.StatusForbidden)
})
grant("s3:GetObject", "s3:GetIncompleteUpload")
t.Run("GetIncompleteUpload opens the part", func(t *testing.T) {
expectStatus(t, openKey, openID, http.StatusOK)
})
}
// TestS3GetPartSSES3 reads SSE-S3 parts back decrypted, before and after the
// upload completes.
func TestS3GetPartSSES3(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
cluster, err := startMiniCluster(t)
require.NoError(t, err)
defer cluster.Stop()
client := cluster.s3Client
admin := client.Config.Credentials
bucket := createTestBucket(t, cluster, "test-get-part-sse-")
key := "secret.bin"
part1 := bytes.Repeat([]byte("0123456789"), 600*1024)
part2 := []byte("encrypted tail")
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(key), ServerSideEncryption: aws.String("AES256"),
})
require.NoError(t, err)
var completed []*s3.CompletedPart
for i, data := range [][]byte{part1, part2} {
out, err := client.UploadPart(&s3.UploadPartInput{
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
PartNumber: aws.Int64(int64(i + 1)), Body: bytes.NewReader(data),
})
require.NoError(t, err)
completed = append(completed, &s3.CompletedPart{PartNumber: aws.Int64(int64(i + 1)), ETag: out.ETag})
}
uploadID := aws.StringValue(created.UploadId)
check := func(t *testing.T, status string) {
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
assert.Equal(t, status, resp.Header.Get("x-amz-multipart-upload-status"))
assert.True(t, bytes.Equal(part1, body), "part 1 does not decrypt to what was uploaded")
resp, body = getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=0-8"}})
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
assert.Equal(t, fmt.Sprintf("bytes 0-8/%d", len(part2)), resp.Header.Get("Content-Range"))
assert.Equal(t, string(part2[:9]), string(body))
}
t.Run("open", func(t *testing.T) { check(t, "IN_PROGRESS") })
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{Parts: completed},
})
require.NoError(t, err)
t.Run("completed", func(t *testing.T) { check(t, "COMPLETED") })
}
@@ -79,6 +79,53 @@ func TestWriteMalformedMultipartAndMD5Mismatch(t *testing.T) {
}
}
// TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS checks that in strict FIPS
// mode (GODEBUG=fips140=only for Go, fips.mode strict for Rust), where no MD5
// may be computed, an upload whose Content-MD5 does not match its body is
// stored with the client's value instead of refused. The master and volume
// server inherit the environment set here; this test process keeps the mode it
// started with.
func TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
t.Setenv("GODEBUG", "fips140=only")
t.Setenv("WEED_FIPS_MODE", "strict")
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(97)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
url := clusterHarness.VolumeAdminURL() + "/" + framework.NewFileID(volumeID, 772101, 0x1A2B3C4D)
payload := []byte("content-md5-unchecked-body")
const wrongMD5 = "AAAAAAAAAAAAAAAAAAAAAA=="
uploadReq := newUploadRequest(t, url, payload)
uploadReq.Header.Set("Content-MD5", wrongMD5)
uploadResp := framework.DoRequest(t, client, uploadReq)
uploadBody := framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("content-md5 mismatch write under strict FIPS mode expected 201, got %d: %s", uploadResp.StatusCode, uploadBody)
}
if !strings.Contains(string(uploadBody), `"contentMd5":"`+wrongMD5+`"`) {
t.Fatalf("upload result should carry the client's Content-MD5 %s, got %s", wrongMD5, uploadBody)
}
readReq, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
t.Fatalf("create read request: %v", err)
}
readResp := framework.DoRequest(t, client, readReq)
readBody := framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK || !bytes.Equal(readBody, payload) {
t.Fatalf("read back expected 200 with the payload, got %d: %q", readResp.StatusCode, readBody)
}
}
func TestWriteReadOnlyReportsConflictAndSafeRefusal(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
+6
View File
@@ -56,6 +56,9 @@ type AdminData struct {
// VersionSummary reports whether all cluster nodes run the same binary
// version, so the dashboard can warn about partially upgraded clusters.
VersionSummary ClusterVersionSummary `json:"version_summary"`
UnderReplicatedVolumes int `json:"under_replicated_volumes"`
MisplacedVolumes int `json:"misplaced_volumes"`
}
// Object Store Users management structures
@@ -261,6 +264,9 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
Trends: s.GetDashboardTrends(),
TierStats: topology.TierStats,
VersionSummary: buildClusterVersionSummary(volumeServersData.VolumeServers, filerNodes, s3Nodes, messageBrokers),
UnderReplicatedVolumes: topology.UnderReplicatedVolumes,
MisplacedVolumes: topology.MisplacedVolumes,
}
return adminData, nil
+1
View File
@@ -251,6 +251,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo)
topology.TierStats = CollectTierStats(resp.TopologyInfo, volumeSizeLimitMb)
topology.UnderReplicatedVolumes, topology.MisplacedVolumes = countReplicaIssues(resp.TopologyInfo)
}
return nil
+50
View File
@@ -0,0 +1,50 @@
package dash
import (
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/topology/balancer"
)
// countReplicaIssues counts the volumes volume.fix.replication would repair:
// under-replicated ones, missing a copy or not spread as their placement
// asks, and misplaced ones.
func countReplicaIssues(topologyInfo *master_pb.TopologyInfo) (underReplicated, misplaced int) {
replicas := make(map[uint32][]balancer.Replica)
placements := make(map[uint32]uint32)
for _, dc := range topologyInfo.GetDataCenterInfos() {
for _, rack := range dc.RackInfos {
for _, dn := range rack.DataNodeInfos {
loc := balancer.Location{
DataCenter: dc.Id,
Rack: rack.Id,
NodeID: dn.Id,
Host: pb.NewServerAddressFromDataNode(dn).ToHost(),
}
for _, disk := range dn.DiskInfos {
for _, v := range disk.VolumeInfos {
if _, found := placements[v.Id]; !found {
placements[v.Id] = v.ReplicaPlacement
}
replicas[v.Id] = append(replicas[v.Id], balancer.Replica{Location: loc})
}
}
}
}
}
for vid, rs := range replicas {
rp, _ := super_block.NewReplicaPlacementFromByte(byte(placements[vid]))
locs := make([]balancer.Location, len(rs))
for i, r := range rs {
locs[i] = r.Location
}
switch {
case rp.GetCopyCount() > len(rs) || !balancer.SatisfyReplicaCurrentLocation(rp, locs):
underReplicated++
case balancer.IsMisplaced(rs, rp):
misplaced++
}
}
return
}
+46
View File
@@ -0,0 +1,46 @@
package dash
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
func TestCountReplicaIssues(t *testing.T) {
node := func(id string, volumes ...*master_pb.VolumeInformationMessage) *master_pb.DataNodeInfo {
return &master_pb.DataNodeInfo{
Id: id,
Address: id,
DiskInfos: map[string]*master_pb.DiskInfo{"": {VolumeInfos: volumes}},
}
}
volume := func(id uint32, placement uint32) *master_pb.VolumeInformationMessage {
return &master_pb.VolumeInformationMessage{Id: id, ReplicaPlacement: placement}
}
dc := func(id string, nodes ...*master_pb.DataNodeInfo) *master_pb.DataCenterInfo {
return &master_pb.DataCenterInfo{Id: id, RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: nodes}}}
}
// placements are stored as their decimal digits: 200, 100, 001 as 1.
topo := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{
dc("dc1",
node("10.0.0.11:8080", volume(1, 200), volume(2, 200), volume(3, 100), volume(4, 1), volume(5, 0)),
node("10.0.0.12:8080", volume(4, 1))),
dc("dc2", node("10.0.0.21:8080", volume(1, 200), volume(2, 200), volume(3, 100))),
dc("dc3", node("10.0.0.31:8080", volume(1, 200))),
}}
// volume 1 has its 3 copies; volume 2, grown degraded, misses its dc3 copy.
under, misplaced := countReplicaIssues(topo)
if under != 1 || misplaced != 0 {
t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 0", under, misplaced)
}
// volume 6 (010) has its two racks, but in two data centers.
dc1 := topo.DataCenterInfos[0].RackInfos[0].DataNodeInfos[0].DiskInfos[""]
dc2 := topo.DataCenterInfos[1].RackInfos[0].DataNodeInfos[0].DiskInfos[""]
dc1.VolumeInfos = append(dc1.VolumeInfos, volume(6, 10))
dc2.VolumeInfos = append(dc2.VolumeInfos, volume(6, 10))
under, misplaced = countReplicaIssues(topo)
if under != 1 || misplaced != 1 {
t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 1", under, misplaced)
}
}
+4
View File
@@ -29,6 +29,10 @@ type ClusterTopology struct {
// TierStats breaks volumes and EC shards down by storage tier: local
// disk types plus one entry per remote storage holding tiered volumes.
TierStats []TierStats `json:"tier_stats"`
// UnderReplicatedVolumes and MisplacedVolumes count the volumes
// volume.fix.replication would repair.
UnderReplicatedVolumes int `json:"under_replicated_volumes"`
MisplacedVolumes int `json:"misplaced_volumes"`
}
type MasterNode struct {
+3 -3
View File
@@ -78,7 +78,7 @@ func (at *ActiveTopology) GetEffectiveAvailableEcShardSlots(nodeID string, diskI
diskKey := fmt.Sprintf("%s:%d", nodeID, diskID)
disk, exists := at.disks[diskKey]
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
return 0
}
@@ -284,7 +284,7 @@ func (at *ActiveTopology) CanAccommodateTask(nodeID string, diskID uint32, taskT
// getPlanningCapacityUnsafe considers both pending and active tasks for planning
func (at *ActiveTopology) getPlanningCapacityUnsafe(disk *activeDisk) StorageSlotChange {
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
return StorageSlotChange{}
}
@@ -358,7 +358,7 @@ func (at *ActiveTopology) getEffectiveCapacityUnsafe(disk *activeDisk) StorageSl
// getEffectiveAvailableCapacityUnsafe returns detailed available capacity as StorageSlotChange
func (at *ActiveTopology) getEffectiveAvailableCapacityUnsafe(disk *activeDisk) StorageSlotChange {
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
return StorageSlotChange{}
}
+7
View File
@@ -64,6 +64,13 @@ func (at *ActiveTopology) assignTaskToDisk(task *taskState) {
}
}
// inMaintenanceUnsafe reports whether the disk's volume server is in
// maintenance mode. Such a server refuses new data, so it is a source only.
func (at *ActiveTopology) inMaintenanceUnsafe(disk *activeDisk) bool {
node := at.nodes[disk.NodeID]
return node != nil && node.nodeInfo.GetMaintenance()
}
// isDiskAvailable checks if a disk can accept new tasks. Per-volume safety is
// enforced by HasAnyTask at detection time, so cross-type tasks on the same
// disk are intentionally not considered conflicting (see #9147).
+55
View File
@@ -0,0 +1,55 @@
package topology
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
func TestMaintenanceNodeHasNoCapacity(t *testing.T) {
t.Parallel()
topo := singleDiskTopologyInfoForCapacityTest()
rack := topo.DataCenterInfos[0].RackInfos[0]
rack.DataNodeInfos = append(rack.DataNodeInfos, &master_pb.DataNodeInfo{
Id: "node-b",
Maintenance: true,
DiskInfos: map[string]*master_pb.DiskInfo{
"hdd": {DiskId: 0, Type: "hdd", MaxVolumeCount: 1000},
},
})
at := NewActiveTopology(0)
if err := at.UpdateTopology(topo); err != nil {
t.Fatalf("UpdateTopology: %v", err)
}
if got := at.GetEffectiveAvailableCapacity("node-b", 0); got != 0 {
t.Errorf("GetEffectiveAvailableCapacity(node-b) = %d, want 0", got)
}
if got := at.GetEffectiveAvailableEcShardSlots("node-b", 0, 0); got != 0 {
t.Errorf("GetEffectiveAvailableEcShardSlots(node-b) = %d, want 0", got)
}
if got := at.GetEffectiveAvailableCapacity("node-a", 0); got != 1000 {
t.Errorf("GetEffectiveAvailableCapacity(node-a) = %d, want 1000", got)
}
for _, d := range at.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 1) {
if d.NodeID == "node-b" {
t.Errorf("GetDisksWithEffectiveCapacity returned maintenance node-b")
}
}
for _, d := range at.GetAvailableDisks(TaskTypeBalance, "") {
if d.NodeID == "node-b" {
t.Errorf("GetAvailableDisks returned maintenance node-b")
}
}
sources := 0
for _, d := range at.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 0) {
if d.NodeID == "node-b" {
sources++
}
}
if sources != 1 {
t.Errorf("maintenance node-b should stay listed with zero capacity, got %d entries", sources)
}
}
+2 -2
View File
@@ -165,8 +165,8 @@ func (at *ActiveTopology) GetAvailableDisks(taskType TaskType, excludeNodeID str
var available []*DiskInfo
for _, disk := range at.disks {
if disk.NodeID == excludeNodeID {
continue // Skip excluded node
if disk.NodeID == excludeNodeID || at.inMaintenanceUnsafe(disk) {
continue
}
if at.isDiskAvailable(disk, taskType) {
+3 -1
View File
@@ -75,7 +75,9 @@ func TestClusterHealthSummary(t *testing.T) {
degraded := healthy
degraded.MasterNodes = []dash.MasterNode{{Address: "m1:9333"}}
degraded.DiskUsage = 95
want := "Needs attention: no master leader, disks 95% full. 2 volume servers and 1 filer reporting, 1 master configured."
degraded.UnderReplicatedVolumes = 3
degraded.MisplacedVolumes = 1
want := "Needs attention: no master leader, disks 95% full, 3 volumes under-replicated, 1 volume misplaced. 2 volume servers and 1 filer reporting, 1 master configured."
if got := clusterHealthSummary(degraded); got != want {
t.Errorf("degraded summary = %q, want %q", got, want)
}
+6
View File
@@ -24,6 +24,12 @@ func clusterHealthIssues(data dash.AdminData) []string {
issues = append(issues, fmt.Sprintf("disks %d%% full", p))
}
}
if data.UnderReplicatedVolumes > 0 {
issues = append(issues, countNoun(data.UnderReplicatedVolumes, "volume")+" under-replicated")
}
if data.MisplacedVolumes > 0 {
issues = append(issues, countNoun(data.MisplacedVolumes, "volume")+" misplaced")
}
if data.VersionSummary.Mixed() {
issues = append(issues, "mixed server versions")
}
@@ -56,6 +56,7 @@ func buildPolicyActionSuggestions() []string {
s3_constants.S3_ACTION_UPLOAD_PART_COPY,
s3_constants.S3_ACTION_LIST_PARTS,
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,
s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD,
s3_constants.S3_ACTION_CREATE_BUCKET,
s3_constants.S3_ACTION_DELETE_BUCKET,
s3_constants.S3_ACTION_LIST_BUCKET,
+9 -6
View File
@@ -172,7 +172,7 @@ type LiveLock struct {
isLocked int32 // 0 = unlocked, 1 = locked; use atomic operations
self string
lc *LockClient
owner string
owner atomic.Pointer[string] // read by other goroutines through LockOwner
lockTTL time.Duration
consecutiveFailures int // Track connection failures to trigger fallback
}
@@ -497,7 +497,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
lock.key, lock.hostFiler, lock.self)
previousHostFiler := lock.hostFiler
previousOwner := lock.owner
previousOwner := lock.LockOwner()
err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
// Bound each attempt: a ring member that is reachable from the masters
@@ -549,12 +549,12 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
if resp.LockOwner != "" && resp.LockOwner != previousOwner {
// Only log if the owner actually changed
glog.V(2).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
lock.owner = resp.LockOwner
lock.owner.Store(&resp.LockOwner)
} else if resp.LockOwner != "" {
lock.owner = resp.LockOwner
lock.owner.Store(&resp.LockOwner)
} else if previousOwner != "" {
glog.V(2).Infof("LOCK: Owner cleared for key=%s", lock.key)
lock.owner = ""
lock.owner.Store(nil)
}
}
return err
@@ -575,7 +575,10 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
}
func (lock *LiveLock) LockOwner() string {
return lock.owner
if owner := lock.owner.Load(); owner != nil {
return *owner
}
return ""
}
// Generation returns the fencing token for this lock.
+27 -1
View File
@@ -327,7 +327,7 @@ type grantingLockFiler struct {
}
func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
return &filer_pb.LockResponse{RenewToken: "tok", LockOwner: req.Owner}, nil
}
type rotatingAuthLockFiler struct {
@@ -819,3 +819,29 @@ func TestLiveLockIsLockedOnlyWithinLease(t *testing.T) {
t.Fatal("a lock whose lease ran out must not read as locked")
}
}
// Other goroutines read the owner while renewals rewrite it.
func TestLiveLockOwnerReadDuringRenewal(t *testing.T) {
lock := newGrantingLockClient(t).NewShortLivedLock("test-key", "test-owner")
if lock == nil {
t.Fatal("lock not granted")
}
done := make(chan struct{})
go func() {
defer close(done)
for i := 0; i < 20; i++ {
lock.AttemptToLock(5 * time.Second)
}
}()
for {
select {
case <-done:
if got := lock.LockOwner(); got != "test-owner" {
t.Fatalf("owner = %q, want test-owner", got)
}
return
default:
_ = lock.LockOwner()
}
}
}
+58 -9
View File
@@ -36,17 +36,47 @@ import (
)
var (
f FilerOptions
filerStartS3 *bool
filerS3Options S3Options
filerStartWebDav *bool
filerWebDavOptions WebDavOption
filerStartIam *bool
filerIamOptions IamOptions
filerStartSftp *bool
filerSftpOptions SftpOptions
f FilerOptions
filerStartS3 *bool
filerS3Options S3Options
filerStartS3MqBroker *bool
filerS3MqBrokerOptions MessageQueueBrokerOptions
filerStartWebDav *bool
filerWebDavOptions WebDavOption
filerStartIam *bool
filerIamOptions IamOptions
filerStartSftp *bool
filerSftpOptions SftpOptions
)
// filerRunsMqBrokerBesideS3 reports whether weed filer starts a broker with
// its S3 gateway; the filer has no other broker to collide with.
func filerRunsMqBrokerBesideS3(brokerFlagPassed bool) bool {
return *filerStartS3 && wantsMqBrokerBesideS3("s3.mq.broker", *filerStartS3MqBroker, brokerFlagPassed)
}
// filerPortsBesideS3 lists the ports of the filer and the other servers weed
// filer starts with its gateway, derived gRPC ports included.
func filerPortsBesideS3() []int {
ports := append([]int{*f.metricsHttpPort}, withGrpc(f.port, f.portGrpc)...)
if *f.debug {
ports = append(ports, *f.debugPort)
}
if *f.publicPort != 0 {
ports = append(ports, *f.publicPort)
}
if *filerStartWebDav {
ports = append(ports, *filerWebDavOptions.port)
}
if *filerStartIam {
ports = append(ports, *filerIamOptions.port)
}
if *filerStartSftp {
ports = append(ports, *filerSftpOptions.port)
}
return ports
}
// allowUntrustedRemoteEndpointsUsage documents the flag shared by the filer and
// S3 gateway, whose remote-mount read paths dial the mounted endpoint directly.
const allowUntrustedRemoteEndpointsUsage = "if true, a read of a remote-only entry accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints."
@@ -225,6 +255,8 @@ func init() {
filerS3Options.unreachableOwnerTTL = cmdFiler.Flag.Duration("s3.unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage)
filerS3Options.volumeLookupTimeout = cmdFiler.Flag.Duration("s3.volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage)
filerS3Options.preStopSeconds = cmdFiler.Flag.Int("s3.preStopSeconds", 0, s3PreStopSecondsUsage)
filerStartS3MqBroker = cmdFiler.Flag.Bool("s3.mq.broker", false, mqBrokerBesideS3Usage)
filerS3MqBrokerOptions.port = cmdFiler.Flag.Int("s3.mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
// start webdav on filer
filerStartWebDav = cmdFiler.Flag.Bool("webdav", false, "whether to start webdav gateway")
@@ -282,6 +314,10 @@ func filerLongDesc() string {
The example filer.toml configuration file can be generated by "weed scaffold -config=filer"
With -s3, and grpc.msg_broker cert and key in security.toml, a message queue broker
runs beside the S3 gateway on -s3.mq.broker.port; use -s3.mq.broker=false to leave it
out, or -s3.mq.broker=true to run it without TLS.
Supported Filer Stores:
`
@@ -346,8 +382,21 @@ func runFiler(cmd *Command, args []string) bool {
if *filerS3Options.metricsHttpIp == "" {
*filerS3Options.metricsHttpIp = *filerS3Options.bindIp
}
filerS3Options.mqBroker = nil
if filerRunsMqBrokerBesideS3(isFlagExplicitlySet(cmdFiler, "s3.mq.broker")) {
filerS3Options.mqBroker = &filerS3MqBrokerOptions
if err := filerS3Options.checkMqBrokerPort("s3.mq.broker.port", isFlagExplicitlySet(cmdFiler, "s3.mq.broker.port"), filerPortsBesideS3()...); err != nil {
glog.Fatalf("%v", err)
}
}
go func(delay time.Duration) {
time.Sleep(delay * time.Second)
// By now startFiler has filled an empty -ip.bind, which the gateway
// and its broker both bind.
if b := filerS3Options.mqBroker; b != nil {
filerS3Options.brokerBeside(b)
b.dataCenter, b.rack = f.dataCenter, f.rack
}
filerS3Options.startS3Server()
}(startDelay)
startDelay++
+74
View File
@@ -0,0 +1,74 @@
package command
import "testing"
func TestFilerS3MqBrokerFlagDefaults(t *testing.T) {
for name, want := range map[string]string{
"s3": "false",
"s3.mq.broker": "false",
"s3.mq.broker.port": "17777",
} {
flag := cmdFiler.Flag.Lookup(name)
if flag == nil {
t.Fatalf("weed filer does not expose -%s", name)
}
if flag.DefValue != want {
t.Errorf("-%s default = %q, want %q", name, flag.DefValue, want)
}
}
}
func TestFilerRunsMqBrokerOnlyBesideS3(t *testing.T) {
oldS3, oldBroker := *filerStartS3, *filerStartS3MqBroker
defer func() { *filerStartS3, *filerStartS3MqBroker = oldS3, oldBroker }()
for _, tc := range mqBrokerDefaultCases {
t.Run("-s3 "+tc.name, func(t *testing.T) {
withMqBrokerTLS(t, tc.tls)
*filerStartS3, *filerStartS3MqBroker = true, tc.value
if got := filerRunsMqBrokerBesideS3(tc.passed); got != tc.want {
t.Errorf("runs broker %v, want %v", got, tc.want)
}
})
}
t.Run("no -s3", func(t *testing.T) {
withMqBrokerTLS(t, true)
*filerStartS3, *filerStartS3MqBroker = false, true
if filerRunsMqBrokerBesideS3(true) {
t.Error("broker started without the S3 gateway")
}
})
}
// weed filer -s3 -webdav -webdav.port=17777, weed filer -port=7777 -s3
// whose filer gRPC port is 17777, and weed filer -s3 -debug -debug.port=17777.
func TestFilerDefaultBrokerYieldsToFilerProcessPorts(t *testing.T) {
port, portGrpc, webdav, webdavPort := *f.port, *f.portGrpc, *filerStartWebDav, *filerWebDavOptions.port
debug, debugPort := *f.debug, *f.debugPort
t.Cleanup(func() {
*f.port, *f.portGrpc, *filerStartWebDav, *filerWebDavOptions.port = port, portGrpc, webdav, webdavPort
*f.debug, *f.debugPort = debug, debugPort
})
for _, tc := range []struct {
name string
filerPort, webdavPort int
webdav bool
debugPort int
}{
{"-webdav.port on the broker port", 8888, 17777, true, 0},
{"-port whose derived gRPC port is the broker's", 7777, 7333, false, 0},
{"-debug.port on the broker port", 8888, 7333, false, 17777},
} {
t.Run(tc.name, func(t *testing.T) {
*f.port, *f.portGrpc, *filerStartWebDav, *filerWebDavOptions.port = tc.filerPort, 0, tc.webdav, tc.webdavPort
*f.debug, *f.debugPort = tc.debugPort != 0, tc.debugPort
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("s3.mq.broker.port", false, filerPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on a filer process port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("s3.mq.broker.port", true, filerPortsBesideS3()...); err == nil {
t.Fatal("explicit -s3.mq.broker.port on a filer process port was accepted")
}
})
}
}
+67 -5
View File
@@ -300,6 +300,10 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -437,6 +441,10 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -474,6 +482,11 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
return nil
}
}
// deleteOldFile removes the renamed-from object. When the entry
// is written to a new key too, that runs first: the old key can
// hold the only remote copy, and a rename whose local data turns
// out to be gone (errSourceGone) leaves it where it is.
var deleteOldFile func() error
if oldOk {
client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
if err != nil {
@@ -486,9 +499,15 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
glog.V(0).Infof("keep %s: the renamed entry's only content", remote_storage.FormatLocation(oldDest))
return nil
}
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
if err := deleteRemoteFileIfUnchanged(client, oldDest, message.OldEntry.GetRemoteEntry()); err != nil {
return err
deleteOldFile = func() error {
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
return deleteRemoteFileIfUnchanged(client, oldDest, message.OldEntry.GetRemoteEntry())
}
if !newOk || message.NewEntry.IsDirectory {
if err := deleteOldFile(); err != nil {
return err
}
deleteOldFile = nil
}
}
if newOk {
@@ -501,12 +520,30 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
return client.WriteDirectory(newDest, message.NewEntry)
}
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, newDest)
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can
// upload it, and the old object stays
if deleteOldFile != nil {
glog.Errorf("source data gone: keeping %s (renamed to %s)", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(newDest))
}
return nil
}
if writeErr != nil && !errors.Is(writeErr, errSuperseded) {
return writeErr
}
if errors.Is(writeErr, errSuperseded) {
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
if deleteOldFile != nil {
if err := gatewaySupersededRename(filerSource, option, option, resp, deleteOldFile); err != nil {
return err
}
}
return releaseGatewayRenamedSource(filerSource, option, message)
}
if writeErr != nil {
return writeErr
if deleteOldFile != nil {
if err := deleteOldFile(); err != nil {
return err
}
}
if err := updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry); err != nil {
return err
@@ -520,6 +557,31 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
return eachEntryFunc, nil
}
// gatewaySupersededRename settles the renamed-from object of a rename the
// filer has moved past, as uploadCurrentEntry does for filer.remote.sync: a
// remote-only entry is copied from it; otherwise it no longer holds the
// entry's content (the entry is gone, the superseding event writes its new
// content to the new key, or a later rename's source holds it), so it goes.
func gatewaySupersededRename(filerSource, filerClient filer_pb.FilerClient, option *RemoteGatewayOptions, resp *filer_pb.SubscribeMetadataResponse, deleteOldFile func() error) error {
message := resp.EventNotification
current, err := currentEntry(filerSource, message.NewParentPath, message.NewEntry.Name)
if err != nil {
return err
}
if isRemoteOnly(current) {
if err := gatewayRemoteOnlyRename(filerClient, option, resp, current); err != nil {
return err
}
src := util.FullPath(current.Extended[filer.ExtRemoteRenameSourceKey])
if src == "" || src == util.NewFullPath(resp.Directory, message.OldEntry.Name) {
return nil
}
// copied from an earlier rename's source: the entry no longer reads
// the old object
}
return deleteOldFile()
}
// gatewayRemoteOnlyRename completes a rename whose content exists only as
// the object the renamed-from path maps to: the chunkless entry has nothing
// to upload. When the destination already holds what the entry's stamp
@@ -575,3 +575,66 @@ func TestGatewayLockReleaseLooksUpTheKeptMarker(t *testing.T) {
})
}
}
// TestGatewaySupersededRenameSettlesTheOldObject: a rename the filer has moved
// past removes the renamed-from object once it no longer holds the entry's
// content (the entry was deleted or rewritten since), so a rename followed by
// a delete or rewrite leaves nothing behind; an entry that has become
// remote-only is copied from it instead.
func TestGatewaySupersededRenameSettlesTheOldObject(t *testing.T) {
option, remote := gatewayTestOption("gatewaytest-superseded")
t.Cleanup(func() {
delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-superseded")
remote_storage.ResetRemoteStorageClients()
})
const newPath = "/buckets/gold/dir/new.txt"
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-superseded", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/gold/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: &filer_pb.Entry{Name: "old.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5}, RemoteEntry: stamp},
NewParentPath: "/buckets/gold/dir",
NewEntry: entryWith("new.txt", stamp, chunk("3,01", "e1")),
},
}
remoteOnly := &filer_pb.Entry{Name: "new.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5}, RemoteEntry: stamp}
fromLaterRename := &filer_pb.Entry{
Name: "new.txt",
Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5},
RemoteEntry: stamp,
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/buckets/gold/dir/other.txt")},
}
for _, tc := range []struct {
name string
current *filer_pb.Entry
wantDelete bool
}{
{"deleted since", nil, true},
{"rewritten since", entryWith("new.txt", nil, chunk("4,02", "e2")), true},
{"remote-only since", remoteOnly, false},
// renamed over by another remote-only entry: copied from that one's
// source, and the old object is no longer read
{"remote-only from a later rename", fromLaterRename, true},
} {
t.Run(tc.name, func(t *testing.T) {
*remote = recordingRemote{objects: map[string][]byte{"/dir/old.txt": []byte("hello"), "/dir/other.txt": []byte("hello")}, statETag: `"abc"`, statMtime: 100}
entries := map[string]*filer_pb.Entry{}
if tc.current != nil {
entries[newPath] = tc.current
}
filerClient := &stubFilerClient{entries: entries}
deleted := 0
if err := gatewaySupersededRename(filerClient, filerClient, option, resp, func() error { deleted++; return nil }); err != nil {
t.Fatal(err)
}
if got := deleted == 1; got != tc.wantDelete {
t.Errorf("deleted the old object %d times, want delete=%v", deleted, tc.wantDelete)
}
if isRemoteOnly(tc.current) && (len(remote.writes) != 1 || remote.writes[0].Path != "/dir/new.txt") {
t.Errorf("writes = %+v, want the source object copied to /dir/new.txt", remote.writes)
}
})
}
}
+139 -32
View File
@@ -711,6 +711,10 @@ func processCreateEvent(
}
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -935,7 +939,32 @@ func processUpdateEvent(
return nil
}
glog.V(2).Infof("update: %s/%s ts_ns=%d", filer_pb.MetadataEventTargetDirectory(resp), message.GetNewEntry().GetName(), resp.TsNs)
if !proto.Equal(oldDest, dest) {
// deleteOld removes the renamed-from key, once the new key holds the
// content. A multipart part or a system path whose old key cannot be
// deleted is left behind, as it always was; the new key is written, so
// the event still goes on to stamp the entry.
deleteOld := func() error {
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
if err := client.DeleteFile(oldDest); err != nil {
if isMultipartUploadFile(resp.Directory, message.OldEntry.Name) || isSystemPath(resp.Directory, message.OldEntry.Name) {
glog.V(0).Infof("leaving %s: %v", remote_storage.FormatLocation(oldDest), err)
return nil
}
if !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
return err
}
}
return nil
}
// The old key can hold the entry's only remote copy, whether or not the
// event's old entry carries a stamp (an upload whose stamp was refused by
// a rename in between leaves an unstamped copy there). So it is deleted
// only once the new key holds the content: a rename whose local data turns
// out to be gone (errSourceGone) leaves it where it is, and a remote-only
// entry can still be copied from it. Deleting a key that was never written
// is harmless (ErrRemoteObjectNotFound).
renamed := !proto.Equal(oldDest, dest)
if renamed {
// A renamed entry that holds no local data now (the snapshot was
// remote-only, or remote.uncache ran since) has its content only as a
// remote object. Remote-only reads resolve by the entry's own path, so
@@ -966,34 +995,51 @@ func processUpdateEvent(
glog.V(0).Infof("keep %s: the pending rename moved on", remote_storage.FormatLocation(oldDest))
return nil
}
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
if err := client.DeleteFile(oldDest); err != nil {
if isMultipartUploadFile(resp.Directory, message.OldEntry.Name) || isSystemPath(resp.Directory, message.OldEntry.Name) {
return nil
}
if !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
return err
}
}
}
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
if errors.Is(writeErr, errSuperseded) {
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
if !proto.Equal(oldDest, dest) {
if err := uploadCurrentEntry(filerClient, filerSource, client, message.NewParentPath, message.NewEntry.Name, eventSource, dest, storageClass, sourceOf); err != nil {
if renamed {
// what the filer holds now goes up first: when it has become
// remote-only, the old key is what it is copied from
old, err := uploadCurrentEntry(filerClient, filerSource, client, message.NewParentPath, message.NewEntry.Name, eventSource, dest, storageClass, sourceOf)
if err != nil {
return err
}
switch old {
case oldKeyKeep:
glog.Errorf("source data gone: keeping %s (renamed to %s)", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(dest))
return nil
case oldKeyDelete:
if err := deleteOld(); err != nil {
return err
}
}
// oldKeyHandled: the remote-only copy cleaned up its own source,
// only while it was still the object the stamp describes
return releaseRenamedSource(filerSource, client, mountedDir, remoteStorageMountLocation, message)
}
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
if renamed {
glog.Errorf("source data gone: keeping %s (renamed to %s)", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(dest))
}
return nil
}
if writeErr != nil {
return writeErr
}
if renamed {
if err := deleteOld(); err != nil {
return err
}
}
if err := updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, remoteEntry); err != nil {
return err
}
if !proto.Equal(oldDest, dest) {
if renamed {
return releaseRenamedSource(filerSource, client, mountedDir, remoteStorageMountLocation, message)
}
return nil
@@ -1160,38 +1206,67 @@ func openRemoteObject(client remote_storage.RemoteStorageClient, loc *remote_pb.
// up once. A remote-only entry is finished the way completeRemoteOnlyRename
// finishes a rename: its stamp can already describe the destination (a sync
// plus remote.uncache in the meantime), and only then is it complete.
func uploadCurrentEntry(filerClient filer_pb.FilerClient, filerSource filer_pb.FilerClient, client remote_storage.RemoteStorageClient, dir, name string, oldSource renameSource, dest *remote_pb.RemoteStorageLocation, storageClass string, sourceOf func(*filer_pb.Entry, renameSource) renameSource) error {
//
// The result says what the caller does with the old key once this returns
// without an error: oldKeyKeep when the current entry's data is gone
// (errSourceGone) and the old key may hold the only copy; oldKeyHandled when
// the remote-only copy came from the old key and already removed it, and only
// if it was still the object its stamp describes; oldKeyDelete otherwise.
func uploadCurrentEntry(filerClient filer_pb.FilerClient, filerSource filer_pb.FilerClient, client remote_storage.RemoteStorageClient, dir, name string, oldSource renameSource, dest *remote_pb.RemoteStorageLocation, storageClass string, sourceOf func(*filer_pb.Entry, renameSource) renameSource) (oldKey, error) {
ctx, cancel := lookupContext()
defer cancel()
current, _, _, err := filer_pb.GetEntry(ctx, filerSource, util.NewFullPath(dir, name))
if errors.Is(err, filer_pb.ErrNotFound) {
return nil
return oldKeyDelete, nil
}
if err != nil {
return err
return oldKeyDelete, err
}
if current.IsDirectory {
return nil
return oldKeyDelete, nil
}
if isRemoteOnly(current) {
return completeRemoteOnlyRename(filerClient, client, dir, current, sourceOf(current, oldSource), dest, storageClass)
source := sourceOf(current, oldSource)
if err := completeRemoteOnlyRename(filerClient, client, dir, current, source, dest, storageClass); err != nil {
return oldKeyHandled, err
}
if !proto.Equal(source.loc, oldSource.loc) {
// copied from an earlier rename's source: the entry no longer
// reads the old key
return oldKeyDelete, nil
}
return oldKeyHandled, nil
}
if shouldSendToRemote(current) {
glog.V(0).Infof("leaving %s to the rewrite that superseded the rename", remote_storage.FormatLocation(dest))
return nil
return oldKeyDelete, nil
}
glog.V(0).Infof("uploading the current %s in place of the superseded rename", remote_storage.FormatLocation(dest))
remoteEntry, writeErr := retriedWriteFile(client, filerSource, dir, remoteWriteEntry(current, storageClass), dest)
if errors.Is(writeErr, errSuperseded) {
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
return nil
return oldKeyDelete, nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return oldKeyKeep, nil
}
if writeErr != nil {
return writeErr
return oldKeyDelete, writeErr
}
return updateLocalEntry(filerClient, dir, current, remoteEntry)
return oldKeyDelete, updateLocalEntry(filerClient, dir, current, remoteEntry)
}
// oldKey is what a superseded rename does with its renamed-from key
// (uploadCurrentEntry).
type oldKey int
const (
oldKeyDelete oldKey = iota
oldKeyKeep
oldKeyHandled
)
// recoverSupersededCreate finishes a create reshaped from a rename into the
// mount when the filer has moved past the entry the event described. A plain
// superseded create skips because the superseding event follows in the log; a
@@ -1233,6 +1308,10 @@ func recoverSupersededCreate(
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -1449,43 +1528,71 @@ var errLookupUnanswered = errors.New("supersession lookup unanswered")
// trip the remote's per-object mutation rate limit; only the version the filer
// still holds is worth sending. After: a dead chunk reads as a transient
// "RequestError" from the SDK, and waiting out the backoff on it buys nothing.
// An entry the filer still holds whose chunk the volume servers answer 404 for
// ends in errSourceGone once that has held for sourceGoneGrace: the caller
// treats the event as handled, and the path is logged with the chunk's fid.
func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource filer_pb.FilerClient, dir string, newEntry *filer_pb.Entry, dest *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
path := string(util.NewFullPath(dir, newEntry.Name))
if superseded, lookupErr := isSuperseded(filerSource, dir, newEntry); lookupErr != nil {
return nil, fmt.Errorf("%s: supersession lookup: %w", util.NewFullPath(dir, newEntry.Name), lookupErr)
sourceGone.forget(path)
return nil, fmt.Errorf("%s: supersession lookup: %w", path, lookupErr)
} else if superseded {
return nil, fmt.Errorf("%s %w", util.NewFullPath(dir, newEntry.Name), errSuperseded)
sourceGone.forget(path)
return nil, fmt.Errorf("%s %w", path, errSuperseded)
}
// A failed attempt is retried only once the filer has answered that the
// entry is still the one the event described; an unanswered lookup
// ends the loop so no further attempt uploads an unverified snapshot.
afterFailure := func(attemptErr error) error {
// sourceErr is what the entry's own chunks answered, never the remote.
afterFailure := func(attemptErr, sourceErr error) error {
superseded, lookupErr := isSuperseded(filerSource, dir, newEntry)
if lookupErr != nil {
return fmt.Errorf("%s %w: %w (after: %v)", util.NewFullPath(dir, newEntry.Name), errLookupUnanswered, lookupErr, attemptErr)
sourceGone.forget(path)
return fmt.Errorf("%s %w: %w (after: %v)", path, errLookupUnanswered, lookupErr, attemptErr)
}
if superseded {
return fmt.Errorf("%s %w: %w", util.NewFullPath(dir, newEntry.Name), errSuperseded, attemptErr)
return fmt.Errorf("%s %w: %w", path, errSuperseded, attemptErr)
}
return attemptErr
if !isSourceGone(sourceErr) {
sourceGone.forget(path)
return attemptErr
}
fid := goneFid(sourceErr, newEntry)
gone, isNew := sourceGone.observe(path, chunkSetKey(newEntry), time.Now())
if !gone {
return attemptErr
}
if isNew {
n := sourceGoneCount.Add(1)
glog.Errorf("source data gone: %s (fid %s): not written back to %s (%d in this process; %v)", path, fid, remote_storage.FormatLocation(dest), n, sourceErr)
}
return fmt.Errorf("%s (fid %s): %w", path, fid, errSourceGone)
}
err = util.RetryOnError("writeFile", func(err error) bool {
return !errors.Is(err, errSuperseded) && !errors.Is(err, errLookupUnanswered) && util.IsTransientError(err)
return !errors.Is(err, errSuperseded) && !errors.Is(err, errLookupUnanswered) && !errors.Is(err, errSourceGone) && util.IsTransientError(err)
}, func() error {
reader, closeFn, readerErr := remoteUploadReader(filerSource, newEntry)
if readerErr != nil {
return afterFailure(readerErr)
return afterFailure(readerErr, readerErr)
}
if closeFn != nil {
defer closeFn()
}
body, recorder := newSourceReadRecorder(reader)
glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
var writeErr error
remoteEntry, writeErr = client.WriteFile(dest, newEntry, reader)
remoteEntry, writeErr = client.WriteFile(dest, newEntry, body)
if writeErr != nil {
return afterFailure(writeErr)
return afterFailure(writeErr, recorder.readErr())
}
return nil
})
if errors.Is(err, errSourceGone) {
return nil, err
}
if err == nil || errors.Is(err, errSuperseded) {
sourceGone.forget(path)
}
if err != nil && !errors.Is(err, errSuperseded) {
glog.Errorf("write to %s: %v", dest, err)
}
+134 -2
View File
@@ -550,6 +550,39 @@ func entryWith(name string, remote *filer_pb.RemoteEntry, chunks ...*filer_pb.Fi
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: remote, Chunks: chunks}
}
// changingFilerClient answers its i-th lookup with seq[i], and the last one
// after that: the filer's entry changing while an event is processed.
type changingFilerClient struct {
stubFilerClient
seq []*filer_pb.Entry
}
func (c *changingFilerClient) LookupDirectoryEntry(_ context.Context, _ *filer_pb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
i := min(c.lookups, len(c.seq)-1)
c.lookups++
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.seq[i]}, nil
}
func (c *changingFilerClient) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return fn(c)
}
// replacingRemote puts another object at path once a write completes: a
// replacement landing on a key while something else is being copied.
type replacingRemote struct {
*recordingRemote
path string
with []byte
}
func (r replacingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
e, err := r.recordingRemote.WriteFile(loc, entry, reader)
if err == nil {
r.objects[r.path] = r.with
}
return e, err
}
// blockingFilerClient answers a lookup only when its context ends.
type blockingFilerClient struct {
stubFilerClient
@@ -1183,6 +1216,10 @@ func (r *recordingRemote) ReadFile(loc *remote_pb.RemoteStorageLocation, offset
func (r *recordingRemote) DeleteFile(loc *remote_pb.RemoteStorageLocation) error {
r.deletes = append(r.deletes, loc)
if r.deleteErr == nil && r.objects != nil {
// the object is gone for a later copy or read, as on a real remote
delete(r.objects, loc.Path)
}
return r.deleteErr
}
@@ -1840,6 +1877,84 @@ func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
}
})
t.Run("uncached between the check and the upload: copied from the old key before it goes", func(t *testing.T) {
// remote.uncache drops the written-back entry's chunks after the
// remote-only check and before the upload's supersession lookup: the
// old key is where the content is copied from, so it must still be
// there when uploadCurrentEntry runs.
stamp := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
synced := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/b/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: entryWith("a.txt", stamp, chunk("3,01", "e1")),
NewParentPath: "/buckets/b/dir",
NewEntry: entryWith("b.txt", stamp, chunk("3,01", "e1")),
},
}
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
filerClient := &changingFilerClient{seq: []*filer_pb.Entry{
entryWith("b.txt", stamp, chunk("3,01", "e1")), // the remote-only check
entryWith("b.txt", stamp), // uncached since
}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, synced); err != nil {
t.Fatalf("err = %v, want nil: the content is copied from the old key", err)
}
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) || string(remote.written[0]) != "payload" {
t.Fatalf("writes = %+v (%q), want the old object's bytes at the new key", remote.writes, remote.written)
}
if _, ok := remote.objects["/b/dir/a.txt"]; ok {
t.Errorf("the old key is still there after the rename completed")
}
})
t.Run("uncached, and the old key replaced during the copy: the replacement stays", func(t *testing.T) {
// the copy cleans up its source only while it is the object the
// stamp describes; nothing after it may delete the old key blindly
stamp := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
synced := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/b/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: entryWith("a.txt", stamp, chunk("3,01", "e1")),
NewParentPath: "/buckets/b/dir",
NewEntry: entryWith("b.txt", stamp, chunk("3,01", "e1")),
},
}
inner := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
remote := replacingRemote{recordingRemote: inner, path: "/b/dir/a.txt", with: []byte("a newer object")}
filerClient := &changingFilerClient{seq: []*filer_pb.Entry{
entryWith("b.txt", stamp, chunk("3,01", "e1")),
entryWith("b.txt", stamp),
}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, synced); err != nil {
t.Fatalf("err = %v", err)
}
if len(inner.writes) != 1 || string(inner.written[0]) != "payload" {
t.Fatalf("writes = %+v (%q), want the old object copied", inner.writes, inner.written)
}
if got := string(inner.objects["/b/dir/a.txt"]); got != "a newer object" {
t.Errorf("old key holds %q, want the replacement kept", got)
}
})
t.Run("current entry's chunks gone: the old key stays", func(t *testing.T) {
// the old entry carries no stamp (its upload's stamp was refused by
// a rename in between), yet the old key holds the only copy
withSourceGone(t, 0, 1)
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 1024, LastLocalSyncTsNs: 1786096669*1e9 + 1}, chunk("3,02", "e2"))
filerClient, done := servingFilerClient(current, map[string][]byte{})
defer done()
remote := bodyReadingRemote{&recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err)
}
if len(remote.deletes) != 0 {
t.Errorf("deletes = %+v, want none: the old key holds the only copy", remote.deletes)
}
if got := sourceGoneCount.Load(); got != 1 {
t.Errorf("counted %d gone entries, want 1", got)
}
})
t.Run("snapshot already remote-only: completed the same way", func(t *testing.T) {
remoteOnly := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
snapshot := &filer_pb.SubscribeMetadataResponse{
@@ -1867,7 +1982,7 @@ func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 1024})
remote := &recordingRemote{}
filerClient := &stubFilerClient{entry: current}
err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource)
_, err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource)
if err == nil || !strings.Contains(err.Error(), "neither") {
t.Errorf("err = %v, want the lost-content failure", err)
}
@@ -1876,11 +1991,28 @@ func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
}
})
t.Run("uncached with a later rename's source: copied from it, the old key deleted", func(t *testing.T) {
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/c.txt": []byte("payload")}}
filerClient := &stubFilerClient{entry: current}
laterSource := renameSource{loc: &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/dir/c.txt"}}
old, err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", func(*filer_pb.Entry, renameSource) renameSource { return laterSource })
if err != nil {
t.Fatalf("err = %v", err)
}
if len(remote.writes) != 1 || string(remote.written[0]) != "payload" {
t.Errorf("writes = %+v (%q), want the later source copied to the destination", remote.writes, remote.written)
}
if old != oldKeyDelete {
t.Errorf("old key = %v, want oldKeyDelete: the entry no longer reads it", old)
}
})
t.Run("uncached with the destination already synced: complete without a write", func(t *testing.T) {
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload"), "/b/dir/b.txt": []byte("payload")}}
filerClient := &stubFilerClient{entry: current}
if err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource); err != nil {
if _, err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource); err != nil {
t.Fatalf("err = %v, want nil: the destination object matches the entry's stamp", err)
}
if len(remote.writes) != 0 {
+238
View File
@@ -0,0 +1,238 @@
package command
import (
"errors"
"fmt"
"hash/fnv"
"io"
"regexp"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// errSourceGone marks an upload whose source data no longer exists in this
// cluster: a volume server answered 404 for one of the entry's chunks (read
// with readDeleted=true, so not even a deleted needle is left), the filer
// still holds the entry as the event described it, and that held for
// sourceGoneGrace over sourceGoneMinAnswers attempts in a row. Retrying
// cannot produce the bytes: the write-back reports the path once and moves
// past the event instead of holding the directory's offset on it forever.
// A volume lost with its disk (a server restored from a metadata-only
// backup) leaves entries like this behind.
var errSourceGone = errors.New("source data gone")
// A 404 can also come from a volume server that has not loaded the volume
// yet, or from a stale location right after a move; neither lasts. Only a
// 404 that persists this long, over this many attempts with nothing else in
// between, counts as gone. A volume the master cannot locate at all is also
// what a volume server that is down looks like, so it never counts.
var (
sourceGoneGrace = 5 * time.Minute
sourceGoneMinAnswers = 3
)
// sourceGoneRemembered bounds how many paths a process keeps, both those with
// sightings in a row and those found gone.
const sourceGoneRemembered = 10000
// sourceGoneCount is how many entries this process left unwritten because
// their source data was gone.
var sourceGoneCount atomic.Int64
// sourceReadRecorder keeps the first error the upload body's reader returned.
// Remote clients wrap a body read failure in their own errors (the AWS SDK's
// RequestError has no Unwrap), so the write error cannot say whether the
// source or the remote failed; the recorder can, and a 404 from the remote
// itself never reaches it.
type sourceReadRecorder struct {
r io.Reader
mu sync.Mutex
err error
}
func (s *sourceReadRecorder) Read(p []byte) (int, error) {
n, err := s.r.Read(p)
s.record(err)
return n, err
}
// sourceReadAtRecorder keeps an io.ReaderAt + io.Seeker body one: an S3
// uploader reads the parts of such a body in place and in parallel, where a
// plain io.Reader is copied into a buffer per part.
type sourceReadAtRecorder struct {
*sourceReadRecorder
ra io.ReaderAt
sk io.Seeker
}
func (s *sourceReadAtRecorder) ReadAt(p []byte, off int64) (int, error) {
n, err := s.ra.ReadAt(p, off)
s.record(err)
return n, err
}
func (s *sourceReadAtRecorder) Seek(offset int64, whence int) (int64, error) {
return s.sk.Seek(offset, whence)
}
// newSourceReadRecorder wraps an upload body, keeping the shape the remote
// client sees.
func newSourceReadRecorder(r io.Reader) (io.Reader, *sourceReadRecorder) {
rec := &sourceReadRecorder{r: r}
ra, okAt := r.(io.ReaderAt)
sk, okSeek := r.(io.Seeker)
if okAt && okSeek {
return &sourceReadAtRecorder{sourceReadRecorder: rec, ra: ra, sk: sk}, rec
}
return rec, rec
}
func (s *sourceReadRecorder) record(err error) {
if err == nil || err == io.EOF {
return
}
s.mu.Lock()
if s.err == nil {
s.err = err
}
s.mu.Unlock()
}
func (s *sourceReadRecorder) readErr() error {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
return s.err
}
// isSourceGone reports whether a read of the entry's own chunks says the data
// may be gone: every location of a chunk answered 404
// (util_http.NotFoundEverywhere). Only errors from the source side are passed
// here: the upload body's reader or the chunk view resolution.
func isSourceGone(sourceErr error) bool {
return errors.Is(sourceErr, util_http.ErrNotFound)
}
var fidInURL = regexp.MustCompile(`/(\d+,[0-9a-fA-F]+)(?:[?:/\s"]|$)`)
// goneFid names the chunk the sighting was for, for the log: the file id in
// the URL the error carries, else the entry's first chunk and how many more
// it has.
func goneFid(sourceErr error, entry *filer_pb.Entry) string {
if m := fidInURL.FindStringSubmatch(sourceErr.Error()); m != nil {
return m[1]
}
chunks := entry.GetChunks()
switch len(chunks) {
case 0:
return "unknown"
case 1:
return chunks[0].GetFileIdString()
}
return fmt.Sprintf("%s and %d more", chunks[0].GetFileIdString(), len(chunks)-1)
}
// chunkSetKey identifies the content a sighting is about: the entry's chunk
// file ids, in any order. The chunk that fails first can differ from one
// attempt to the next (an uploader reads parts in parallel), so sightings in
// a row are counted per content, not per failing chunk.
func chunkSetKey(entry *filer_pb.Entry) string {
fids := make([]string, 0, len(entry.GetChunks()))
for _, c := range entry.GetChunks() {
fids = append(fids, c.GetFileIdString())
}
sort.Strings(fids)
h := fnv.New64a()
for _, f := range fids {
h.Write([]byte(f))
h.Write([]byte{0})
}
return fmt.Sprintf("%d:%016x", len(fids), h.Sum64())
}
type goneSighting struct {
key string
first time.Time
last time.Time
answers int
}
// sourceGoneTracker holds, per path, the sightings seen in a row. Any other
// outcome for the path forgets them, so the grace starts again. A path found
// gone is remembered with its content key: a later event of the same entry (a
// metadata update, a replay) is skipped at once instead of holding the
// directory's offset for another grace.
type sourceGoneTracker struct {
mu sync.Mutex
seen map[string]*goneSighting
gone map[string]string
}
func newSourceGoneTracker() *sourceGoneTracker {
return &sourceGoneTracker{seen: map[string]*goneSighting{}, gone: map[string]string{}}
}
var sourceGone = newSourceGoneTracker()
// observe records a sighting for path under key (chunkSetKey) and reports
// whether it has now held for sourceGoneGrace over sourceGoneMinAnswers
// attempts, and whether this call is the one that found it gone (a path
// already known gone reports gone, not new).
func (t *sourceGoneTracker) observe(path, key string, now time.Time) (gone, isNew bool) {
t.mu.Lock()
defer t.mu.Unlock()
if g, ok := t.gone[path]; ok && g == key {
return true, false
}
s := t.seen[path]
if s == nil || s.key != key {
if s == nil && len(t.seen) >= sourceGoneRemembered {
t.pruneSeen(now)
}
s = &goneSighting{key: key, first: now}
t.seen[path] = s
}
s.answers++
s.last = now
if s.answers >= sourceGoneMinAnswers && now.Sub(s.first) >= sourceGoneGrace {
delete(t.seen, path)
if len(t.gone) >= sourceGoneRemembered {
t.gone = map[string]string{}
}
t.gone[path] = key
return true, true
}
return false, false
}
// pruneSeen drops sightings of paths no attempt has reached for longer than
// the grace (the entry was deleted, or the subscription moved past it), and
// every sighting if the map is still full. Dropping one only restarts that
// path's grace.
func (t *sourceGoneTracker) pruneSeen(now time.Time) {
stale := 2 * sourceGoneGrace
for p, s := range t.seen {
if now.Sub(s.last) > stale {
delete(t.seen, p)
}
}
if len(t.seen) >= sourceGoneRemembered {
t.seen = map[string]*goneSighting{}
}
}
// forget drops path's sightings, and its gone mark: the entry was written
// back, superseded, or failed some other way.
func (t *sourceGoneTracker) forget(path string) {
t.mu.Lock()
delete(t.seen, path)
delete(t.gone, path)
t.mu.Unlock()
}
+357
View File
@@ -0,0 +1,357 @@
package command
import (
"bytes"
"errors"
"fmt"
"io"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"google.golang.org/protobuf/proto"
)
func withSourceGone(t *testing.T, grace time.Duration, minAnswers int) {
t.Helper()
prevGrace, prevMin, prevWait := sourceGoneGrace, sourceGoneMinAnswers, util.RetryWaitTime
sourceGoneGrace, sourceGoneMinAnswers = grace, minAnswers
// one pass of the chunk fetch's and the upload's backoff loops
util.RetryWaitTime = 1100 * time.Millisecond
sourceGone = newSourceGoneTracker()
sourceGoneCount.Store(0)
t.Cleanup(func() {
sourceGoneGrace, sourceGoneMinAnswers, util.RetryWaitTime = prevGrace, prevMin, prevWait
sourceGone = newSourceGoneTracker()
sourceGoneCount.Store(0)
})
}
// TestRetriedWriteFileSourceGone: an entry the filer still holds whose chunk
// the volume server answers 404 for (a volume lost with its disk) ends in
// errSourceGone once the 404 has held, instead of failing its event forever
// and holding the directory's offset behind it. The encrypted read path
// (GetAuthenticated) must report the 404 as ErrNotFound too: production
// cells encrypt volume data.
func TestRetriedWriteFileSourceGone(t *testing.T) {
const dir = "/buckets/garden--blobs/camera"
for _, tc := range []struct {
name string
chunk *filer_pb.FileChunk
}{
{"plain chunk", &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 100}},
{"encrypted chunk", &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 100, CipherKey: make([]byte, 32)}},
} {
t.Run(tc.name, func(t *testing.T) {
withSourceGone(t, 0, 3)
entry := entryWith("snapshot.jpg", nil, tc.chunk)
entry.Attributes.FileSize = 100
filerClient, done := servingFilerClient(entry, map[string][]byte{}) // the chunk is gone
defer done()
dest := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/camera/snapshot.jpg"}
for call := 1; call <= 2; call++ {
_, err := retriedWriteFile(&captureRemote{}, filerClient, dir, entry, dest)
if err == nil || errors.Is(err, errSourceGone) || errors.Is(err, errSuperseded) {
t.Fatalf("call %d: err = %v, want the read failure itself while the 404 is young", call, err)
}
}
_, err := retriedWriteFile(&captureRemote{}, filerClient, dir, entry, dest)
if !errors.Is(err, errSourceGone) {
t.Fatalf("third call: err = %v, want errSourceGone", err)
}
if got := sourceGoneCount.Load(); got != 1 {
t.Errorf("counted %d gone entries, want 1", got)
}
want := fmt.Sprintf("%s/snapshot.jpg (fid 79,2cb9d2dd0ea2)", dir)
if msg := err.Error(); len(msg) < len(want) || msg[:len(want)] != want {
t.Errorf("err = %q, want it to start with %q", msg, want)
}
})
}
}
// TestRetriedWriteFileRemoteNotFoundIsNeverGone: only the source's own chunk
// reads decide. A remote that answers 404 (or anything else) to the upload,
// while the chunks read fine, is retried as before: skipping it would drop
// data that exists.
// TestRetriedWriteFileSourceGoneAcrossChunks: an uploader reads the parts of
// a ReaderAt body in parallel, so which lost chunk fails first changes from
// one attempt to the next. The sightings are of the same content and must
// add up, or a large file missing several chunks holds the offset forever.
func TestRetriedWriteFileSourceGoneAcrossChunks(t *testing.T) {
withSourceGone(t, 0, 3)
entry := entryWith("big.bin", nil,
&filer_pb.FileChunk{FileId: "7,01", ETag: "e1", Offset: 0, Size: 4},
&filer_pb.FileChunk{FileId: "8,02", ETag: "e2", Offset: 4, Size: 4})
entry.Attributes.FileSize = 8
filerClient, done := servingFilerClient(entry, map[string][]byte{}) // both chunks lost
defer done()
dest := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/big.bin"}
remote := &partReadingRemote{}
for call := 1; call <= 3; call++ {
_, err := retriedWriteFile(remote, filerClient, "/buckets/b", entry, dest)
if call < 3 && errors.Is(err, errSourceGone) {
t.Fatalf("call %d: gone before three sightings", call)
}
if call == 3 && !errors.Is(err, errSourceGone) {
t.Fatalf("call 3: err = %v, want errSourceGone after three sightings of the same entry", err)
}
}
if len(remote.offsets) < 2 || remote.offsets[0] == remote.offsets[1] {
t.Fatalf("precondition: the attempts read different parts, got offsets %v", remote.offsets)
}
}
// partReadingRemote reads one 4-byte part of the body per write, the next
// part on each call, as parallel part readers do in no fixed order.
type partReadingRemote struct {
recordingRemote
offsets []int64
}
func (r *partReadingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
ra, ok := reader.(io.ReaderAt)
if !ok {
return nil, errors.New("body is not a ReaderAt")
}
off := int64(len(r.offsets)%2) * 4
r.offsets = append(r.offsets, off)
if _, err := ra.ReadAt(make([]byte, 4), off); err != nil {
return nil, fmt.Errorf("RequestError: send request failed\ncaused by: %v", err)
}
return r.recordingRemote.WriteFile(loc, entry, reader)
}
func TestRetriedWriteFileRemoteNotFoundIsNeverGone(t *testing.T) {
withSourceGone(t, 0, 1)
const dir = "/buckets/ingest"
entry := entryWith("lease.json", nil, chunk("3,01", "e1"))
filerClient := &stubFilerClient{entry: entryWith(entry.Name, nil, chunk("3,01", "e1"))}
dest := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "tier", Path: "/lease.json"}
remoteErr := fmt.Errorf("https://s3.example.com/tier/lease.json: 404 Not Found: %w", util_http.ErrNotFound)
for call := 1; call <= 3; call++ {
_, err := retriedWriteFile(&failingRemote{err: remoteErr}, filerClient, dir, entry, dest)
if err == nil || errors.Is(err, errSourceGone) {
t.Fatalf("call %d: err = %v, want the remote's failure, never errSourceGone", call, err)
}
}
if got := sourceGoneCount.Load(); got != 0 {
t.Errorf("counted %d gone entries, want 0", got)
}
}
// TestSourceGoneTrackerGrace: a sighting counts as gone only after both the
// grace and the answer count, for the same chunk, with nothing else in
// between; a gone path is then skipped at once until something else happens.
func TestSourceGoneTrackerGrace(t *testing.T) {
withSourceGone(t, 5*time.Minute, 3)
t0 := time.Unix(1_800_000_000, 0)
tr := newSourceGoneTracker()
observe := func(path, key string, at time.Time) bool {
gone, _ := tr.observe(path, key, at)
return gone
}
if observe("/a", "1,01", t0) || observe("/a", "1,01", t0.Add(time.Minute)) || observe("/a", "1,01", t0.Add(2*time.Minute)) {
t.Fatal("gone before the grace ended")
}
if !observe("/a", "1,01", t0.Add(5*time.Minute)) {
t.Fatal("not gone after the grace and three answers")
}
// a later event of the same gone entry is skipped at once
if !observe("/a", "1,01", t0.Add(6*time.Minute)) {
t.Fatal("a known-gone entry waits for another grace")
}
// written back or failed otherwise since: the grace starts again
tr.forget("/a")
if observe("/a", "1,01", t0.Add(7*time.Minute)) {
t.Fatal("gone on the first answer after forget")
}
// an unknown path never matches the empty fid of a chunkless entry
if observe("/c", "", t0) {
t.Fatal("a first sighting with an empty fid counted as gone")
}
// many answers inside the grace are not enough
for i := 0; i < 10; i++ {
if observe("/b", "1,02", t0.Add(time.Duration(i)*time.Second)) {
t.Fatalf("answer %d: gone inside the grace", i)
}
}
tr.forget("/b")
if observe("/b", "1,02", t0.Add(6*time.Minute)) || observe("/b", "1,02", t0.Add(7*time.Minute)) || observe("/b", "1,02", t0.Add(8*time.Minute)) {
t.Fatal("gone without a full grace after forget")
}
// another chunk of the same path starts again too
if observe("/b", "1,03", t0.Add(20*time.Minute)) {
t.Fatal("gone on a new chunk's first answer")
}
}
// TestSourceGoneTrackerCountsOnce: a path is new-gone once; replayed events
// of it are skipped without another log line or count.
func TestSourceGoneTrackerCountsOnce(t *testing.T) {
withSourceGone(t, 5*time.Minute, 3)
t0 := time.Unix(1_800_000_000, 0)
entry := entryWith("x.jpg", nil, chunk("79,01", "e1"))
tr := newSourceGoneTracker()
key := chunkSetKey(entry)
for i, at := range []time.Duration{0, time.Minute, 5 * time.Minute} {
gone, isNew := tr.observe("/x", key, t0.Add(at))
if want := i == 2; gone != want || isNew != want {
t.Fatalf("answer %d: gone=%v new=%v, want %v %v", i, gone, isNew, want, want)
}
}
if gone, isNew := tr.observe("/x", key, t0.Add(6*time.Minute)); !gone || isNew {
t.Errorf("a replay of a gone path: gone=%v new=%v, want gone and not new", gone, isNew)
}
}
// TestIsSourceGone: only a 404 from every location of a chunk is a sighting.
func TestIsSourceGone(t *testing.T) {
for _, tc := range []struct {
err error
want bool
}{
{fmt.Errorf("http://v:8080/79,2cb9: 404 Not Found: %w", util_http.ErrNotFound), true},
// a volume the master cannot locate: a volume server that is down
// looks the same
{errors.New("failed to locate 79,2cb9d2dd0ea2"), false},
// a 404 on one replica while another failed otherwise
{util_http.NotFoundEverywhere(fmt.Errorf("a: %w", util_http.ErrNotFound), errors.New("b: 503 Service Unavailable")), false},
{errors.New("http://v:8080/79,2cb9: 500 Internal Server Error"), false},
{errors.New("read tcp: connection reset by peer"), false},
{nil, false},
} {
if got := isSourceGone(tc.err); got != tc.want {
t.Errorf("isSourceGone(%v) = %v, want %v", tc.err, got, tc.want)
}
}
}
// TestSourceReadRecorderKeepsReaderAt: the recorder must not hide a
// ReaderAt + Seeker body, or an S3 uploader buffers every part in memory.
func TestSourceReadRecorderKeepsReaderAt(t *testing.T) {
body, rec := newSourceReadRecorder(io.NewSectionReader(goneChunkReaderAt{}, 0, 10))
ra, okAt := body.(io.ReaderAt)
_, okSeek := body.(io.Seeker)
if !okAt || !okSeek {
t.Fatalf("body %T: ReaderAt %v, Seeker %v; want both", body, okAt, okSeek)
}
if _, err := ra.ReadAt(make([]byte, 4), 0); err == nil {
t.Fatal("ReadAt succeeded")
}
if !errors.Is(rec.readErr(), util_http.ErrNotFound) {
t.Errorf("recorded %v, want the ReadAt failure", rec.readErr())
}
if _, ok := mustReader(newSourceReadRecorder(bytes.NewBufferString("x"))).(io.ReaderAt); ok {
t.Error("a plain reader gained ReadAt")
}
}
type goneChunkReaderAt struct{}
func (goneChunkReaderAt) ReadAt([]byte, int64) (int, error) {
return 0, fmt.Errorf("http://v:8080/79,2cb9: 404 Not Found: %w", util_http.ErrNotFound)
}
func mustReader(r io.Reader, _ *sourceReadRecorder) io.Reader { return r }
// bodyReadingRemote reads the upload body before recording the write, as a
// real remote does; a body read failure fails the write.
type bodyReadingRemote struct{ *recordingRemote }
func (r bodyReadingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
if _, err := io.ReadAll(reader); err != nil {
return nil, fmt.Errorf("RequestError: send request failed\ncaused by: %v", err)
}
return r.recordingRemote.WriteFile(loc, entry, reader)
}
// TestRenameOfGoneEntryKeepsTheOldKey: a written-back entry renamed after its
// local chunks were lost still has its content under the old key. The event
// is acknowledged as gone, and the old key is not deleted: it is the only
// copy left. With the chunks present, the old key goes once the new one is
// written.
func TestRenameOfGoneEntryKeepsTheOldKey(t *testing.T) {
const mountedDir = "/buckets"
mountLoc := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/"}
oldKey := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/b/src/photo.jpg"}
newKey := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/b/dst/photo.jpg"}
event := func(stamped bool) (*filer_pb.Entry, *filer_pb.SubscribeMetadataResponse) {
newEntry := entryWith("photo.jpg", nil, &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 4})
newEntry.Attributes.FileSize = 4
var stamp *filer_pb.RemoteEntry
if stamped {
stamp = &filer_pb.RemoteEntry{StorageName: "bunny", RemoteETag: "etag", RemoteSize: 4, RemoteMtime: 1786096669}
}
oldEntry := entryWith("photo.jpg", stamp, &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 4})
return newEntry, &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/b/src",
EventNotification: &filer_pb.EventNotification{
OldEntry: oldEntry,
NewParentPath: "/buckets/b/dst",
NewEntry: newEntry,
},
}
}
t.Run("chunks gone", func(t *testing.T) {
withSourceGone(t, 0, 1)
newEntry, resp := event(true)
filerClient, done := servingFilerClient(newEntry, map[string][]byte{})
defer done()
remote := bodyReadingRemote{&recordingRemote{}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err)
}
if len(remote.deletes) != 0 {
t.Errorf("deleted %+v; the old key holds the only copy", remote.deletes)
}
if len(remote.writes) != 0 {
t.Errorf("wrote %+v, want nothing", remote.writes)
}
if got := sourceGoneCount.Load(); got != 1 {
t.Errorf("counted %d gone entries, want 1", got)
}
})
t.Run("chunks gone, old entry unstamped", func(t *testing.T) {
// the upload's stamp was refused by the rename in between: the old
// key still holds the only copy
withSourceGone(t, 0, 1)
newEntry, resp := event(false)
filerClient, done := servingFilerClient(newEntry, map[string][]byte{})
defer done()
remote := bodyReadingRemote{&recordingRemote{}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err)
}
if len(remote.deletes) != 0 {
t.Errorf("deletes = %+v; the old key holds the only copy", remote.deletes)
}
})
t.Run("chunks present", func(t *testing.T) {
withSourceGone(t, 0, 1)
newEntry, resp := event(true)
filerClient, done := servingFilerClient(newEntry, map[string][]byte{"79,2cb9d2dd0ea2": []byte("jpeg")})
defer done()
remote := bodyReadingRemote{&recordingRemote{}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v", err)
}
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], newKey) {
t.Errorf("writes = %+v, want the new key", remote.writes)
}
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], oldKey) {
t.Errorf("deletes = %+v, want the old key once the new one is written", remote.deletes)
}
})
}
+28 -17
View File
@@ -46,12 +46,23 @@ func partitionedEvents(numDirs, filesPerDir int) (partitions [][]*filer_pb.Subsc
// runSingleStream feeds all events through one MetadataProcessor with a per-event
// stream delivery delay (simulating a single gRPC SubscribeMetadata stream).
func runSingleStream(events []*filer_pb.SubscribeMetadataResponse, concurrency int, streamDelay, processDelay time.Duration) (processed int64, elapsed time.Duration) {
// peakInFlight is the most jobs that ran at the same time.
func runSingleStream(events []*filer_pb.SubscribeMetadataResponse, concurrency int, streamDelay, processDelay time.Duration) (processed int64, elapsed time.Duration, peakInFlight int64) {
var wg sync.WaitGroup
var inFlight atomic.Int64
var peak atomic.Int64
processFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
defer wg.Done()
n := inFlight.Add(1)
for {
p := peak.Load()
if n <= p || peak.CompareAndSwap(p, n) {
break
}
}
time.Sleep(processDelay)
inFlight.Add(-1)
atomic.AddInt64(&processed, 1)
return nil
}
@@ -68,6 +79,7 @@ func runSingleStream(events []*filer_pb.SubscribeMetadataResponse, concurrency i
}
wg.Wait()
elapsed = time.Since(start)
peakInFlight = peak.Load()
return
}
@@ -126,7 +138,7 @@ func TestStreamDeliveryBottleneck(t *testing.T) {
partitions, allEvents := partitionedEvents(numDirs, filesPerDir)
singleCount, singleElapsed := runSingleStream(allEvents, 256, streamDelay, processDelay)
singleCount, singleElapsed, _ := runSingleStream(allEvents, 256, streamDelay, processDelay)
singleRate := float64(singleCount) / singleElapsed.Seconds()
t.Logf("1 stream: %4d events %v %6.0f events/sec",
singleCount, singleElapsed.Round(time.Millisecond), singleRate)
@@ -166,21 +178,20 @@ func TestConcurrencyIneffectiveOnStreamBottleneck(t *testing.T) {
_, allEvents := partitionedEvents(numDirs, filesPerDir)
var rates []float64
for _, concurrency := range []int{32, 128, 512} {
count, elapsed := runSingleStream(allEvents, concurrency, streamDelay, processDelay)
rate := float64(count) / elapsed.Seconds()
rates = append(rates, rate)
t.Logf("concurrency=%3d: %d events %v %.0f events/sec",
concurrency, count, elapsed.Round(time.Millisecond), rate)
}
if len(rates) >= 2 {
ratio := rates[len(rates)-1] / rates[0]
t.Logf("concurrency 512 vs 32: %.2fx (expected ~1.0x when stream-limited)", ratio)
// Should be within 50% — concurrency doesn't help a stream bottleneck
if ratio > 1.5 || ratio < 0.5 {
t.Errorf("unexpected ratio %.2f: concurrency should not affect stream-limited throughput", ratio)
concurrencies := []int{32, 128, 512}
for _, concurrency := range concurrencies {
count, elapsed, peak := runSingleStream(allEvents, concurrency, streamDelay, processDelay)
t.Logf("concurrency=%3d: %d events %v %.0f events/sec peak in flight %d",
concurrency, count, elapsed.Round(time.Millisecond), float64(count)/elapsed.Seconds(), peak)
if count != int64(numDirs*filesPerDir) {
t.Errorf("concurrency=%d: expected %d events, got %d", concurrency, numDirs*filesPerDir, count)
}
// Wall-clock rates of separate runs vary with runner load, so check
// the cause instead: the stream never fills even the smallest limit,
// so the limit never holds back an event and raising it changes nothing.
if peak >= int64(concurrencies[0]) {
t.Errorf("concurrency=%d: %d jobs in flight reached the smallest limit %d, so the stream is not the bottleneck",
concurrency, peak, concurrencies[0])
}
}
}
+1
View File
@@ -28,6 +28,7 @@ import (
_ "github.com/seaweedfs/seaweedfs/weed/filer/mysql2"
_ "github.com/seaweedfs/seaweedfs/weed/filer/postgres"
_ "github.com/seaweedfs/seaweedfs/weed/filer/postgres2"
_ "github.com/seaweedfs/seaweedfs/weed/filer/postgres_flat"
_ "github.com/seaweedfs/seaweedfs/weed/filer/redis"
_ "github.com/seaweedfs/seaweedfs/weed/filer/redis2"
_ "github.com/seaweedfs/seaweedfs/weed/filer/redis3"
+89 -20
View File
@@ -64,18 +64,20 @@ const (
)
var (
miniOptions MiniOptions
miniMasterOptions MasterOptions
miniFilerOptions FilerOptions
miniS3Options S3Options
miniWebDavOptions WebDavOption
miniAdminOptions AdminOptions
miniOptions MiniOptions
miniMasterOptions MasterOptions
miniFilerOptions FilerOptions
miniS3Options S3Options
miniMqBrokerOptions MessageQueueBrokerOptions
miniWebDavOptions WebDavOption
miniAdminOptions AdminOptions
// Flags explicitly provided on the command line or via WEED_* env vars,
// captured before the saved options file is applied
explicitFlags map[string]bool
miniEnableWebDAV *bool
miniWebDavAllowInsecureBind *bool
miniEnableS3 *bool
miniEnableMqBroker *bool
miniEnableAdminUI *bool
miniAdminWorkerBindIP *string
miniS3IamReadOnly *bool
@@ -224,6 +226,9 @@ func miniStartupServices() []string {
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
services = append(services, "Lance")
}
if miniEnableMqBroker != nil && *miniEnableMqBroker {
services = append(services, "MQ Broker")
}
}
services = append(services, "Admin")
return services
@@ -348,7 +353,7 @@ var cmdMini = &Command{
Long: `start a complete SeaweedFS setup with all components optimized for small/dev use cases
This command starts all components in one process (master, volume, filer,
S3 gateway, WebDAV gateway, and Admin UI).
S3 gateway with its message queue broker, WebDAV gateway, and Admin UI).
All settings are optimized for small/dev use cases:
- Volume size limit: auto configured based on disk space (64MB-1024MB)
@@ -378,6 +383,7 @@ After starting, you can access:
- Iceberg Catalog: http://localhost:8181
- WebDAV: http://localhost:7333
- Admin UI: http://localhost:12535
- MQ Broker: localhost:17777 (gRPC; -mq.broker=false to turn off)
S3 Access:
The S3 endpoint is available at http://localhost:8333. For client
@@ -418,7 +424,7 @@ var (
miniS3AutoCreateBucket = cmdMini.Flag.Bool("s3.autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
miniBucket = cmdMini.Flag.String("bucket", "", "comma-separated S3 bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_BUCKET env var.")
miniTableBucket = cmdMini.Flag.String("tableBucket", "", "comma-separated S3 Tables buckets to create on startup if they do not already exist, each name[:FORMAT] with FORMAT one of ICEBERG (default) or LANCE, e.g. warehouse,vectors:LANCE; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
miniVector = cmdMini.Flag.Bool("vector", false, "start the weed-vector engine for vector indexes and search")
miniVector = cmdMini.Flag.Bool("vector", true, "start the weed-vector engine for vector indexes and search, and the weed-worker that builds its indexes, when they are installed")
miniVectorBinary = cmdMini.Flag.String("vector.binary", "weed-vector", "path to the vector engine binary")
miniVectorPort = cmdMini.Flag.Int("vector.port", 8090, "vector engine gRPC port")
miniVectorMetricsPort = cmdMini.Flag.Int("vector.metricsPort", 0, "optional vector HTTP health and metrics port")
@@ -582,6 +588,22 @@ func initMiniS3Flags() {
// In mini mode, S3 uses the shared debug server started at line 681, not its own separate debug server
miniS3Options.debug = new(bool) // explicitly false
miniS3Options.debugPort = cmdMini.Flag.Int("s3.debug.port", 6060, "http port for debugging (unused in mini mode)")
miniEnableMqBroker = cmdMini.Flag.Bool("mq.broker", true, "start a message queue broker beside the S3 gateway, on its own gRPC port, with or without grpc.msg_broker TLS")
miniMqBrokerOptions.port = cmdMini.Flag.Int("mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
}
// miniRunsMqBroker reports whether mini starts the broker beside its S3 gateway.
func miniRunsMqBroker() bool {
return *miniEnableS3 && *miniEnableMqBroker
}
// miniMqBrokerAddress is the broker address for the welcome banner, or empty
// when the broker is off or did not bind.
func miniMqBrokerAddress() string {
if !miniRunsMqBroker() || !miniMqBrokerOptions.bound.Load() {
return ""
}
return util.JoinHostPort(*miniIp, *miniMqBrokerOptions.port)
}
// initMiniWebDAVFlags initializes WebDAV server flag options
@@ -967,6 +989,16 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
}{miniS3Options.portLance, "Lance", "s3.port.lance", nil, listenOnLocalhost})
}
}
if miniRunsMqBroker() {
// The broker port is itself gRPC; there is no derived port to reserve.
portConfigs = append(portConfigs, struct {
port *int
name string
flagName string
grpcPtr *int
localhost bool
}{miniMqBrokerOptions.port, "MQ Broker", "mq.broker.port", nil, listenOnLocalhost})
}
if *miniVector {
portConfigs = append(portConfigs, struct {
port *int
@@ -1005,14 +1037,21 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
// First, reserve all gRPC ports that will be calculated to prevent HTTP port allocation from using them
// This prevents collisions like: HTTP port moves to X, then gRPC port is calculated as Y where Y == X
reservedPorts := make(map[int]bool)
for _, config := range portConfigs {
if config.grpcPtr != nil && *config.grpcPtr == 0 {
// This gRPC port will be calculated as httpPort + GrpcPortOffset
calculatedGrpcPort := *config.port + GrpcPortOffset
reservedPorts[calculatedGrpcPort] = true
reserveGrpcPorts := func() map[int]bool {
reserved := make(map[int]bool)
for _, config := range portConfigs {
if config.grpcPtr != nil && *config.grpcPtr == 0 {
// This gRPC port will be calculated as httpPort + GrpcPortOffset
reserved[*config.port+GrpcPortOffset] = true
} else if config.grpcPtr != nil {
// A gRPC port given outright is reserved too, or a port without a
// gRPC companion (the broker's) could take it first.
reserved[*config.grpcPtr] = true
}
}
return reserved
}
reservedPorts := reserveGrpcPorts()
chosenPorts := make(map[int]string)
for _, config := range portConfigs {
@@ -1053,10 +1092,10 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
if *config.port > 0 {
chosenPorts[*config.port] = config.flagName
}
// If port was changed, update the reserved gRPC ports mapping
// If port was changed, rebuild the reserved gRPC ports: the old derived
// port may also be another service's explicit gRPC port.
if *config.port != original && config.grpcPtr != nil && *config.grpcPtr == 0 {
delete(reservedPorts, original+GrpcPortOffset)
reservedPorts[*config.port+GrpcPortOffset] = true
reservedPorts = reserveGrpcPorts()
}
}
@@ -1163,6 +1202,9 @@ func initializeGrpcPortsOnIP(bindIp string, listenOnLocalhost bool) map[int]bool
allocatedPorts[*miniS3Options.portLance] = true
}
}
if miniRunsMqBroker() {
allocatedPorts[*miniMqBrokerOptions.port] = true
}
if *miniVector {
allocatedPorts[*miniVectorPort] = true
@@ -1490,6 +1532,7 @@ func runMini(cmd *Command, args []string) bool {
// plaintext-KEK warning and the IAM "no signing key" error don't fire.
// Does nothing for keys the operator has already configured.
ensureMiniDevSSES3Keys(*miniDataFolders)
prepareMiniVector()
*miniOptions.cpuprofile = util.ResolvePath(*miniOptions.cpuprofile)
*miniOptions.memprofile = util.ResolvePath(*miniOptions.memprofile)
@@ -1548,6 +1591,13 @@ func runMini(cmd *Command, args []string) bool {
miniS3Options.ip = miniIp
miniS3Options.bindIp = miniBindIp
miniS3Options.listenOnLocalhost = &listenOnLocalhost
miniS3Options.mqBroker = nil
miniMqBrokerOptions.bound.Store(false)
if miniRunsMqBroker() {
miniS3Options.mqBroker = miniS3Options.brokerBeside(&miniMqBrokerOptions)
miniMqBrokerOptions.dataCenter = miniDataCenter
miniMqBrokerOptions.rack = miniRack
}
webDavBindIP := miniWebDavBindIP(*miniBindIp)
if *miniEnableWebDAV && webDavBindIP != *miniBindIp {
glog.Warningf("WebDAV has no authentication; binding it to %s instead of %s. Set [webdav.basic_auth] in security.toml, or use -webdav.allowInsecureBind to keep the network bind.", webDavBindIP, *miniBindIp)
@@ -1741,9 +1791,9 @@ func runMini(cmd *Command, args []string) bool {
}
if *miniVector {
if err := startMiniVector(); err != nil {
glog.Errorf("start vector engine: %v", err)
triggerMiniClientsShutdown(5 * time.Second)
return false
glog.Errorf("vector engine not started, continuing without vector search: %v", err)
} else if err := startMiniVectorWorker(); err != nil {
glog.Errorf("weed-worker not started, continuing without vector index maintenance: %v", err)
}
}
@@ -1821,6 +1871,9 @@ func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) {
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
defer reportMiniStopped("Lance")
}
if miniRunsMqBroker() {
defer reportMiniStopped("MQ Broker")
}
startMiniService("S3", startS3Service, *miniS3Options.port)
}()
}
@@ -1871,6 +1924,19 @@ func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) {
glog.Warningf("Lance namespace server on port %d did not start; see S3 startup log", *miniS3Options.portLance)
}
}
if miniRunsMqBroker() {
// The S3 gateway binds the broker before it serves, so this is final.
if miniMqBrokerOptions.bound.Load() {
if miniProgressBoard != nil {
miniProgressBoard.ready("MQ Broker")
}
} else {
if miniProgressBoard != nil {
miniProgressBoard.failed("MQ Broker")
}
glog.Warningf("message queue broker on port %d did not start; see S3 startup log", *miniMqBrokerOptions.port)
}
}
}
if *miniEnableWebDAV {
waitForServiceReady("WebDAV", *miniWebDavOptions.port, *miniWebDavOptions.ipBind)
@@ -2391,6 +2457,9 @@ func printWelcomeMessage() {
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
fmt.Fprintf(&sb, " Lance Namespace: http://%s:%d\n", *miniIp, *miniS3Options.portLance)
}
if addr := miniMqBrokerAddress(); addr != "" {
fmt.Fprintf(&sb, " MQ Broker: %s (gRPC)\n", addr)
}
}
if *miniEnableAdminUI {
fmt.Fprintf(&sb, " Admin UI: http://%s\n", adminHTTPAddress)
+179
View File
@@ -0,0 +1,179 @@
package command
import (
"net"
"strconv"
"strings"
"testing"
)
func TestMqBrokerDefaultPortBelowEphemeralFloor(t *testing.T) {
if defaultMqBrokerPort >= linuxEphemeralPortFloor {
t.Fatalf("default broker port %d must stay below the ephemeral floor %d", defaultMqBrokerPort, linuxEphemeralPortFloor)
}
for _, c := range []struct {
name string
cmd *Command
flag string
}{
{"mini", cmdMini, "mq.broker.port"},
{"s3", cmdS3, "mq.broker.port"},
{"server", cmdServer, "mq.broker.port"},
{"mq.broker", cmdMqBroker, "port"},
} {
flag := c.cmd.Flag.Lookup(c.flag)
if flag == nil {
t.Fatalf("%s: flag -%s not registered", c.name, c.flag)
}
if flag.DefValue != strconv.Itoa(defaultMqBrokerPort) {
t.Errorf("%s -%s default = %s, want %d", c.name, c.flag, flag.DefValue, defaultMqBrokerPort)
}
}
if flag := cmdMini.Flag.Lookup("mq.broker"); flag == nil || flag.DefValue != "true" {
t.Fatalf("mini -mq.broker should default to true, got %v", flag)
}
}
func TestMiniRunsMqBrokerOnlyBesideS3(t *testing.T) {
// Mini keeps its broker on by default without grpc.msg_broker TLS.
withMqBrokerTLS(t, false)
oldS3, oldBroker := *miniEnableS3, *miniEnableMqBroker
defer func() { *miniEnableS3, *miniEnableMqBroker = oldS3, oldBroker }()
for _, tc := range []struct {
s3, broker, want bool
}{
{true, true, true},
{true, false, false},
{false, true, false},
{false, false, false},
} {
*miniEnableS3, *miniEnableMqBroker = tc.s3, tc.broker
if got := miniRunsMqBroker(); got != tc.want {
t.Errorf("-s3=%v -mq.broker=%v: runs broker %v, want %v", tc.s3, tc.broker, got, tc.want)
}
}
}
// The broker port takes part in mini's port layout, so it cannot silently
// share a port with another mini service.
func TestMiniMqBrokerPortJoinsPortLayout(t *testing.T) {
oldS3, oldBroker, oldS3Port, oldBrokerPort, oldVector, oldFlags := *miniEnableS3, *miniEnableMqBroker, *miniS3Options.port, *miniMqBrokerOptions.port, *miniVector, explicitFlags
defer func() {
*miniEnableS3, *miniEnableMqBroker, *miniS3Options.port, *miniMqBrokerOptions.port, *miniVector, explicitFlags = oldS3, oldBroker, oldS3Port, oldBrokerPort, oldVector, oldFlags
}()
*miniEnableS3, *miniEnableMqBroker, *miniVector = true, true, false
*miniS3Options.port = 8333
*miniMqBrokerOptions.port = 8333
explicitFlags = map[string]bool{"s3.port": true, "mq.broker.port": true}
err := ensureAllPortsAvailableOnIP("127.0.0.1", false)
if err == nil || !strings.Contains(err.Error(), "shared by explicit flags s3.port and mq.broker.port") {
t.Fatalf("broker port conflict not rejected: %v", err)
}
}
func TestMiniExplicitS3GrpcPortIsReservedFromBroker(t *testing.T) {
saved := []*int{miniMasterOptions.port, miniFilerOptions.port, miniOptions.v.port, miniS3Options.port,
miniS3Options.portGrpc, miniS3Options.portIceberg, miniS3Options.portLance, miniMqBrokerOptions.port}
values := make([]int, len(saved))
for i, p := range saved {
values[i] = *p
}
oldS3, oldBroker, oldVector, oldWebDav, oldFlags := *miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags
defer func() {
for i, p := range saved {
*p = values[i]
}
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags = oldS3, oldBroker, oldVector, oldWebDav, oldFlags
}()
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV = true, true, false, false
*miniS3Options.portIceberg, *miniS3Options.portLance = 0, 0
port := freePort(t)
*miniS3Options.portGrpc, *miniMqBrokerOptions.port = port, port
explicitFlags = map[string]bool{"s3.port.grpc": true, "mq.broker.port": true}
err := ensureAllPortsAvailableOnIP("127.0.0.1", false)
if err == nil || !strings.Contains(err.Error(), "mq.broker.port") {
t.Fatalf("explicit broker port on the explicit S3 gRPC port not rejected: %v", err)
}
}
// The filer's HTTP port is taken, so it moves; its old derived gRPC port is
// also the explicit S3 gRPC port, which must stay reserved from the broker.
func TestMiniMovedFilerKeepsExplicitS3GrpcPortReserved(t *testing.T) {
saved := []*int{miniMasterOptions.port, miniFilerOptions.port, miniFilerOptions.portGrpc, miniOptions.v.port, miniS3Options.port,
miniS3Options.portGrpc, miniS3Options.portIceberg, miniS3Options.portLance, miniMqBrokerOptions.port}
values := make([]int, len(saved))
for i, p := range saved {
values[i] = *p
}
oldS3, oldBroker, oldVector, oldWebDav, oldFlags := *miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags
defer func() {
for i, p := range saved {
*p = values[i]
}
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags = oldS3, oldBroker, oldVector, oldWebDav, oldFlags
}()
var held net.Listener
filerPort := 0
for p := 20000; p < 30000 && held == nil; p += 7 {
l, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(p))
if err != nil {
continue
}
if probe, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(p+GrpcPortOffset)); err == nil {
probe.Close()
held, filerPort = l, p
} else {
l.Close()
}
}
if held == nil {
t.Skip("no free port pair")
}
defer held.Close()
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV = true, true, false, false
*miniS3Options.portIceberg, *miniS3Options.portLance = 0, 0
*miniFilerOptions.port, *miniFilerOptions.portGrpc = filerPort, 0
*miniS3Options.portGrpc, *miniMqBrokerOptions.port = filerPort+GrpcPortOffset, filerPort+GrpcPortOffset
explicitFlags = map[string]bool{"s3.port.grpc": true, "mq.broker.port": true}
err := ensureAllPortsAvailableOnIP("127.0.0.1", false)
if err == nil || !strings.Contains(err.Error(), "mq.broker.port") {
t.Fatalf("explicit broker port on the explicit S3 gRPC port not rejected after the filer moved: %v", err)
}
}
func TestMiniListsMqBrokerOnlyWhenRunning(t *testing.T) {
oldS3, oldBroker, oldIp, oldPort := *miniEnableS3, *miniEnableMqBroker, *miniIp, *miniMqBrokerOptions.port
defer func() {
*miniEnableS3, *miniEnableMqBroker, *miniIp, *miniMqBrokerOptions.port = oldS3, oldBroker, oldIp, oldPort
miniMqBrokerOptions.bound.Store(false)
}()
*miniIp, *miniMqBrokerOptions.port = "127.0.0.1", 17777
hasRow := func() bool {
for _, s := range miniStartupServices() {
if s == "MQ Broker" {
return true
}
}
return false
}
for _, tc := range []struct {
name string
s3, broker, bound bool
wantRow bool
wantAddr string
}{
{"running", true, true, true, true, "127.0.0.1:17777"},
{"failed to bind", true, true, false, true, ""},
{"turned off", true, false, false, false, ""},
{"no S3", false, true, false, false, ""},
} {
*miniEnableS3, *miniEnableMqBroker = tc.s3, tc.broker
miniMqBrokerOptions.bound.Store(tc.bound)
if got := hasRow(); got != tc.wantRow {
t.Errorf("%s: progress row %v, want %v", tc.name, got, tc.wantRow)
}
if got := miniMqBrokerAddress(); got != tc.wantAddr {
t.Errorf("%s: banner address %q, want %q", tc.name, got, tc.wantAddr)
}
}
}
+121 -13
View File
@@ -2,6 +2,8 @@ package command
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net"
"os"
@@ -16,19 +18,128 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
func startMiniVector() error {
binary := *miniVectorBinary
if binary == "weed-vector" {
// miniVectorPath and miniVectorWorkerPath are the resolved binaries, empty
// for a component mini does not start.
var miniVectorPath, miniVectorWorkerPath string
// lookMiniBinary finds a companion binary named by its default name next to
// weed first, then next to each of besides, then on PATH; any other value is
// used as given.
func lookMiniBinary(binary, defaultName string, besides ...string) (string, error) {
if binary == defaultName {
if executable, err := os.Executable(); err == nil {
candidate := filepath.Join(filepath.Dir(executable), binary)
if resolved, err := exec.LookPath(candidate); err == nil {
binary = resolved
besides = append([]string{executable}, besides...)
}
for _, path := range besides {
directory, err := filepath.Abs(filepath.Dir(path))
if err != nil {
continue
}
if resolved, err := exec.LookPath(filepath.Join(directory, binary)); err == nil {
return resolved, nil
}
}
}
if _, err := exec.LookPath(binary); err != nil {
return fmt.Errorf("%s is unavailable: install the vector component or set -vector.binary: %w", binary, err)
return exec.LookPath(binary)
}
// miniSecurityToml is the security.toml in -config_dir for a child process,
// unless its own environment variable already names one.
func miniSecurityToml(env string) string {
directory := util.ConfigurationFileDirectory.String()
if directory == "" {
return ""
}
path := filepath.Join(util.ResolvePath(directory), "security.toml")
if _, explicit := os.LookupEnv(env); explicit || !util.FileExists(path) {
return ""
}
return path
}
// prepareMiniVector finds weed-vector and weed-worker before ports are
// reserved and the S3 gateway starts. A component that is not installed is
// logged and left out. The Lance Namespace trusts the worker only by a token
// signed with a key derived from jwt.filer_signing.key, so when the cluster
// has none, the namespace and the worker share a key made for this run.
func prepareMiniVector() {
miniVectorPath, miniVectorWorkerPath, miniS3Options.lanceWorkerKey = "", "", nil
if !*miniVector {
return
}
binary, err := lookMiniBinary(*miniVectorBinary, "weed-vector")
if err != nil {
glog.Warningf("%s is unavailable, starting without vector search: install weed-vector or set -vector.binary: %v", *miniVectorBinary, err)
*miniVector = false
return
}
miniVectorPath = binary
binary, err = lookMiniBinary("weed-worker", "weed-worker", miniVectorPath)
if err != nil {
glog.Warningf("weed-worker is unavailable, so vector and metadata indexes will not be built: install it beside weed or weed-vector, or on PATH: %v", err)
return
}
miniVectorWorkerPath = binary
if util.GetViper().GetString("jwt.filer_signing.key") != "" {
return
}
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
glog.Warningf("weed-worker will not be started: generate its signing key: %v", err)
miniVectorWorkerPath = ""
return
}
miniS3Options.lanceWorkerKey = security.SigningKey(hex.EncodeToString(key))
}
// startMiniVectorWorker starts weed-worker against mini's admin, which names
// the filers and the Lance Namespace with every job.
// miniWorkerTLSArgs passes the [grpc.worker] certificates the Go workers dial
// admin with, chosen as security.LoadClientTLS chooses them: weed-worker takes
// its admin TLS only as flags, not from security.toml.
func miniWorkerTLSArgs(config util.Configuration) []string {
cert, key := config.GetString("grpc.worker.client_cert"), config.GetString("grpc.worker.client_key")
if cert == "" || key == "" {
cert, key = config.GetString("grpc.worker.cert"), config.GetString("grpc.worker.key")
}
ca := config.GetString("grpc.ca")
if cert == "" || key == "" || ca == "" {
return nil
}
return []string{"--tls-ca=" + ca, "--tls-cert=" + cert, "--tls-key=" + key}
}
func startMiniVectorWorker() error {
if miniVectorWorkerPath == "" {
return nil
}
admin := pb.NewServerAddress(miniAdminWorkerDialIP(miniAdminOptions.workerGrpcBindIp), *miniAdminOptions.port, *miniAdminOptions.grpcPort)
args := []string{"--admin=" + string(admin)}
if path := miniSecurityToml("WEED_WORKER_SECURITY_TOML"); path != "" {
args = append(args, "--security-toml="+path)
}
args = append(args, miniWorkerTLSArgs(util.GetViper())...)
command := exec.CommandContext(miniClientsCtx(), miniVectorWorkerPath, args...)
command.Stdout, command.Stderr = os.Stdout, os.Stderr
if key := miniS3Options.lanceWorkerKey; len(key) > 0 {
command.Env = append(os.Environ(), "WEED_FILER_SIGNING_KEY="+string(key))
}
if err := command.Start(); err != nil {
return err
}
done := trackMiniClient()
go func() {
defer done()
if err := command.Wait(); err != nil && miniClientsCtx().Err() == nil {
glog.Errorf("weed-worker exited: %v", err)
}
}()
glog.V(0).Infof("weed-worker started against admin %s", admin)
return nil
}
func startMiniVector() error {
binary := miniVectorPath
address := util.JoinHostPort(*miniIp, *miniVectorPort)
bindIP := *miniBindIp
if bindIP == "" {
@@ -54,11 +165,8 @@ func startMiniVector() error {
if *miniVectorMetricsPort > 0 {
args = append(args, fmt.Sprintf("--metrics-port=%d", *miniVectorMetricsPort), "--metrics-ip="+bindIP)
}
if directory := util.ConfigurationFileDirectory.String(); directory != "" {
path := filepath.Join(util.ResolvePath(directory), "security.toml")
if _, explicit := os.LookupEnv("WEED_VECTOR_SECURITY_TOML"); !explicit && util.FileExists(path) {
args = append(args, "--security-toml="+path)
}
if path := miniSecurityToml("WEED_VECTOR_SECURITY_TOML"); path != "" {
args = append(args, "--security-toml="+path)
}
command := exec.CommandContext(miniClientsCtx(), binary, args...)
command.Stdout, command.Stderr = os.Stdout, os.Stderr
+75
View File
@@ -1,10 +1,62 @@
package command
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/spf13/viper"
)
func TestPrepareMiniVector(t *testing.T) {
oldVector, oldVectorBinary := *miniVector, *miniVectorBinary
oldPaths, oldKey := [2]string{miniVectorPath, miniVectorWorkerPath}, miniS3Options.lanceWorkerKey
defer func() {
*miniVector, *miniVectorBinary = oldVector, oldVectorBinary
miniVectorPath, miniVectorWorkerPath, miniS3Options.lanceWorkerKey = oldPaths[0], oldPaths[1], oldKey
}()
both, vectorOnly, besideVector, empty := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir()
for dir, names := range map[string][]string{both: {"weed-vector", "weed-worker"}, vectorOnly: {"weed-vector"}, besideVector: {"weed-vector", "weed-worker"}} {
for _, name := range names {
if err := os.WriteFile(filepath.Join(dir, name), []byte("#!/bin/sh\n"), 0755); err != nil {
t.Fatal(err)
}
}
}
t.Chdir(besideVector)
t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "")
defer util.GetViper().Set("jwt.filer_signing.key", "")
for _, tc := range []struct {
name string
path string
vector bool
vectorBinary string
clusterKey string
wantVector bool
wantVectorPath, wantWorker string
wantKey bool
}{
{"both installed", both, true, "weed-vector", "", true, filepath.Join(both, "weed-vector"), filepath.Join(both, "weed-worker"), true},
{"weed-worker not installed after a run that started it", vectorOnly, true, "weed-vector", "", true, filepath.Join(vectorOnly, "weed-vector"), "", false},
{"cluster key configured", both, true, "weed-vector", "cluster-key", true, filepath.Join(both, "weed-vector"), filepath.Join(both, "weed-worker"), false},
{"weed-worker beside an explicit -vector.binary", empty, true, filepath.Join(besideVector, "weed-vector"), "", true, filepath.Join(besideVector, "weed-vector"), filepath.Join(besideVector, "weed-worker"), true},
{"weed-worker beside a relative -vector.binary", empty, true, "./weed-vector", "", true, "./weed-vector", filepath.Join(besideVector, "weed-worker"), true},
{"weed-vector not installed", empty, true, "weed-vector", "", false, "", "", false},
{"-vector=false", both, false, "weed-vector", "", false, "", "", false},
} {
t.Setenv("PATH", tc.path)
*miniVector, *miniVectorBinary = tc.vector, tc.vectorBinary
util.GetViper().Set("jwt.filer_signing.key", tc.clusterKey)
prepareMiniVector()
if *miniVector != tc.wantVector || miniVectorPath != tc.wantVectorPath || miniVectorWorkerPath != tc.wantWorker || (len(miniS3Options.lanceWorkerKey) == 64) != tc.wantKey {
t.Errorf("%s: vector %v %q, worker %q, key length %d", tc.name, *miniVector, miniVectorPath, miniVectorWorkerPath, len(miniS3Options.lanceWorkerKey))
}
}
}
func TestMiniVectorRejectsExplicitListenerConflict(t *testing.T) {
oldVector, oldPort, oldMetrics, oldFlags := *miniVector, *miniVectorPort, *miniVectorMetricsPort, explicitFlags
defer func() {
@@ -19,3 +71,26 @@ func TestMiniVectorRejectsExplicitListenerConflict(t *testing.T) {
t.Fatalf("listener conflict not rejected: %v", err)
}
}
func TestMiniWorkerTLSArgs(t *testing.T) {
for _, tc := range []struct {
name string
settings map[string]string
want []string
}{
{"plaintext", nil, nil},
{"worker cert", map[string]string{"grpc.ca": "ca.crt", "grpc.worker.cert": "w.crt", "grpc.worker.key": "w.key"},
[]string{"--tls-ca=ca.crt", "--tls-cert=w.crt", "--tls-key=w.key"}},
{"client cert preferred", map[string]string{"grpc.ca": "ca.crt", "grpc.worker.cert": "w.crt", "grpc.worker.key": "w.key", "grpc.worker.client_cert": "c.crt", "grpc.worker.client_key": "c.key"},
[]string{"--tls-ca=ca.crt", "--tls-cert=c.crt", "--tls-key=c.key"}},
{"no CA", map[string]string{"grpc.worker.cert": "w.crt", "grpc.worker.key": "w.key"}, nil},
} {
v := viper.New()
for key, value := range tc.settings {
v.Set(key, value)
}
if got := miniWorkerTLSArgs(util.NewViperProxy(v)); strings.Join(got, " ") != strings.Join(tc.want, " ") {
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
}
}
}
+2 -2
View File
@@ -119,7 +119,7 @@ func init() {
mountOptions.concurrentWriters = cmdMount.Flag.Int("concurrentWriters", 128, "limit concurrent goroutine writers")
mountOptions.concurrentReaders = cmdMount.Flag.Int("concurrentReaders", 128, "limit concurrent chunk fetches for read operations")
mountOptions.volumeReadAuth = cmdMount.Flag.Bool("volumeReadAuth", false, "read chunks with the exact-fid tokens the filer returns (LookupDirectoryEntries read_auth) instead of signing with jwt.signing.read.key")
mountOptions.memoryLimitMB = cmdMount.Flag.Int64("memoryLimitMB", 0, "soft Go runtime memory limit in MiB; 0 preserves GOMEMLIMIT; leave headroom below the container limit")
mountOptions.memoryLimitMB = cmdMount.Flag.Int64("memoryLimitMB", 0, "soft Go runtime memory limit in MiB; 0 keeps GOMEMLIMIT or 90% of the cgroup memory limit; leave headroom below the container limit")
mountOptions.readerCacheSizeMB = cmdMount.Flag.Int64("readerCacheSizeMB", 256, "memory budget in MiB for downloaded and in-flight reader buffers across all files; must fit the largest pooled chunk buffer")
mountOptions.cacheDirForRead = cmdMount.Flag.String("cacheDir", os.TempDir(), "local cache directory for file chunks and meta data")
mountOptions.cacheSizeMBForRead = cmdMount.Flag.Int64("cacheCapacityMB", 128, "file chunk read cache capacity in MB")
@@ -179,7 +179,7 @@ func init() {
// FUSE performance options
mountOptions.writebackCache = cmdMount.Flag.Bool("writebackCache", false, "enable FUSE writeback cache for improved write performance (at risk of data loss on crash)")
mountOptions.asyncDio = cmdMount.Flag.Bool("asyncDio", false, "enable async direct I/O for better concurrency")
mountOptions.nfsExport = cmdMount.Flag.Bool("nfsExport", false, "support file handles that outlive the kernel's inode cache, for re-exporting the mount over NFS")
mountOptions.nfsExport = cmdMount.Flag.Bool("nfsExport", false, "support file handles that outlive the kernel's inode cache or, without -filer.tokenFile, a mount restart, for re-exporting the mount over NFS")
mountOptions.cacheSymlink = cmdMount.Flag.Bool("cacheSymlink", false, "enable symlink caching to reduce metadata lookups")
mountOptions.fuseMaxBackground = cmdMount.Flag.Int("fuse.maxBackground", 128, "FUSE max_background: maximum in-flight asynchronous requests the kernel will queue. Heavy upload workloads may benefit from higher values (e.g. 2048). Equivalent to writing /sys/fs/fuse/connections/<id>/max_background. If -fuse.congestionThreshold is 0, the kernel derives it as 3/4 of this value.")
mountOptions.fuseCongestionThreshold = cmdMount.Flag.Int("fuse.congestionThreshold", 0, "FUSE congestion_threshold: in-flight async request count at which the kernel marks the FUSE bdi as congested and throttles new submissions. 0 means use the default (3/4 of -fuse.maxBackground). Equivalent to writing /sys/fs/fuse/connections/<id>/congestion_threshold. The kernel silently clamps this to -fuse.maxBackground when set higher.")
+2 -1
View File
@@ -284,7 +284,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
ConcurrentWriteMerge: option.concurrentWriteMerge != nil && *option.concurrentWriteMerge,
WritebackCache: option.writebackCache != nil && *option.writebackCache,
NfsExport: option.nfsExport != nil && *option.nfsExport,
EagerFilerCreate: p.eagerFilerCreate,
EagerFilerCreate: p.eagerFilerCreate || (option.nfsExport != nil && *option.nfsExport && (option.writebackCache == nil || !*option.writebackCache)),
PosixDirNlink: option.posixDirNlink != nil && *option.posixDirNlink,
AccessReport: option.accessReport != nil && *option.accessReport,
AccessReportInterval: *option.accessReportInterval,
@@ -451,6 +451,7 @@ func configureMountMemory(option *MountOptions) error {
}
if *option.memoryLimitMB > 0 {
debug.SetMemoryLimit(*option.memoryLimitMB << 20)
glog.V(0).Infof("Go memory limit: %d MiB from -memoryLimitMB", *option.memoryLimitMB)
}
}
return nil
+95 -29
View File
@@ -1,6 +1,11 @@
package command
import (
"context"
"fmt"
"net"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
@@ -17,6 +22,11 @@ var (
mqBrokerStandaloneOptions MessageQueueBrokerOptions
)
const (
defaultMqBrokerPort = 17777
defaultMqBrokerLogFlushInterval = 5
)
type MessageQueueBrokerOptions struct {
masters map[string]pb.ServerAddress
mastersString *string
@@ -32,6 +42,15 @@ type MessageQueueBrokerOptions struct {
logFlushInterval *int
debug *bool
debugPort *int
// shutdownCtx, when non-nil, stops the broker once cancelled, in addition
// to on interrupt. Set by commands that embed the broker; not a flag.
shutdownCtx context.Context
// bound records whether the gRPC port is bound, so weed mini lists the
// broker only when it runs; not a flag.
bound atomic.Bool
// TLS options listenQueueServer loads for serveQueueServer.
grpcDialOption grpc.DialOption
grpcServerOptions []grpc.ServerOption
}
func init() {
@@ -40,12 +59,12 @@ func init() {
mqBrokerStandaloneOptions.filerGroup = cmdMqBroker.Flag.String("filerGroup", "", "share metadata with other filers in the same filerGroup")
mqBrokerStandaloneOptions.ip = cmdMqBroker.Flag.String("ip", util.DetectedHostAddress(), "broker host address")
mqBrokerStandaloneOptions.ipBind = cmdMqBroker.Flag.String("ip.bind", "", "ip address to bind to. If empty, listen on all interfaces.")
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", 17777, "broker gRPC listen port")
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", defaultMqBrokerPort, "broker gRPC listen port")
mqBrokerStandaloneOptions.dataCenter = cmdMqBroker.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
mqBrokerStandaloneOptions.rack = cmdMqBroker.Flag.String("rack", "", "prefer to write to volumes in this rack")
mqBrokerStandaloneOptions.cpuprofile = cmdMqBroker.Flag.String("cpuprofile", "", "cpu profile output file")
mqBrokerStandaloneOptions.memprofile = cmdMqBroker.Flag.String("memprofile", "", "memory profile output file")
mqBrokerStandaloneOptions.logFlushInterval = cmdMqBroker.Flag.Int("logFlushInterval", 5, "log buffer flush interval in seconds")
mqBrokerStandaloneOptions.logFlushInterval = cmdMqBroker.Flag.Int("logFlushInterval", defaultMqBrokerLogFlushInterval, "log buffer flush interval in seconds")
mqBrokerStandaloneOptions.debug = cmdMqBroker.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
mqBrokerStandaloneOptions.debugPort = cmdMqBroker.Flag.Int("debug.port", 6060, "http port for debugging")
}
@@ -68,20 +87,59 @@ func runMqBroker(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
mqBrokerStandaloneOptions.masters = pb.ServerAddresses(*mqBrokerStandaloneOptions.mastersString).ToAddressMap()
return mqBrokerStandaloneOptions.startQueueServer()
}
func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
*mqBrokerStandaloneOptions.cpuprofile = util.ResolvePath(*mqBrokerStandaloneOptions.cpuprofile)
*mqBrokerStandaloneOptions.memprofile = util.ResolvePath(*mqBrokerStandaloneOptions.memprofile)
grace.SetupProfiling(*mqBrokerStandaloneOptions.cpuprofile, *mqBrokerStandaloneOptions.memprofile)
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.msg_broker")
mqBrokerStandaloneOptions.masters = pb.ServerAddresses(*mqBrokerStandaloneOptions.mastersString).ToAddressMap()
if err := mqBrokerStandaloneOptions.startQueueServer(); err != nil {
glog.Fatalf("%v", err)
}
return true
}
// startQueueServer serves the broker until it is interrupted or shutdownCtx is
// cancelled. It returns an error only when the broker could not start.
func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() error {
grpcL, localL, err := mqBrokerOpt.listenQueueServer()
if err != nil {
return err
}
return mqBrokerOpt.serveQueueServer(grpcL, localL)
}
// listenQueueServer loads the broker's TLS config and binds its gRPC port.
// Bind before creating the broker: it registers with the master as soon as
// it exists, and a broker that cannot serve must not.
func (mqBrokerOpt *MessageQueueBrokerOptions) listenQueueServer() (grpcL, localL net.Listener, err error) {
mqBrokerOpt.bound.Store(false)
// Returned, not fatal: a gateway's broker must not take the gateway down.
if mqBrokerOpt.grpcDialOption, err = security.TryLoadClientTLS(util.GetViper(), "grpc.msg_broker", "grpc.msg_broker"); err != nil {
return nil, nil, fmt.Errorf("message queue broker gRPC client TLS: %v", err)
}
tlsCreds, tlsVerify, err := security.TryLoadServerTLS(util.GetViper(), "grpc.msg_broker")
if err != nil {
return nil, nil, fmt.Errorf("message queue broker gRPC server TLS: %v", err)
}
mqBrokerOpt.grpcServerOptions = append([]grpc.ServerOption{tlsCreds, tlsVerify}, broker.GrpcServerOptions()...)
// The loopback companion listener is only kept while -ip.bind is unset.
// An explicit -ip.bind pins the port to exactly that address.
listenOnLocalhost := *mqBrokerOpt.ipBind == ""
if mqBrokerOpt.listenOnLocalhost != nil {
listenOnLocalhost = *mqBrokerOpt.listenOnLocalhost
}
grpcL, localL, err = util.NewIpAndLocalListeners(*mqBrokerOpt.ipBind, *mqBrokerOpt.port, 0, listenOnLocalhost)
if err != nil {
return nil, nil, fmt.Errorf("message queue broker failed to listen on grpc port %d: %v", *mqBrokerOpt.port, err)
}
mqBrokerOpt.bound.Store(true)
return grpcL, localL, nil
}
func (mqBrokerOpt *MessageQueueBrokerOptions) serveQueueServer(grpcL, localL net.Listener) error {
qs, err := broker.NewMessageBroker(&broker.MessageQueueBrokerOption{
Masters: mqBrokerOpt.masters,
FilerGroup: *mqBrokerOpt.filerGroup,
@@ -92,34 +150,30 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
Ip: *mqBrokerOpt.ip,
Port: *mqBrokerOpt.port,
LogFlushInterval: *mqBrokerOpt.logFlushInterval,
}, grpcDialOption)
}, mqBrokerOpt.grpcDialOption)
if err != nil {
glog.Fatalf("failed to create new message broker for queue server: %v", err)
}
// The loopback companion listener is only kept while -ip.bind is unset.
// An explicit -ip.bind pins the port to exactly that address.
listenOnLocalhost := *mqBrokerOpt.ipBind == ""
if mqBrokerOpt.listenOnLocalhost != nil {
listenOnLocalhost = *mqBrokerOpt.listenOnLocalhost
}
// start grpc listener
grpcL, localL, err := util.NewIpAndLocalListeners(*mqBrokerOpt.ipBind, *mqBrokerOpt.port, 0, listenOnLocalhost)
if err != nil {
glog.Fatalf("failed to listen on grpc port %d: %v", *mqBrokerOpt.port, err)
mqBrokerOpt.bound.Store(false)
grpcL.Close()
if localL != nil {
localL.Close()
}
return fmt.Errorf("failed to create new message broker for queue server: %v", err)
}
// Create main gRPC server
grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.msg_broker"))
serverOptions := mqBrokerOpt.grpcServerOptions
grpcS := pb.NewGrpcServer(serverOptions...)
mq_pb.RegisterSeaweedMessagingServer(grpcS, qs)
reflection.Register(grpcS)
grace.OnInterrupt(grpcS.Stop)
// Start localhost listener if available
var localGrpcS *grpc.Server
if localL != nil {
localGrpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.msg_broker"))
localGrpcS = pb.NewGrpcServer(serverOptions...)
mq_pb.RegisterSeaweedMessagingServer(localGrpcS, qs)
reflection.Register(localGrpcS)
grace.OnInterrupt(localGrpcS.Stop)
go func() {
glog.V(0).Infof("MQ Broker listening on localhost:%d", *mqBrokerOpt.port)
if err := localGrpcS.Serve(localL); err != nil && err != grpc.ErrServerStopped {
@@ -127,12 +181,24 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
}
}()
}
// Hooks run last-registered first: flush the partitions, then drop the connections.
grace.OnInterrupt(qs.Stop)
if mqBrokerOpt.shutdownCtx != nil {
go func() {
<-mqBrokerOpt.shutdownCtx.Done()
qs.Stop()
if localGrpcS != nil {
localGrpcS.Stop()
}
grpcS.Stop()
}()
}
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ipBind, *mqBrokerOpt.port)
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
glog.Errorf("Failed to serve MQ Broker: %v", err)
}
return true
return nil
}
+87
View File
@@ -0,0 +1,87 @@
package command
import (
"context"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
func testBrokerOptions(port int) *MessageQueueBrokerOptions {
bind := "127.0.0.1"
empty := ""
noLocalhost := false
flushInterval := 5
return &MessageQueueBrokerOptions{
// Nothing listens here; the broker keeps retrying until stopped.
masters: map[string]pb.ServerAddress{"127.0.0.1:1": "127.0.0.1:1"},
filerGroup: &empty,
ip: &bind,
ipBind: &bind,
listenOnLocalhost: &noLocalhost,
port: &port,
dataCenter: &empty,
rack: &empty,
logFlushInterval: &flushInterval,
}
}
func freePort(t *testing.T) int {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
return port
}
func TestQueueServerReturnsErrorOnOccupiedPort(t *testing.T) {
opt := testBrokerOptions(holdPort(t))
errCh := make(chan error, 1)
go func() { errCh <- opt.startQueueServer() }()
select {
case err := <-errCh:
if err == nil {
t.Fatal("startQueueServer on an occupied port returned nil")
}
case <-time.After(5 * time.Second):
t.Fatal("startQueueServer did not return for an occupied port")
}
}
func TestQueueServerStopsOnShutdownCtx(t *testing.T) {
port := freePort(t)
opt := testBrokerOptions(port)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
opt.shutdownCtx = ctx
errCh := make(chan error, 1)
go func() { errCh <- opt.startQueueServer() }()
deadline := time.Now().Add(5 * time.Second)
for {
conn, err := net.Dial("tcp", pb.NewServerAddress("127.0.0.1", port, 0).String())
if err == nil {
conn.Close()
break
}
if time.Now().After(deadline) {
t.Fatalf("broker never listened on %d: %v", port, err)
}
time.Sleep(20 * time.Millisecond)
}
cancel()
select {
case err := <-errCh:
if err != nil {
t.Fatalf("startQueueServer = %v after a clean stop", err)
}
case <-time.After(10 * time.Second):
t.Fatal("broker did not stop when shutdownCtx was cancelled")
}
}
+157 -2
View File
@@ -40,7 +40,9 @@ import (
)
var (
s3StandaloneOptions S3Options
s3StandaloneOptions S3Options
s3StandaloneMqBrokerOptions MessageQueueBrokerOptions
s3StandaloneStartMqBroker *bool
)
// S3Options holds CLI flags for the S3 gateway.
@@ -114,6 +116,12 @@ type S3Options struct {
icebergBound atomic.Bool
lanceBound atomic.Bool
lanceServer *lance.Server
// lanceWorkerKey is set by mini for the weed-worker it starts when the
// cluster has no jwt.filer_signing.key; not a flag.
lanceWorkerKey security.SigningKey
// mqBroker, when set by the command, is the message queue broker started
// beside this gateway once the filer is reached; not a flag.
mqBroker *MessageQueueBrokerOptions
}
func init() {
@@ -166,6 +174,30 @@ func init() {
s3StandaloneOptions.routedLookupTimeout = cmdS3.Flag.Duration("routedLookupTimeout", defaultS3RoutedLookupTimeout, s3RoutedLookupTimeoutUsage)
s3StandaloneOptions.unreachableOwnerTTL = cmdS3.Flag.Duration("unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage)
s3StandaloneOptions.volumeLookupTimeout = cmdS3.Flag.Duration("volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage)
s3StandaloneStartMqBroker = cmdS3.Flag.Bool("mq.broker", false, mqBrokerBesideS3Usage)
s3StandaloneMqBrokerOptions.port = cmdS3.Flag.Int("mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
}
const mqBrokerBesideS3Usage = "start a message queue broker beside the S3 gateway, on its own gRPC port; it joins the cluster like any other broker. When not set, it starts only if grpc.msg_broker has a cert and key in security.toml"
// mqBrokerTLSConfigured reports whether security.toml gives the broker a
// server cert and key. Without them the broker serves any peer.
func mqBrokerTLSConfigured() bool {
v := util.GetViper()
return v.GetString("grpc.msg_broker.cert") != "" && v.GetString("grpc.msg_broker.key") != ""
}
// wantsMqBrokerBesideS3 decides the broker beside a gateway: a flag given on
// the command line wins, and an unset one starts it only with TLS.
func wantsMqBrokerBesideS3(flagName string, value, passed bool) bool {
if passed {
return value
}
if mqBrokerTLSConfigured() {
return true
}
glog.V(0).Infof("message queue broker beside the S3 gateway is off: grpc.msg_broker TLS is not configured; -%s=true runs it without TLS", flagName)
return false
}
var cmdS3 = &Command{
@@ -256,6 +288,13 @@ var cmdS3 = &Command{
and no configuration is available from the filer. This provides a simple way
to get started without requiring configuration files.
When grpc.msg_broker has a cert and key in security.toml, the gateway
also runs a message queue broker on -mq.broker.port (17777), a separate
gRPC server that finds the masters through the filer and joins the
cluster like any other broker. -mq.broker=true runs it without TLS too,
and -mq.broker=false never runs it. If the broker cannot start, for
example because the port is taken, the gateway logs it and keeps serving.
`,
}
@@ -275,6 +314,13 @@ func runS3(cmd *Command, args []string) bool {
}
go stats_collect.StartMetricsServer(*s3StandaloneOptions.metricsHttpIp, *s3StandaloneOptions.metricsHttpPort)
if wantsMqBrokerBesideS3("mq.broker", *s3StandaloneStartMqBroker, isFlagExplicitlySet(cmdS3, "mq.broker")) {
s3StandaloneOptions.mqBroker = s3StandaloneOptions.brokerBeside(&s3StandaloneMqBrokerOptions)
if err := s3StandaloneOptions.checkMqBrokerPort("mq.broker.port", isFlagExplicitlySet(cmdS3, "mq.broker.port")); err != nil {
glog.Fatalf("%v", err)
}
}
return s3StandaloneOptions.startS3Server()
}
@@ -364,6 +410,7 @@ func (s3opt *S3Options) startS3Server() bool {
}
}
adoptFilerDigest(*s3opt.filer, filerDigest)
s3opt.startMqBroker(masterAddresses, filerGroup)
go stats_collect.LoopPushingMetric("s3", stats_collect.SourceName(uint32(*s3opt.port)), metricsAddress, metricsIntervalSec)
@@ -627,6 +674,105 @@ func (s3opt *S3Options) startS3Server() bool {
}
// gatewayPorts lists the ports the gateway binds itself, the derived gRPC
// port included.
func (s3opt *S3Options) gatewayPorts() []int {
ports := []int{*s3opt.port}
grpcPort := 10000 + *s3opt.port
if s3opt.portGrpc != nil && *s3opt.portGrpc != 0 {
grpcPort = *s3opt.portGrpc
}
ports = append(ports, grpcPort)
if s3opt.tlsPrivateKey != nil && *s3opt.tlsPrivateKey != "" && s3opt.portHttps != nil && *s3opt.portHttps > 0 {
ports = append(ports, *s3opt.portHttps)
}
for _, p := range []*int{s3opt.portIceberg, s3opt.portLance, s3opt.metricsHttpPort} {
if p != nil && *p > 0 {
ports = append(ports, *p)
}
}
return ports
}
// checkMqBrokerPort keeps the broker off the gateway's own ports and off
// processPorts, those of the servers started with it: the broker can bind
// first, and a server exits when its port is taken. A default port that
// clashes drops the broker; a port given as flagName is an error.
func (s3opt *S3Options) checkMqBrokerPort(flagName string, explicit bool, processPorts ...int) error {
b := s3opt.mqBroker
if b == nil {
return nil
}
for _, port := range append(s3opt.gatewayPorts(), processPorts...) {
if port != *b.port {
continue
}
if explicit {
return fmt.Errorf("-%s=%d is also a port of the S3 gateway or a server started with it", flagName, port)
}
glog.Warningf("not starting the message queue broker: its default port %d is a port of the S3 gateway or a server started with it; set -%s to run it", port, flagName)
s3opt.mqBroker = nil
return nil
}
return nil
}
// brokerBeside points b at the address this gateway binds and advertises.
// Call it before startS3Server, which rewrites an empty -ip.bind.
func (s3opt *S3Options) brokerBeside(b *MessageQueueBrokerOptions) *MessageQueueBrokerOptions {
advertised := (&s3api.S3ApiServerOption{Ip: *s3opt.ip, BindIp: *s3opt.bindIp}).AdvertisedHost()
bindIp := *s3opt.bindIp
listenOnLocalhost := bindIp == ""
if s3opt.listenOnLocalhost != nil {
listenOnLocalhost = *s3opt.listenOnLocalhost
}
b.ip = &advertised
b.ipBind = &bindIp
b.listenOnLocalhost = &listenOnLocalhost
b.dataCenter = s3opt.dataCenter
if b.rack == nil {
b.rack = new(string)
}
if b.logFlushInterval == nil {
flushInterval := defaultMqBrokerLogFlushInterval
b.logFlushInterval = &flushInterval
}
return b
}
// startMqBroker starts the gateway's broker on its own port and lifecycle. A
// broker that cannot start is logged and the gateway keeps serving.
func (s3opt *S3Options) startMqBroker(masters []pb.ServerAddress, filerGroup string) {
b := s3opt.mqBroker
if b == nil {
return
}
if len(masters) == 0 {
glog.Warningf("S3 gateway not starting its message queue broker: filers %s reported no masters", *s3opt.filer)
return
}
b.masters = make(map[string]pb.ServerAddress, len(masters))
for _, master := range masters {
b.masters[string(master)] = master
}
b.filerGroup = &filerGroup
b.shutdownCtx = s3opt.shutdownCtx
// Bind here, before the gateway serves, so once the S3 port answers
// b.bound is final, as for the auxiliary catalogs.
grpcL, localL, err := b.listenQueueServer()
if err != nil {
glog.Errorf("S3 gateway continues without its message queue broker: %v", err)
return
}
done := trackMiniClient()
go func() {
defer done()
if err := b.serveQueueServer(grpcL, localL); err != nil {
glog.Errorf("S3 gateway continues without its message queue broker: %v", err)
}
}()
}
func (s3opt *S3Options) newShutdown(stopGrpc func(), s3ApiServer *s3api.S3ApiServer, httpServers []*http.Server) func() {
shutdown := newGracefulShutdown(stopGrpc, s3ApiServer.Shutdown, httpServers...)
var cancelled <-chan struct{}
@@ -748,7 +894,16 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, liste
func (s3opt *S3Options) newLanceServer(s3ApiServer *s3api.S3ApiServer) *lance.Server {
lanceServer := lance.NewServer(s3ApiServer, s3ApiServer)
lanceServer.SetCredentialValidator(s3ApiServer)
lanceServer.SetSigningKey(s3ApiServer.FilerSigningKey)
signingKey := s3ApiServer.FilerSigningKey
if workerKey := s3opt.lanceWorkerKey; len(workerKey) > 0 {
signingKey = func() security.SigningKey {
if key := s3ApiServer.FilerSigningKey(); len(key) > 0 {
return key
}
return workerKey
}
}
lanceServer.SetSigningKey(signingKey)
if s3opt.vendsCredentials() {
lanceServer.SetCredentialVendor(lanceCredentialVendor{s3ApiServer})
}
+252
View File
@@ -0,0 +1,252 @@
package command
import (
"context"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestS3MqBrokerFlagDefaults(t *testing.T) {
for name, want := range map[string]string{
"mq.broker": "false",
"mq.broker.port": "17777",
} {
flag := cmdS3.Flag.Lookup(name)
if flag == nil {
t.Fatalf("weed s3 does not expose -%s", name)
}
if flag.DefValue != want {
t.Errorf("-%s default = %q, want %q", name, flag.DefValue, want)
}
}
}
// withMqBrokerTLS sets or clears grpc.msg_broker cert and key for the test.
func withMqBrokerTLS(t *testing.T, on bool) {
t.Helper()
v := util.GetViper()
cert, key := "", ""
if on {
cert, key = "/etc/seaweedfs/broker.crt", "/etc/seaweedfs/broker.key"
}
v.Set("grpc.msg_broker.cert", cert)
v.Set("grpc.msg_broker.key", key)
t.Cleanup(func() {
v.Set("grpc.msg_broker.cert", "")
v.Set("grpc.msg_broker.key", "")
})
}
// The cases the flag of weed s3, weed server and weed filer share.
var mqBrokerDefaultCases = []struct {
name string
tls, value, passed bool
want bool
}{
{"unset with TLS", true, false, false, true},
{"unset without TLS", false, false, false, false},
{"explicit true without TLS", false, true, true, true},
{"explicit false with TLS", true, false, true, false},
}
func TestS3MqBrokerStartsByDefaultOnlyWithTLS(t *testing.T) {
for _, tc := range mqBrokerDefaultCases {
t.Run(tc.name, func(t *testing.T) {
withMqBrokerTLS(t, tc.tls)
if got := wantsMqBrokerBesideS3("mq.broker", tc.value, tc.passed); got != tc.want {
t.Errorf("weed s3 runs broker %v, want %v", got, tc.want)
}
})
}
}
func TestS3BrokerBesideAdvertisesGatewayAddress(t *testing.T) {
detected := util.DetectedHostAddress()
for _, tc := range []struct {
name, ip, bindIp string
wantIp string
wantLocalhostPeer bool
}{
{"defaults bind everywhere and advertise the detected address", "", "", detected, true},
{"explicit bind is advertised and pinned", "", "10.0.0.5", "10.0.0.5", false},
{"advertised ip wins over a wildcard bind", "s3.example.com", "0.0.0.0", "s3.example.com", false},
} {
t.Run(tc.name, func(t *testing.T) {
ip, bindIp, dc := tc.ip, tc.bindIp, "dc1"
s3opt := &S3Options{ip: &ip, bindIp: &bindIp, dataCenter: &dc}
b := s3opt.brokerBeside(&MessageQueueBrokerOptions{})
if *b.ip != tc.wantIp {
t.Errorf("broker ip = %q, want %q", *b.ip, tc.wantIp)
}
if *b.ipBind != tc.bindIp {
t.Errorf("broker ip.bind = %q, want %q", *b.ipBind, tc.bindIp)
}
if *b.listenOnLocalhost != tc.wantLocalhostPeer {
t.Errorf("broker listenOnLocalhost = %v, want %v", *b.listenOnLocalhost, tc.wantLocalhostPeer)
}
if *b.dataCenter != "dc1" || *b.rack != "" || *b.logFlushInterval != defaultMqBrokerLogFlushInterval {
t.Errorf("broker dc/rack/flush = %q/%q/%d", *b.dataCenter, *b.rack, *b.logFlushInterval)
}
// startS3Server rewrites an empty -ip.bind; the broker keeps its copy.
bindIp = "0.0.0.0"
if *b.ipBind != tc.bindIp {
t.Errorf("broker ip.bind followed the gateway's rewrite to %q", *b.ipBind)
}
})
}
}
// startMqBroker hands the broker the masters and filer group the gateway read
// from its filer, and ties it to the gateway's shutdown.
func startTestGatewayBroker(t *testing.T, port int) *MessageQueueBrokerOptions {
t.Helper()
savedClients, savedClusterCtx := miniClients, MiniClusterCtx
t.Cleanup(func() { miniClients, MiniClusterCtx = savedClients, savedClusterCtx })
clusterCtx, stopCluster := context.WithCancel(context.Background())
t.Cleanup(stopCluster)
MiniClusterCtx = clusterCtx
resetMiniClients()
filer := "127.0.0.1:2"
b := testBrokerOptions(port)
s3opt := &S3Options{filer: &filer, shutdownCtx: miniClientsCtx(), mqBroker: b}
s3opt.startMqBroker([]pb.ServerAddress{"127.0.0.1:1"}, "group1")
if _, ok := b.masters["127.0.0.1:1"]; !ok || len(b.masters) != 1 || *b.filerGroup != "group1" {
t.Fatalf("broker masters %v filerGroup %q, want the filer's", b.masters, *b.filerGroup)
}
return b
}
func waitMiniClientsDrained(t *testing.T, within time.Duration) bool {
t.Helper()
clients := miniClients
drained := make(chan struct{})
go func() {
clients.wg.Wait()
close(drained)
}()
select {
case <-drained:
return true
case <-time.After(within):
return false
}
}
func TestS3GatewaySurvivesBrokerThatFailsToStart(t *testing.T) {
b := startTestGatewayBroker(t, holdPort(t))
// startMqBroker returned and the process, gateway included, is still here.
if b.bound.Load() {
t.Error("broker on an occupied port reported bound")
}
if !waitMiniClientsDrained(t, 5*time.Second) {
t.Fatal("broker on an occupied port did not return")
}
}
// A bad grpc.msg_broker TLS config used to exit the process from inside the
// broker; the gateway must log it and keep serving.
func TestS3GatewaySurvivesBrokerTLSConfigError(t *testing.T) {
v := util.GetViper()
v.Set("grpc.msg_broker.cert", "/nonexistent/broker.crt")
t.Cleanup(func() { v.Set("grpc.msg_broker.cert", "") })
port := freePort(t)
b := startTestGatewayBroker(t, port)
if b.bound.Load() {
t.Error("broker with a bad TLS config reported bound")
}
if !waitMiniClientsDrained(t, 5*time.Second) {
t.Fatal("broker with a bad TLS config did not return")
}
l, err := net.Listen("tcp", pb.NewServerAddress("127.0.0.1", port, 0).String())
if err != nil {
t.Fatalf("broker port %d left bound after the TLS error: %v", port, err)
}
l.Close()
}
func TestS3GatewayBrokerStopsWithGateway(t *testing.T) {
b := startTestGatewayBroker(t, freePort(t))
if !b.bound.Load() {
t.Fatal("broker not bound once startMqBroker returned")
}
if waitMiniClientsDrained(t, 300*time.Millisecond) {
t.Fatal("broker returned before the gateway shut down")
}
triggerMiniClientsShutdown(10 * time.Second)
if !waitMiniClientsDrained(t, time.Second) {
t.Fatal("broker still running after the gateway shut down")
}
}
func TestS3GatewayWithoutMastersSkipsBroker(t *testing.T) {
filer := "127.0.0.1:2"
b := testBrokerOptions(holdPort(t))
b.masters = nil
s3opt := &S3Options{filer: &filer, mqBroker: b}
s3opt.startMqBroker(nil, "")
if b.masters != nil {
t.Fatal("broker was started without masters")
}
}
func gatewayWithBroker(httpPort, grpcPort, brokerPort int) *S3Options {
filer, empty, zero := "127.0.0.1:2", "", 0
return &S3Options{
filer: &filer, port: &httpPort, portGrpc: &grpcPort, portHttps: &zero,
portIceberg: &zero, portLance: &zero, tlsPrivateKey: &empty,
mqBroker: testBrokerOptions(brokerPort),
}
}
func TestS3DefaultBrokerYieldsToGatewayPorts(t *testing.T) {
brokerPort := freePort(t)
for _, tc := range []struct {
name string
httpPort, grpcPort int
}{
{"-port whose derived gRPC port is the broker's", brokerPort - 10000, 0},
{"-port.grpc on the broker port", 8333, brokerPort},
{"-port on the broker port", brokerPort, 0},
} {
t.Run(tc.name, func(t *testing.T) {
s3opt := gatewayWithBroker(tc.httpPort, tc.grpcPort, brokerPort)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false); err != nil {
t.Fatalf("default broker port clash returned %v, want the broker skipped", err)
}
if s3opt.mqBroker != nil {
t.Fatal("broker kept a port the gateway binds")
}
// Nothing binds for the skipped broker, so the gateway still gets its port.
s3opt.startMqBroker([]pb.ServerAddress{"127.0.0.1:1"}, "")
l, err := net.Listen("tcp", pb.NewServerAddress("127.0.0.1", brokerPort, 0).String())
if err != nil {
t.Fatalf("gateway port %d taken: %v", brokerPort, err)
}
l.Close()
})
}
}
func TestS3ExplicitBrokerPortClashIsRejected(t *testing.T) {
for _, s3opt := range []*S3Options{
gatewayWithBroker(7777, 0, 17777),
gatewayWithBroker(8333, 17777, 17777),
} {
if err := s3opt.checkMqBrokerPort("mq.broker.port", true); err == nil {
t.Errorf("explicit -mq.broker.port on gateway port of %d/%d was accepted", *s3opt.port, *s3opt.portGrpc)
}
}
}
func TestS3BrokerPortOffTheGatewayIsKept(t *testing.T) {
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", true); err != nil || s3opt.mqBroker == nil {
t.Fatalf("broker on a free port dropped: %v", err)
}
}
+35
View File
@@ -200,6 +200,41 @@ upsertQuery = """
meta=EXCLUDED.meta
"""
[postgres_flat]
# Rows are keyed by their full path, which inside a bucket's table is the
# object key. Give it a database or schema apart from the postgres and
# postgres2 stores. The path index caps a path at about 2700 bytes.
enabled = false
createTable = """
CREATE TABLE IF NOT EXISTS "%s" (
path TEXT COLLATE "C" PRIMARY KEY,
directory TEXT COLLATE "C" NOT NULL,
name TEXT COLLATE "C" NOT NULL,
meta bytea,
UNIQUE (directory, name)
);
"""
hostname = "localhost"
port = 5432
username = "postgres"
password = ""
database = "postgres" # create or use an existing database
schema = ""
sslmode = "disable"
# sslcert = "/path/to/client.crt"
# sslkey = "/path/to/client.key"
# sslrootcert = "/path/to/ca.crt"
# sslcrl = "/path/to/client.crl"
connection_max_idle = 50
connection_max_lifetime_seconds = 300
pgbouncer_compatible = false
enableUpsert = true
upsertQuery = """
INSERT INTO "%[1]s" (path, directory, name, meta)
VALUES($1, $2, $3, $4)
ON CONFLICT (path) DO UPDATE SET meta=EXCLUDED.meta
"""
[cassandra2]
# CREATE TABLE filemeta (
# dirhash bigint,
+72 -5
View File
@@ -55,6 +55,9 @@ var cmdServer = &Command{
Optionally, a filer server can be started.
Also optionally, a S3 gateway can be started.
When grpc.msg_broker has a cert and key in security.toml, a S3 gateway
brings a message queue broker on -mq.broker.port; use -mq.broker=false
to leave it out, or -mq.broker=true to run a broker without TLS.
`,
}
@@ -71,7 +74,7 @@ var (
volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
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.")
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, until free space is 1% of the disk above the limit.")
serverMetricsHttpPort = cmdServer.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
serverMetricsHttpIp = cmdServer.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
serverGrpcLocalSocketDir = cmdServer.Flag.String("grpc.localSocketDir", "/tmp", "directory for the local gRPC Unix sockets; default to /tmp. Point it at a directory a temp cleaner does not sweep, such as /run/seaweedfs")
@@ -84,7 +87,7 @@ var (
isStartingSftp = cmdServer.Flag.Bool("sftp", false, "whether to start Sftp server")
isStartingIam = cmdServer.Flag.Bool("iam", false, "whether to start IAM service")
isStartingWebDav = cmdServer.Flag.Bool("webdav", false, "whether to start WebDAV gateway")
isStartingMqBroker = cmdServer.Flag.Bool("mq.broker", false, "whether to start message queue broker")
isStartingMqBroker = cmdServer.Flag.Bool("mq.broker", false, "whether to start message queue broker; when not set, -s3 starts one beside the gateway if grpc.msg_broker has a cert and key in security.toml")
isStartingMqAgent = cmdServer.Flag.Bool("mq.agent", false, "whether to start message queue agent")
False = false
@@ -249,14 +252,65 @@ func init() {
webdavOptions.filerRootPath = cmdServer.Flag.String("webdav.filer.path", "/", "use this remote path from filer server")
webdavOptions.idleTimeout = cmdServer.Flag.Int("webdav.idleTimeout", 10, "connection idle seconds")
mqBrokerOptions.port = cmdServer.Flag.Int("mq.broker.port", 17777, "message queue broker gRPC listen port")
mqBrokerOptions.logFlushInterval = cmdServer.Flag.Int("mq.broker.logFlushInterval", 5, "log buffer flush interval in seconds")
mqBrokerOptions.port = cmdServer.Flag.Int("mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
mqBrokerOptions.logFlushInterval = cmdServer.Flag.Int("mq.broker.logFlushInterval", defaultMqBrokerLogFlushInterval, "log buffer flush interval in seconds")
mqAgentServerOptions.brokersString = cmdServer.Flag.String("mq.agent.brokers", "localhost:17777", "comma-separated message queue brokers")
mqAgentServerOptions.port = cmdServer.Flag.Int("mq.agent.port", 16777, "message queue agent gRPC listen port")
}
// serverRunsMqBrokerBesideS3 reports whether the S3 gateway starts the broker.
// -mq.broker (or -mq.agent) starts it on its own and a failure to start is
// fatal; -s3 with -mq.broker unset brings it along when grpc.msg_broker TLS
// is configured, and a failure is only logged, so a host that already runs a
// broker on the port keeps its gateway.
func serverRunsMqBrokerBesideS3(s3, broker, brokerFlagPassed bool) bool {
return s3 && !broker && wantsMqBrokerBesideS3("mq.broker", broker, brokerFlagPassed)
}
// withGrpc is a server's port and its gRPC port, derived when unset.
func withGrpc(port, portGrpc *int) []int {
if *portGrpc != 0 {
return []int{*port, *portGrpc}
}
return []int{*port, 10000 + *port}
}
// serverPortsBesideS3 lists the ports of the other servers weed server
// starts, derived gRPC ports included.
func serverPortsBesideS3() []int {
ports := []int{*serverMetricsHttpPort}
if *serverOptions.debug {
ports = append(ports, *serverOptions.debugPort)
}
if *isStartingMasterServer {
ports = append(ports, withGrpc(masterOptions.port, masterOptions.portGrpc)...)
}
if *isStartingVolumeServer {
ports = append(ports, withGrpc(serverOptions.v.port, serverOptions.v.portGrpc)...)
if *serverOptions.v.publicPort != 0 {
ports = append(ports, *serverOptions.v.publicPort)
}
}
if *isStartingFiler {
ports = append(ports, withGrpc(filerOptions.port, filerOptions.portGrpc)...)
if *filerOptions.publicPort != 0 {
ports = append(ports, *filerOptions.publicPort)
}
}
if *isStartingWebDav {
ports = append(ports, *webdavOptions.port)
}
if *isStartingSftp {
ports = append(ports, *sftpOptions.port)
}
if *isStartingIam {
ports = append(ports, *iamOptions.port)
}
return ports
}
// isServerFlagPassed checks if a specific flag was passed on the command line
func isServerFlagPassed(name string) bool {
found := false
@@ -307,6 +361,12 @@ func runServer(cmd *Command, args []string) bool {
*isStartingMqBroker = true
*isStartingFiler = true
}
if serverRunsMqBrokerBesideS3(*isStartingS3, *isStartingMqBroker, isServerFlagPassed("mq.broker")) {
s3Options.mqBroker = &mqBrokerOptions
if err := s3Options.checkMqBrokerPort("mq.broker.port", isServerFlagPassed("mq.broker.port"), serverPortsBesideS3()...); err != nil {
glog.Fatalf("%v", err)
}
}
var actualPeersForComponents string
var embeddedMaster atomic.Pointer[weed_server.MasterServer]
@@ -420,6 +480,11 @@ func runServer(cmd *Command, args []string) bool {
iamOptions.filer = &filerAddress
webdavOptions.filer = &filerAddress
mqBrokerOptions.filerGroup = filerOptions.filerGroup
if s3Options.mqBroker != nil {
// The broker beside the gateway binds where -s3.ip.bind puts it.
s3Options.brokerBeside(s3Options.mqBroker)
mqBrokerOptions.dataCenter = serverDataCenter
}
go stats_collect.StartMetricsServer(*serverMetricsHttpIp, *serverMetricsHttpPort)
@@ -532,7 +597,9 @@ func runServer(cmd *Command, args []string) bool {
if *isStartingMqBroker {
go func() {
time.Sleep(2 * time.Second)
mqBrokerOptions.startQueueServer()
if err := mqBrokerOptions.startQueueServer(); err != nil {
glog.Fatalf("%v", err)
}
}()
}
+87
View File
@@ -29,6 +29,93 @@ func TestServerGatewayDataCenterFlags(t *testing.T) {
}
}
func TestServerStartsAtMostOneMqBroker(t *testing.T) {
for _, tc := range []struct {
name string
s3, broker, passed, agent, tls bool
wantStandalone, wantBesideS3 bool
}{
{name: "nothing", tls: true},
{name: "-s3 with TLS", s3: true, tls: true, wantBesideS3: true},
{name: "-s3 without TLS", s3: true},
{name: "-s3 -mq.broker=false with TLS", s3: true, passed: true, tls: true},
{name: "-s3 -mq.broker without TLS", s3: true, broker: true, passed: true, wantStandalone: true},
{name: "-mq.broker", broker: true, passed: true, wantStandalone: true},
{name: "-mq.broker=false", passed: true, tls: true},
{name: "-s3 -mq.agent", s3: true, agent: true, tls: true, wantStandalone: true},
{name: "-s3 -mq.agent -mq.broker=false", s3: true, passed: true, agent: true, tls: true, wantStandalone: true},
} {
t.Run(tc.name, func(t *testing.T) {
withMqBrokerTLS(t, tc.tls)
// runServer turns -mq.agent into -mq.broker before deciding.
broker := tc.broker || tc.agent
besideS3 := serverRunsMqBrokerBesideS3(tc.s3, broker, tc.passed)
if broker != tc.wantStandalone || besideS3 != tc.wantBesideS3 {
t.Fatalf("standalone %v beside S3 %v, want %v %v", broker, besideS3, tc.wantStandalone, tc.wantBesideS3)
}
if broker && besideS3 {
t.Fatal("two brokers would start")
}
})
}
}
// weed server -s3 -filer.port.public=17777, which -s3 turns the filer on for.
func TestServerDefaultBrokerYieldsToFilerPublicPort(t *testing.T) {
startFiler, publicPort := *isStartingFiler, *filerOptions.publicPort
t.Cleanup(func() { *isStartingFiler, *filerOptions.publicPort = startFiler, publicPort })
*isStartingFiler, *filerOptions.publicPort = true, 17777
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false, serverPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on the filer public port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", true, serverPortsBesideS3()...); err == nil {
t.Fatal("explicit -mq.broker.port on the filer public port was accepted")
}
}
func TestServerDefaultBrokerYieldsToVolumeGrpcPort(t *testing.T) {
volumePort, volumeGrpcPort, startVolume := *serverOptions.v.port, *serverOptions.v.portGrpc, *isStartingVolumeServer
t.Cleanup(func() {
*serverOptions.v.port, *serverOptions.v.portGrpc, *isStartingVolumeServer = volumePort, volumeGrpcPort, startVolume
})
*serverOptions.v.port, *serverOptions.v.portGrpc, *isStartingVolumeServer = 7777, 0, true
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false, serverPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on the volume gRPC port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", true, serverPortsBesideS3()...); err == nil {
t.Fatal("explicit -mq.broker.port on the volume gRPC port was accepted")
}
publicPort := *serverOptions.v.publicPort
t.Cleanup(func() { *serverOptions.v.publicPort = publicPort })
*serverOptions.v.port, *serverOptions.v.publicPort = 8080, 17777
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false, serverPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on the volume public port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
}
func TestServerMqBrokerFlagDefaults(t *testing.T) {
for name, want := range map[string]string{
"mq.broker": "false",
"mq.broker.port": "17777",
} {
flag := cmdServer.Flag.Lookup(name)
if flag == nil {
t.Fatalf("weed server does not expose -%s", name)
}
if flag.DefValue != want {
t.Errorf("-%s default = %q, want %q", name, flag.DefValue, want)
}
}
}
func TestIdleTimeoutSeconds(t *testing.T) {
if got := idleTimeoutSeconds(nil); got != 10*time.Second {
t.Fatalf("idleTimeoutSeconds(nil) = %v, want 10s", got)
+1 -1
View File
@@ -271,7 +271,7 @@ var (
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.")
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, until free space is 1% of the disk above the limit.")
)
func runVolume(cmd *Command, args []string) bool {
+2 -3
View File
@@ -7,6 +7,7 @@ import (
"strings"
"sync"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
@@ -14,7 +15,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
@@ -383,8 +383,7 @@ func (cm *CredentialManager) LoadS3ConfigFile(path string) error {
return fmt.Errorf("read %s: %w", path, err)
}
config := &iam_pb.S3ApiConfiguration{}
opts := protojson.UnmarshalOptions{DiscardUnknown: true, AllowPartial: true}
if err := opts.Unmarshal(content, config); err != nil {
if err := filer.ParseS3ConfigurationFromBytes(content, config); err != nil {
return fmt.Errorf("parse %s: %w", path, err)
}
for _, ident := range config.Identities {
@@ -0,0 +1,26 @@
package credential
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestLoadS3ConfigFileKeepsTheContentOutOfParseErrors(t *testing.T) {
path := filepath.Join(t.TempDir(), "s3.json")
content := `{"identities": [{"name": "a", "credentials": [{"accessKey": "AK", "secretKey": 102030405060708090}]}]}`
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
t.Fatal(err)
}
err := (&CredentialManager{}).LoadS3ConfigFile(path)
if err == nil {
t.Fatal("expected a parse error")
}
if strings.Contains(err.Error(), "102030405060708090") {
t.Fatalf("parse error quotes the secret key: %v", err)
}
if want := "invalid configuration at line 1, column 80: invalid value for string field secretKey"; !strings.HasSuffix(err.Error(), want) {
t.Fatalf("got %v, want it to end with %s", err, want)
}
}
+7 -20
View File
@@ -2,6 +2,7 @@ package credential
import (
"context"
"slices"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
@@ -90,18 +91,11 @@ func TestCredentialManagerCreation(t *testing.T) {
}
func TestCredentialInterface(t *testing.T) {
// Skip if no stores are registered
if len(Stores) == 0 {
t.Skip("No credential stores registered - for full testing see test/ package")
if !slices.Contains(GetAvailableStores(), StoreTypeMemory) {
t.Skip("memory store not registered - for full testing see test/ package")
}
// Test the interface with the first available store
availableStores := GetAvailableStores()
if len(availableStores) == 0 {
t.Skip("No stores available for testing")
}
testCredentialInterfaceWithStore(t, availableStores[0])
testCredentialInterfaceWithStore(t, StoreTypeMemory)
}
func testCredentialInterfaceWithStore(t *testing.T, storeName CredentialStoreTypeName) {
@@ -173,18 +167,11 @@ func testCredentialInterfaceWithStore(t *testing.T, storeName CredentialStoreTyp
}
func TestCredentialManagerIntegration(t *testing.T) {
// Skip if no stores are registered
if len(Stores) == 0 {
t.Skip("No credential stores registered - for full testing see test/ package")
if !slices.Contains(GetAvailableStores(), StoreTypeMemory) {
t.Skip("memory store not registered - for full testing see test/ package")
}
// Test with the first available store
availableStores := GetAvailableStores()
if len(availableStores) == 0 {
t.Skip("No stores available for testing")
}
storeName := availableStores[0]
storeName := StoreTypeMemory
config := util.GetViper()
cm, err := NewCredentialManager(storeName, config, "test.")
if err != nil {
+33
View File
@@ -0,0 +1,33 @@
package ec
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/ecbalancer"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
// A volume server in maintenance mode refuses every shard copy, so the shell
// planner must not target it even when its slot count says it has room (a
// shard it gives up frees a slot during planning).
func TestEcBalanceSkipsMaintenanceTarget(t *testing.T) {
maintenance := newEcNode("dc1", "rack2", "dn2", 100)
maintenance.Info.Maintenance = true
ecNodes := []*EcNode{
newEcNode("dc1", "rack1", "dn1", 100).addEcVolumeAndShardsForTest(1, "c1", []erasure_coding.ShardId{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}),
maintenance,
newEcNode("dc1", "rack3", "dn3", 100),
newEcNode("dc1", "rack4", "dn4", 100),
}
topo, _, _ := toBalancerTopology(ecNodes, []string{"c1"}, types.HardDriveType, nil, nil, nil, nil)
moves := ecbalancer.Plan(topo, ecbalancer.Options{})
if len(moves) == 0 {
t.Fatal("expected moves off dn1")
}
for _, m := range moves {
if m.TargetNode == "dn2" {
t.Fatalf("shard %d.%d planned onto dn2, which is in maintenance mode", m.VolumeID, m.ShardID)
}
}
}
+2 -2
View File
@@ -358,7 +358,7 @@ func CountShards(ecShardInfos []*master_pb.VolumeEcShardInformationMessage) (cou
}
func CountFreeShardSlots(dn *master_pb.DataNodeInfo, diskType types.DiskType) (count int) {
if dn.DiskInfos == nil {
if dn.DiskInfos == nil || dn.GetMaintenance() {
return 0
}
diskInfo := dn.DiskInfos[string(diskType)]
@@ -1174,7 +1174,7 @@ func toBalancerTopology(ecNodes []*EcNode, collections []string, diskType types.
for _, en := range ecNodes {
rackKey := string(en.DC) + ":" + string(en.Rack)
node := topo.AddNode(en.Info.Id, string(en.DC), rackKey, en.FreeEcSlot)
if noReceiveTargets[en.Info.Id] {
if noReceiveTargets[en.Info.Id] || en.Info.GetMaintenance() {
node.SetNoReceive()
}
// Group by physical machine (host) so shards spread across machines, not just
+19
View File
@@ -9,6 +9,25 @@ import (
"github.com/stretchr/testify/assert"
)
// A volume server in maintenance mode refuses every shard copy, so it has no
// free shard slots whatever its disks report.
func TestCountFreeShardSlotsMaintenance(t *testing.T) {
dn := &master_pb.DataNodeInfo{
Id: "n1",
Maintenance: true,
DiskInfos: map[string]*master_pb.DiskInfo{
"": {MaxVolumeCount: 100},
},
}
if got := CountFreeShardSlots(dn, types.HardDriveType); got != 0 {
t.Errorf("maintenance node free shard slots = %d, want 0", got)
}
dn.Maintenance = false
if got := CountFreeShardSlots(dn, types.HardDriveType); got <= 0 {
t.Errorf("free shard slots after maintenance off = %d, want > 0", got)
}
}
// countFreeShardSlots must report zero for a physically near-full disk even
// though its slot math (MaxVolumeCount - VolumeCount) says it has room, so EC
// placement never piles shards onto a full disk. Mirrors the volume #10160 gate.
+56 -25
View File
@@ -15,20 +15,39 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// RowKey is the primary key of a row: an entry's directory and name, or the
// split of a key-value key that GenDirAndName makes.
type RowKey struct {
DirHash int64
Name string
Directory string
}
func EntryRowKey(dir, name string) RowKey {
return RowKey{DirHash: util.HashStringToLong(dir), Name: name, Directory: dir}
}
// Args returns the key's values in (dirhash, name, directory) order, then extra.
func (k RowKey) Args(extra ...interface{}) []interface{} {
return append([]interface{}{k.DirHash, k.Name, k.Directory}, extra...)
}
// SqlGenerator returns each statement together with its arguments.
type SqlGenerator interface {
GetSqlInsert(tableName string) string
GetSqlUpdate(tableName string) string
GetSqlFind(tableName string) string
// GetSqlFindBatch selects dirhash, name, directory and meta of the rows
// matching count (dirhash, name, directory) triples, as GetSqlFind does one.
GetSqlFindBatch(tableName string, count int) string
GetSqlDelete(tableName string) string
GetSqlDeleteFolderChildren(tableName string) string
GetSqlListExclusive(tableName string) string
GetSqlListInclusive(tableName string) string
GetSqlInsert(tableName string, key RowKey, meta []byte) (string, []interface{})
GetSqlUpdate(tableName string, key RowKey, meta []byte) (string, []interface{})
GetSqlFind(tableName string, key RowKey) (string, []interface{})
// GetSqlFindBatch selects name, directory and meta of the rows of keys.
GetSqlFindBatch(tableName string, keys []RowKey) (string, []interface{})
GetSqlDelete(tableName string, key RowKey) (string, []interface{})
GetSqlDeleteFolderChildren(tableName string, dir string) (string, []interface{})
// GetSqlListExclusive selects name and meta of the entries in dir after
// startFileName whose name is LIKE namePattern, in name order.
GetSqlListExclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{})
GetSqlListInclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{})
// GetSqlScanPage returns the query and arguments selecting dirhash, name,
// directory and meta of up to limit rows after the (dirhash, name) cursor.
GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{})
// directory and meta of up to limit rows after the cursor row.
GetSqlScanPage(tableName string, after RowKey, limit int) (string, []interface{})
GetSqlCreateTable(tableName string) string
GetSqlDropTable(tableName string) string
}
@@ -39,9 +58,13 @@ type AbstractSqlStore struct {
KvDB *sql.DB
// ScanDB, when set, is the pool snapshot scans run on (SQLite's main pool
// is a single connection that a long scan must not hold).
ScanDB *sql.DB
SupportBucketTable bool
SkipDDL bool
ScanDB *sql.DB
SupportBucketTable bool
SkipDDL bool
// KvSqlGenerator, when set, keeps the key-value records in KvTable, out
// of the entry tables.
KvSqlGenerator SqlGenerator
KvTable string
dbs map[string]bool
dbsLock sync.Mutex
RetryableErrorCallback func(err error) bool
@@ -247,13 +270,16 @@ func (store *AbstractSqlStore) InsertEntry(ctx context.Context, entry *filer.Ent
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
meta = util.MaybeGzipData(meta)
}
key := EntryRowKey(dir, name)
sqlInsert := "insert"
res, err := db.ExecContext(ctx, store.GetSqlInsert(bucket), util.HashStringToLong(dir), name, dir, meta)
sqlText, args := store.GetSqlInsert(bucket, key, meta)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil && strings.Contains(strings.ToLower(err.Error()), "duplicate entry") {
// now the insert failed possibly due to duplication constraints
sqlInsert = "falls back to update"
glog.V(1).InfofCtx(ctx, "insert %s %s: %v", entry.FullPath, sqlInsert, err)
res, err = db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
sqlText, args = store.GetSqlUpdate(bucket, key, meta)
res, err = db.ExecContext(ctx, sqlText, args...)
}
if err != nil {
return fmt.Errorf("%s %s: %w", sqlInsert, entry.FullPath, err)
@@ -291,7 +317,8 @@ func (store *AbstractSqlStore) UpdateEntry(ctx context.Context, entry *filer.Ent
return fmt.Errorf("encode %s: %w", entry.FullPath, err)
}
res, err := db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlUpdate(bucket, EntryRowKey(dir, name), meta)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("update %s: %w", entry.FullPath, err)
}
@@ -320,7 +347,8 @@ func (store *AbstractSqlStore) FindEntry(ctx context.Context, fullpath util.Full
}
dir, name := shortPath.DirAndName()
row := db.QueryRowContext(ctx, store.GetSqlFind(bucket), util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlFind(bucket, EntryRowKey(dir, name))
row := db.QueryRowContext(ctx, sqlText, args...)
var data []byte
if err := row.Scan(&data); err != nil {
@@ -351,7 +379,8 @@ func (store *AbstractSqlStore) DeleteEntry(ctx context.Context, fullpath util.Fu
dir, name := shortPath.DirAndName()
res, err := db.ExecContext(ctx, store.GetSqlDelete(bucket), util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlDelete(bucket, EntryRowKey(dir, name))
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("delete %s: %w", fullpath, err)
}
@@ -392,8 +421,9 @@ func (store *AbstractSqlStore) DeleteFolderChildren(ctx context.Context, fullpat
}
}
glog.V(4).InfofCtx(ctx, "delete %s SQL %s %d", string(shortPath), store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)))
res, err := db.ExecContext(ctx, store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)), string(shortPath))
sqlText, args := store.GetSqlDeleteFolderChildren(bucket, string(shortPath))
glog.V(4).InfofCtx(ctx, "delete %s SQL %s %v", string(shortPath), sqlText, args)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("deleteFolderChildren %s: %w", fullpath, err)
}
@@ -429,12 +459,13 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err)
}
sqlText := store.GetSqlListExclusive(bucket)
getSqlList := store.GetSqlListExclusive
if includeStartFile {
sqlText = store.GetSqlListInclusive(bucket)
getSqlList = store.GetSqlListInclusive
}
sqlText, args := getSqlList(bucket, string(shortPath), startFileName, LikePattern(prefix), limit+1)
rows, err := db.QueryContext(ctx, sqlText, util.HashStringToLong(string(shortPath)), startFileName, string(shortPath), LikePattern(prefix), limit+1)
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
}
@@ -24,13 +24,22 @@ func (store *AbstractSqlStore) kvDB(ctx context.Context) TxOrDB {
return store.DB
}
func (store *AbstractSqlStore) kvSql() (SqlGenerator, string) {
if store.KvSqlGenerator != nil {
return store.KvSqlGenerator, store.KvTable
}
return store.SqlGenerator, DEFAULT_TABLE
}
func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
rowKey := kvRowKey(key)
_, err = db.ExecContext(ctx, store.GetSqlInsert(DEFAULT_TABLE), dirHash, name, dirStr, value)
gen, table := store.kvSql()
sqlText, args := gen.GetSqlInsert(table, rowKey, value)
_, err = db.ExecContext(ctx, sqlText, args...)
if err == nil {
return
}
@@ -43,7 +52,8 @@ func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []by
// now the insert failed possibly due to duplication constraints
glog.V(1).InfofCtx(ctx, "kv insert falls back to update: %s", err)
res, err := db.ExecContext(ctx, store.GetSqlUpdate(DEFAULT_TABLE), value, dirHash, name, dirStr)
sqlText, args = gen.GetSqlUpdate(table, rowKey, value)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("kv upsert: %s", err)
}
@@ -60,8 +70,9 @@ func (store *AbstractSqlStore) KvGet(ctx context.Context, key []byte) (value []b
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
row := db.QueryRowContext(ctx, store.GetSqlFind(DEFAULT_TABLE), dirHash, name, dirStr)
gen, table := store.kvSql()
sqlText, args := gen.GetSqlFind(table, kvRowKey(key))
row := db.QueryRowContext(ctx, sqlText, args...)
err = row.Scan(&value)
@@ -82,23 +93,22 @@ const kvBatchGetSize = 256
func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
db := store.kvDB(ctx)
gen, table := store.kvSql()
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
type row struct {
dirHash int64
name, directory string
}
type row struct{ name, directory string }
asked := make(map[row][]string, len(batch))
args := make([]interface{}, 0, 3*len(batch))
rowKeys := make([]RowKey, 0, len(batch))
for _, key := range batch {
dirStr, dirHash, name := GenDirAndName(key)
r := row{dirHash, name, dirStr}
rowKey := kvRowKey(key)
r := row{rowKey.Name, rowKey.Directory}
asked[r] = append(asked[r], string(key))
args = append(args, dirHash, name, dirStr)
rowKeys = append(rowKeys, rowKey)
}
if err := func() error {
rows, err := db.QueryContext(ctx, store.GetSqlFindBatch(DEFAULT_TABLE, len(batch)), args...)
sqlText, args := gen.GetSqlFindBatch(table, rowKeys)
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return err
}
@@ -106,7 +116,7 @@ func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (m
for rows.Next() {
var r row
var value []byte
if err := rows.Scan(&r.dirHash, &r.name, &r.directory, &value); err != nil {
if err := rows.Scan(&r.name, &r.directory, &value); err != nil {
return err
}
for _, key := range asked[r] {
@@ -125,9 +135,9 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
res, err := db.ExecContext(ctx, store.GetSqlDelete(DEFAULT_TABLE), dirHash, name, dirStr)
gen, table := store.kvSql()
sqlText, args := gen.GetSqlDelete(table, kvRowKey(key))
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("kv delete: %s", err)
}
@@ -141,6 +151,11 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er
}
func kvRowKey(key []byte) RowKey {
dirStr, dirHash, name := GenDirAndName(key)
return RowKey{DirHash: dirHash, Name: name, Directory: dirStr}
}
func GenDirAndName(key []byte) (dirStr string, dirHash int64, name string) {
for len(key) < 8 {
key = append(key, 0)
@@ -100,7 +100,8 @@ func (store *AbstractSqlStore) readRowInSnapshot(ctx context.Context, tx *sql.Tx
}
}
var data []byte
err := tx.QueryRowContext(ctx, store.GetSqlFind(table), util.HashStringToLong(shortDir), name, shortDir).Scan(&data)
sqlText, args := store.GetSqlFind(table, EntryRowKey(shortDir, name))
err := tx.QueryRowContext(ctx, sqlText, args...).Scan(&data)
if err == sql.ErrNoRows {
return nil, nil
}
@@ -227,7 +228,8 @@ func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx,
}
var rows []row
if err := func() error {
res, err := tx.QueryContext(ctx, store.GetSqlListExclusive(DEFAULT_TABLE), util.HashStringToLong(bucketsRoot), startFrom, bucketsRoot, "%", page)
sqlText, args := store.GetSqlListExclusive(DEFAULT_TABLE, bucketsRoot, startFrom, "%", page)
res, err := tx.QueryContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("list %s: %v", bucketsRoot, err)
}
@@ -266,17 +268,17 @@ func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx,
}
// scanOneTable reads one table in primary-key pages and hands the entries
// strictly below dirPath to fn (the root itself is read separately). Key-value
// records share the default table; GenDirAndName stores the raw key bytes as
// their dirhash while entry rows hash the directory, so the mismatch
// identifies them exactly.
// strictly below dirPath to fn (the root itself is read separately). Unless
// they have a table of their own, key-value records share the default table;
// GenDirAndName stores the raw key bytes as their dirhash while entry rows
// hash the directory, so the mismatch identifies them exactly.
func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t scanTable, dirPath util.FullPath, fn func(ctx context.Context, entry *filer.Entry) error) error {
type row struct {
dirHash int64
name, dir string
data []byte
}
cursorHash, cursorName := int64(math.MinInt64), ""
cursor := RowKey{DirHash: math.MinInt64}
firstPage := true
for {
var page []row
@@ -289,7 +291,7 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s
return fmt.Errorf("scan table %s: %v", t.table, err)
}
}
sqlText, args := store.GetSqlScanPage(t.table, cursorHash, cursorName, scanPageSize)
sqlText, args := store.GetSqlScanPage(t.table, cursor, scanPageSize)
rows, err := tx.QueryContext(ctx, sqlText, args...)
if err != nil {
if t.cachedOnly && isMissingTableError(err) {
@@ -314,8 +316,8 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s
}
for _, r := range page {
cursorHash, cursorName = r.dirHash, r.name
if r.dirHash != util.HashStringToLong(r.dir) {
cursor = RowKey{DirHash: r.dirHash, Name: r.name, Directory: r.dir}
if store.KvSqlGenerator == nil && r.dirHash != util.HashStringToLong(r.dir) {
continue // a key-value record, see GenDirAndName
}
fullPath := util.NewFullPath(t.base+r.dir, r.name)
@@ -149,8 +149,12 @@ func TestBucketHooksSkipInvalidBucketNames(t *testing.T) {
type listGen struct{ SqlGenerator }
func (listGen) GetSqlListExclusive(string) string { return "SELECT name, meta" }
func (listGen) GetSqlListInclusive(string) string { return "SELECT name, meta" }
func (listGen) GetSqlListExclusive(string, string, string, string, int64) (string, []interface{}) {
return "SELECT name, meta", nil
}
func (listGen) GetSqlListInclusive(string, string, string, string, int64) (string, []interface{}) {
return "SELECT name, meta", nil
}
// A listing that loses its connection partway through must report the error,
// not return the rows read so far as if the directory ended there.
@@ -220,8 +224,10 @@ func TestListDirectoryEntriesStoppedByCallbackWithCanceledContext(t *testing.T)
type writeGen struct{ SqlGenerator }
func (writeGen) GetSqlInsert(string) string { return "INSERT entry" }
func (writeGen) GetSqlDelete(string) string { return "DELETE entry" }
func (writeGen) GetSqlInsert(string, RowKey, []byte) (string, []interface{}) {
return "INSERT entry", nil
}
func (writeGen) GetSqlDelete(string, RowKey) (string, []interface{}) { return "DELETE entry", nil }
// What IsolatesTransactions declares: an entry write, an entry delete and a KV
// write under a transaction's context all go through that transaction, the KV
@@ -331,7 +337,7 @@ func (r *busyRows) Next(dest []driver.Value) error {
type findGen struct{ listGen }
func (findGen) GetSqlFind(string) string { return "SELECT meta" }
func (findGen) GetSqlFind(string, RowKey) (string, []interface{}) { return "SELECT meta", nil }
// A transaction has one connection, so a listing in one (a directory rename)
// must close its rows before the callback reads a hard link on it.
@@ -366,3 +372,33 @@ func TestListDirectoryEntriesInTransactionClosesRowsBeforeCallback(t *testing.T)
t.Errorf("listed %v, want %v", listed, want)
}
}
type kvTableGen struct{ SqlGenerator }
func (kvTableGen) GetSqlInsert(table string, key RowKey, meta []byte) (string, []interface{}) {
return "INSERT kv " + table, key.Args(meta)
}
func (kvTableGen) GetSqlFind(table string, key RowKey) (string, []interface{}) {
return "SELECT kv " + table, key.Args()
}
func TestKvRecordsGoToTheirOwnTable(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer db.Close()
mock.ExpectExec("INSERT kv filemeta_kv").WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery("SELECT kv filemeta_kv").WillReturnRows(sqlmock.NewRows([]string{"meta"}).AddRow([]byte("v")))
store := &AbstractSqlStore{SqlGenerator: writeGen{}, KvSqlGenerator: kvTableGen{}, KvTable: "filemeta_kv", DB: db}
if err := store.KvPut(context.Background(), []byte("key"), []byte("v")); err != nil {
t.Fatal(err)
}
if v, err := store.KvGet(context.Background(), []byte("key")); err != nil || string(v) != "v" {
t.Fatalf("KvGet = %q, %v", v, err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Error(err)
}
}
+7 -1
View File
@@ -101,7 +101,13 @@ func (group *ChunkGroup) ReadDataAt(ctx context.Context, fileSize int64, buff []
return 0, 0, group.resolveErr
}
sectionIndexStart, sectionIndexStop := SectionIndex(offset/SectionSize), SectionIndex((offset+int64(len(buff)))/SectionSize)
if len(buff) == 0 {
return 0, 0, nil
}
if int64(len(buff)) > fileSize-offset {
buff = buff[:fileSize-offset]
}
sectionIndexStart, sectionIndexStop := SectionIndex(offset/SectionSize), SectionIndex((offset+int64(len(buff))-1)/SectionSize)
numSections := int(sectionIndexStop - sectionIndexStart + 1)
// For single section or when concurrency is disabled, use sequential reading
+54
View File
@@ -0,0 +1,54 @@
package filer
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func TestChunkGroupReadAcrossEOF(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1")
_, _ = w.Write([]byte{'A'})
}))
defer server.Close()
lookup := func(ctx context.Context, id string) ([]string, error) {
return []string{server.URL + "/" + id}, ctx.Err()
}
const offset = SectionSize - 4
const fileSize = SectionSize - 3
for _, hasData := range []bool{false, true} {
for _, concurrent := range []int{1, 16} {
for _, length := range []int{1, 8} {
t.Run(fmt.Sprintf("data_%v/readers_%d/bytes_%d", hasData, concurrent, length), func(t *testing.T) {
var chunks []*filer_pb.FileChunk
expected := byte(0)
if hasData {
chunks = []*filer_pb.FileChunk{{FileId: "1,0100000001", Offset: offset, Size: 1, ModifiedTsNs: 1}}
expected = 'A'
}
group, err := NewChunkGroup(lookup, newMockChunkCacheForReaderCache(), chunks, concurrent, nil, nil)
if err != nil {
t.Fatal(err)
}
defer group.Close()
dst := bytes.Repeat([]byte{0xcd}, length)
n, _, err := group.ReadDataAt(context.Background(), fileSize, dst, offset)
t.Logf("offset=%d fileSize=%d requested=%d n=%d err=%v data=%x", offset, fileSize, length, n, err, dst)
if n != 1 || (err != nil && err != io.EOF) || dst[0] != expected {
t.Fatal("section aggregation returned an invalid count/content for a valid read crossing EOF")
}
if !bytes.Equal(dst[1:], bytes.Repeat([]byte{0xcd}, length-1)) {
t.Fatal("read modified the buffer beyond EOF")
}
})
}
}
}
}
+5
View File
@@ -472,6 +472,7 @@ func retriedStreamFetchChunkData(ctx context.Context, writer io.Writer, urlStrin
retriedCnt := 0
var failed bool
var otherErr error
for _, urlString := range util_http.ReachableFirst(urlStrings) {
// Check for context cancellation before each volume server request
select {
@@ -510,6 +511,9 @@ func retriedStreamFetchChunkData(ctx context.Context, writer io.Writer, urlStrin
err = writeErr
break
}
if err != nil && !errors.Is(err, util_http.ErrNotFound) {
otherErr = err
}
if !shouldRetry {
break
}
@@ -520,6 +524,7 @@ func retriedStreamFetchChunkData(ctx context.Context, writer io.Writer, urlStrin
break
}
}
err = util_http.NotFoundEverywhere(err, otherErr)
if err == nil && failed && refreshUrls != nil {
refreshUrls()
}
+68 -2
View File
@@ -141,8 +141,19 @@ func FindGarbageChunks(visibles *IntervalList[*VisibleInterval], start int64, st
return
}
// MinusChunks returns the chunks as reads that bs does not: data chunks and
// manifests, with manifests on both sides resolved to what they hold.
//
// A manifest both lists hold is the same needle on both sides, so all it holds
// is held by both and none of it can be in the result. Such manifests are left
// out of both lists and read only if something else as holds might be held by
// bs through one of them. An update that keeps a file's manifests, such as an
// attribute change or an append to a file whose older chunks are folded, then
// reads none of them, where it used to read each one twice.
func MinusChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, as, bs []*filer_pb.FileChunk, invalidator CacheInvalidator) (delta []*filer_pb.FileChunk, err error) {
as, bs, shared := splitSharedManifests(as, bs)
aData, aMeta, aErr := ResolveChunkManifest(ctx, lookupFileIdFn, as, 0, math.MaxInt64, invalidator, false)
if aErr != nil {
return nil, aErr
@@ -152,11 +163,66 @@ func MinusChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFuncti
return nil, bErr
}
delta = append(delta, DoMinusChunks(aData, bData)...)
delta = append(delta, DoMinusChunks(aMeta, bMeta)...)
dataDelta := DoMinusChunks(aData, bData)
metaDelta := DoMinusChunks(aMeta, bMeta)
if len(shared) > 0 && (len(dataDelta) > 0 || len(metaDelta) > 0) {
// bs may still hold some of these through a manifest both sides keep
sData, sMeta, sErr := ResolveChunkManifest(ctx, lookupFileIdFn, shared, 0, math.MaxInt64, invalidator, false)
if sErr != nil {
return nil, sErr
}
dataDelta = DoMinusChunks(dataDelta, sData)
metaDelta = DoMinusChunks(metaDelta, sMeta)
}
delta = append(delta, dataDelta...)
delta = append(delta, metaDelta...)
return
}
// splitSharedManifests takes the manifests that both as and bs resolve out of
// both lists and returns them apart, as bs lists them.
func splitSharedManifests(as, bs []*filer_pb.FileChunk) (aRest, bRest, shared []*filer_pb.FileChunk) {
// what ResolveChunkManifest over a whole file visits: a chunk with an
// empty span is skipped, along with all it holds
resolved := func(chunk *filer_pb.FileChunk) bool {
return chunk.IsChunkManifest && max(chunk.Offset, 0) < min(chunk.Offset+int64(chunk.Size), math.MaxInt64)
}
inA := make(map[string]bool)
for _, chunk := range as {
if resolved(chunk) {
inA[ChunkIdentity(chunk.GetFileIdString())] = true
}
}
both := make(map[string]bool)
for _, chunk := range bs {
if resolved(chunk) {
if id := ChunkIdentity(chunk.GetFileIdString()); inA[id] {
both[id] = true
}
}
}
if len(both) == 0 {
return as, bs, nil
}
// a skipped listing of a shared manifest adds nothing on either side
keep := func(chunks []*filer_pb.FileChunk, collect bool) (rest []*filer_pb.FileChunk) {
for _, chunk := range chunks {
if chunk.IsChunkManifest && both[ChunkIdentity(chunk.GetFileIdString())] {
if collect && resolved(chunk) {
shared = append(shared, chunk)
}
continue
}
rest = append(rest, chunk)
}
return rest
}
aRest = keep(as, false)
bRest = keep(bs, true)
return aRest, bRest, shared
}
func DoMinusChunks(as, bs []*filer_pb.FileChunk) (delta []*filer_pb.FileChunk) {
fileIds := make(map[string]bool)
+222
View File
@@ -0,0 +1,222 @@
package filer
import (
"context"
"fmt"
"math"
"math/rand"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync/atomic"
"testing"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// manifestVolume serves the manifests of a testManifestStore by file id, as a
// volume server would, and counts the reads.
type manifestVolume struct {
store *testManifestStore
reads atomic.Int64
url string
}
func newManifestVolume(t *testing.T) *manifestVolume {
t.Helper()
v := &manifestVolume{store: newTestManifestStore()}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v.reads.Add(1)
data, ok := v.store.stored[strings.TrimPrefix(r.URL.Path, "/")]
if !ok {
http.NotFound(w, r)
return
}
w.Write(data)
}))
t.Cleanup(srv.Close)
v.url = srv.URL
return v
}
func (v *manifestVolume) lookup(ctx context.Context, fileId string) ([]string, error) {
return []string{v.url + "/" + fileId}, nil
}
// manifest stores a manifest holding chunks and returns its chunk.
func (v *manifestVolume) manifest(t *testing.T, chunks ...*filer_pb.FileChunk) *filer_pb.FileChunk {
t.Helper()
held := make([]*filer_pb.FileChunk, len(chunks))
for i, c := range chunks {
held[i] = proto.Clone(c).(*filer_pb.FileChunk)
}
filer_pb.BeforeEntrySerialization(held)
data, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held})
if err != nil {
t.Fatal(err)
}
// a manifest covers the span of what it holds
start, stop := int64(math.MaxInt64), int64(0)
for _, c := range chunks {
start, stop = min(start, c.Offset), max(stop, c.Offset+int64(c.Size))
}
v.store.nextID++
m := &filer_pb.FileChunk{
Fid: &filer_pb.FileId{VolumeId: 999, FileKey: uint64(v.store.nextID), Cookie: 7},
IsChunkManifest: true,
Offset: start,
Size: uint64(stop - start),
}
v.store.stored[m.GetFileIdString()] = data
return m
}
func ids(chunks []*filer_pb.FileChunk) []string {
out := make([]string, 0, len(chunks))
for _, c := range chunks {
out = append(out, ChunkIdentity(c.GetFileIdString()))
}
sort.Strings(out)
return out
}
// minusEveryManifest is MinusChunks as it was: every manifest on both sides
// resolved.
func minusEveryManifest(t *testing.T, v *manifestVolume, as, bs []*filer_pb.FileChunk) []*filer_pb.FileChunk {
t.Helper()
aData, aMeta, err := ResolveChunkManifest(context.Background(), v.lookup, as, 0, math.MaxInt64, nil, false)
if err != nil {
t.Fatal(err)
}
bData, bMeta, err := ResolveChunkManifest(context.Background(), v.lookup, bs, 0, math.MaxInt64, nil, false)
if err != nil {
t.Fatal(err)
}
return append(DoMinusChunks(aData, bData), DoMinusChunks(aMeta, bMeta)...)
}
func TestMinusChunksReadsOnlyTheManifestsAnUpdateChanges(t *testing.T) {
v := newManifestVolume(t)
d := func(i int) *filer_pb.FileChunk {
return testChunk(1, uint64(i), uint32(i), int64(i*100), 100, int64(i))
}
m1 := v.manifest(t, d(1), d(2), d(3))
m2 := v.manifest(t, d(4), d(5), d(6))
m3 := v.manifest(t, d(7), d(8))
cases := []struct {
name string
old, new []*filer_pb.FileChunk
want []*filer_pb.FileChunk
wantReads int64
everyReads int64 // what resolving every manifest costs
}{
{"attribute change", []*filer_pb.FileChunk{m1, m2, d(7)}, []*filer_pb.FileChunk{m1, m2, d(7)}, nil, 0, 4},
{"append", []*filer_pb.FileChunk{m1, m2, d(7)}, []*filer_pb.FileChunk{m1, m2, d(7), d(8)}, nil, 0, 4},
{"fold the tail", []*filer_pb.FileChunk{m1, m2, d(7), d(8)}, []*filer_pb.FileChunk{m1, m2, m3}, nil, 1, 5},
{"rewrite the tail", []*filer_pb.FileChunk{m1, m2, d(7)}, []*filer_pb.FileChunk{m1, m2, d(9)}, []*filer_pb.FileChunk{d(7)}, 2, 4},
{"truncate to 0", []*filer_pb.FileChunk{m1, m2, d(7)}, nil, []*filer_pb.FileChunk{d(1), d(2), d(3), d(4), d(5), d(6), d(7), m1, m2}, 2, 2},
{"a dropped chunk still held through a kept manifest", []*filer_pb.FileChunk{m1, d(2)}, []*filer_pb.FileChunk{m1}, nil, 1, 2},
{"a dropped manifest", []*filer_pb.FileChunk{m1, m2}, []*filer_pb.FileChunk{m1}, []*filer_pb.FileChunk{d(4), d(5), d(6), m2}, 2, 3},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
v.reads.Store(0)
got, err := MinusChunks(context.Background(), v.lookup, tc.old, tc.new, nil)
if err != nil {
t.Fatal(err)
}
reads := v.reads.Load()
v.reads.Store(0)
every := minusEveryManifest(t, v, tc.old, tc.new)
if g, w := ids(got), ids(tc.want); fmt.Sprint(g) != fmt.Sprint(w) {
t.Errorf("got %v, want %v", g, w)
}
if g, w := ids(got), ids(every); fmt.Sprint(g) != fmt.Sprint(w) {
t.Errorf("got %v, resolving every manifest gives %v", g, w)
}
if reads != tc.wantReads {
t.Errorf("read %d manifests, want %d", reads, tc.wantReads)
}
if r := v.reads.Load(); r != tc.everyReads {
t.Errorf("resolving every manifest read %d, test expects %d", r, tc.everyReads)
}
})
}
}
// Random old and new chunk lists, with manifests held by both, nested
// manifests and chunks listed twice: the delta is the one resolving every
// manifest gives.
func TestMinusChunksMatchesResolvingEveryManifest(t *testing.T) {
v := newManifestVolume(t)
rnd := rand.New(rand.NewSource(13))
data := make([]*filer_pb.FileChunk, 40)
for i := range data {
data[i] = testChunk(uint32(1+i%3), uint64(i+1), uint32(i+1), int64(i*100), 100, int64(i+1))
}
pick := func(from []*filer_pb.FileChunk, n int) []*filer_pb.FileChunk {
var out []*filer_pb.FileChunk
for i := 0; i < n; i++ {
out = append(out, from[rnd.Intn(len(from))])
}
return out
}
for iter := 0; iter < 400; iter++ {
var manifests []*filer_pb.FileChunk
for k := 0; k < 1+rnd.Intn(6); k++ {
held := pick(data, 1+rnd.Intn(6))
if len(manifests) > 0 && rnd.Intn(3) == 0 {
held = append(held, manifests[rnd.Intn(len(manifests))]) // nested
}
manifests = append(manifests, v.manifest(t, held...))
}
listed := func() []*filer_pb.FileChunk {
out := append(pick(data, rnd.Intn(6)), pick(manifests, rnd.Intn(4))...)
if rnd.Intn(5) == 0 {
// a listing with an empty span, which resolving skips
empty := proto.Clone(manifests[rnd.Intn(len(manifests))]).(*filer_pb.FileChunk)
empty.Size = 0
out = append(out, empty)
}
return out
}
old, cur := listed(), listed()
if rnd.Intn(4) == 0 {
cur = append(cur, old...) // an update that keeps everything
}
rnd.Shuffle(len(old), func(i, j int) { old[i], old[j] = old[j], old[i] })
rnd.Shuffle(len(cur), func(i, j int) { cur[i], cur[j] = cur[j], cur[i] })
got, err := MinusChunks(context.Background(), v.lookup, old, cur, nil)
if err != nil {
t.Fatal(err)
}
want := minusEveryManifest(t, v, old, cur)
if g, w := ids(got), ids(want); fmt.Sprint(g) != fmt.Sprint(w) {
t.Fatalf("iteration %d: old %v new %v: got %v, resolving every manifest gives %v", iter, ids(old), ids(cur), g, w)
}
}
}
// A manifest both sides keep is not read, so one that cannot be read does not
// fail an update that drops nothing; one that has to be read still does.
func TestMinusChunksUnreadableKeptManifest(t *testing.T) {
v := newManifestVolume(t)
d := func(i int) *filer_pb.FileChunk {
return testChunk(1, uint64(i), uint32(i), int64(i*100), 100, int64(i))
}
m1 := v.manifest(t, d(1), d(2))
delete(v.store.stored, m1.GetFileIdString())
got, err := MinusChunks(context.Background(), v.lookup, []*filer_pb.FileChunk{m1, d(3)}, []*filer_pb.FileChunk{m1, d(3), d(4)}, nil)
if err != nil || len(got) != 0 {
t.Fatalf("an update keeping the manifest: got %v, %v; want nothing, no error", ids(got), err)
}
if _, err := MinusChunks(context.Background(), v.lookup, []*filer_pb.FileChunk{m1, d(3)}, []*filer_pb.FileChunk{m1}, nil); err == nil {
t.Fatal("an update dropping a chunk the kept manifest might hold: want the read error")
}
}
+19 -1
View File
@@ -1106,6 +1106,19 @@ var (
}
)
type lookupWritesContextKey struct{}
// ErrLookupNeedsWrite is what a lookup made with WithoutLookupWrites returns
// in place of a write it would make: deleting an expired S3 object, or
// importing an object from a remote mount.
var ErrLookupNeedsWrite = errors.New("lookup needs a write")
// WithoutLookupWrites makes FindEntry report a write it would make instead of
// making it, so a caller can redo the lookup under a lock that covers writes.
func WithoutLookupWrites(ctx context.Context) context.Context {
return context.WithValue(ctx, lookupWritesContextKey{}, true)
}
// FindEntry looks up the entry at p, serving a path the store does not hold
// from a remote mount when one covers it.
func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
@@ -1134,6 +1147,9 @@ func (f *Filer) findEntry(ctx context.Context, p util.FullPath) (entry *Entry, f
// lookup outside a transaction removes it.
gone := false
if ctx.Value(storeTransactionKey{}) == nil {
if ctx.Value(lookupWritesContextKey{}) != nil {
return nil, false, ErrLookupNeedsWrite
}
if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil {
glog.ErrorfCtx(ctx, "FindEntry doDeleteEntryMetaAndData %s failed: %v", entry.FullPath, delErr)
} else {
@@ -1154,7 +1170,9 @@ func (f *Filer) findEntry(ctx context.Context, p util.FullPath) (entry *Entry, f
}
if entry == nil && (err == nil || errors.Is(err, filer_pb.ErrNotFound)) {
if lazy, lazyErr := f.maybeLazyFetchFromRemote(ctx, p); lazyErr != nil {
if lazy, lazyErr := f.maybeLazyFetchFromRemote(ctx, p); errors.Is(lazyErr, ErrLookupNeedsWrite) {
return nil, false, lazyErr
} else if lazyErr != nil {
glog.V(1).InfofCtx(ctx, "FindEntry lazy fetch %s: %v", p, lazyErr)
} else if lazy != nil {
return lazy, false, nil
+51 -8
View File
@@ -23,12 +23,17 @@ import (
)
const (
// Maximum number of retry attempts for failed deletions
// Backed-off retry attempts before a failed deletion moves to the dead letter queues
MaxRetryAttempts = 10
// Initial retry delay (will be doubled with each attempt)
InitialRetryDelay = 5 * time.Minute
// Maximum retry delay
MaxRetryDelay = 6 * time.Hour
// Deletions still failing after MaxRetryAttempts move to a dead letter
// queue retried after DeadLetterRetryDelay, then to a second one retried
// after DeadLetterFinalRetryDelay, and are dropped if that fails too.
DeadLetterRetryDelay = 24 * time.Hour
DeadLetterFinalRetryDelay = 48 * time.Hour
// Interval for checking retry queue for ready items
DeletionRetryPollInterval = 1 * time.Minute
// Maximum number of items to process per retry iteration
@@ -60,6 +65,8 @@ var retryablePatterns = []string{
"lookup failed", // Volume server discovery issues
"too many requests", // Rate limiting / backpressure
"try again", // Explicit retry suggestion
"replication copy count", // A replica is offline; deletes wait for it to return
"no space left on device", // A low-disk replica could not append the tombstone yet
// A volume server in maintenance mode refuses BatchDelete until it is switched off.
// The other replicas already dropped the needle, so a delete that is not retried
// leaves this replica live for good.
@@ -174,6 +181,31 @@ func calculateBackoff(retryCount int) time.Duration {
return delay
}
const deadLetterQueues = 2
// deadLetterQueue reports which dead letter queue an item with this retry
// count is in: 0 while it is still in the regular retry schedule.
func deadLetterQueue(retryCount int) int {
if retryCount <= MaxRetryAttempts {
return 0
}
return retryCount - MaxRetryAttempts
}
// retryDelay is the wait before the attempt numbered retryCount. Items past
// the last dead letter queue are due at once so the next poll drops them.
func retryDelay(retryCount int) time.Duration {
switch deadLetterQueue(retryCount) {
case 0:
return calculateBackoff(retryCount)
case 1:
return DeadLetterRetryDelay
case 2:
return DeadLetterFinalRetryDelay
}
return 0
}
// AddOrUpdate adds a new failed deletion or updates an existing one
// Time complexity: O(log N) for insertion/update
func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string, ledgerEpoch uint64) {
@@ -234,8 +266,7 @@ func (q *DeletionRetryQueue) RequeueForRetry(item *DeletionRetryItem, errorMsg s
item.RetryCount++
item.LastError = errorMsg
// Calculate next retry time with exponential backoff
delay := calculateBackoff(item.RetryCount)
delay := retryDelay(item.RetryCount)
item.NextRetryAt = time.Now().Add(delay)
item.inFlight = false // Clear in-flight flag
glog.V(2).Infof("requeued retry for %s: attempt %d, next retry in %v", item.FileId, item.RetryCount, delay)
@@ -267,14 +298,13 @@ func (q *DeletionRetryQueue) GetReadyItems(maxItems int) (ready []*DeletionRetry
// Remove from heap but keep in itemIndex with inFlight flag
heap.Pop(&q.heap)
if item.RetryCount <= MaxRetryAttempts {
if deadLetterQueue(item.RetryCount) <= deadLetterQueues {
item.inFlight = true // Mark as being processed
ready = append(ready, item)
} else {
// Max attempts reached, log and discard completely
delete(q.itemIndex, item.FileId)
expired = append(expired, item)
glog.Warningf("max retry attempts (%d) reached for %s, last error: %s", MaxRetryAttempts, item.FileId, item.LastError)
glog.Warningf("giving up deleting %s after %d retries, last error: %s", item.FileId, item.RetryCount-1, item.LastError)
}
}
@@ -753,6 +783,7 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
// Process outcomes - iterate over readyItems to ensure all items are accounted for
var successCount, notFoundCount, retryCount, permanentErrorCount, volumeGoneCount int
var deadLettered, finalDeadLettered int
for _, item := range readyItems {
outcome := outcomes[item.FileId]
_, fsynced := fsyncIds[item.FileId]
@@ -782,6 +813,12 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
glog.Warningf("no deletion result for retried file %s, re-queuing to avoid loss", item.FileId)
}
// Keep in the durable ledger: still not confirmed.
switch deadLetterQueue(item.RetryCount + 1) {
case 1:
deadLettered++
case 2:
finalDeadLettered++
}
f.DeletionRetryQueue.RequeueForRetry(item, outcome.errorMsg)
case deletionOutcomePermanent:
permanentErrorCount++
@@ -801,6 +838,12 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
if retryCount > 0 {
glog.V(1).Infof("retry: %d files still failing, will retry again later", retryCount)
}
if deadLettered > 0 {
glog.Warningf("retry: %d files moved to the dead letter queue, next retry in %v", deadLettered, DeadLetterRetryDelay)
}
if finalDeadLettered > 0 {
glog.Warningf("retry: %d files moved to the second dead letter queue, next retry in %v", finalDeadLettered, DeadLetterFinalRetryDelay)
}
if volumeGoneCount > 0 {
glog.V(0).Infof("retry: %d files were on volumes the master has not known for %v, dropped as deleted with their volume", volumeGoneCount, VolumeGoneGrace)
}
@@ -869,8 +912,8 @@ func (f *Filer) manifestRetries() *DeletionRetryQueue {
}
// processManifestRetries resolves manifests that failed to resolve on delete.
// One that never resolves within MaxRetryAttempts is deleted alone, leaving
// its sub-chunks to volume.fsck. A pass stops after manifestRetryTimeout and
// One that never resolves through the retries and both dead letter queues is
// deleted alone, leaving its sub-chunks to volume.fsck. A pass stops after manifestRetryTimeout and
// leaves the rest queued, so the shared retry loop gets its turn.
func (f *Filer) processManifestRetries(ctx context.Context) {
q := f.manifestRetries()
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff. Show more