Compare commits

..
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 e2e8af7890 mq logstore: read older parquet rows in a merged timestamp read
A merged timestamp read took the log files first and started parquet at the
latest time they delivered, so parquet rows older than the newest log message
were never read: a read from the beginning of a partition whose older offsets
were compacted and their logs removed returned only the log files' messages.

Both sources are now read from the read's start, parquet first and only below
the earliest offset the listed log files hold, as an offset read does, so each
message comes once and from its log file where one remains. A read stopped in
parquet resumes below the first message of every log file, a read stopped in
the log files resumes where they say, and a full read returns the later of the
two positions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:06:32 -08:00
Chris LuandClaude Opus 5.5 2b30b7112b mq logstore: resume a stopped offset read below every unread log file
A stopped offset read of the log files returned the offset after the last one
it delivered. Files are read by their first offset, but in a partition written
under clock skew their ranges can overlap, so after delivering 0, 1 and 4 from
one file the resume at 5 skipped 2 and 3 in the next. The next offset is now
kept at or below the first offset of every file the read did not reach, as for
parquet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:05:24 -08:00
Chris LuandClaude Opus 5.5 f88f59527f mq broker: bound older files' messages by their write time when seeding stamps
A loaded partition seeds its buffer's last timestamp from the newest ts_max its
files record, but files flushed before ts_max was recorded contributed nothing,
so a slow-clock leader could still stamp new messages below what such a file
holds. A data file recording no ts_max now bounds its messages by the end of the
second its mtime names, since it was written after they were stamped. A message
whose time a client set later than the file's write is still not bounded; the
doc comment says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:51:07 -08:00
Chris LuandClaude Opus 5.5 96fbacae68 mq logstore: compact a group's source logs in offset order
Compaction wrote a group's rows in the order its source logs are listed, by
name, and a window flushed under clock skew sorts before windows holding lower
offsets, so a compacted file could hold offsets 1000, 1001 and then 0 to 999.
Sources are now written in the order of their recorded offset ranges, and a log
file's own entries are already in offset order, so new files hold their rows in
offset order. The file keeps its name and source list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:48:11 -08:00
Chris LuandClaude Opus 5.5 fa2f554e8c mq logstore: deliver a parquet file's rows in offset order for an offset read
Compaction writes rows in the order it reads its source logs, which need not be
offset order, so a file could hold offsets 1000, 1001 and then 0 to 999. An
offset read that stopped after 1001 returned 1002 as the next offset and the
resume skipped 0 to 999. An offset read now delivers a file's eligible rows
sorted by offset, and a stopped or failed read resumes at the offset after its
last delivered row, kept at or below the first offset of every file it did not
finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:47:12 -08:00
Chris LuandClaude Opus 5.5 b2da504615 mq logstore: deliver a parquet file's rows in time order
Rows of windows flushed across a reload are not in time order within a
compacted file, so a timestamp read that stopped after the row at 9s returned
9s and the resume skipped the 7s row it had not reached. A timestamp read now
gathers a file's eligible rows and delivers them sorted by time, and a stopped
or failed read resumes no later than its last delivered row and below the first
row of every file it did not finish, so it never skips a row. The rows are
buffered past the next ReadRows call, so their key and value bytes are copied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:46:23 -08:00
Chris LuandClaude Opus 5.5 dc6f80c8c6 mq logstore: resume a stopped log read below every unread message
A timestamp read that the callback stopped returned the latest time it had
delivered. Files sort by name, and a later-named file can hold earlier
messages, so after delivering 100 from one file and 50 from the next, a resume
from 100 skipped the next file's 60. A stopped read now resumes from the last
time it delivered, kept below the first message of every file it did not reach,
and from the read's own start when one of those records no first message.
Messages only grow in time within a file, so this skips nothing and at most
redelivers. A read that ran to the end still returns the latest time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:45:13 -08:00
Chris Lu bf7927f756 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.
2026-12-01 12:12:05 -08:00
Chris LuandClaude Opus 5.5 8c9a331568 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>
2026-12-01 11:53:08 -08:00
Chris LuandClaude Opus 5.5 6eeb764409 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>
2026-12-01 11:52:38 -08:00
Chris LuandClaude Opus 5.5 f94aaf6dc8 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>
2026-12-01 11:42:53 -08:00
Chris LuandClaude Opus 5.5 d058214660 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>
2026-12-01 11:40:02 -08:00
Chris LuandClaude Opus 5.5 f720c0e584 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>
2026-12-01 11:21:43 -08:00
Chris LuandClaude Opus 5.5 7c0e2c39d4 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>
2026-12-01 11:21:36 -08:00
Chris LuandClaude Opus 5.5 49d6091e59 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>
2026-12-01 11:17:57 -08:00
Chris LuandClaude Opus 5.5 be7b803379 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>
2026-12-01 11:16:23 -08:00
Chris LuandClaude Opus 5.5 54a6c0dce1 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>
2026-12-01 11:15:15 -08:00
Chris LuandClaude Opus 5.5 6860a6404e 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>
2026-12-01 11:13:47 -08:00
Chris LuandClaude Opus 5.5 c9e84e4463 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>
2026-12-01 11:12:29 -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
227 changed files with 18066 additions and 6614 deletions

No files matched your search

@@ -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=
+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

+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;
+62 -1
View File
@@ -188,7 +188,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,
@@ -374,6 +374,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 {
@@ -1717,6 +1738,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();
+80 -10
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,
@@ -828,7 +831,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 +842,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 +1018,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
@@ -4927,7 +4936,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,
@@ -5485,6 +5494,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]
@@ -6420,7 +6490,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 +6541,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());
+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.
+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") })
}
+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()
}
}
}
+5 -4
View File
@@ -418,7 +418,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")
@@ -1490,6 +1490,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)
@@ -1741,9 +1742,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)
}
}
+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)
}
}
}
+1 -1
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")
+1
View File
@@ -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
+8 -2
View File
@@ -111,15 +111,19 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
}
// Create main gRPC server
grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.msg_broker"))
tlsCreds, tlsVerify := security.LoadServerTLS(util.GetViper(), "grpc.msg_broker")
serverOptions := append([]grpc.ServerOption{tlsCreds, tlsVerify}, broker.GrpcServerOptions()...)
grpcS := pb.NewGrpcServer(serverOptions...)
mq_pb.RegisterSeaweedMessagingServer(grpcS, qs)
reflection.Register(grpcS)
grace.OnInterrupt(grpcS.Stop)
// Start localhost listener if available
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,6 +131,8 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
}
}()
}
// Hooks run last-registered first: flush the partitions, then drop the connections.
grace.OnInterrupt(qs.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 {
+13 -1
View File
@@ -114,6 +114,9 @@ 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
}
func init() {
@@ -748,7 +751,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})
}
+1 -1
View File
@@ -71,7 +71,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")
+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.
+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")
}
})
}
}
}
}
+20 -13
View File
@@ -351,19 +351,26 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
return
}
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
// readsRange reports whether chunkView is fetched as a range rather than
// through the shared whole-chunk download.
//
// A view clipped to part of its chunk (e.g. the edge of a ranged GET,
// whose views ViewFromVisibleIntervals clips to the request) only ever
// needs that part: fetch it as a range no matter the detected pattern.
// Fetching the chunk whole would multiply volume-server reads. Ciphered
// and compressed chunks are the exception: the volume server reads the
// whole blob to serve a range, so they take the shared whole-chunk path
// where one download serves every buffer. A chunk that cannot fit the
// reader budget is always fetched as a range, as nothing else can serve it.
func (c *ChunkReadAt) readsRange(chunkView *ChunkView) bool {
if !c.readerCache.budget.canFit(int(chunkView.ChunkSize)) {
return true
}
return chunkView.CanRangeFetch() && (!chunkView.IsFullChunk() || c.readerPattern.IsRandomMode())
}
// A view clipped to part of its chunk (e.g. the edge of a ranged GET,
// whose views ViewFromVisibleIntervals clips to the request) only ever
// needs that part: fetch it as a range no matter the detected pattern.
// Fetching the chunk whole would multiply volume-server reads. Ciphered
// and compressed chunks are the exception: the volume server reads the
// whole blob to serve a range, so they take the shared whole-chunk path
// where one download serves every buffer — unless the whole chunk cannot
// even fit the reader budget, in which case a range fetch is the only
// way to serve the request.
rangeFetch := chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))
if rangeFetch && (!chunkView.IsFullChunk() || c.readerPattern.IsRandomMode()) {
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
if c.readsRange(chunkView) {
c.readerCache.releaseStream(&c.stream)
n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
if n > 0 {
@@ -393,7 +400,7 @@ func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunk
// readChunkSliceAtForParallel is a simplified version for parallel chunk fetching
// It doesn't update lastChunkFid or trigger prefetch (handled by the caller)
func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64) (n int, err error) {
if (chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
if c.readsRange(chunkView) {
n, err = c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
if n > 0 {
return n, err
+101
View File
@@ -403,6 +403,107 @@ func TestChunkReadAtOversizedCompressedChunkFallsBackToRange(t *testing.T) {
}
}
// A whole chunk larger than the reader cache budget is range-fetched in a
// sequential read too, as the budget can't hold it whole.
func TestChunkReadAtOversizedFullChunkFallsBackToRange(t *testing.T) {
const chunkSize = 1 << 20
const sliceSize = 16 << 10
budget := NewReaderCacheBudget(64 << 10)
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil, budget)
defer rc.destroy()
fetches := fetchRecorder(rc)
views := NewIntervalList[*ChunkView]()
views.AppendInterval(&Interval[*ChunkView]{
StartOffset: 0,
StopOffset: chunkSize,
Value: &ChunkView{FileId: "chunk0", ViewSize: chunkSize, ChunkSize: chunkSize},
})
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
defer reader.ReleaseStream()
if n, err := reader.ReadAt(make([]byte, sliceSize), 0); err != nil || n != sliceSize {
t.Fatalf("read: n=%d err=%v", n, err)
}
if len(*fetches) != 1 {
t.Fatalf("got %d fetches, want 1 range fetch: %+v", len(*fetches), *fetches)
}
if f := (*fetches)[0]; f.isFullChunk || f.offset != 0 || f.size != sliceSize {
t.Fatalf("fetch = %+v, want range fetch offset=0 size=%d", f, sliceSize)
}
}
// A read across chunks bigger than the budget range-fetches each of them, as
// the parallel path can't download them whole either.
func TestChunkReadAtOversizedFullChunksAcrossABoundaryFallBackToRange(t *testing.T) {
const chunkSize = 1 << 20
const sliceSize = 16 << 10
budget := NewReaderCacheBudget(64 << 10)
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil, budget)
defer rc.destroy()
fetches := fetchRecorder(rc)
views := NewIntervalList[*ChunkView]()
for i := int64(0); i < 2; i++ {
views.AppendInterval(&Interval[*ChunkView]{
StartOffset: i * chunkSize,
StopOffset: (i + 1) * chunkSize,
Value: &ChunkView{FileId: fmt.Sprintf("chunk%d", i), ViewOffset: i * chunkSize, ViewSize: chunkSize, ChunkSize: chunkSize},
})
}
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, 2*chunkSize, 0)
defer reader.ReleaseStream()
if n, err := reader.ReadAt(make([]byte, sliceSize), chunkSize-sliceSize/2); err != nil || n != sliceSize {
t.Fatalf("read: n=%d err=%v", n, err)
}
if len(*fetches) != 2 {
t.Fatalf("got %d fetches, want 2 range fetches: %+v", len(*fetches), *fetches)
}
for _, f := range *fetches {
if f.isFullChunk || f.size != sliceSize/2 {
t.Fatalf("fetch = %+v, want a range fetch of size %d", f, sliceSize/2)
}
}
}
// Prefetch skips a chunk that cannot fit the reader budget: only a range
// fetch can serve it, so a whole-chunk prefetch would take a download slot
// the chunks after it could use, and then fail.
func TestReaderCacheMaybeCacheSkipsOversizedChunk(t *testing.T) {
const oversized = 1 << 20
const small = 4 << 10
rc := NewReaderCache(1, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil, NewReaderCacheBudget(64<<10))
defer rc.destroy()
fetchRecorder(rc)
views := NewIntervalList[*ChunkView]()
views.AppendInterval(&Interval[*ChunkView]{StartOffset: 0, StopOffset: oversized,
Value: &ChunkView{FileId: "chunk0", ViewSize: oversized, ChunkSize: oversized}})
views.AppendInterval(&Interval[*ChunkView]{StartOffset: oversized, StopOffset: oversized + small,
Value: &ChunkView{FileId: "chunk1", ViewOffset: oversized, ViewSize: small, ChunkSize: small}})
rc.MaybeCache(views.Front(), 2)
rc.Lock()
_, prefetched := rc.downloaders["chunk1"]
rc.Unlock()
if !prefetched {
t.Fatal("the chunk after one over the budget was not prefetched")
}
}
// A chunk a stream is positioned in must outlast downloader-limit eviction:
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
+6 -6
View File
@@ -114,12 +114,12 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
// abort when slots are filled
return
}
if (chunkView.CanRangeFetch() || !rc.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
// the view is clipped to part of the chunk and will be
// range-fetched, so prefetching it whole would download bytes
// nobody needs; a ciphered or compressed partial view needs
// the whole blob anyway and is worth prefetching, but not when
// it cannot fit the budget at all
if !rc.budget.canFit(int(chunkView.ChunkSize)) || (chunkView.CanRangeFetch() && !chunkView.IsFullChunk()) {
// a chunk that cannot fit the budget is only ever range-fetched,
// and so is a view clipped to part of the chunk, so prefetching
// it whole would download bytes nobody needs; a ciphered or
// compressed partial view needs the whole blob anyway and is
// worth prefetching
continue
}
+52 -3
View File
@@ -1,23 +1,72 @@
package filer
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"strings"
"unicode/utf8"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
jsonpb "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var protojsonError = regexp.MustCompile(`\(line (\d+):(\d+)\): (invalid value for \w+ field \w+)?`)
func ParseS3ConfigurationFromBytes[T proto.Message](content []byte, config T) error {
options := &jsonpb.UnmarshalOptions{
DiscardUnknown: true,
AllowPartial: true,
}
if err := options.Unmarshal(content, config); err != nil {
return err
err := options.Unmarshal(content, config)
if err == nil {
return nil
}
return nil
// protojson's errors quote the token they reject, which in these files can be a secret
// key or KMS key material, so an error only says where it is and, for a value of the
// wrong type, which field it's for. encoding/json finds syntax errors and gives an offset
// instead of a quote, so protojson's text is only read for a file that is valid JSON.
decoder := json.NewDecoder(bytes.NewReader(content))
var syntaxErr *json.SyntaxError
switch jsonErr := decoder.Decode(new(json.RawMessage)); {
case jsonErr == io.EOF || jsonErr == io.ErrUnexpectedEOF:
return errors.New("invalid configuration: unexpected end of input")
case errors.As(jsonErr, &syntaxErr):
return fmt.Errorf("invalid configuration at %s", position(content, int(syntaxErr.Offset)-1))
case jsonErr == nil:
if rest := bytes.TrimLeft(content[decoder.InputOffset():], " \t\r\n"); len(rest) > 0 {
return fmt.Errorf("invalid configuration at %s", position(content, len(content)-len(rest)))
}
}
if strings.HasSuffix(err.Error(), io.ErrUnexpectedEOF.Error()) {
// protojson reads six bytes past a \u escape of a surrogate, so on one near the end of
// the file it runs out of input. With room after it, it says where the escape is.
if padded := options.Unmarshal(append(bytes.Clone(content), " "...), config.ProtoReflect().New().Interface()); padded != nil {
err = padded
}
}
found := protojsonError.FindStringSubmatch(err.Error())
switch {
case found != nil && found[3] != "":
return fmt.Errorf("invalid configuration at line %s, column %s: %s", found[1], found[2], found[3])
case found != nil:
return fmt.Errorf("invalid configuration at line %s, column %s", found[1], found[2])
}
return errors.New("invalid configuration")
}
// position gives offset as protojson's errors do, with the column in runes.
func position(content []byte, offset int) string {
before := content[:offset]
line := bytes.Count(before, []byte("\n")) + 1
if i := bytes.LastIndexByte(before, '\n'); i >= 0 {
before = before[i+1:]
}
return fmt.Sprintf("line %d, column %d", line, utf8.RuneCount(before)+1)
}
func ProtoToText(writer io.Writer, config proto.Message) error {
+30
View File
@@ -7,6 +7,7 @@ import (
. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
"github.com/stretchr/testify/assert"
)
@@ -181,3 +182,32 @@ func TestCheckDuplicateAccessKey(t *testing.T) {
}
}
}
func TestParseErrorKeepsTheContentOut(t *testing.T) {
for content, want := range map[string]string{
`{"kms": {"providers": {"local": {"keys": [{"key_material": fa0102030405060708090a0b0c0d0e0f}]}}}}`: "invalid configuration at line 1, column 62",
`{"kms": {"providers": {"local": {"keys": [{"key_material": "\ud800fa0102030405"}]}}}}`: "invalid configuration at line 1, column 60",
`{"identities": [{"name": "a", "credentials": [{"accessKey": "AK", "secretKey": 102030405060708090}]}]}`: "invalid configuration at line 1, column 80: invalid value for string field secretKey",
`{"identities": [{"name": "a", "credentials": [{"secretKey": 102030405060708090`: "invalid configuration: unexpected end of input",
`{"identities": [{"name": "a", "credentials": [{"secretKey": "c2VjcmV0`: "invalid configuration: unexpected end of input",
`{"identities": "c2VjcmV0"}`: "invalid configuration at line 1, column 16",
`"c2VjcmV0"`: "invalid configuration at line 1, column 1",
`{"identities": [{"name": "\ud800"}]}`: "invalid configuration at line 1, column 26",
`{"identities": [{"name": 5, "actions": [`: "invalid configuration: unexpected end of input",
`{"identities": [{"name": "a"}]}"`: "invalid configuration at line 1, column 32",
`{"é": nul#`: "invalid configuration at line 1, column 10",
"{}\n \"x": "invalid configuration at line 2, column 3",
"{\"a\": 1} \t\r\n\"x": "invalid configuration at line 2, column 1",
" \n": "invalid configuration: unexpected end of input",
} {
err := ParseS3ConfigurationFromBytes([]byte(content), &iam_pb.S3ApiConfiguration{})
if err == nil || err.Error() != want {
t.Errorf("%q: got %v, want %s", content, err, want)
}
}
err := ParseS3ConfigurationFromBytes([]byte(`{"global": {"enabled": "yes"}}`), &s3_pb.S3CircuitBreakerConfig{})
if want := "invalid configuration at line 1, column 24: invalid value for bool field enabled"; err == nil || err.Error() != want {
t.Errorf("circuit breaker: got %v, want %s", err, want)
}
}
+3
View File
@@ -156,6 +156,7 @@ var baseS3ActionMap = map[string]string{
// resolved request action.
"ListBucketMultipartUploads": s3_constants.ACTION_LIST_MULTIPART_UPLOADS,
"ListMultipartUploadParts": s3_constants.ACTION_LIST_PARTS,
"GetIncompleteUpload": s3_constants.ACTION_GET_INCOMPLETE_UPLOAD,
// Retention and legal hold operations
"GetObjectRetention": s3_constants.ACTION_GET_OBJECT_RETENTION,
"PutObjectRetention": s3_constants.ACTION_PUT_OBJECT_RETENTION,
@@ -230,6 +231,8 @@ func MapToIdentitiesAction(action string) string {
return "ListBucketMultipartUploads"
case s3_constants.ACTION_LIST_PARTS:
return "ListMultipartUploadParts"
case s3_constants.ACTION_GET_INCOMPLETE_UPLOAD:
return "GetIncompleteUpload"
default:
return ""
}
+271
View File
@@ -0,0 +1,271 @@
package mount
import (
"context"
"fmt"
"sync"
"time"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
)
var (
// chunkProofLimit bounds the assignment proofs a mount keeps at once, a few
// hundred bytes each. Reaching it means that many uploaded chunks still
// wait for their entry to be stored.
chunkProofLimit = 1 << 16
// chunkProofWait is how long an upload waits for room to keep its proof
// before it fails. Tests shorten it.
chunkProofWait = time.Minute
// chunkProofExpiryGrace keeps a proof past its expiry for as long as a
// filer's clock leeway may still accept it.
chunkProofExpiryGrace = 5 * time.Minute
)
// chunkProofs keeps the assignment proofs that a filer returns with
// AssignVolume to a scoped token. Such a filer stores a chunk it does not
// already hold at that path only when the request carries the chunk's proof
// in chunk_auth, so every proof is kept from the upload until a filer has
// acknowledged an entry that names the chunk. A failed or timed out commit
// may or may not have been stored, so it releases nothing: the retry still
// carries the proof, and a proof for a chunk the filer already holds is
// ignored there.
//
// The store is bounded. Once it is full an upload waits, before it is
// assigned a file id, for commits to make room, and fails after
// chunkProofWait instead of evicting a proof a pending commit still needs.
// Only proofs past their expiry are dropped to make room: a filer refuses
// them anyway.
//
// A nil *chunkProofs keeps nothing and attaches nothing: a mount without a
// filer token is never given proofs, and its requests are left as they are.
type chunkProofs struct {
mu sync.Mutex
held map[string]chunkProof // by the file id a chunk names
reserved int // uploads under way that may add a proof
limit int
room chan struct{} // closed and replaced when room may have been made
}
type chunkProof struct {
auth string
expires time.Time // zero when the proof does not say
}
func newChunkProofs(limit int) *chunkProofs {
return &chunkProofs{held: make(map[string]chunkProof), limit: limit, room: make(chan struct{})}
}
// reserve makes room for the proofs of an upload of n file ids before it is
// assigned, waiting up to chunkProofWait for commits to release some.
func (p *chunkProofs) reserve(n int) error {
if p == nil {
return nil
}
if n > p.limit {
return fmt.Errorf("an upload of %d file ids needs more assignment proofs than the %d a mount keeps", n, p.limit)
}
deadline := time.Now().Add(chunkProofWait)
logged := false
p.mu.Lock()
defer p.mu.Unlock()
for len(p.held)+p.reserved+n > p.limit {
if p.dropExpiredLocked() {
continue
}
wait := time.Until(deadline)
if wait <= 0 {
return fmt.Errorf("%d uploaded chunks still wait for their entries to be stored: no room to keep another assignment proof", len(p.held))
}
if !logged {
logged = true
glog.V(0).Infof("%d uploaded chunks still wait for their entries to be stored: the next upload waits for a commit", len(p.held))
}
room := p.room
p.mu.Unlock()
timer := time.NewTimer(wait)
select {
case <-room:
case <-timer.C:
}
timer.Stop()
p.mu.Lock()
}
p.reserved += n
return nil
}
// keep ends the reservation of n file ids made for an upload that stored its
// data under fileId, and keeps the proof the filer returned for them. An
// empty proof keeps nothing: the filer did not ask for one.
func (p *chunkProofs) keep(fileId, auth string, n int) {
if p == nil {
return
}
covered := n
var expires time.Time
if claims, ok := security.AssignProofClaims(security.EncodedJwt(auth)); ok {
if claims.ExpiresAt != nil {
expires = claims.ExpiresAt.Time
}
// A proof covers fileId and fileId_1 up to its count.
if int(claims.Count) < covered {
covered = int(claims.Count)
}
}
p.mu.Lock()
defer p.mu.Unlock()
p.reserved -= n
if auth != "" {
for i := 0; i < covered; i++ {
fid := fileId
if i > 0 {
fid = fmt.Sprintf("%s_%d", fileId, i)
}
p.held[fid] = chunkProof{auth: auth, expires: expires}
}
}
p.signalLocked()
}
// unreserve ends the reservation of n file ids made for a failed upload.
func (p *chunkProofs) unreserve(n int) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
p.reserved -= n
p.signalLocked()
}
// attach adds to *auth the proof of each chunk the store holds one for, and
// reports whether there was any. It writes nothing once *auth carries them,
// so a request already handed to a send that is still in flight can be
// attached to again for its retry: the proofs of the chunks a request names
// are kept before the request is built.
func (p *chunkProofs) attach(chunks []*filer_pb.FileChunk, auth *map[string]string) (held bool) {
if p == nil || len(chunks) == 0 {
return false
}
p.mu.Lock()
defer p.mu.Unlock()
if len(p.held) == 0 {
return false
}
for _, chunk := range chunks {
fid := chunk.GetFileIdString()
proof, ok := p.held[fid]
if !ok {
continue
}
held = true
if current, ok := (*auth)[fid]; ok && current == proof.auth {
continue
}
if *auth == nil {
*auth = make(map[string]string)
}
(*auth)[fid] = proof.auth
}
return held
}
// release drops the proofs of chunks once a filer acknowledged an entry that
// names them: it holds the chunks now and asks for no proof again.
func (p *chunkProofs) release(chunks []*filer_pb.FileChunk) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
released := false
for _, chunk := range chunks {
fid := chunk.GetFileIdString()
if _, ok := p.held[fid]; ok {
delete(p.held, fid)
released = true
}
}
if released {
p.signalLocked()
}
}
// count reports how many file ids have a proof kept.
func (p *chunkProofs) count() int {
if p == nil {
return 0
}
p.mu.Lock()
defer p.mu.Unlock()
return len(p.held)
}
func (p *chunkProofs) dropExpiredLocked() (dropped bool) {
now := time.Now()
for fid, proof := range p.held {
if !proof.expires.IsZero() && now.After(proof.expires.Add(chunkProofExpiryGrace)) {
delete(p.held, fid)
dropped = true
}
}
return dropped
}
func (p *chunkProofs) signalLocked() {
close(p.room)
p.room = make(chan struct{})
}
// requestChunks returns the chunks a filer request stores and the map their
// proofs go in, or nil for a request that stores none.
func requestChunks(req any) ([]*filer_pb.FileChunk, *map[string]string) {
switch r := req.(type) {
case *filer_pb.CreateEntryRequest:
return r.GetEntry().GetChunks(), &r.ChunkAuth
case *filer_pb.UpdateEntryRequest:
return r.GetEntry().GetChunks(), &r.ChunkAuth
case *filer_pb.AppendToEntryRequest:
return r.GetChunks(), &r.ChunkAuth
}
return nil, nil
}
// stored reports whether reply acknowledges that the filer stored the
// request's entry. A create reports a refused condition in its reply.
func stored(reply any) bool {
if r, ok := reply.(*filer_pb.CreateEntryResponse); ok {
return r.GetError() == "" && r.GetErrorCode() == filer_pb.FilerError_OK
}
return true
}
// conn attaches the kept proofs to every unary create, update and append the
// mount sends through cc, on each attempt, and releases them once the filer
// acknowledged the request.
func (p *chunkProofs) conn(cc grpc.ClientConnInterface) grpc.ClientConnInterface {
if p == nil {
return cc
}
return &chunkProofConn{ClientConnInterface: cc, proofs: p}
}
type chunkProofConn struct {
grpc.ClientConnInterface
proofs *chunkProofs
}
func (c *chunkProofConn) Invoke(ctx context.Context, method string, args, reply any, opts ...grpc.CallOption) error {
chunks, auth := requestChunks(args)
held := auth != nil && c.proofs.attach(chunks, auth)
err := c.ClientConnInterface.Invoke(ctx, method, args, reply, opts...)
if err == nil && held && stored(reply) {
c.proofs.release(chunks)
}
return err
}
+763
View File
@@ -0,0 +1,763 @@
package mount
import (
"context"
"fmt"
"io"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/go-fuse/v2/fuse"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
var proofTestKey = security.SigningKey("chunk-proof-test-signing-key")
// proofCluster is what the filers of one cluster share: their entries and the
// file ids they assign.
type proofCluster struct {
mu sync.Mutex
entries map[string]*filer_pb.Entry
received []proofRequest
assigned atomic.Uint64
}
type proofRequest struct {
via string // "unary" or "stream"
chunk []*filer_pb.FileChunk
auth map[string]string
}
func newProofCluster() *proofCluster {
return &proofCluster{entries: make(map[string]*filer_pb.Entry)}
}
func (c *proofCluster) entry(path string) *filer_pb.Entry {
c.mu.Lock()
defer c.mu.Unlock()
return c.entries[path]
}
func (c *proofCluster) put(path string, entry *filer_pb.Entry) {
c.mu.Lock()
defer c.mu.Unlock()
c.entries[path] = entry
}
func (c *proofCluster) requests() []proofRequest {
c.mu.Lock()
defer c.mu.Unlock()
return append([]proofRequest(nil), c.received...)
}
// proofFiler applies a scoped filer's rule for new chunks with the real
// assignment proof primitives. AssignVolume to a scoped token returns a proof
// bound to the token's id; a create, update or append naming a chunk the
// stored entry lacks is refused unless chunk_auth holds a valid proof for it,
// and chunks cannot be added to an entry that holds manifests. A token
// without path grants gets no proof and is not checked. Filers sharing a
// cluster accept each other's proofs, as they share the signing key.
type proofFiler struct {
fakeFilerServer
cluster *proofCluster
volume string
assigns atomic.Int32
failCommits atomic.Int32 // commits answered Unavailable before storing
holdCommits atomic.Int32 // commits held until the caller gives up
}
func newProofFiler(t *testing.T, cluster *proofCluster, volume string) (*proofFiler, pb.ServerAddress) {
f := &proofFiler{cluster: cluster, volume: volume}
return f, listenFiler(t, f)
}
func proofHolder(ctx context.Context) (string, bool) {
md, _ := metadata.FromIncomingContext(ctx)
token, ok := strings.CutPrefix(joinAuthorization(md), "Bearer ")
if !ok {
return "", false
}
claims, ok := security.FilerTokenClaims(security.EncodedJwt(token))
if !ok || !claims.IsScoped() {
return "", false
}
return claims.ID, true
}
func (f *proofFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
f.assigns.Add(1)
fid := needle.NewFileId(3, f.cluster.assigned.Add(1), 0x637037d6).String()
resp := &filer_pb.AssignVolumeResponse{
FileId: fid,
Count: req.GetCount(),
Location: &filer_pb.Location{Url: f.volume, PublicUrl: f.volume},
}
if holder, scoped := proofHolder(ctx); scoped {
resp.AssignAuth = string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, holder, req.GetCount(), ""))
}
return resp, nil
}
// commit checks a request the way a scoped filer does and stores entry at
// path. appended chunks are added to the stored entry instead.
func (f *proofFiler) commit(ctx context.Context, via, method, path string, entry *filer_pb.Entry, appended []*filer_pb.FileChunk, auth map[string]string) error {
requested := entry.GetChunks()
if appended != nil {
requested = appended
}
f.cluster.mu.Lock()
defer f.cluster.mu.Unlock()
f.cluster.received = append(f.cluster.received, proofRequest{via: via, chunk: requested, auth: auth})
if f.failCommits.Load() > 0 {
f.failCommits.Add(-1)
return status.Error(codes.Unavailable, "filer restarting")
}
if f.holdCommits.Load() > 0 {
f.holdCommits.Add(-1)
f.cluster.mu.Unlock()
<-ctx.Done()
f.cluster.mu.Lock()
return ctx.Err()
}
stored := f.cluster.entries[path]
if holder, scoped := proofHolder(ctx); scoped {
known := make(map[string]bool)
for _, chunk := range stored.GetChunks() {
if chunk.GetIsChunkManifest() && len(requested) > 0 {
return status.Errorf(codes.PermissionDenied, "filer: %s: chunks cannot be written to an entry containing manifests", method)
}
known[chunk.GetFileIdString()] = true
}
for _, chunk := range requested {
fid := chunk.GetFileIdString()
if !known[fid] && !security.VerifyAssignJwt(proofTestKey, nil, security.EncodedJwt(auth[fid]), fid, holder, 0, "") {
return status.Errorf(codes.PermissionDenied, "filer: %s: %s %s", method, filer_pb.ChunkProofRefused, fid)
}
}
}
if appended != nil {
next := proto.Clone(stored).(*filer_pb.Entry)
next.Chunks = append(next.Chunks, appended...)
entry = next
}
f.cluster.entries[path] = proto.Clone(entry).(*filer_pb.Entry)
return nil
}
func (f *proofFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if err := f.commit(ctx, "unary", "CreateEntry", string(util.NewFullPath(req.Directory, req.Entry.Name)), req.Entry, nil, req.ChunkAuth); err != nil {
return nil, err
}
return f.fakeFilerServer.CreateEntry(ctx, req)
}
func (f *proofFiler) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
if err := f.commit(ctx, "unary", "UpdateEntry", string(util.NewFullPath(req.Directory, req.Entry.Name)), req.Entry, nil, req.ChunkAuth); err != nil {
return nil, err
}
return f.fakeFilerServer.UpdateEntry(ctx, req)
}
func (f *proofFiler) AppendToEntry(ctx context.Context, req *filer_pb.AppendToEntryRequest) (*filer_pb.AppendToEntryResponse, error) {
if err := f.commit(ctx, "unary", "AppendToEntry", string(util.NewFullPath(req.Directory, req.EntryName)), nil, req.Chunks, req.ChunkAuth); err != nil {
return nil, err
}
return &filer_pb.AppendToEntryResponse{}, nil
}
// StreamMutateEntry answers a refusal in the response, with EACCES, as the
// scoped filer's stream check does.
func (f *proofFiler) StreamMutateEntry(stream filer_pb.SeaweedFiler_StreamMutateEntryServer) error {
for {
req, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
out := &filer_pb.StreamMutateEntryResponse{RequestId: req.RequestId, IsLast: true}
switch r := req.Request.(type) {
case *filer_pb.StreamMutateEntryRequest_CreateRequest:
c := r.CreateRequest
err = f.commit(stream.Context(), "stream", "CreateEntry", string(util.NewFullPath(c.Directory, c.Entry.Name)), c.Entry, nil, c.ChunkAuth)
out.Response = &filer_pb.StreamMutateEntryResponse_CreateResponse{CreateResponse: &filer_pb.CreateEntryResponse{}}
case *filer_pb.StreamMutateEntryRequest_UpdateRequest:
u := r.UpdateRequest
err = f.commit(stream.Context(), "stream", "UpdateEntry", string(util.NewFullPath(u.Directory, u.Entry.Name)), u.Entry, nil, u.ChunkAuth)
out.Response = &filer_pb.StreamMutateEntryResponse_UpdateResponse{UpdateResponse: &filer_pb.UpdateEntryResponse{}}
default:
err = fmt.Errorf("unexpected request %T", req.Request)
}
if err != nil {
out.Response = nil
out.Error, out.Errno = err.Error(), int32(syscall.EACCES)
}
if err := stream.Send(out); err != nil {
return err
}
}
}
// newProofMount is a mount writing through filers (in walk order) with token,
// which also keeps assignment proofs unless token is empty. Chunks go straight
// to the volume stub the filers assign.
func newProofMount(t *testing.T, token security.EncodedJwt, filers ...pb.ServerAddress) *WFS {
t.Helper()
wfs := newInvalidateTestWFS(t)
wfs.filerCallTimeout = 5 * time.Second
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
wfs.option.FilerAddresses = filers
atomic.StoreInt32(&wfs.option.filerIndex, 0)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(filers, wfs.option.GrpcDialOption, "")
if token != "" {
wfs.option.FilerTokenSource = func(context.Context) (security.EncodedJwt, error) { return token, nil }
wfs.chunkProofs = newChunkProofs(chunkProofLimit)
}
return wfs
}
func scopedMountToken() security.EncodedJwt {
return security.GenJwtForFilerScope(proofTestKey, time.Hour, "mount-1", []string{"/dir"}, nil)
}
// openDirtyFile opens /dir/file holding stored, which the cluster stores too,
// with data written after it and not uploaded yet.
func openDirtyFile(t *testing.T, wfs *WFS, cluster *proofCluster, stored ...*filer_pb.FileChunk) *FileHandle {
t.Helper()
data := []byte("data written by a scoped mount")
offset := int64(filer.TotalSize(stored))
entry := &filer_pb.Entry{
Name: "file",
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(offset) + uint64(len(data)), FileMode: 0100644},
Chunks: stored,
}
if len(stored) > 0 {
cluster.put("/dir/file", proto.Clone(entry).(*filer_pb.Entry))
}
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
t.Cleanup(func() { wfs.ReleaseHandle(fh.fh) })
if _, err := fh.dirtyPages.AddPage(offset, data, true, time.Now().UnixNano()); err != nil {
t.Fatalf("AddPage: %v", err)
}
fh.dirtyMetadata = true
return fh
}
func flushFile(wfs *WFS, fh *FileHandle) fuse.Status {
return wfs.Flush(nil, &fuse.FlushIn{InHeader: fuse.InHeader{NodeId: fh.inode}, Fh: uint64(fh.fh)})
}
// newChunks returns the chunks of req the cluster had not stored before it.
func newChunks(req proofRequest, before map[string]bool) []string {
var fids []string
for _, chunk := range req.chunk {
if !before[chunk.GetFileIdString()] {
fids = append(fids, chunk.GetFileIdString())
}
}
return fids
}
// checkCarriesProofs asserts auth holds a valid proof for every one of fids
// and nothing else.
func checkCarriesProofs(t *testing.T, auth map[string]string, fids ...string) {
t.Helper()
if len(auth) != len(fids) {
t.Fatalf("chunk_auth names %d chunks, want exactly %v: %v", len(auth), fids, auth)
}
for _, fid := range fids {
if !security.VerifyAssignJwt(proofTestKey, nil, security.EncodedJwt(auth[fid]), fid, "mount-1", 0, "") {
t.Fatalf("chunk_auth carries no valid proof for %s", fid)
}
}
}
// A scoped mount's flush stores its new chunk only with the chunk's proof,
// and the proof is dropped once the filer acknowledged it. Without the proofs
// (the mount before it kept them) the filer refuses the same flush.
func TestScopedMountFlushCommitsNewChunkWithItsProof(t *testing.T) {
for _, keep := range []bool{true, false} {
t.Run(fmt.Sprintf("keeps proofs %v", keep), func(t *testing.T) {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
if !keep {
wfs.chunkProofs = nil
}
fh := openDirtyFile(t, wfs, cluster)
status := flushFile(wfs, fh)
if !keep {
if status == fuse.OK || cluster.entry("/dir/file") != nil {
t.Fatalf("Flush = %v without proofs, want the filer to refuse it", status)
}
return
}
if status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
stored := cluster.entry("/dir/file")
if len(stored.GetChunks()) != 1 {
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
}
requests := cluster.requests()
if len(requests) != 1 {
t.Fatalf("filer received %d commits, want 1", len(requests))
}
checkCarriesProofs(t, requests[0].auth, stored.Chunks[0].GetFileIdString())
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
})
}
}
// A commit that failed may still have been stored, so it releases nothing:
// the retry, on the same filer or another one of the cluster, carries the
// proof the first filer issued.
func TestScopedMountRetriedCommitCarriesProof(t *testing.T) {
for _, tc := range []struct {
name string
filers int
failing int32 // commits the first filer fails
}{
{name: "same filer", filers: 1, failing: 1},
{name: "assigned on one filer, stored by another", filers: 2, failing: 1 << 20},
} {
t.Run(tc.name, func(t *testing.T) {
cluster := newProofCluster()
volume := newVolumeStub(t)
first, addr := newProofFiler(t, cluster, volume)
first.failCommits.Store(tc.failing)
addrs := []pb.ServerAddress{addr}
var second *proofFiler
if tc.filers == 2 {
var addr2 pb.ServerAddress
second, addr2 = newProofFiler(t, cluster, volume)
addrs = append(addrs, addr2)
}
wfs := newProofMount(t, scopedMountToken(), addrs...)
fh := openDirtyFile(t, wfs, cluster)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
stored := cluster.entry("/dir/file")
if len(stored.GetChunks()) != 1 {
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
}
fid := stored.Chunks[0].GetFileIdString()
requests := cluster.requests()
if len(requests) != 2 {
t.Fatalf("filers received %d commits, want the failed one and its retry", len(requests))
}
for _, req := range requests {
checkCarriesProofs(t, req.auth, fid)
}
if first.assigns.Load() != 1 {
t.Fatalf("first filer assigned %d file ids, want 1", first.assigns.Load())
}
if second != nil && second.assigns.Load() != 0 {
t.Fatalf("second filer assigned %d file ids, want none: the proof is from the first", second.assigns.Load())
}
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
})
}
}
// A commit that timed out is not known to have failed: the proof stays, and
// the next flush stores the chunk with it.
func TestScopedMountKeepsProofAfterTimedOutCommit(t *testing.T) {
saved := metadataFlushTimeout
metadataFlushTimeout = 300 * time.Millisecond
t.Cleanup(func() { metadataFlushTimeout = saved })
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
fake.holdCommits.Store(1)
wfs := newProofMount(t, scopedMountToken(), addr)
fh := openDirtyFile(t, wfs, cluster)
if status := flushFile(wfs, fh); status == fuse.OK {
t.Fatal("Flush = OK against a filer that never answered the commit")
}
if n := wfs.chunkProofs.count(); n != 1 {
t.Fatalf("%d proofs kept after a timed out commit, want the chunk's", n)
}
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("second Flush = %v, want OK", status)
}
stored := cluster.entry("/dir/file")
if len(stored.GetChunks()) != 1 {
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
}
requests := cluster.requests()
checkCarriesProofs(t, requests[len(requests)-1].auth, stored.Chunks[0].GetFileIdString())
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
}
// Creates and updates carry the proofs of the chunks the filer does not hold
// yet, over the mutation stream and over unary calls alike.
func TestScopedMountCreateAndUpdateCarryProofs(t *testing.T) {
for _, via := range []string{"unary", "stream"} {
t.Run(via, func(t *testing.T) {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
if via == "stream" {
wfs.streamMutate = newStreamMutateMux(wfs)
t.Cleanup(wfs.streamMutate.Close)
}
save := wfs.saveDataAsChunk("/dir/f")
upload := func(offset int64) *filer_pb.FileChunk {
chunk, err := save(strings.NewReader("chunk"), "f", offset, time.Now().UnixNano(), 0)
if err != nil {
t.Fatalf("upload: %v", err)
}
return chunk
}
first := upload(0)
if _, err := wfs.streamCreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{first}},
}); err != nil {
t.Fatalf("create: %v", err)
}
second := upload(5)
if _, err := wfs.streamUpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{first, second}},
}); err != nil {
t.Fatalf("update: %v", err)
}
requests := cluster.requests()
if len(requests) != 2 {
t.Fatalf("filer received %d commits, want 2", len(requests))
}
for _, req := range requests {
if req.via != via {
t.Fatalf("commit went %s, want %s", req.via, via)
}
}
checkCarriesProofs(t, requests[0].auth, first.GetFileIdString())
// The update only adds the second chunk: the first one is stored.
checkCarriesProofs(t, requests[1].auth, second.GetFileIdString())
if got := len(cluster.entry("/dir/f").GetChunks()); got != 2 {
t.Fatalf("stored chunks = %d, want 2", got)
}
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commits were acknowledged, want 0", n)
}
})
}
}
// A refused update releases nothing: the chunk's proof is kept for a later
// commit, here an append.
func TestScopedMountRefusedCommitKeepsProof(t *testing.T) {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
chunk, err := wfs.saveDataAsChunk("/dir/f")(strings.NewReader("chunk"), "f", 0, time.Now().UnixNano(), 0)
if err != nil {
t.Fatalf("upload: %v", err)
}
cluster.put("/dir/f", &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{{FileId: "4,01637037d6", IsChunkManifest: true}}})
_, err = wfs.streamUpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: "/dir",
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{chunk}},
})
if status.Code(err) != codes.PermissionDenied {
t.Fatalf("update onto an entry of manifests = %v, want the filer's refusal", err)
}
if n := wfs.chunkProofs.count(); n != 1 {
t.Fatalf("%d proofs kept after a refused commit, want the chunk's", n)
}
cluster.put("/dir/f", &filer_pb.Entry{Name: "f"})
if err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.AppendToEntry(context.Background(), &filer_pb.AppendToEntryRequest{Directory: "/dir", EntryName: "f", Chunks: []*filer_pb.FileChunk{chunk}})
return err
}); err != nil {
t.Fatalf("append: %v", err)
}
requests := cluster.requests()
checkCarriesProofs(t, requests[len(requests)-1].auth, chunk.GetFileIdString())
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the append was acknowledged, want 0", n)
}
}
// A filer serving a scoped token stores no new chunk in an entry that holds
// manifests, so a mount with a token keeps the chunk list flat where an
// unscoped mount would fold it: the flush that completes a batch of small
// chunks commits them as they are, and the file stays writable.
func TestScopedMountKeepsChunkListsFlat(t *testing.T) {
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
// One chunk short of a batch: the chunk this flush uploads completes it.
stored := storedSmallChunks(filer.SmallChunkManifestBatch - 1)
fh := openDirtyFile(t, wfs, cluster, stored...)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
if got := fake.assigns.Load(); got != 1 {
t.Fatalf("AssignVolume calls = %d, want only the data chunk", got)
}
committed := cluster.entry("/dir/file").GetChunks()
if len(committed) != filer.SmallChunkManifestBatch {
t.Fatalf("stored %d chunks, want the %d small chunks unfolded", len(committed), filer.SmallChunkManifestBatch)
}
for _, chunk := range committed {
if chunk.GetIsChunkManifest() {
t.Fatalf("stored a manifest %s; a scoped filer refuses later writes to such an entry", chunk.GetFileIdString())
}
}
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
}
}
// A mount whose token the filer does not scope folds chunk lists as a mount
// without a token does.
func TestUnscopedTokenMountFoldsChunkLists(t *testing.T) {
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, security.GenJwtForFilerAdmin(proofTestKey, 3600), addr)
stored := storedSmallChunks(filer.SmallChunkManifestBatch - 1)
fh := openDirtyFile(t, wfs, cluster, stored...)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
if got := fake.assigns.Load(); got != 2 {
t.Fatalf("AssignVolume calls = %d, want the data chunk and its manifest", got)
}
manifests := 0
for _, chunk := range cluster.entry("/dir/file").GetChunks() {
if chunk.GetIsChunkManifest() {
manifests++
}
}
if manifests != 1 {
t.Fatalf("stored %d manifests, want the %d small chunks folded into one", manifests, filer.SmallChunkManifestBatch)
}
}
// Without a scoped token the filer issues no proofs, and a flush sends the
// same chunks and no chunk_auth, whether or not the mount has a token.
func TestUnscopedMountRequestsCarryNoProofs(t *testing.T) {
var lists [][]string
// A filer token with no path grants is unscoped: it has full access.
unscoped := security.GenJwtForFilerAdmin(proofTestKey, 3600)
if unscoped == "" {
t.Fatal("no unscoped filer token was signed")
}
for _, token := range []security.EncodedJwt{"", unscoped} {
cluster := newProofCluster()
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, token, addr)
if (token == "") != (wfs.chunkProofs == nil) {
t.Fatal("a mount keeps proofs only with a filer token")
}
fh := openDirtyFile(t, wfs, cluster)
if status := flushFile(wfs, fh); status != fuse.OK {
t.Fatalf("Flush = %v, want OK", status)
}
requests := cluster.requests()
if len(requests) != 1 || requests[0].auth != nil {
t.Fatalf("commits = %+v, want one without chunk_auth", requests)
}
var list []string
for _, chunk := range requests[0].chunk {
list = append(list, fmt.Sprintf("%s@%d+%d", chunk.GetFileIdString(), chunk.Offset, chunk.Size))
}
lists = append(lists, list)
if n := wfs.chunkProofs.count(); n != 0 {
t.Fatalf("%d proofs kept without a scoped token", n)
}
}
if fmt.Sprint(lists[0]) != fmt.Sprint(lists[1]) {
t.Fatalf("chunk lists differ with and without a token: %v vs %v", lists[0], lists[1])
}
}
// One proof covers each file id of a multi-count assignment, and each is
// released on its own.
func TestChunkProofsCoverEveryIdOfAnAssignment(t *testing.T) {
const fid = "3,01637037d6"
proof := string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 3, ""))
p := newChunkProofs(8)
if err := p.reserve(3); err != nil {
t.Fatal(err)
}
p.keep(fid, proof, 3)
chunks := []*filer_pb.FileChunk{{FileId: fid + "_2"}, {FileId: fid}, {FileId: "3,02637037d6"}}
var auth map[string]string
if !p.attach(chunks, &auth) {
t.Fatal("attach found no proofs")
}
checkCarriesProofs(t, auth, fid, fid+"_2")
p.release(chunks[1:2])
auth = nil
p.attach([]*filer_pb.FileChunk{{FileId: fid}, {FileId: fid + "_1"}}, &auth)
checkCarriesProofs(t, auth, fid+"_1")
if n := p.count(); n != 2 {
t.Fatalf("proofs kept = %d, want 2", n)
}
// A proof covers no more ids than its count, whatever the upload asked.
q := newChunkProofs(8)
if err := q.reserve(2); err != nil {
t.Fatal(err)
}
q.keep(fid, string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 1, "")), 2)
if n := q.count(); n != 1 || q.reserved != 0 {
t.Fatalf("proofs kept = %d, reserved = %d, want 1 and 0", n, q.reserved)
}
}
func expiredProof(t *testing.T, fid string, expired time.Duration) string {
t.Helper()
collection := ""
claims := security.SeaweedAssignClaims{Fid: fid, Count: 1, Collection: &collection, RegisteredClaims: jwt.RegisteredClaims{
ID: "mount-1", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-expired)),
}}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(security.AssignSigningKey(proofTestKey)))
if err != nil {
t.Fatal(err)
}
return signed
}
// A full store holds an upload back until a commit makes room, and fails it
// when none does instead of dropping a proof a commit still needs. Only
// proofs past their expiry make room by themselves.
func TestChunkProofsFullStoreWaitsThenFails(t *testing.T) {
saved := chunkProofWait
chunkProofWait = 300 * time.Millisecond
t.Cleanup(func() { chunkProofWait = saved })
proof := func(fid string) string {
return string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 1, ""))
}
held := []*filer_pb.FileChunk{{FileId: "3,01637037d6"}, {FileId: "3,02637037d6"}}
t.Run("a commit makes room", func(t *testing.T) {
p := newChunkProofs(2)
for _, chunk := range held {
if err := p.reserve(1); err != nil {
t.Fatal(err)
}
p.keep(chunk.FileId, proof(chunk.FileId), 1)
}
done := make(chan error, 1)
go func() { done <- p.reserve(1) }()
select {
case err := <-done:
t.Fatalf("reserve on a full store returned %v before any commit", err)
case <-time.After(50 * time.Millisecond):
}
p.release(held[:1])
if err := <-done; err != nil {
t.Fatalf("reserve after a commit made room: %v", err)
}
})
t.Run("nothing makes room", func(t *testing.T) {
p := newChunkProofs(2)
for _, chunk := range held {
if err := p.reserve(1); err != nil {
t.Fatal(err)
}
p.keep(chunk.FileId, proof(chunk.FileId), 1)
}
start := time.Now()
if err := p.reserve(1); err == nil {
t.Fatal("reserve succeeded on a store no commit drained")
}
if elapsed := time.Since(start); elapsed < chunkProofWait {
t.Fatalf("reserve failed after %v, want it to wait %v", elapsed, chunkProofWait)
}
var auth map[string]string
p.attach(held, &auth)
checkCarriesProofs(t, auth, held[0].FileId, held[1].FileId)
})
t.Run("expired proofs make room", func(t *testing.T) {
p := newChunkProofs(2)
for _, tc := range []struct {
fid string
expired time.Duration
}{{held[0].FileId, chunkProofExpiryGrace + time.Minute}, {held[1].FileId, chunkProofExpiryGrace - time.Minute}} {
if err := p.reserve(1); err != nil {
t.Fatal(err)
}
p.keep(tc.fid, expiredProof(t, tc.fid, tc.expired), 1)
}
if err := p.reserve(1); err != nil {
t.Fatalf("reserve with a proof past its expiry: %v", err)
}
var auth map[string]string
p.attach(held, &auth)
if _, ok := auth[held[0].FileId]; ok || len(auth) != 1 {
t.Fatalf("kept proofs = %v, want only the one still within its grace", auth)
}
})
}
// An upload the store has no room for fails before it is assigned a file id,
// so no data is stored that no commit could name.
func TestScopedMountUploadFailsWhenProofsAreFull(t *testing.T) {
saved := chunkProofWait
chunkProofWait = 100 * time.Millisecond
t.Cleanup(func() { chunkProofWait = saved })
cluster := newProofCluster()
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
wfs := newProofMount(t, scopedMountToken(), addr)
wfs.chunkProofs = newChunkProofs(1)
save := wfs.saveDataAsChunk("/dir/f")
if _, err := save(strings.NewReader("one"), "f", 0, time.Now().UnixNano(), 0); err != nil {
t.Fatalf("first upload: %v", err)
}
if _, err := save(strings.NewReader("two"), "f", 3, time.Now().UnixNano(), 0); err == nil {
t.Fatal("upload succeeded with no room to keep its proof")
}
if got := fake.assigns.Load(); got != 1 {
t.Fatalf("AssignVolume calls = %d, want only the first upload's", got)
}
if wfs.chunkProofs.reserved != 0 {
t.Fatalf("reserved = %d after the uploads ended, want 0", wfs.chunkProofs.reserved)
}
}
+2
View File
@@ -28,6 +28,8 @@ type FileHandle struct {
// Nested handle lock order: wfs.fhLockTable[fh.fh] -> entryLock ->
// LockedEntry.RWMutex. Paths may use a subset, but must never acquire an
// earlier lock while holding a later one. Release in reverse order.
// Only CopyFileRange holds the fhLockTable locks of two handles at once; it
// takes them in ascending FileHandleId order.
entryLock sync.RWMutex
entryChunkGroup *filer.ChunkGroup
inode uint64
+61 -5
View File
@@ -4,8 +4,10 @@ import (
"context"
"encoding/hex"
"errors"
"math"
"os"
"sync"
"sync/atomic"
"time"
"golang.org/x/sync/singleflight"
@@ -23,10 +25,19 @@ import (
// need to have logic similar to FilerStoreWrapper
// e.g. fill fileId field for chunks
// metaBatchStore takes the batched writes of a directory build: the inserts of
// the listing and the wipe before them. It is the leveldb store; tests stand
// in for it to fill the cache disk.
type metaBatchStore interface {
BatchInsertEntries(ctx context.Context, entries []*filer.Entry) error
BatchDeleteEntries(ctx context.Context, paths []util.FullPath) error
}
type MetaCache struct {
root util.FullPath
localStore filer.VirtualFilerStore
leveldbStore *leveldb.LevelDBStore // direct reference for batch operations
batchStore metaBatchStore
sync.RWMutex
uidGidMapper *UidGidMapper
markCachedFn func(fullpath util.FullPath)
@@ -49,6 +60,11 @@ type MetaCache struct {
// instead of streaming to the limit again to rediscover them.
oversizedDirs map[util.FullPath]struct{}
// storeRefusedUntil is when, in unix nanoseconds, builds are tried again
// after the store refused one: until then directories read through. Zero
// when no build was refused.
storeRefusedUntil atomic.Int64
// rebuildWipeInserts holds the children inserted into each directory
// while its rebuild wipe runs; the wipe keeps them.
rebuildWipeInserts map[util.FullPath]map[string]struct{}
@@ -136,6 +152,7 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
root: root,
localStore: virtualStore,
leveldbStore: leveldbStore,
batchStore: leveldbStore,
markCachedFn: markCachedFn,
isCachedFn: isCachedFn,
uidGidMapper: uidGidMapper,
@@ -204,7 +221,7 @@ func (mc *MetaCache) doInsertEntry(ctx context.Context, entry *filer.Entry, vers
// This is more efficient than inserting entries one by one.
func (mc *MetaCache) doBatchInsertEntries(ctx context.Context, entries []*filer.Entry) error {
return mc.leveldbStore.BatchInsertEntries(ctx, entries)
return mc.batchStore.BatchInsertEntries(ctx, entries)
}
func (mc *MetaCache) AtomicUpdateEntryFromFiler(ctx context.Context, oldPath util.FullPath, newEntry *filer.Entry) error {
@@ -473,7 +490,7 @@ func (mc *MetaCache) FindEntry(ctx context.Context, fp util.FullPath) (entry *fi
if unversioned {
return entry, 0, nil
}
return entry, mc.entryVersionFloorLocked(fp, recordTsNs), nil
return entry, mc.entryVersionFloorLocked(fp, max(recordTsNs, entry.CommitTsNs)), nil
}
// entryVersionKeyPrefix namespaces per-entry version records apart from entry
@@ -647,9 +664,15 @@ func (mc *MetaCache) entryVersionBlocksLocked(ctx context.Context, fp util.FullP
// event can correct it.
return false
}
if !tombstone && !mc.entryExistsLocked(ctx, fp) {
entry, err := mc.localStore.FindEntry(ctx, fp)
live := err == nil && entry != nil && !isTtlExpired(entry)
if !tombstone && !live {
recordTsNs = 0
}
// A live entry reflects its own commit, even under an older listing floor.
if live && entry.CommitTsNs > recordTsNs {
recordTsNs = entry.CommitTsNs
}
floorTsNs := mc.entryVersionFloorLocked(fp, recordTsNs)
if removal && !tombstone {
return floorTsNs > tsNs
@@ -874,7 +897,7 @@ func (mc *MetaCache) deleteFolderChildrenBatch(ctx context.Context, dirPath util
if err != nil {
return "", err
}
if err := mc.leveldbStore.BatchDeleteEntries(ctx, doomed); err != nil {
if err := mc.batchStore.BatchDeleteEntries(ctx, doomed); err != nil {
return "", err
}
if visited < rebuildWipeBatchSize {
@@ -906,6 +929,35 @@ func (mc *MetaCache) ListDirectoryEntries(ctx context.Context, dirPath util.Full
})
}
// LocalOnlyChildren returns, in name order, the children of dirPath that the
// local store holds and a rebuild keeps (see SetPinnedChildFn): files this
// mount created that are not on the filer yet. It covers the names after
// startFileName and, unless stopFileName is empty, up to it. A listing read
// through from the filer leaves them out; whether the directory is cached does
// not matter.
func (mc *MetaCache) LocalOnlyChildren(ctx context.Context, dirPath util.FullPath, startFileName, stopFileName string) ([]*filer.Entry, error) {
if mc.pinnedChildFn == nil {
return nil, nil
}
mc.RLock()
defer mc.RUnlock()
var children []*filer.Entry
_, err := mc.localStore.ListDirectoryEntries(ctx, dirPath, startFileName, false, math.MaxInt64, func(entry *filer.Entry) (bool, error) {
if stopFileName != "" && entry.Name() > stopFileName {
return false, nil
}
if entry.TtlSec > 0 && entry.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now()) {
return true, nil
}
if mc.pinnedChildFn(entry) {
mc.mapIdFromFilerToLocal(entry)
children = append(children, entry)
}
return true, nil
})
return children, err
}
func (mc *MetaCache) markOversized(dirPath util.FullPath) {
mc.Lock()
defer mc.Unlock()
@@ -1302,13 +1354,17 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
mc.Lock()
// Last-writer-wins per entry: an event at or below an entry's version is
// already reflected in it, and applying it would roll the entry back while
// the version keeps the newer claim. Each half is gated independently.
// the version keeps the newer claim. Each half is gated independently,
// except an in-place update: a reflected one must not remove its entry.
if resp.TsNs != 0 {
if oldPath != "" && mc.entryVersionBlocksLocked(ctx, oldPath, resp.TsNs, true) {
oldPath = ""
}
if newEntry != nil {
if mc.entryVersionBlocksLocked(ctx, newEntry.FullPath, resp.TsNs, false) {
if oldPath == newEntry.FullPath {
oldPath = ""
}
newEntry = nil
} else if mc.hardLinkVersionFloorLocked(ctx, newEntry.HardLinkId) > resp.TsNs {
// The group's shared content is newer than this event — the
@@ -957,3 +957,70 @@ func TestUnversionedWriteDoesNotInheritDirectoryFloor(t *testing.T) {
}
mc.WaitForEntryInvalidations()
}
// A listing snapshot can trail the listed entries: a peer's held watermark
// caps it below writes already in the store. A delayed older event must not
// roll a listed entry back to the state it replaced.
func TestBuildKeepsListedEntryNewerThanSnapshot(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
"/": true,
"/dir": true,
})
defer mc.Shutdown()
if err := mc.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
t.Fatalf("begin build: %v", err)
}
if err := mc.doBatchInsertEntries(context.Background(), []*filer.Entry{{
FullPath: "/dir/file",
Attr: filer.Attr{
Crtime: time.Unix(1, 0),
Mtime: time.Unix(1, 0),
Mode: 0100644,
FileSize: 300,
},
CommitTsNs: 3000,
}}); err != nil {
t.Fatalf("batch insert: %v", err)
}
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
t.Fatalf("complete build: %v", err)
}
// open handles compare invalidations against this version
if _, versionTsNs, err := mc.FindEntry(context.Background(), util.FullPath("/dir/file")); err != nil || versionTsNs != 3000 {
t.Fatalf("listed entry version = %d, %v; want its commit 3000", versionTsNs, err)
}
apply := func(tsNs int64, oldEntry, newEntry *filer_pb.Entry) {
t.Helper()
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: tsNs,
EventNotification: &filer_pb.EventNotification{
OldEntry: oldEntry,
NewEntry: newEntry,
NewParentPath: "/dir",
},
}
if err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply event at %d: %v", tsNs, err)
}
}
wantSize := func(want uint64, why string) {
t.Helper()
entry, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/file"))
if err != nil || entry.FileSize != want {
t.Fatalf("entry = %+v, %v; want size %d (%s)", entry, err, want, why)
}
}
apply(2500, nil, &filer_pb.Entry{Name: "file", CommitTsNs: 2500, Attributes: &filer_pb.FuseAttributes{FileMode: 0100644}})
wantSize(300, "the create below the listed commit is already reflected")
apply(2500, &filer_pb.Entry{Name: "file"}, nil)
wantSize(300, "a removal below the listed commit is already reflected")
apply(3000, &filer_pb.Entry{Name: "file"}, &filer_pb.Entry{Name: "file", CommitTsNs: 3000, Attributes: &filer_pb.FuseAttributes{FileSize: 300, FileMode: 0100644}})
wantSize(300, "the update that made the listed commit is already reflected")
apply(3500, &filer_pb.Entry{Name: "file"}, &filer_pb.Entry{Name: "file", CommitTsNs: 3500, Attributes: &filer_pb.FuseAttributes{FileSize: 500, FileMode: 0100644}})
wantSize(500, "a change past the listed commit applies")
mc.WaitForEntryInvalidations()
}
+67 -3
View File
@@ -24,6 +24,48 @@ func (e *DirectoryTooLargeError) Error() string {
return fmt.Sprintf("directory %s is too large to cache locally", e.Path)
}
// LocalStoreError reports a directory build the local store refused: a write
// to the cache disk failed, typically because the disk is full. The directory
// reads through to the filer, the way an oversized one does, until the store
// takes writes again.
type LocalStoreError struct {
Path util.FullPath
Err error
}
func (e *LocalStoreError) Error() string {
return fmt.Sprintf("local store cannot cache directory %s: %v", e.Path, e.Err)
}
func (e *LocalStoreError) Unwrap() error {
return e.Err
}
// storeRefusalBackoff is how long directories read through after the store
// refused a build before a build is tried again. A build on a full disk lists
// the directory from the filer only to fail at its first write.
var storeRefusalBackoff = 10 * time.Second
var errStoreRefusing = errors.New("it refused a write moments ago")
// noteStoreRefusal starts the backoff after a build the store refused. It logs
// once per backoff, not once per listing.
func (mc *MetaCache) noteStoreRefusal(path util.FullPath, err error) {
now := time.Now()
if previous := mc.storeRefusedUntil.Swap(now.Add(storeRefusalBackoff).UnixNano()); previous <= now.UnixNano() {
glog.Warningf("local store cannot cache %s, listing directories from the filer for %v: %v", path, storeRefusalBackoff, err)
}
}
// storeRefusal is errStoreRefusing while the backoff after a refused build
// lasts, nil otherwise.
func (mc *MetaCache) storeRefusal() error {
if time.Now().UnixNano() < mc.storeRefusedUntil.Load() {
return errStoreRefusing
}
return nil
}
// maxCacheableEntries is the directory size above which a build gives up, or 0
// to cache everything.
func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClient, dirPath util.FullPath, maxCacheableEntries int) error {
@@ -59,6 +101,11 @@ func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClie
return nil
}
// A build the store refused moments ago would be refused again.
if err := mc.storeRefusal(); err != nil {
return &LocalStoreError{Path: dirPath, Err: err}
}
// Fetch all uncached directories in parallel with context for cancellation
// If one fetch fails, cancel the others to avoid unnecessary work
g, ctx := errgroup.WithContext(ctx)
@@ -161,7 +208,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
sections = sectionBoundsCollector{}
var batch []*filer.Entry // reset on retry, allow GC of previous entries
if err := mc.deleteFolderChildrenForRebuild(buildCtx, path); err != nil {
return fmt.Errorf("clear existing entries for %s: %w", path, err)
return &LocalStoreError{Path: path, Err: fmt.Errorf("clear existing entries: %w", err)}
}
var listErr error
snapshotTsNs, listErr = filer_pb.ReadDirAllEntriesWithSnapshot(buildCtx, client, path, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
@@ -180,7 +227,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
// flush by size, not isLast: hidden entries can return early
if len(batch) >= batchInsertSize {
if err := mc.doBatchInsertEntries(buildCtx, batch); err != nil {
return fmt.Errorf("batch insert for %s: %w", path, err)
return &LocalStoreError{Path: path, Err: fmt.Errorf("batch insert: %w", err)}
}
batch = make([]*filer.Entry, 0, batchInsertSize)
}
@@ -191,7 +238,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
}
if len(batch) > 0 {
if err := mc.doBatchInsertEntries(buildCtx, batch); err != nil {
return fmt.Errorf("batch insert remaining for %s: %w", path, err)
return &LocalStoreError{Path: path, Err: fmt.Errorf("batch insert remaining: %w", err)}
}
}
return nil
@@ -199,8 +246,18 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
return entryCount, snapshotTsNs, sections, err
}
// noteIfRefused starts the store backoff when a build failed on the
// store rather than on the filer.
noteIfRefused := func(err error) {
var refused *LocalStoreError
if errors.As(err, &refused) {
mc.noteStoreRefusal(path, refused.Err)
}
}
entryCount, snapshotTsNs, sections, fetchErr := reloadFromFiler()
if fetchErr != nil {
noteIfRefused(fetchErr)
var tooLarge *DirectoryTooLargeError
if errors.As(fetchErr, &tooLarge) {
// Remember the refusal so the next visit fails fast instead of
@@ -230,6 +287,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
}
}
if entryCount, snapshotTsNs, sections, fetchErr = reloadFromFiler(); fetchErr != nil {
noteIfRefused(fetchErr)
cleanupBuild("failed")
return nil, fmt.Errorf("confirm empty list %s: %w", path, fetchErr)
}
@@ -240,6 +298,12 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
if err := mc.CompleteDirectoryBuild(context.Background(), path, snapshotTsNs, sections.bounds); err != nil {
cleanupBuild("unreplayed")
if !errors.Is(err, ErrClosed) && !errors.Is(err, ErrDirectoryBuildDiscarded) {
// Otherwise completing fails only on writing the events
// buffered during the listing to the store.
err = &LocalStoreError{Path: path, Err: fmt.Errorf("replay buffered events: %w", err)}
noteIfRefused(err)
}
return nil, fmt.Errorf("complete build for %s: %w", path, err)
}
cleanupDone = true // Prevent deferred cleanup after successful publish
@@ -0,0 +1,240 @@
package meta_cache
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
)
// fullDiskBatchStore fails a build's batched writes while full is set, the
// way the leveldb store does once the cache disk has no space left. Like the
// store, it writes nothing, and so cannot fail, for an empty batch.
type fullDiskBatchStore struct {
metaBatchStore
full atomic.Bool
}
func (s *fullDiskBatchStore) BatchInsertEntries(ctx context.Context, entries []*filer.Entry) error {
if s.full.Load() && len(entries) > 0 {
return errCacheDiskFull
}
return s.metaBatchStore.BatchInsertEntries(ctx, entries)
}
func (s *fullDiskBatchStore) BatchDeleteEntries(ctx context.Context, paths []util.FullPath) error {
if s.full.Load() && len(paths) > 0 {
return errCacheDiskFull
}
return s.metaBatchStore.BatchDeleteEntries(ctx, paths)
}
// countingListClient counts the listings a build asks the filer for.
type countingListClient struct {
buildListClient
lists atomic.Int32
}
func (c *countingListClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
c.lists.Add(1)
return c.buildListClient.ListEntries(ctx, in, opts...)
}
func shortStoreRefusalBackoff(t *testing.T, d time.Duration) {
t.Helper()
saved := storeRefusalBackoff
storeRefusalBackoff = d
t.Cleanup(func() { storeRefusalBackoff = saved })
}
func countChildren(t *testing.T, mc *MetaCache, dir util.FullPath) int {
t.Helper()
count := 0
if _, err := mc.ListDirectoryEntries(context.Background(), dir, "", false, 1000, func(*filer.Entry) (bool, error) {
count++
return true, nil
}); err != nil {
t.Fatalf("list %s: %v", dir, err)
}
return count
}
// A build on a full cache disk used to fail the listing with EIO. It now
// reports a LocalStoreError, which ReadDir answers from the filer; the next
// builds wait out a backoff instead of re-listing the directory only to fail
// at the first insert again; and once the disk has room the directory caches.
func TestEnsureVisitedOnAFullDiskReportsLocalStoreErrorAndBacksOff(t *testing.T) {
shortStoreRefusalBackoff(t, 200*time.Millisecond)
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
store := &fullDiskBatchStore{metaBatchStore: mc.batchStore}
mc.batchStore = store
store.full.Store(true)
client := &countingListClient{buildListClient: buildListClient{responses: listResponses(3)}}
accessor := &buildFilerAccessor{client: client}
err := EnsureVisited(context.Background(), mc, accessor, "/d", 0)
var refused *LocalStoreError
if !errors.As(err, &refused) {
t.Fatalf("EnsureVisited on a full disk = %v, want a LocalStoreError", err)
}
if refused.Path != "/d" || !errors.Is(err, errCacheDiskFull) {
t.Errorf("refusal = %v, want /d refused with the store's error", err)
}
if mc.IsDirectoryCached("/d") {
t.Error("a directory the store refused is reported cached")
}
lists := client.lists.Load()
// Within the backoff no build is tried: not for this directory, not for
// another one, and the filer is not asked to list either.
for _, dir := range []util.FullPath{"/d", "/e"} {
if err := EnsureVisited(context.Background(), mc, accessor, dir, 0); !errors.As(err, &refused) || refused.Path != dir {
t.Fatalf("EnsureVisited(%s) within the backoff = %v, want a LocalStoreError for it", dir, err)
}
}
if got := client.lists.Load(); got != lists {
t.Errorf("the filer was asked for %d more listings within the backoff, want none", got-lists)
}
// The disk has room again: after the backoff the directory caches.
store.full.Store(false)
time.Sleep(250 * time.Millisecond)
if err := EnsureVisited(context.Background(), mc, accessor, "/d", 0); err != nil {
t.Fatalf("EnsureVisited after the backoff = %v", err)
}
if !mc.IsDirectoryCached("/d") {
t.Fatal("directory not cached once the store took writes again")
}
if n := countChildren(t, mc, "/d"); n != 3 {
t.Errorf("cached %d children, want 3", n)
}
}
// A rebuild that cannot wipe the children it is replacing fails on the store
// too, not on the filer.
func TestEnsureVisitedRebuildThatCannotWipeReportsLocalStoreError(t *testing.T) {
shortStoreRefusalBackoff(t, time.Minute)
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
ctx := context.Background()
for _, name := range []string{"old1", "old2"} {
if err := mc.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath("/d").Child(name), Attr: filer.Attr{Mode: 0o644}}, 0); err != nil {
t.Fatal(err)
}
}
store := &fullDiskBatchStore{metaBatchStore: mc.batchStore}
mc.batchStore = store
store.full.Store(true)
accessor := &buildFilerAccessor{client: &buildListClient{responses: listResponses(3)}}
err := EnsureVisited(ctx, mc, accessor, "/d", 0)
var refused *LocalStoreError
if !errors.As(err, &refused) {
t.Fatalf("EnsureVisited = %v, want a LocalStoreError", err)
}
if mc.IsDirectoryCached("/d") {
t.Error("a directory the store refused is reported cached")
}
}
// The listing fits, but the store refuses the event buffered during it when
// the build completes. That is the store too.
func TestEnsureVisitedRefusedReplayReportsLocalStoreError(t *testing.T) {
shortStoreRefusalBackoff(t, time.Minute)
mc, store, _, _ := newFullDiskMetaCache(t, "/")
defer mc.Shutdown()
var applyErr error
accessor := &buildFilerAccessor{client: &buildListClient{
responses: listResponses(2),
onFirstRecv: func() {
// A peer creates a file while the listing streams: the event is
// buffered for the build, and the disk fills before it completes.
store.full.Store(true)
applyErr = mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
Directory: "/d",
TsNs: time.Now().Add(time.Hour).UnixNano(),
EventNotification: &filer_pb.EventNotification{
NewEntry: fileEntry("late.txt", 2),
NewParentPath: "/d",
},
}, SubscriberMetadataResponseApplyOptions)
},
}}
err := EnsureVisited(context.Background(), mc, accessor, "/d", 0)
if applyErr != nil {
t.Fatalf("buffering the event: %v", applyErr)
}
var refused *LocalStoreError
if !errors.As(err, &refused) {
t.Fatalf("EnsureVisited = %v, want a LocalStoreError", err)
}
if mc.IsDirectoryCached("/d") {
t.Error("a directory whose replay the store refused is reported cached")
}
if mc.storeRefusal() == nil {
t.Error("a refused replay did not start the backoff")
}
}
// A listing the filer fails is not the store's doing: no backoff.
func TestEnsureVisitedFilerFailureStartsNoStoreBackoff(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
accessor := &buildFilerAccessor{client: failingListClient{err: errors.New("filer exploded")}}
err := EnsureVisited(context.Background(), mc, accessor, "/d", 0)
if err == nil {
t.Fatal("EnsureVisited with a failing filer = nil")
}
var refused *LocalStoreError
if errors.As(err, &refused) {
t.Fatalf("a filer failure was reported as the store's: %v", err)
}
if mc.storeRefusal() != nil {
t.Error("a filer failure started the store backoff")
}
}
type failingListClient struct {
filer_pb.SeaweedFilerClient
err error
}
func (c failingListClient) ListEntries(context.Context, *filer_pb.ListEntriesRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
return nil, c.err
}
// A build discarded by a distrust is listed again. That is not the store's
// doing: it starts no backoff.
func TestEnsureVisitedDiscardedBuildStartsNoStoreBackoff(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
var discardOnce sync.Once
accessor := &buildFilerAccessor{client: &buildListClient{
responses: listResponses(2),
onFirstRecv: func() {
discardOnce.Do(func() { mc.DiscardDirectoryBuilds(func() {}) })
},
}}
if err := EnsureVisited(context.Background(), mc, accessor, "/d", 0); err != nil {
t.Fatalf("EnsureVisited = %v", err)
}
if !mc.IsDirectoryCached("/d") {
t.Error("directory not cached once its discarded build was listed again")
}
if mc.storeRefusal() != nil {
t.Error("a discarded build started the store backoff")
}
}
+27 -4
View File
@@ -1,6 +1,7 @@
package page_writer
import (
"fmt"
"io"
"os"
"sync"
@@ -211,13 +212,35 @@ func (sc *SwapFileChunk) SaveContent(saveFn SaveToStorageFunc) {
}
data := mem.Allocate(int(stopOffset - startOffset))
n, _ := sc.swapfile.file.ReadAt(data, startOffset+int64(sc.actualChunkIndex)*sc.swapfile.chunkSize)
if n > 0 {
reader := util.NewBytesReader(data[:n])
saveFn(reader, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(n), tsNs, func() {
n, err := sc.swapfile.file.ReadAt(data, startOffset+int64(sc.actualChunkIndex)*sc.swapfile.chunkSize)
if n < len(data) {
// The bytes were acknowledged to the writer, so uploading less than
// the interval or skipping it would publish a hole. Hand the upload a
// reader that fails, which records the failure on the handle like a
// failed chunk upload, and stop: the handle cannot flush cleanly.
if err == nil || err == io.EOF {
err = io.ErrUnexpectedEOF
}
err = fmt.Errorf("read swap file in %s [%d,%d) of chunk %d: %w", sc.swapfile.dir, startOffset, stopOffset, sc.logicChunkIndex, err)
glog.Errorf("%v", err)
saveFn(&failedReader{err: err}, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(len(data)), tsNs, func() {
})
mem.Free(data)
return
}
reader := util.NewBytesReader(data)
saveFn(reader, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(len(data)), tsNs, func() {
})
mem.Free(data)
}
}
// failedReader fails every read with err.
type failedReader struct {
err error
}
func (r *failedReader) Read([]byte) (int, error) {
return 0, r.err
}
@@ -1,9 +1,15 @@
package page_writer
import (
"errors"
"io"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// When the swap file cannot be created, SaveDataAt must fail the write
@@ -54,3 +60,114 @@ func TestSaveDataAtReportsFailedSwapWrite(t *testing.T) {
t.Fatalf("write through a closed swap file = %d, %v; want 0 and an error", n, err)
}
}
// swapReadBackProbe collects what the pipeline hands to its uploader and the
// errors the uploader meets reading it, the way a chunk upload does.
type swapReadBackProbe struct {
mu sync.Mutex
uploaded map[int64][]byte
errs []error
}
func (p *swapReadBackProbe) save(reader io.Reader, offset int64, size int64, modifiedTsNs int64, cleanupFn func()) {
defer cleanupFn()
body, err := io.ReadAll(reader)
p.mu.Lock()
defer p.mu.Unlock()
if err != nil {
p.errs = append(p.errs, err)
return
}
if p.uploaded == nil {
p.uploaded = make(map[int64][]byte)
}
p.uploaded[offset] = body
}
// Dirty pages in the swap file were acknowledged to the writer. When they
// cannot be read back at upload time the interval must fail the upload, not
// go out short or be skipped, and the chunk must still release its budget.
func TestSwapChunkReadBackFailureFailsTheUpload(t *testing.T) {
for _, tc := range []struct {
name string
breakF func(t *testing.T, f *os.File)
}{
{"closed swap file", func(t *testing.T, f *os.File) {
if err := f.Close(); err != nil {
t.Fatal(err)
}
}},
{"truncated swap file", func(t *testing.T, f *os.File) {
if err := f.Truncate(0); err != nil {
t.Fatal(err)
}
}},
} {
t.Run(tc.name, func(t *testing.T) {
probe := &swapReadBackProbe{}
accountant := NewWriteBufferAccountant(1 << 20)
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, probe.save, 16, t.TempDir(), accountant)
defer up.Shutdown()
// Not sequential: the chunk goes to the swap file.
if n, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 {
t.Fatalf("write = %d, %v", n, err)
}
tc.breakF(t, up.swapFile.file)
up.FlushAll()
probe.mu.Lock()
defer probe.mu.Unlock()
if len(probe.uploaded) != 0 {
t.Errorf("uploaded %v from a swap file that cannot be read", probe.uploaded)
}
if len(probe.errs) != 1 {
t.Fatalf("upload read errors = %v, want exactly one", probe.errs)
}
t.Logf("upload error: %v", probe.errs[0])
waitForBudgetRelease(t, accountant)
})
}
}
// A swap file cut short fails only the intervals it no longer holds, and the
// upload of the first failed interval ends the chunk's save: the handle cannot
// flush cleanly anyway.
func TestSwapChunkReadBackFailureKeepsReadableIntervals(t *testing.T) {
probe := &swapReadBackProbe{}
accountant := NewWriteBufferAccountant(1 << 20)
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, probe.save, 16, t.TempDir(), accountant)
defer up.Shutdown()
if _, err := up.SaveDataAt([]byte("head"), 0, false, 1); err != nil {
t.Fatal(err)
}
if _, err := up.SaveDataAt([]byte("tail"), 600, false, 2); err != nil {
t.Fatal(err)
}
// The chunk is slot 1 of the swap file: [1024, 2048). Cut it inside the
// second interval.
if err := up.swapFile.file.Truncate(1024 + 602); err != nil {
t.Fatal(err)
}
up.FlushAll()
probe.mu.Lock()
defer probe.mu.Unlock()
if string(probe.uploaded[0]) != "head" || len(probe.uploaded) != 1 {
t.Errorf("uploaded %v, want only the first interval", probe.uploaded)
}
if len(probe.errs) != 1 || !errors.Is(probe.errs[0], io.ErrUnexpectedEOF) {
t.Errorf("upload read errors = %v, want one unexpected EOF", probe.errs)
}
waitForBudgetRelease(t, accountant)
}
func waitForBudgetRelease(t *testing.T, accountant *WriteBufferAccountant) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for accountant.Used() != 0 {
if time.Now().After(deadline) {
t.Fatalf("write budget still holds %d bytes after the failed upload", accountant.Used())
}
time.Sleep(5 * time.Millisecond)
}
}
+13
View File
@@ -15,6 +15,7 @@ import (
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"golang.org/x/sync/semaphore"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
@@ -164,6 +165,9 @@ type Option struct {
type WFS struct {
readAuth *ReadAuth
// chunkProofs keeps the assignment proofs of uploaded chunks until their
// entries are stored; nil without a filer token, which gets none.
chunkProofs *chunkProofs
// Metadata-only refusal token, detached at final Forget; no live resources retained.
writebackContentErrors sync.Map
// https://dl.acm.org/doi/fullHtml/10.1145/3310148
@@ -266,6 +270,11 @@ type WFS struct {
// lockClient is the DLM client for cross-mount write coordination.
// Non-nil only when EnableDistributedLock is true.
lockClient *cluster.LockClient
// storeRefusedListings bounds the listings read through while the local
// store refuses writes; see readDirectoryDirectStoreRefused.
storeRefusedListings *semaphore.Weighted
storeRefusedListingsOnce sync.Once
}
const defaultDirIdleEvict = 10 * time.Minute
@@ -324,6 +333,10 @@ func NewSeaweedFileSystem(option *Option) *WFS {
dirIdleEvict: dirIdleEvict,
}
if option.FilerTokenSource != nil {
wfs.chunkProofs = newChunkProofs(chunkProofLimit)
}
// With writeback caching, this mount is the single writer. Increase kernel
// FUSE cache TTLs so the kernel doesn't re-issue Lookup/GetAttr for every
// path component and stat — the local meta cache is authoritative.
+113 -17
View File
@@ -13,6 +13,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/sync/semaphore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -305,6 +306,10 @@ func (wfs *WFS) doReadDirectory(ctx context.Context, input *fuse.ReadIn, out Dir
if errors.As(err, &tooLarge) {
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
}
var refused *meta_cache.LocalStoreError
if errors.As(err, &refused) {
return wfs.readDirectoryDirectStoreRefused(ctx, input, out, dh, dirPath, processEachEntryFn)
}
return dirReadStatus(ctx, err, "dir ReadDirAll %s: %v", dirPath, err)
}
@@ -354,13 +359,22 @@ func (wfs *WFS) doReadDirectory(ctx context.Context, input *fuse.ReadIn, out Dir
}
}
// A hand-over to the direct path below keeps the pagination state on
// dh, so it carries on from wherever the cached walk reached -- within
// this request too: the entries the walk just put in the reply are not
// to be sent again.
resumed := *input
resumed.Offset = dh.entryStreamOffset + uint64(entryCurrentIndex)
// Cache exhausted, load next batch
if err := wfs.ensureDirectoryVisited(ctx, dirPath); err != nil {
var tooLarge *meta_cache.DirectoryTooLargeError
if errors.As(err, &tooLarge) {
// The direct path keeps the same pagination state on dh, so it
// carries on from wherever the cached walk reached.
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
return wfs.readDirectoryDirect(ctx, &resumed, out, dh, dirPath, processEachEntryFn)
}
var refused *meta_cache.LocalStoreError
if errors.As(err, &refused) {
return wfs.readDirectoryDirectStoreRefused(ctx, &resumed, out, dh, dirPath, processEachEntryFn)
}
return dirReadStatus(ctx, err, "dir ReadDirAll %s: %v", dirPath, err)
}
@@ -378,7 +392,7 @@ func (wfs *WFS) doReadDirectory(ctx context.Context, input *fuse.ReadIn, out Dir
if errors.Is(err, meta_cache.ErrRefreshRangeTooLarge) {
// re-tile with a full rebuild; serve this request direct
wfs.purgeDirectoryCache(dirPath)
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
return wfs.readDirectoryDirect(ctx, &resumed, out, dh, dirPath, processEachEntryFn)
}
glog.V(1).Infof("refresh %s sections: %v", dirPath, err)
}
@@ -430,7 +444,9 @@ func dirReadStatus(ctx context.Context, err error, format string, args ...any) f
// ensureDirectoryVisited pulls the directory into the local cache, unless it is
// too large to cache: then the directory is marked read-through, so later
// listings go straight to the filer without re-asking.
// listings go straight to the filer without re-asking. A directory the local
// store refused (cache disk full) is not marked: the store's own backoff
// decides when a listing tries to cache again.
func (wfs *WFS) ensureDirectoryVisited(ctx context.Context, dirPath util.FullPath) error {
err := meta_cache.EnsureVisited(ctx, wfs.metaCache, wfs, dirPath, wfs.option.CacheDirMaxEntries)
var tooLarge *meta_cache.DirectoryTooLargeError
@@ -440,6 +456,31 @@ func (wfs *WFS) ensureDirectoryVisited(ctx context.Context, dirPath util.FullPat
return err
}
// storeRefusedListingLimit caps the directory listings one mount reads through
// at once while its local store refuses writes. Every listing of the mount
// then goes to the filer instead of the cache; the cap spreads a burst out
// rather than sending it all at once.
const storeRefusedListingLimit = 4
// readDirectoryDirectStoreRefused serves a listing from the filer because the
// local store could not cache the directory, at most storeRefusedListingLimit
// of them at a time per mount.
func (wfs *WFS) readDirectoryDirectStoreRefused(ctx context.Context, input *fuse.ReadIn, out DirEntrySink, dh *DirectoryHandle, dirPath util.FullPath, processEachEntryFn func(entry *filer.Entry, index int64) bool) fuse.Status {
slots := wfs.storeRefusedListingSlots()
if err := slots.Acquire(ctx, 1); err != nil {
return fuse.EINTR
}
defer slots.Release(1)
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
}
func (wfs *WFS) storeRefusedListingSlots() *semaphore.Weighted {
wfs.storeRefusedListingsOnce.Do(func() {
wfs.storeRefusedListings = semaphore.NewWeighted(storeRefusedListingLimit)
})
return wfs.storeRefusedListings
}
func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out DirEntrySink, dh *DirectoryHandle, dirPath util.FullPath, processEachEntryFn func(entry *filer.Entry, index int64) bool) fuse.Status {
listingCtx := filer_pb.WithChunksOmitted(ctx)
var lastEntryName string
@@ -447,11 +488,11 @@ func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out
if input.Offset >= dh.entryStreamOffset {
if len(dh.entryStream) == 0 && input.Offset > dh.entryStreamOffset {
skipCount := uint32(input.Offset-dh.entryStreamOffset) + batchSize
entries, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
entries, listed, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
if err != nil {
return dirReadStatus(ctx, err, "list filer directory: %v", err)
}
dh.entryStream = append(dh.entryStream, entries...)
dh.entryStream = append(dh.entryStream, wfs.withLocalOnly(listingCtx, dirPath, entries, "", listed < int(skipCount))...)
if dh.snapshotTsNs == 0 {
dh.snapshotTsNs = snapshotTs
}
@@ -480,24 +521,31 @@ func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out
}
}
entries, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
entries, listed, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
if err != nil {
return dirReadStatus(ctx, err, "list filer directory: %v", err)
}
if dh.snapshotTsNs == 0 {
dh.snapshotTsNs = snapshotTs
}
// Only a short page from the filer ends the directory: the hidden
// system entries the loader leaves out shorten a full one.
lastPage := listed < int(batchSize)
entries = wfs.withLocalOnly(listingCtx, dirPath, entries, lastEntryName, lastPage)
// The whole page goes on the handle, and the next requests take what
// this reply has no room for from there, as from the cache, rather
// than listing the filer again and merging the unflushed creates again
// for every reply.
bufferFull := false
for _, entry := range entries {
currentIndex := int64(len(dh.entryStream))
dh.entryStream = append(dh.entryStream, entry)
if !processEachEntryFn(entry, currentIndex) {
if !bufferFull && !processEachEntryFn(entry, currentIndex) {
bufferFull = true
break
}
}
if !bufferFull && len(entries) < int(batchSize) {
if !bufferFull && lastPage {
dh.isFinished = true
// After a full successful read-through listing, exit direct mode
// so subsequent reads can use the cache instead of hitting the filer.
@@ -508,7 +556,53 @@ func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out
return fuse.OK
}
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64, includeSystemEntries bool) ([]*filer.Entry, int64, error) {
// withLocalOnly merges into a page listed from the filer the children this
// mount holds that are not on the filer yet (MetaCache.LocalOnlyChildren),
// such as a file created and not flushed, so a listing read through shows them
// as a cached one does. It takes those named after `after` and up to the
// page's last name, or every one past `after` on the directory's last page;
// later ones come with later pages. The page stays in name order, and a name
// the filer has by now is listed once, as the filer has it.
func (wfs *WFS) withLocalOnly(ctx context.Context, dirPath util.FullPath, page []*filer.Entry, after string, lastPage bool) []*filer.Entry {
upTo := ""
if !lastPage {
if len(page) == 0 {
return page
}
upTo = page[len(page)-1].Name()
}
local, err := wfs.metaCache.LocalOnlyChildren(ctx, dirPath, after, upTo)
if err != nil {
glog.V(1).Infof("list unflushed children of %s: %v", dirPath, err)
return page
}
if len(local) == 0 {
return page
}
merged := make([]*filer.Entry, 0, len(page)+len(local))
i, j := 0, 0
for i < len(page) && j < len(local) {
switch a, b := page[i].Name(), local[j].Name(); {
case a < b:
merged = append(merged, page[i])
i++
case b < a:
merged = append(merged, local[j])
j++
default:
merged = append(merged, page[i])
i++
j++
}
}
merged = append(merged, page[i:]...)
return append(merged, local[j:]...)
}
// loadDirectoryEntriesDirect lists up to limit entries from the filer. listed
// counts every entry the filer sent, the hidden system entries left out of
// entries included, so a caller can tell a full page from the last one.
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64, includeSystemEntries bool) (entries []*filer.Entry, listed int, actualSnapshotTsNs int64, err error) {
// limit can be a client-supplied resume offset rather than a batch size, so
// preallocating for it would size the slice from where the caller happened to
// seek. Reserve a batch and let append find the rest.
@@ -516,11 +610,13 @@ func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient
if prealloc > batchSize {
prealloc = batchSize
}
entries := make([]*filer.Entry, 0, prealloc)
var actualSnapshotTsNs int64
err := client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
entries = make([]*filer.Entry, 0, prealloc)
err = client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
// reset in case a failover retry re-runs a partly streamed page
entries, listed = entries[:0], 0
var innerErr error
actualSnapshotTsNs, innerErr = filer_pb.DoSeaweedListWithSnapshot(ctx, sc, dirPath, "", func(entry *filer_pb.Entry, isLast bool) error {
listed++
if !includeSystemEntries && meta_cache.IsHiddenSystemEntry(string(dirPath), entry.Name) {
return nil
}
@@ -533,7 +629,7 @@ func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient
return innerErr
})
if err != nil {
return nil, actualSnapshotTsNs, err
return nil, 0, actualSnapshotTsNs, err
}
return entries, actualSnapshotTsNs, nil
return entries, listed, actualSnapshotTsNs, nil
}
@@ -5,6 +5,9 @@ import (
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"sync/atomic"
"testing"
"time"
@@ -357,3 +360,304 @@ func TestReadDirPlusSanitizedName(t *testing.T) {
t.Errorf("%s keyed on the unsanitized name", dir.Child(rawName))
}
}
// A listing that began from the cache hands over to the filer when the
// directory stops being cacheable partway: here its cached listing is dropped
// and the rebuild finds it too large. The hand-over resumed the direct walk at
// the request's offset, so the entries the cached walk had just put in the same
// reply were sent again and the client saw names twice. A full cache disk
// takes the same hand-over on every request.
func TestReadDirHandOverToTheFilerMidWalkSendsEachNameOnce(t *testing.T) {
dir := util.FullPath("/d")
const total = 2500
var names []string
for i := 0; i < total; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
// The cache holds the first 1500 names, the filer all of them: a walk
// that lists every name finished from the filer.
wfs := newPagingWFS(t, dir, names[:1500], 0)
wfs.option.CacheDirMaxEntries = 100
startFakeFiler(t, wfs, &listingFilerServer{names: names})
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 64}
var offset uint64
dropped := false
for round := 0; round < 1000; round++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if !dropped {
// The cached listing goes away after the first reply.
wfs.inodeToPath.InvalidateChildrenCache(dir)
dropped = true
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
seen := map[string]int{}
var listed []string
for _, n := range sink.names {
if n == "." || n == ".." {
continue
}
seen[n]++
listed = append(listed, n)
}
for n, count := range seen {
if count > 1 {
t.Errorf("%s listed %d times", n, count)
}
}
if len(seen) != total {
t.Fatalf("listed %d distinct names (%d in all), want %d", len(seen), len(listed), total)
}
}
// listWholeDirectory lists dir through one handle in replies of at most
// sinkLimit entries, calling afterReply after each, and returns the names in
// listing order without "." and "..".
func listWholeDirectory(t *testing.T, wfs *WFS, dir util.FullPath, sinkLimit int, afterReply func(reply int)) []string {
t.Helper()
dirInode, found := wfs.inodeToPath.GetInode(dir)
if !found {
t.Fatalf("no inode for %s", dir)
}
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: sinkLimit}
var offset uint64
for reply := 0; reply < 100000; reply++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if afterReply != nil {
afterReply(reply)
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
var names []string
for _, name := range sink.names {
if name != "." && name != ".." {
names = append(names, name)
}
}
return names
}
// requireListing fails unless got is want: every name once, in order.
func requireListing(t *testing.T, got, want []string) {
t.Helper()
if slices.Equal(got, want) {
return
}
seen := map[string]int{}
for _, name := range got {
seen[name]++
}
var twice, missing []string
for name, count := range seen {
if count > 1 {
twice = append(twice, name)
}
}
for _, name := range want {
if seen[name] == 0 {
missing = append(missing, name)
}
}
sort.Strings(twice)
first := func(names []string) []string {
if len(names) > 5 {
return names[:5]
}
return names
}
t.Fatalf("listed %d names, want %d; listed more than once: %d %v; missing: %d %v", len(got), len(want), len(twice), first(twice), len(missing), first(missing))
}
// createUnflushed leaves dir/name as Create leaves a file before its first
// flush: a placeholder in the local store, and an open handle with dirty
// metadata.
func createUnflushed(t *testing.T, wfs *WFS, dir util.FullPath, name string) {
t.Helper()
path := dir.Child(name)
now := time.Now()
inode := wfs.inodeToPath.Lookup(path, now.Unix(), false, false, 0, true)
entry := &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, Mtime: now.Unix(), Crtime: now.Unix(), Inode: inode},
}
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(string(dir), entry), 0); err != nil {
t.Fatalf("insert placeholder %s: %v", path, err)
}
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
fh.dirtyMetadata = true
t.Cleanup(fh.dirtyPages.Destroy)
}
// A directory read through from the filer lists the files this mount created
// and has not flushed, as a cached listing does, though the filer has none of
// them yet: each once and in name order, wherever it falls among the filer's
// pages. One the filer has by now is listed once.
func TestReadDirReadThroughListsUnflushedCreates(t *testing.T) {
dir := util.FullPath("/d")
var filerNames []string
for i := 0; i < 2500; i++ {
filerNames = append(filerNames, fmt.Sprintf("f%05d", i))
}
// Before the first page, right after a page's last name, inside a page, a
// name the filer has by now, and past the last page.
unflushed := []string{"a-new", "f00999x", "f01500x", "f02000", "z-new"}
want := append(append([]string{}, filerNames...), "a-new", "f00999x", "f01500x", "z-new")
sort.Strings(want)
for _, sinkLimit := range []int{64, 5000} {
t.Run(fmt.Sprintf("replies of %d", sinkLimit), func(t *testing.T) {
wfs := newPagingWFS(t, dir, nil, 0)
wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry)
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
for _, name := range unflushed {
createUnflushed(t, wfs, dir, name)
}
// Too large to cache: listings read it through.
wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now())
requireListing(t, listWholeDirectory(t, wfs, dir, sinkLimit, nil), want)
})
}
}
// The mount's root read through from the filer. The loader leaves out the
// hidden system entries, etc and topics, so a full page from the filer that
// held one came back short and was taken for the end of the directory.
func TestReadDirReadThroughRootPastHiddenEntries(t *testing.T) {
root := util.FullPath("/")
var visible []string
for _, prefix := range []string{"d", "s", "u"} {
for i := 0; i < 500; i++ {
visible = append(visible, fmt.Sprintf("%s%04d", prefix, i))
}
}
// etc falls inside the first page of 1000, topics inside the second.
filerNames := append([]string{"etc", "topics"}, visible...)
sort.Strings(filerNames)
wfs := newPagingWFS(t, "/x", nil, 0)
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
wfs.inodeToPath.MarkDirectoryReadThrough(root, time.Now())
requireListing(t, listWholeDirectory(t, wfs, root, 5000, nil), visible)
}
// A listing walking the cache hands over to the filer when a section of the
// directory changed so much that refreshing it would list more than a
// refresh may (ErrRefreshRangeTooLarge). That hand-over, too, resumed at the
// request's offset and sent again the entries the cached walk had just put in
// the reply.
func TestReadDirHandOverOnOvergrownSectionSendsEachNameOnce(t *testing.T) {
ctx := context.Background()
dir := util.FullPath("/d")
var cached, filerNames, burst []string
for i := 0; i < 2000; i++ {
cached = append(cached, fmt.Sprintf("f%05d", i))
}
// Far more than one refresh may list.
for i := 0; i < 6000; i++ {
filerNames = append(filerNames, fmt.Sprintf("f%05d", i))
}
// Enough changes in one go to make a section stale.
for i := 0; i < 64; i++ {
burst = append(burst, fmt.Sprintf("g-%03d", i))
}
filerNames = append(filerNames, burst...)
wfs := newPagingWFS(t, dir, cached, 0)
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
// One section over the directory, as a build of it leaves.
if err := wfs.metaCache.BeginDirectoryBuild(ctx, dir); err != nil {
t.Fatalf("begin build: %v", err)
}
if err := wfs.metaCache.CompleteDirectoryBuild(ctx, dir, 1000, nil); err != nil {
t.Fatalf("complete build: %v", err)
}
got := listWholeDirectory(t, wfs, dir, 64, func(reply int) {
if reply != 0 {
return
}
// After the first reply other clients create a burst of files: the
// section goes stale, and refreshing it would list too much.
for i, name := range burst {
resp := &filer_pb.SubscribeMetadataResponse{
Directory: string(dir),
EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0o100644, FileSize: 1},
}},
TsNs: 2000 + int64(i),
}
if err := wfs.metaCache.ApplyMetadataResponse(ctx, resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply %s: %v", name, err)
}
}
})
requireListing(t, got, filerNames)
}
// countingListingFilerServer counts the listings it serves.
type countingListingFilerServer struct {
listingFilerServer
listings atomic.Int32
}
func (s *countingListingFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
s.listings.Add(1)
return s.listingFilerServer.ListEntries(req, stream)
}
// A page listed from the filer stays on the handle until the client has read
// it. A listing in small replies then lists each filer page once, and merges
// the unflushed creates once per page, rather than again for every reply.
func TestReadDirReadThroughListsEachFilerPageOnce(t *testing.T) {
dir := util.FullPath("/d")
var names []string
for i := 0; i < 2500; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
wfs := newPagingWFS(t, dir, nil, 0)
server := &countingListingFilerServer{listingFilerServer: listingFilerServer{names: names}}
startFakeFiler(t, wfs, server)
wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now())
requireListing(t, listWholeDirectory(t, wfs, dir, 64, nil), names)
// Three pages, and the empty one that finds the end.
if n := server.listings.Load(); n > 4 {
t.Errorf("the filer was asked for %d listings, want one per page of %d", n, batchSize)
}
}
@@ -0,0 +1,122 @@
package mount
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// heldListingFilerServer lists names, holding every listing until release is
// closed, and records how many it held at once.
type heldListingFilerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
names []string
release chan struct{}
inFlight atomic.Int32
peak atomic.Int32
}
func (s *heldListingFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
n := s.inFlight.Add(1)
defer s.inFlight.Add(-1)
for {
peak := s.peak.Load()
if n <= peak || s.peak.CompareAndSwap(peak, n) {
break
}
}
select {
case <-s.release:
case <-stream.Context().Done():
return stream.Context().Err()
}
for _, name := range s.names {
if name <= req.StartFromFileName {
continue
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, FileSize: 1},
}}); err != nil {
return err
}
}
return nil
}
func waitUntil(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(5 * time.Millisecond)
}
}
// While the local store refuses writes every listing of the mount reads
// through to the filer. Each still lists the whole directory, but no more than
// storeRefusedListingLimit go to the filer at once; a listing waiting for a
// slot gives up with EINTR when its request is interrupted.
func TestReadDirStoreRefusedListsFromTheFilerAFewAtATime(t *testing.T) {
dir := util.FullPath("/d")
names := []string{"a", "b", "c"}
wfs := newPagingWFS(t, dir, nil, 0)
server := &heldListingFilerServer{names: names, release: make(chan struct{})}
startFakeFiler(t, wfs, server)
const listings = 3 * storeRefusedListingLimit
results := make([][]string, listings)
statuses := make([]fuse.Status, listings)
var wg sync.WaitGroup
for i := 0; i < listings; i++ {
dhid, dh := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
wg.Add(1)
go func(i int, dh *DirectoryHandle) {
defer wg.Done()
statuses[i] = wfs.readDirectoryDirectStoreRefused(context.Background(), &fuse.ReadIn{Offset: directoryStreamBaseOffset}, &pagingSink{limit: 100}, dh, dir, func(entry *filer.Entry, index int64) bool {
results[i] = append(results[i], entry.Name())
return true
})
}(i, dh)
}
waitUntil(t, "the first listings to reach the filer", func() bool { return server.inFlight.Load() == storeRefusedListingLimit })
time.Sleep(50 * time.Millisecond)
if n := server.inFlight.Load(); n != storeRefusedListingLimit {
t.Errorf("%d listings at the filer at once, want %d", n, storeRefusedListingLimit)
}
// Every slot is taken: an interrupted request stops waiting.
ctx, cancel := context.WithCancel(context.Background())
cancel()
dhid, dh := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
if status := wfs.readDirectoryDirectStoreRefused(ctx, &fuse.ReadIn{Offset: directoryStreamBaseOffset}, &pagingSink{limit: 100}, dh, dir, func(*filer.Entry, int64) bool { return true }); status != fuse.EINTR {
t.Errorf("an interrupted listing waiting for a slot = %v, want EINTR", status)
}
close(server.release)
wg.Wait()
if peak := server.peak.Load(); peak > storeRefusedListingLimit {
t.Errorf("up to %d listings at the filer at once, want at most %d", peak, storeRefusedListingLimit)
}
for i := 0; i < listings; i++ {
if statuses[i] != fuse.OK {
t.Errorf("listing %d = %v", i, statuses[i])
}
if got := fmt.Sprint(results[i]); got != fmt.Sprint(names) {
t.Errorf("listing %d = %s, want %s", i, got, fmt.Sprint(names))
}
}
}
+2 -2
View File
@@ -90,7 +90,7 @@ func TestLoadDirectoryEntriesDirectFiltersHiddenEntriesAndMapsIds(t *testing.T)
},
}
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, mapper, util.FullPath("/"), "", false, 10, 0, false)
entries, _, _, err := loadDirectoryEntriesDirect(context.Background(), client, mapper, util.FullPath("/"), "", false, 10, 0, false)
if err != nil {
t.Fatalf("loadDirectoryEntriesDirect: %v", err)
}
@@ -115,7 +115,7 @@ func TestLoadDirectoryEntriesDirectShowsSystemEntriesWhenEnabled(t *testing.T) {
},
}
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, nil, util.FullPath("/"), "", false, 10, 0, true)
entries, _, _, err := loadDirectoryEntriesDirect(context.Background(), client, nil, util.FullPath("/"), "", false, 10, 0, true)
if err != nil {
t.Fatalf("loadDirectoryEntriesDirect: %v", err)
}
+25 -7
View File
@@ -93,18 +93,13 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
}
// lock source and target file handles
fhOutActiveLock := fhOut.wfs.fhLockTable.AcquireLock("CopyFileRange", fhOut.fh, util.ExclusiveLock)
defer fhOut.wfs.fhLockTable.ReleaseLock(fhOut.fh, fhOutActiveLock)
unlockHandles := lockCopyFileRangeHandles(fhIn, fhOut)
defer unlockHandles()
if fhOut.entry == nil {
return 0, fuse.ENOENT
}
if fhIn.fh != fhOut.fh {
fhInActiveLock := fhIn.wfs.fhLockTable.AcquireLock("CopyFileRange", fhIn.fh, util.SharedLock)
defer fhIn.wfs.fhLockTable.ReleaseLock(fhIn.fh, fhInActiveLock)
}
// directories are not supported
if fhIn.entry.IsDirectory || fhOut.entry.IsDirectory {
return 0, fuse.EISDIR
@@ -224,6 +219,29 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
return written, fuse.OK
}
// lockCopyFileRangeHandles takes the destination handle's lock exclusively and
// the source handle's lock shared, in ascending FileHandleId order whichever of
// the two is the destination. Two copies in opposite directions between the
// same pair of files would otherwise each hold their destination and wait for
// their source. It returns the function that releases both.
func lockCopyFileRangeHandles(fhIn, fhOut *FileHandle) (unlock func()) {
lockTable := fhOut.wfs.fhLockTable
if fhIn.fh == fhOut.fh {
lock := lockTable.AcquireLock("CopyFileRange", fhOut.fh, util.ExclusiveLock)
return func() { lockTable.ReleaseLock(fhOut.fh, lock) }
}
first, firstType, second, secondType := fhOut, util.ExclusiveLock, fhIn, util.SharedLock
if fhIn.fh < fhOut.fh {
first, firstType, second, secondType = fhIn, util.SharedLock, fhOut, util.ExclusiveLock
}
firstLock := lockTable.AcquireLock("CopyFileRange", first.fh, firstType)
secondLock := lockTable.AcquireLock("CopyFileRange", second.fh, secondType)
return func() {
lockTable.ReleaseLock(second.fh, secondLock)
lockTable.ReleaseLock(first.fh, firstLock)
}
}
func (wfs *WFS) tryServerSideWholeFileCopy(cancel <-chan struct{}, in *fuse.CopyFileRangeIn, fhIn, fhOut *FileHandle) (written uint32, handled bool, code fuse.Status) {
if !wfs.canSignFilerCopy() {
glog.V(4).Infof("server-side copy: skipped (filer token file without a filer signing key)")
+87
View File
@@ -6,7 +6,10 @@ import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
@@ -539,3 +542,87 @@ func TestServerSideCopyNeedsASigningKeyWithAFilerTokenFile(t *testing.T) {
})
}
}
// Two copies in opposite directions between the same pair of files must not
// wait on each other's handle locks. The test holds the lower handle's lock so
// that the first copy queues for it and the second copy has to take its
// handle locks while the first one is still waiting for its own: with the
// destination locked before the source, each copy then holds its destination
// and waits for its source.
func TestCopyFileRangeInOppositeDirectionsDoesNotDeadlock(t *testing.T) {
wfs := newCopyRangeTestWFS()
var handles [2]*FileHandle
for i, name := range []string{"a.txt", "b.txt"} {
path := util.FullPath("/" + name)
inode := wfs.inodeToPath.Lookup(path, 1, false, false, 0, true)
handle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: inode},
Content: []byte("hello"),
}, 0, 0)
handle.RememberPath(path)
t.Cleanup(handle.dirtyPages.Destroy)
handles[i] = handle
}
low, high := handles[0], handles[1]
if high.fh < low.fh {
low, high = high, low
}
copyFromTo := func(src, dst *FileHandle) <-chan fuse.Status {
done := make(chan fuse.Status, 1)
go func() {
_, status := wfs.CopyFileRange(make(chan struct{}), &fuse.CopyFileRangeIn{
FhIn: uint64(src.fh),
FhOut: uint64(dst.fh),
Len: 5,
})
done <- status
}()
return done
}
held := wfs.fhLockTable.AcquireLock("test", low.fh, util.ExclusiveLock)
intoLow := copyFromTo(high, low)
waitForBlockedCopyFileRange(t, 1)
intoHigh := copyFromTo(low, high)
waitForBlockedCopyFileRange(t, 2)
wfs.fhLockTable.ReleaseLock(low.fh, held)
for name, done := range map[string]<-chan fuse.Status{"into low": intoLow, "into high": intoHigh} {
select {
case status := <-done:
if status != fuse.OK {
t.Errorf("CopyFileRange (%s) status = %v, want OK", name, status)
}
case <-time.After(10 * time.Second):
t.Fatalf("CopyFileRange (%s) did not finish: the two copies hold each other's handle locks", name)
}
}
}
// waitForBlockedCopyFileRange waits until n CopyFileRange calls are parked in
// a handle lock queue, which the lock table does not otherwise expose.
func waitForBlockedCopyFileRange(t *testing.T, n int) {
t.Helper()
buf := make([]byte, 1<<20)
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
size := runtime.Stack(buf, true)
if size == len(buf) { // the dump was cut short: look at all of it
buf = make([]byte, 2*len(buf))
continue
}
blocked := 0
for _, stack := range strings.Split(string(buf[:size]), "\n\n") {
if strings.Contains(stack, "mount.(*WFS).CopyFileRange(") && strings.Contains(stack, "sync.(*Cond).Wait") {
blocked++
}
}
if blocked >= n {
return
}
time.Sleep(time.Millisecond)
}
t.Fatalf("%d CopyFileRange calls never blocked on a handle lock", n)
}
+1 -1
View File
@@ -377,7 +377,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
// no chunk deleter here: a failed fold reports the blobs it saved
unfolded := chunks
chunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, chunks)
chunks, manifestErr := wfs.maybeManifestize(fileFullPath, chunks)
if manifestErr != nil {
// not good, but should be ok
glog.V(0).Infof("MaybeManifestize: %v", manifestErr)
+74 -15
View File
@@ -17,27 +17,18 @@ import (
"google.golang.org/protobuf/proto"
)
// A write the swap file cannot buffer fails, and must not grow the file: the
// next flush would publish that size with a hole where its data should be. A
// write that buffers only its first chunk is a short write of those bytes, or
// an error for kernel writeback, which would drop the rest silently.
func TestFailedWriteDoesNotGrowFile(t *testing.T) {
t.Run("short write", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, 0) })
t.Run("kernel writeback", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, fuse.WRITE_CACHE) })
}
func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
// openSwapWriteHandle opens /dir/file for writing on a WFS with one writable
// chunk slot, so a second chunk is buffered in the swap file under swapDir.
// The file holds 256 'O' bytes on the fake filer.
func openSwapWriteHandle(t *testing.T, swapDir string) (*WFS, *FileHandle, *g6ConditionalPeer, *fuse.OpenOut) {
t.Helper()
base := attributeAppendEntry(1)
base.CommitTsNs = 100
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
peer.blobs = map[string][]byte{base.Chunks[0].GetFileIdString(): bytes.Repeat([]byte{'O'}, 256)}
w := newInvalidateTestWFS(t)
notADir := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(notADir, nil, 0600); err != nil {
t.Fatal(err)
}
w.option.uniqueCacheDirForWrite = filepath.Join(notADir, "swap")
w.option.uniqueCacheDirForWrite = swapDir
w.option.DefaultPermissions = true
w.posixLocks = NewPosixLockTable()
w.option.ConcurrentWriters = 1
@@ -56,6 +47,25 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
fh := w.GetHandle(FileHandleId(out.Fh))
g6AppendUploader(t, fh, 100, peer)
return w, fh, peer, out
}
// A write the swap file cannot buffer fails, and must not grow the file: the
// next flush would publish that size with a hole where its data should be. A
// write that buffers only its first chunk is a short write of those bytes, or
// an error for kernel writeback, which would drop the rest silently.
func TestFailedWriteDoesNotGrowFile(t *testing.T) {
t.Run("short write", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, 0) })
t.Run("kernel writeback", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, fuse.WRITE_CACHE) })
}
func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
notADir := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(notADir, nil, 0600); err != nil {
t.Fatal(err)
}
w, fh, peer, out := openSwapWriteHandle(t, filepath.Join(notADir, "swap"))
write := func(offset uint64, size int, value byte) (uint32, fuse.Status) {
return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: uint32(size), WriteFlags: writeFlags}, bytes.Repeat([]byte{value}, size))
}
@@ -93,3 +103,52 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
t.Fatalf("stored size %d, want 1024 with the original and buffered bytes", peer.entry.Attributes.FileSize)
}
}
// Writes buffered in the swap file were acknowledged to the application. If the
// swap file cannot be read back when they upload, fsync must fail like a failed
// chunk upload and the filer must not get an entry that claims those bytes.
func TestFsyncFailsWhenSwapFileCannotBeReadBack(t *testing.T) {
swapDir := t.TempDir()
w, _, peer, out := openSwapWriteHandle(t, swapDir)
peer.mu.Lock()
before := proto.Clone(peer.entry).(*filer_pb.Entry)
peer.mu.Unlock()
write := func(offset uint64, value byte) (uint32, fuse.Status) {
return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: 256}, bytes.Repeat([]byte{value}, 256))
}
if n, code := write(256, 'A'); n != 256 || code != fuse.OK {
t.Fatalf("buffered write = %d, %v", n, code)
}
// The only writable chunk slot is taken, so this write goes to the swap file.
if n, code := write(4096, 'B'); n != 256 || code != fuse.OK {
t.Fatalf("swap file write = %d, %v", n, code)
}
swapFiles, err := os.ReadDir(swapDir)
if err != nil || len(swapFiles) != 1 {
t.Fatalf("swap dir = %v, %v; want one swap file", swapFiles, err)
}
// An outside cleanup cuts the swap file after the write was acknowledged.
if err := os.Truncate(filepath.Join(swapDir, swapFiles[0].Name()), 0); err != nil {
t.Fatal(err)
}
code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh})
if code == fuse.OK {
t.Fatal("fsync succeeded although acknowledged bytes could not be uploaded")
}
t.Logf("fsync = %v", code)
if _, code := write(8192, 'C'); code == fuse.OK {
t.Error("write after the failed upload succeeded; the handle can no longer flush cleanly")
}
peer.mu.Lock()
defer peer.mu.Unlock()
// The failed fsync publishes nothing: the filer keeps the entry and the 256
// bytes it had before the writes.
if !proto.Equal(peer.entry, before) {
t.Fatalf("a failed fsync changed the filer entry:\n got %v\nwant %v", peer.entry, before)
}
if stored := g6StoredBytes(t, peer); !bytes.Equal(stored, bytes.Repeat([]byte{'O'}, 256)) {
t.Fatalf("filer content = %q, want the original 256 bytes", stored)
}
}
+12
View File
@@ -76,3 +76,15 @@ func filerTokenExpiry(token security.EncodedJwt) time.Time {
}
return time.Time{}
}
// filerTokenScoped reports whether the filer scopes the mount's current
// token, as it does one with path grants or a method list. A token that
// cannot be read or decoded counts as scoped.
func (wfs *WFS) filerTokenScoped() bool {
token, err := wfs.option.FilerTokenSource(context.Background())
if err != nil {
return true
}
claims, ok := security.FilerTokenClaims(token)
return !ok || claims.IsScoped() || len(claims.AllowedMethods) > 0
}
+1 -1
View File
@@ -156,7 +156,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
// Try to create manifest chunks for large files
// no chunk deleter here: a failed fold reports the blobs it saved
unfolded := compactedChunks
compactedChunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, compactedChunks)
compactedChunks, manifestErr := wfs.maybeManifestize(fileFullPath, compactedChunks)
if manifestErr != nil {
glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr)
}
+15 -1
View File
@@ -102,14 +102,22 @@ func newStreamMutateMux(wfs *WFS) *streamMutateMux {
}
// CreateEntry sends a CreateEntryRequest over the stream and waits for the response.
// The request carries the assignment proofs of the new chunks it stores,
// released once the filer acknowledged it.
func (m *streamMutateMux) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
proofs := m.wfs.chunkProofs
held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth)
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: req},
})
if err != nil {
return nil, err
}
return createEntryFromResponse(resp, req)
cr, err := createEntryFromResponse(resp, req)
if err == nil && held {
proofs.release(req.GetEntry().GetChunks())
}
return cr, err
}
// createEntryFromResponse unwraps a create's nested response, mapping its
@@ -146,7 +154,10 @@ func createEntryFromResponse(resp *filer_pb.StreamMutateEntryResponse, req *file
}
// UpdateEntry sends an UpdateEntryRequest over the stream and waits for the response.
// Proofs are attached and released as for CreateEntry.
func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
proofs := m.wfs.chunkProofs
held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth)
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
Request: &filer_pb.StreamMutateEntryRequest_UpdateRequest{UpdateRequest: req},
})
@@ -154,6 +165,9 @@ func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateE
return nil, err
}
if r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_UpdateResponse); ok {
if held {
proofs.release(req.GetEntry().GetChunks())
}
return r.UpdateResponse, nil
}
return nil, fmt.Errorf("unexpected response type %T", resp.Response)
+21
View File
@@ -25,6 +25,18 @@ func (wfs *WFS) shouldCacheUploadedChunk(offset int64) bool {
return wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil || wfs.readAuth != nil)
}
// maybeManifestize folds a file's chunks into manifests as
// filer.MaybeManifestize does, except on a mount with a scoped filer token: a
// filer serving a scoped token stores no new chunk in an entry that holds
// manifests, so every later write to a folded file would be refused. Such a
// mount keeps chunk lists flat.
func (wfs *WFS) maybeManifestize(fullPath util.FullPath, chunks []*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) {
if wfs.chunkProofs != nil && wfs.filerTokenScoped() {
return chunks, nil
}
return filer.MaybeManifestize(wfs.saveDataAsChunk(fullPath), nil, chunks)
}
func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType {
// Backstop: FUSE entry points sanitize names before they reach
@@ -56,6 +68,12 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
}
}
// A filer serving a scoped token stores the chunk only with the
// assignment proof it returns, so make room to keep it first.
if err = wfs.chunkProofs.reserve(1); err != nil {
glog.V(0).Infof("upload data %v: %v", filename, err)
return nil, fmt.Errorf("upload data: %w", err)
}
fileId, uploadResult, err, data := uploader.UploadWithRetry(
wfs,
&filer_pb.AssignVolumeRequest{
@@ -71,13 +89,16 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
)
if err != nil {
wfs.chunkProofs.unreserve(1)
glog.V(0).Infof("upload data %v: %v", filename, err)
return nil, fmt.Errorf("upload data: %w", err)
}
if uploadResult.Error != "" {
wfs.chunkProofs.unreserve(1)
glog.V(0).Infof("upload failure %v: %v", filename, err)
return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
}
wfs.chunkProofs.keep(fileId, uploadResult.AssignAuth, 1)
// shouldCacheUploadedChunk explains when and why every uploaded
// chunk is cached (peer sharing, and read-auth read-after-write).
+39 -11
View File
@@ -42,13 +42,17 @@ func (wfs *WFS) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr str
ctx, cancelFunc := ctxFromCancel(cancel)
defer cancelFunc()
_, _, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
_, fh, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
if status != fuse.OK {
return 0, status
}
if entry == nil {
return 0, fuse.ENOENT
}
// An open handle's Extended map is shared with the writers of its
// entry, so the value is copied out while the entry lock is held.
unlock, entry := lockExtendedForRead(fh, entry)
defer unlock()
if entry.Extended == nil {
return 0, fuse.ENOATTR
}
@@ -64,6 +68,20 @@ func (wfs *WFS) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr str
return uint32(len(data)), fuse.OK
}
// lockExtendedForRead returns the entry whose Extended map the caller may
// read until it calls unlock. An open handle's entry is changed in place by
// setxattr, removexattr, truncate to zero and the metadata merges, all under
// the LockedEntry lock, and SetEntry can swap the entry since maybeReadEntry
// returned it, so the read takes that lock and the handle's current entry.
// Any other entry is a private copy.
func lockExtendedForRead(fh *FileHandle, entry *filer_pb.Entry) (unlock func(), current *filer_pb.Entry) {
if fh == nil {
return func() {}, entry
}
fh.entry.RLock()
return fh.entry.RUnlock, fh.entry.Entry
}
// SetXAttr writes an extended attribute.
// https://man7.org/linux/man-pages/man2/setxattr.2.html
//
@@ -144,6 +162,11 @@ func (wfs *WFS) SetXAttr(cancel <-chan struct{}, input *fuse.SetXAttrIn, attr st
defer wfs.fhLockTable.ReleaseLock(fh.fh, active)
fh.entryLock.Lock()
defer fh.entryLock.Unlock()
// Readers take only the LockedEntry lock. Re-read the entry under
// it in case SetEntry swapped the pointer since maybeReadEntry.
fh.entry.Lock()
defer fh.entry.Unlock()
entry = fh.entry.Entry
}
if code := applyXAttr(entry, input.Flags, attr, data); code != fuse.OK {
@@ -175,24 +198,24 @@ func (wfs *WFS) ListXAttr(cancel <-chan struct{}, header *fuse.InHeader, dest []
ctx, cancelFunc := ctxFromCancel(cancel)
defer cancelFunc()
_, _, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
_, fh, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
if status != fuse.OK {
return 0, status
}
if entry == nil {
return 0, fuse.ENOENT
}
if entry.Extended == nil {
return 0, fuse.OK
}
var data []byte
for k := range entry.Extended {
if strings.HasPrefix(k, XATTR_PREFIX) {
data = append(data, k[len(XATTR_PREFIX):]...)
data = append(data, 0)
func() {
unlock, live := lockExtendedForRead(fh, entry)
defer unlock()
for k := range live.Extended {
if strings.HasPrefix(k, XATTR_PREFIX) {
data = append(data, k[len(XATTR_PREFIX):]...)
data = append(data, 0)
}
}
}
}()
if len(dest) < len(data) {
return uint32(len(data)), fuse.ERANGE
}
@@ -244,6 +267,11 @@ func (wfs *WFS) RemoveXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr
defer wfs.fhLockTable.ReleaseLock(fh.fh, active)
fh.entryLock.Lock()
defer fh.entryLock.Unlock()
// Readers take only the LockedEntry lock. Re-read the entry under
// it in case SetEntry swapped the pointer since maybeReadEntry.
fh.entry.Lock()
defer fh.entry.Unlock()
entry = fh.entry.Entry
}
if code := removeXAttr(entry, attr); code != fuse.OK {
+154
View File
@@ -0,0 +1,154 @@
//go:build !freebsd
package mount
import (
"fmt"
"sync"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// raceDuration is how long a reader and a writer run against each other. The
// unguarded map access this covers fails within milliseconds: Go aborts the
// whole process on a concurrent map read and write, and -race reports it.
const raceDuration = 300 * time.Millisecond
// openXAttrRaceHandle opens a file with some extended attributes and no name,
// as an unlinked file that is still open: every operation on it works on the
// handle's own entry and none goes to the filer.
func openXAttrRaceHandle(t *testing.T, content []byte) (*WFS, *FileHandle) {
t.Helper()
wfs := newCopyRangeTestWFS()
const inode = 42
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: "x.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: uint64(len(content)), Inode: inode},
Content: content,
Extended: map[string][]byte{
XATTR_PREFIX + "user.a": []byte("1"),
XATTR_PREFIX + "user.b": []byte("2"),
},
}, 0, 0)
t.Cleanup(fh.dirtyPages.Destroy)
fh.dirtyMetadata = true
return wfs, fh
}
// runXAttrRace runs one writer and several readers until the time is up.
func runXAttrRace(writer func(i int), readers ...func(i int)) {
stop := make(chan struct{})
var wg sync.WaitGroup
for _, fn := range append([]func(int){writer}, readers...) {
wg.Add(1)
go func(fn func(int)) {
defer wg.Done()
for i := 0; ; i++ {
select {
case <-stop:
return
default:
}
fn(i)
}
}(fn)
}
time.Sleep(raceDuration)
close(stop)
wg.Wait()
}
func getXAttrReader(t *testing.T, wfs *WFS, inode uint64, name string) func(int) {
dest := make([]byte, 64)
return func(int) {
n, code := wfs.GetXAttr(nil, &fuse.InHeader{NodeId: inode}, name, dest)
if code == fuse.OK && n == 0 {
t.Errorf("GetXAttr(%q) = OK with no bytes", name)
}
}
}
func listXAttrReader(wfs *WFS, inode uint64) func(int) {
dest := make([]byte, 4096)
return func(int) { wfs.ListXAttr(nil, &fuse.InHeader{NodeId: inode}, dest) }
}
// SetXAttr and RemoveXAttr on an open file change its entry's Extended map in
// place while GetXAttr and ListXAttr read it.
func TestXAttrReadsAgainstSetAndRemoveOnOpenFile(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, nil)
inode := fh.inode
runXAttrRace(func(i int) {
// each name is set and then removed, so every removal deletes a key
name := fmt.Sprintf("user.k%d", (i/2)%64)
if i%2 == 0 {
if code := wfs.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: inode}}, name, []byte("v")); code != fuse.OK {
t.Errorf("SetXAttr(%q) = %v", name, code)
}
} else if code := wfs.RemoveXAttr(nil, &fuse.InHeader{NodeId: inode}, name); code != fuse.OK {
t.Errorf("RemoveXAttr(%q) = %v", name, code)
}
}, getXAttrReader(t, wfs, inode, "user.a"), getXAttrReader(t, wfs, inode, "security.capability"), listXAttrReader(wfs, inode))
}
// Truncating an open file to zero removes its S3 encryption attributes from
// the same map.
func TestXAttrReadsAgainstTruncateToZeroOnOpenFile(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, []byte("payload"))
inode := fh.inode
runXAttrRace(func(int) {
// put the keys back so that every truncate deletes something
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Extended[s3_constants.AmzServerSideEncryption] = []byte("AES256")
e.Extended[s3_constants.SeaweedFSSSEIV] = []byte("iv")
})
in := &fuse.SetAttrIn{}
in.NodeId, in.Valid, in.Size = inode, fuse.FATTR_SIZE, 0
if code := wfs.SetAttr(nil, in, &fuse.AttrOut{}); code != fuse.OK {
t.Errorf("truncate = %v", code)
}
}, getXAttrReader(t, wfs, inode, "user.a"), listXAttrReader(wfs, inode))
}
// A flush that merged a peer's change gives the handle the merged entry's
// attributes, Extended among them.
func TestXAttrReadsAgainstFlushMergeOnOpenFile(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, nil)
inode := fh.inode
runXAttrRace(func(i int) {
merged := &filer_pb.Entry{
Name: "x.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: inode},
Extended: map[string][]byte{
XATTR_PREFIX + "user.a": []byte("1"),
XATTR_PREFIX + fmt.Sprintf("user.m%d", i%8): []byte("m"),
},
}
fh.rebaseEntry(merged, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
}, getXAttrReader(t, wfs, inode, "user.a"), listXAttrReader(wfs, inode))
}
// The reply carries the value as it was when it was read, in the caller's
// buffer.
func TestGetXAttrReturnsCopyOfOpenFileValue(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, nil)
dest := make([]byte, 8)
n, code := wfs.GetXAttr(nil, &fuse.InHeader{NodeId: fh.inode}, "user.a", dest)
if code != fuse.OK || string(dest[:n]) != "1" {
t.Fatalf("GetXAttr = %q, %v; want \"1\", OK", dest[:n], code)
}
dest[0] = 'x'
if got := fh.entry.Entry.Extended[XATTR_PREFIX+"user.a"]; string(got) != "1" {
t.Fatalf("the handle's value changed through the caller's buffer: %q", got)
}
if code := wfs.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: fh.inode}}, "user.a", []byte("22")); code != fuse.OK {
t.Fatalf("SetXAttr = %v", code)
}
if n, code = wfs.GetXAttr(nil, &fuse.InHeader{NodeId: fh.inode}, "user.a", dest); code != fuse.OK || string(dest[:n]) != "22" {
t.Fatalf("GetXAttr after SetXAttr = %q, %v; want \"22\", OK", dest[:n], code)
}
}
+3 -2
View File
@@ -155,9 +155,10 @@ func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time
// newFilerClient authorizes each call through the client with the mount's
// filer token source, resolved per attempt so a retry carries a replaced
// token. The cached channel itself carries no identity.
// token. The cached channel itself carries no identity. Creates and updates
// carry the assignment proofs of the new chunks they store.
func (wfs *WFS) newFilerClient(conn *grpc.ClientConn) filer_pb.SeaweedFilerClient {
return filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource))
return filer_pb.NewSeaweedFilerClient(wfs.chunkProofs.conn(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource)))
}
func (wfs *WFS) AdjustedUrl(location *filer_pb.Location) string {
+8 -5
View File
@@ -53,12 +53,15 @@ The client will write the messages for this segment to the selected brokers.
The broker leader does not contain any state. If it fails, the masters will select a different broker.
For a segment, if any one of the selected brokers is down, the remaining brokers should try to write received messages
to the filer, and close the segment to the clients.
A partition's files are written only by the broker holding the partition's fence, so a broker that lost its
leadership cannot add to them. When that broker fails, the partition is assigned to another broker, which takes the
fence at a new epoch and continues from the files.
Then the clients should start a new segment. The masters should assign other healthy brokers to handle the new segment.
So any brokers can go down without losing data.
Each partition has a leader and a follower on two brokers. The leader acknowledges a message once the follower holds
it, and the follower keeps what the leader has not flushed yet in memory. If either is lost, the survivor writes what
it holds, seals the fence and reports the generation ended; the balancer then assigns a new pair at the next epoch,
and publishers resend what was not acknowledged. A partition placed while only one broker is live has no follower,
and messages it acknowledged but had not flushed yet are lost when that broker fails.
## Auto Split or Merge
+26 -9
View File
@@ -2,6 +2,7 @@ package agent
import (
"context"
"fmt"
"log/slog"
"math/rand/v2"
@@ -20,6 +21,7 @@ func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_age
Brokers: a.brokersList(),
PublisherName: req.PublisherName,
RecordType: req.RecordType,
GrpcDialOption: a.grpcDialOption,
})
if err != nil {
return nil, err
@@ -37,18 +39,33 @@ func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_age
}
func (a *MessageQueueAgent) ClosePublishSession(ctx context.Context, req *mq_agent_pb.ClosePublishSessionRequest) (*mq_agent_pb.ClosePublishSessionResponse, error) {
var finishErr string
sessionID := SessionId(req.SessionId)
a.publishersLock.RLock()
entry := a.publishers[sessionID]
a.publishersLock.RUnlock()
if entry == nil {
return &mq_agent_pb.ClosePublishSessionResponse{Error: fmt.Sprintf("publish session id %d not found", sessionID)}, nil
}
if err := a.finishPublisher(sessionID, entry); err != nil {
return &mq_agent_pb.ClosePublishSessionResponse{Error: err.Error()}, nil
}
return &mq_agent_pb.ClosePublishSessionResponse{}, nil
}
// Concurrent closers of the same publisher wait on the same scheduler and observe
// the same acknowledgment count. Keep the session reachable during the flush.
func (a *MessageQueueAgent) finishPublisher(id SessionId, entry *SessionEntry[*pub_client.TopicPublisher]) error {
err := entry.entry.FinishPublish()
if err == nil {
err = entry.entry.Shutdown()
}
a.publishersLock.Lock()
publisherEntry, found := a.publishers[SessionId(req.SessionId)]
if found {
if err := publisherEntry.entry.FinishPublish(); err != nil {
finishErr = err.Error()
if a.publishers[id] == entry {
delete(a.publishers, id)
if err != nil {
slog.Warn("failed to finish publish", "error", err)
}
delete(a.publishers, SessionId(req.SessionId))
}
a.publishersLock.Unlock()
return &mq_agent_pb.ClosePublishSessionResponse{
Error: finishErr,
}, nil
return err
}
+11 -4
View File
@@ -1,12 +1,15 @@
package agent
import (
"context"
"errors"
"fmt"
"io"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
)
func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) error {
func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) (streamErr error) {
m, err := stream.Recv()
if err != nil {
return err
@@ -18,10 +21,11 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
if !found {
return fmt.Errorf("publish session id %d not found", sessionId)
}
// A disconnected stream may already be blocked enqueueing to a full partition.
stopOnDisconnect := context.AfterFunc(stream.Context(), func() { publisherEntry.entry.FinishPublish() })
defer func() {
a.publishersLock.Lock()
delete(a.publishers, sessionId)
a.publishersLock.Unlock()
stopOnDisconnect()
streamErr = errors.Join(streamErr, a.finishPublisher(sessionId, publisherEntry))
}()
if m.Value != nil {
@@ -32,6 +36,9 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
for {
m, err = stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
+158
View File
@@ -0,0 +1,158 @@
package agent
import (
"context"
"net"
"runtime"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/client/agent_client"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type gatedAckBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
closeMarker chan struct{}
allowAck chan struct{}
}
func (b *gatedAckBroker) ConfigureTopic(context.Context, *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
return &mq_pb.ConfigureTopicResponse{}, nil
}
func (b *gatedAckBroker) LookupTopicBrokers(context.Context, *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
return &mq_pb.LookupTopicBrokersResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
Partition: &schema_pb.Partition{RangeStop: pub_balancer.MaxPartitionCount},
LeaderBroker: b.addr,
}}}, nil
}
func (b *gatedAckBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
if _, err := stream.Recv(); err != nil {
return err
}
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
return err
}
for {
req, err := stream.Recv()
if err != nil {
return nil
}
data := req.GetData()
if data.GetCtrl().GetIsClose() {
close(b.closeMarker)
select {
case <-b.allowAck:
case <-stream.Context().Done():
return stream.Context().Err()
}
// The marker acknowledges the entire stream, including the earlier record.
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil {
return err
}
}
}
}
func TestPublishStreamCloseWaitsForAcknowledgment(t *testing.T) {
listen := func() net.Listener {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
return l
}
brokerListener := listen()
broker := &gatedAckBroker{addr: brokerListener.Addr().String(), closeMarker: make(chan struct{}), allowAck: make(chan struct{})}
brokerServer := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(brokerServer, broker)
go brokerServer.Serve(brokerListener)
t.Cleanup(brokerServer.Stop)
agent := NewMessageQueueAgent(&MessageQueueAgentOptions{SeedBrokers: []pb.ServerAddress{pb.ServerAddress(broker.addr)}}, grpc.WithTransportCredentials(insecure.NewCredentials()))
agentListener := listen()
agentServer := grpc.NewServer()
mq_agent_pb.RegisterSeaweedMessagingAgentServer(agentServer, agent)
go agentServer.Serve(agentListener)
t.Cleanup(agentServer.Stop)
client, err := agent_client.NewPublishSession(agentListener.Addr().String(), &schema.Schema{Namespace: "test", Name: "events"}, 1, "test")
if err != nil {
t.Fatal(err)
}
agent.publishersLock.RLock()
var id SessionId
for id = range agent.publishers {
break
}
agent.publishersLock.RUnlock()
if err := client.PublishMessageRecord([]byte("key"), &schema_pb.RecordValue{}); err != nil {
t.Fatal(err)
}
closed := make(chan error, 1)
go func() { closed <- client.CloseSession() }()
select {
case <-broker.closeMarker:
case <-time.After(5 * time.Second):
t.Fatal("closing the stream did not finish the publisher")
}
duplicate := make(chan *mq_agent_pb.ClosePublishSessionResponse, 1)
go func() {
resp, _ := agent.ClosePublishSession(t.Context(), &mq_agent_pb.ClosePublishSessionRequest{SessionId: int64(id)})
duplicate <- resp
}()
waitForFinishers(t, 2)
select {
case <-closed:
t.Fatal("stream close returned before acknowledgment")
case <-duplicate:
t.Fatal("duplicate close returned before acknowledgment")
default:
}
close(broker.allowAck)
select {
case err := <-closed:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("stream close did not finish")
}
select {
case resp := <-duplicate:
if resp == nil || resp.Error != "" {
t.Fatalf("duplicate close returned %v", resp)
}
case <-time.After(5 * time.Second):
t.Fatal("duplicate close did not finish")
}
}
// waitForFinishers waits until n goroutines are flushing a publisher in finishPublisher.
func waitForFinishers(t *testing.T, n int) {
t.Helper()
buf := make([]byte, 1<<20)
deadline := time.Now().Add(10 * time.Second)
for {
stacks := string(buf[:runtime.Stack(buf, true)])
if strings.Count(stacks, "(*MessageQueueAgent).finishPublisher(") >= n {
return
}
if time.Now().After(deadline) {
t.Fatalf("fewer than %d goroutines reached finishPublisher", n)
}
time.Sleep(time.Millisecond)
}
}
+129
View File
@@ -0,0 +1,129 @@
package broker
import (
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// balancerSettleTime outlasts a broker's lock retry (5 x LiveLockTTL/2) plus its
// reconnect, so a new balancer does not take a broker still reconnecting for dead.
const balancerSettleTime = 30 * time.Second
func (b *MessageQueueBroker) balancerSettled() bool {
return time.Now().After(b.balancerSettleDeadline())
}
// balancerSettleDeadline counts from the first sight of the current lease. A
// regained lease has a new generation; a renewal keeps it.
func (b *MessageQueueBroker) balancerSettleDeadline() time.Time {
var generation int64
if lock := b.lockAsBalancer.Load(); lock != nil {
generation = lock.Generation()
}
return b.settleDeadline(generation, time.Now())
}
// balancerSettle is the balancer lease the settle window counts from.
type balancerSettle struct {
sync.Mutex
generation int64
since time.Time
}
func (b *MessageQueueBroker) settleDeadline(generation int64, now time.Time) time.Time {
s := &b.balancerSettle
s.Lock()
defer s.Unlock()
if s.since.IsZero() || generation != s.generation {
s.generation, s.since = generation, now
}
return s.since.Add(balancerSettleTime)
}
// topicConfExpiry ends a config validated at validatedAt by a settling balancer
// at the settle deadline, so the repair it skipped runs as soon as it may, even
// when the deadline passed before the config was cached.
func (b *MessageQueueBroker) topicConfExpiry(validatedAt time.Time) time.Time {
if b.isLockOwner() {
return cacheExpiry(validatedAt, b.topicCacheTTL, b.balancerSettleDeadline())
}
return validatedAt.Add(b.topicCacheTTL)
}
func cacheExpiry(now time.Time, ttl time.Duration, settleDeadline time.Time) time.Time {
if expiry := now.Add(ttl); !now.Before(settleDeadline) || expiry.Before(settleDeadline) {
return expiry
}
return settleDeadline
}
// isLockOwner reports whether this broker holds an unexpired balancer lease.
func (b *MessageQueueBroker) isLockOwner() bool {
lock := b.lockAsBalancer.Load()
return lock != nil && lock.IsLocked()
}
// balancer is the broker that balancer-only requests are proxied to.
func (b *MessageQueueBroker) balancer() (pb.ServerAddress, error) {
if lock := b.lockAsBalancer.Load(); lock != nil {
owner := pb.ServerAddress(lock.LockOwner())
// A lapsed lease still names this broker; proxying to itself would loop.
if owner != "" && !owner.Equals(b.option.BrokerAddress()) {
return owner, nil
}
}
return "", status.Error(codes.Unavailable, "no broker balancer elected yet")
}
func (b *MessageQueueBroker) withBalancerClient(fn func(client mq_pb.SeaweedMessagingClient) error) error {
balancer, err := b.balancer()
if err != nil {
return err
}
return b.withBrokerClient(false, balancer, fn)
}
// lockRing holds the master's filer lock ring until the balancer lock client
// exists, since the master sends the whole ring only when the broker connects.
type lockRing struct {
sync.Mutex
client *cluster.LockClient
servers []pb.ServerAddress
version int64
}
func (r *lockRing) set(servers []pb.ServerAddress, version int64) {
r.Lock()
defer r.Unlock()
if r.client != nil {
r.client.SetRing(servers, version)
return
}
r.servers, r.version = servers, version
}
// reset drops the version gate: ring versions count per master.
func (r *lockRing) reset() {
r.Lock()
defer r.Unlock()
if r.client != nil {
r.client.ResetRing()
return
}
r.version = 0
}
func (r *lockRing) attach(client *cluster.LockClient) {
r.Lock()
defer r.Unlock()
r.client = client
if r.servers != nil {
client.SetRing(r.servers, r.version)
}
}
+124
View File
@@ -0,0 +1,124 @@
package broker
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
func newUnelectedBroker() *MessageQueueBroker {
return &MessageQueueBroker{
option: &MessageQueueBrokerOption{Ip: "127.0.0.1", Port: 17777},
PubBalancer: pub_balancer.NewPubBalancer(),
}
}
// Requests that reach a broker before it has found a filer used to dereference
// the not yet created balancer lock.
func TestBalancerRequestsBeforeElection(t *testing.T) {
b := newUnelectedBroker()
assert.False(t, b.isLockOwner())
_, err := b.LookupTopicBrokers(context.Background(), &mq_pb.LookupTopicBrokersRequest{
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
})
assert.Equal(t, codes.Unavailable, status.Code(err))
_, err = b.ConfigureTopic(context.Background(), &mq_pb.ConfigureTopicRequest{
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
})
assert.Equal(t, codes.Unavailable, status.Code(err))
}
func TestLockRingAppliedWhenClientAttaches(t *testing.T) {
var ring lockRing
ring.set([]pb.ServerAddress{"filer1:8888"}, 3)
client := cluster.NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "filer0:8888")
assert.Equal(t, pb.ServerAddress(""), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
ring.attach(client)
assert.Equal(t, pb.ServerAddress("filer1:8888"), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
ring.set([]pb.ServerAddress{"filer2:8888"}, 4)
assert.Equal(t, pb.ServerAddress("filer2:8888"), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
}
// Only the balancer tracks live brokers; any other broker sees an empty set and
// used to blank every leader of the topic it read.
func TestNonBalancerKeepsStoredAssignments(t *testing.T) {
b := newUnelectedBroker()
conf := &mq_pb.ConfigureTopicResponse{
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
{LeaderBroker: "10.0.0.1:17777", FollowerBroker: "10.0.0.2:17777", Partition: &schema_pb.Partition{RingSize: 2520, RangeStop: 2520}},
},
}
assert.False(t, b.ensureTopicActiveAssignmentsUnsafe(topic.NewTopic("test", "t"), conf))
assert.Equal(t, "10.0.0.1:17777", conf.BrokerPartitionAssignments[0].LeaderBroker)
assert.Equal(t, "10.0.0.2:17777", conf.BrokerPartitionAssignments[0].FollowerBroker)
}
// A new master's ring versions start over, even before the client attaches.
func TestLockRingResetBeforeClientAttaches(t *testing.T) {
var ring lockRing
ring.set([]pb.ServerAddress{"filer1:8888"}, 100)
ring.reset()
client := cluster.NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "filer0:8888")
ring.attach(client)
ring.set([]pb.ServerAddress{"filer2:8888"}, 1)
assert.Equal(t, pb.ServerAddress("filer2:8888"), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
}
func TestSettleWindowRestartsWithANewLease(t *testing.T) {
b := newUnelectedBroker()
start := time.Now()
want := start.Add(balancerSettleTime).UnixNano()
assert.Equal(t, want, b.settleDeadline(1, start).UnixNano())
assert.Equal(t, want, b.settleDeadline(1, start.Add(time.Minute)).UnixNano(), "a renewal keeps the window")
regained := start.Add(2 * time.Minute)
assert.Equal(t, regained.Add(balancerSettleTime).UnixNano(), b.settleDeadline(2, regained).UnixNano())
}
func TestTopicConfCachedNoLongerThanTheSettleWindow(t *testing.T) {
now := time.Now()
ttl := 30 * time.Second
assert.Equal(t, now.Add(10*time.Second), cacheExpiry(now, ttl, now.Add(10*time.Second)), "settling: until the deadline")
assert.Equal(t, now.Add(ttl), cacheExpiry(now, ttl, now.Add(time.Minute)), "deadline past the TTL")
assert.Equal(t, now.Add(ttl), cacheExpiry(now, ttl, now.Add(-time.Second)), "settled")
}
// The balancer records an assignment the broker acknowledged, so a stopping
// broker must refuse it rather than drop the partition and report success.
// That holds for a partition it already hosts, which Shutdown leaves registered.
func TestStoppingBrokerRefusesAssignment(t *testing.T) {
for _, hosted := range []bool{false, true} {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
if hosted {
b.localTopicManager.AddLocalPartition(topic.NewTopic("test", "t"),
topic.NewLocalPartition(topic.Partition{RingSize: 2520, RangeStop: 2520}, 3600, nil, nil))
}
b.localTopicManager.Shutdown()
_, err := b.AssignTopicPartitions(context.Background(), &mq_pb.AssignTopicPartitionsRequest{
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
{Partition: &schema_pb.Partition{RingSize: 2520, RangeStop: 2520}},
},
})
assert.Equal(t, codes.Unavailable, status.Code(err), "hosted=%v", hosted)
}
}
+8 -6
View File
@@ -71,6 +71,11 @@ func (b *MessageQueueBroker) KeepConnectedToBrokerBalancer(newBrokerBalancerCh c
var stopPrevRunChan chan struct{}
for {
select {
case <-b.ctx.Done():
if stopPrevRunChan != nil {
close(stopPrevRunChan)
}
return
case newBrokerBalancer := <-newBrokerBalancerCh:
if stopPrevRunChan != nil {
close(stopPrevRunChan)
@@ -82,17 +87,14 @@ func (b *MessageQueueBroker) KeepConnectedToBrokerBalancer(newBrokerBalancerCh c
go func() {
for {
err := b.BrokerConnectToBalancer(newBrokerBalancer, thisRunStopChan)
if err != nil {
glog.V(0).Infof("connect to balancer %s: %v", newBrokerBalancer, err)
time.Sleep(time.Second)
} else {
if err == nil {
break
}
glog.V(0).Infof("connect to balancer %s: %v", newBrokerBalancer, err)
select {
case <-thisRunStopChan:
return
default:
case <-time.After(time.Second):
}
}
+20 -3
View File
@@ -20,11 +20,16 @@ const (
BrokerErrorTopicAlreadyExists int32 = 36
BrokerErrorInvalidPartitions int32 = 37
BrokerErrorInvalidConfig int32 = 40
BrokerErrorStorageError int32 = 56
// Kafka's code 1, which here is BrokerErrorUnknownServerError
BrokerErrorOffsetOutOfRange int32 = 104
// Publisher/connection errors
BrokerErrorPublisherNotFound int32 = 100
BrokerErrorConnectionFailed int32 = 101
BrokerErrorFollowerConnectionFailed int32 = 102
// the partition's leader/follower pair broke; publishers look it up again and resend
BrokerErrorGenerationEnded int32 = 103
)
// BrokerErrorInfo contains metadata about a broker error
@@ -43,7 +48,7 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
},
BrokerErrorUnknownServerError: {
Code: BrokerErrorUnknownServerError, Name: "UNKNOWN_SERVER_ERROR",
Description: "Unknown server error", KafkaCode: 1,
Description: "Unknown server error", KafkaCode: -1,
},
BrokerErrorTopicNotFound: {
Code: BrokerErrorTopicNotFound, Name: "TOPIC_NOT_FOUND",
@@ -93,14 +98,26 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
Code: BrokerErrorInvalidConfig, Name: "INVALID_CONFIG",
Description: "Invalid configuration", KafkaCode: 40,
},
BrokerErrorStorageError: {
Code: BrokerErrorStorageError, Name: "KAFKA_STORAGE_ERROR",
Description: "Stored messages could not be read", KafkaCode: 56,
},
BrokerErrorOffsetOutOfRange: {
Code: BrokerErrorOffsetOutOfRange, Name: "OFFSET_OUT_OF_RANGE",
Description: "Offset is below the earliest retained offset", KafkaCode: 1,
},
BrokerErrorPublisherNotFound: {
Code: BrokerErrorPublisherNotFound, Name: "PUBLISHER_NOT_FOUND",
Description: "Publisher not found", KafkaCode: 1, // UNKNOWN_SERVER_ERROR
Description: "Publisher not found", KafkaCode: -1, // UNKNOWN_SERVER_ERROR
},
BrokerErrorConnectionFailed: {
Code: BrokerErrorConnectionFailed, Name: "CONNECTION_FAILED",
Description: "Connection failed", KafkaCode: 13, // NETWORK_EXCEPTION
},
BrokerErrorGenerationEnded: {
Code: BrokerErrorGenerationEnded, Name: "GENERATION_ENDED",
Description: "Partition generation ended; look up its new leader", KafkaCode: 6,
},
BrokerErrorFollowerConnectionFailed: {
Code: BrokerErrorFollowerConnectionFailed, Name: "FOLLOWER_CONNECTION_FAILED",
Description: "Failed to connect to follower brokers", KafkaCode: 13, // NETWORK_EXCEPTION
@@ -113,7 +130,7 @@ func GetBrokerErrorInfo(code int32) BrokerErrorInfo {
return info
}
return BrokerErrorInfo{
Code: code, Name: "UNKNOWN", Description: "Unknown broker error code", KafkaCode: 1,
Code: code, Name: "UNKNOWN", Description: "Unknown broker error code", KafkaCode: -1,
}
}
+39 -34
View File
@@ -6,12 +6,13 @@ import (
"sync"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/logstore"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// AssignTopicPartitions Runs on the assigned broker, to execute the topic partition assignment
@@ -23,39 +24,47 @@ func (b *MessageQueueBroker) AssignTopicPartitions(c context.Context, request *m
t := topic.FromPbTopic(request.Topic)
partition := topic.FromPbPartition(assignment.Partition)
b.accessLock.Lock()
localPartition := b.localTopicManager.GetLocalPartition(t, partition)
for !request.IsDraining && localPartition == nil && b.localTopicManager.RetiringPartition(t, partition) != nil {
// its flush takes accessLock, so wait without it
b.accessLock.Unlock()
if err := b.localTopicManager.WaitRetired(c, t, partition); err != nil {
return nil, status.FromContextError(err).Err()
}
b.accessLock.Lock()
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
}
if request.IsDraining {
// TODO drain existing topic partition subscriptions
b.localTopicManager.RemoveLocalPartition(t, partition)
b.localTopicManager.RemoveLocalPartition(t, localPartition)
} else {
var localPartition *topic.LocalPartition
if localPartition = b.localTopicManager.GetLocalPartition(t, partition); localPartition == nil {
localPartition = topic.NewLocalPartition(partition, b.option.LogFlushInterval, b.genLogFlushFunc(t, partition), logstore.GenMergedReadFunc(b, t, partition))
// Initialize offset from existing data to ensure continuity on restart
b.initializePartitionOffsetFromExistingData(localPartition, t, partition)
b.localTopicManager.AddLocalPartition(t, localPartition)
} else {
for b.retireStaleLeader(t, localPartition, assignment.Epoch) {
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
}
// checked after the reload, which can wait out a Shutdown that starts meanwhile
if b.localTopicManager.IsStopping() {
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
}
// a follower learns of its partition from the leader's follow stream
isLeader := assignment.LeaderBroker == "" || pb.ServerAddress(assignment.LeaderBroker).Equals(b.option.BrokerAddress())
if isLeader && localPartition == nil {
localPartition, genErr := b.newLeaderPartition(t, partition, assignment)
if genErr != nil {
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "%v", genErr)
}
if !b.localTopicManager.AddLocalPartition(t, localPartition) {
localPartition.Shutdown()
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
}
go b.watchReplica(t, partition, localPartition, assignment.Epoch)
}
}
b.accessLock.Unlock()
}
// if is leader, notify the followers to drain existing topic partition subscriptions
if request.IsLeader {
for _, brokerPartition := range request.BrokerPartitionAssignments {
if follower := brokerPartition.FollowerBroker; follower != "" {
err := pb.WithBrokerGrpcClient(false, follower, b.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error {
_, err := client.AssignTopicPartitions(context.Background(), request)
return err
})
if err != nil {
return ret, err
}
}
}
}
return ret, nil
}
@@ -70,14 +79,10 @@ func (b *MessageQueueBroker) assignTopicPartitionsToBrokers(ctx context.Context,
defer wg.Done()
if doCreateErr := b.withBrokerClient(false, pb.ServerAddress(bpa.LeaderBroker), func(client mq_pb.SeaweedMessagingClient) error {
_, doCreateErr := client.AssignTopicPartitions(ctx, &mq_pb.AssignTopicPartitionsRequest{
Topic: t,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
{
Partition: bpa.Partition,
},
},
IsLeader: true,
IsDraining: !isAdd,
Topic: t,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{bpa},
IsLeader: true,
IsDraining: !isAdd,
})
if doCreateErr != nil {
if !isAdd {
+1 -2
View File
@@ -3,13 +3,12 @@ package broker
import (
"context"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
)
func (b *MessageQueueBroker) BalanceTopics(ctx context.Context, request *mq_pb.BalanceTopicsRequest) (resp *mq_pb.BalanceTopicsResponse, err error) {
if !b.isLockOwner() {
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.BalanceTopics(ctx, request)
return nil
})
+3 -2
View File
@@ -8,7 +8,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -20,7 +19,7 @@ import (
// and then assign the partitions to the brokers.
func (b *MessageQueueBroker) ConfigureTopic(ctx context.Context, request *mq_pb.ConfigureTopicRequest) (resp *mq_pb.ConfigureTopicResponse, err error) {
if !b.isLockOwner() {
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.ConfigureTopic(ctx, request)
return nil
})
@@ -37,6 +36,8 @@ func (b *MessageQueueBroker) ConfigureTopic(ctx context.Context, request *mq_pb.
}
}
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
t := topic.FromPbTopic(request.Topic)
var readErr, assignErr error
resp, readErr = b.fca.ReadTopicConfFromFiler(t)
+24 -20
View File
@@ -2,11 +2,13 @@ package broker
import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// FetchMessage implements Kafka-style stateless message fetching
@@ -47,14 +49,16 @@ func (b *MessageQueueBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchM
if err != nil {
glog.Errorf("[FetchMessage] Failed to get partition: %v", err)
return &mq_pb.FetchMessageResponse{
Error: fmt.Sprintf("partition not found: %v", err),
ErrorCode: 1,
Error: fmt.Sprintf("partition not found: %v", err),
ErrorCode: 1,
NextOffset: req.StartOffset,
}, nil
}
if localPartition == nil {
return &mq_pb.FetchMessageResponse{
Error: "partition not found",
ErrorCode: 1,
Error: "partition not found",
ErrorCode: 1,
NextOffset: req.StartOffset,
}, nil
}
@@ -119,25 +123,25 @@ func (b *MessageQueueBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchM
nextOffset, endOfPartition, localPartition.LogBuffer.GetLogStartOffset())
}
if err != nil {
// Check if this is an "offset out of range" error
errMsg := err.Error()
if len(errMsg) > 0 && (len(errMsg) < 20 || errMsg[:20] != "offset") {
glog.Errorf("[FetchMessage] Read error: %v", err)
} else {
// Offset out of range - this is expected when consumer requests old data
glog.V(3).Infof("[FetchMessage] Offset out of range: %v", err)
}
// Return empty response with metadata - let client adjust offset
if errors.Is(err, log_buffer.ErrOffsetOutOfRange) {
glog.V(1).Infof("[FetchMessage] %s/%s partition=%v: %v", t.Namespace, t.Name, partition, err)
return &mq_pb.FetchMessageResponse{
Messages: []*mq_pb.DataMessage{},
HighWaterMark: highWaterMark,
LogStartOffset: localPartition.LogBuffer.GetLogStartOffset(),
EndOfPartition: false,
NextOffset: localPartition.LogBuffer.GetLogStartOffset(), // Suggest starting from earliest available
Error: errMsg,
ErrorCode: 2,
NextOffset: requestedOffset,
Error: err.Error(),
ErrorCode: BrokerErrorOffsetOutOfRange,
}, nil
}
if err != nil {
// Any other failed read is retried at the same offset.
glog.Errorf("[FetchMessage] %s/%s partition=%v read at offset %d: %v", t.Namespace, t.Name, partition, requestedOffset, err)
return &mq_pb.FetchMessageResponse{
HighWaterMark: highWaterMark,
LogStartOffset: localPartition.LogBuffer.GetLogStartOffset(),
NextOffset: requestedOffset,
Error: err.Error(),
ErrorCode: BrokerErrorStorageError,
}, nil
}
+115
View File
@@ -0,0 +1,115 @@
package broker
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// A failed disk read must leave the client at the offset it asked for.
func TestFetchMessageReadErrorKeepsRequestedOffset(t *testing.T) {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
tp := topic.NewTopic("test", "t")
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
b.topicCache = map[string]*topicCacheEntry{tp.String(): {conf: &mq_pb.ConfigureTopicResponse{}, expiresAt: time.Now().Add(time.Hour)}}
failingDiskRead := func(log_buffer.MessagePosition, int64, log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return log_buffer.MessagePosition{}, false, errors.New("volume unreachable")
}
lp := topic.NewLocalPartition(partition, 3600, nil, failingDiskRead)
defer lp.Shutdown()
// offsets 0..41 are on disk, the buffer continues at 42
if err := lp.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) { return 41, nil }); err != nil {
t.Fatal(err)
}
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
b.localTopicManager.AddLocalPartition(tp, lp)
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{
Topic: &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name},
Partition: &schema_pb.Partition{RingSize: partition.RingSize, RangeStart: partition.RangeStart, RangeStop: partition.RangeStop, UnixTimeNs: partition.UnixTimeNs},
StartOffset: 10,
})
if err != nil {
t.Fatal(err)
}
if resp.Error == "" || resp.ErrorCode != BrokerErrorStorageError {
t.Errorf("error %q code %d, want a storage error", resp.Error, resp.ErrorCode)
}
if resp.NextOffset != 10 {
t.Errorf("next offset %d after a failed read at 10", resp.NextOffset)
}
if len(resp.Messages) != 0 {
t.Errorf("got %d messages from a failed read", len(resp.Messages))
}
}
// A fetch for a partition this broker cannot load must not point the client at offset 0.
func TestFetchMessageMissingPartitionKeepsRequestedOffset(t *testing.T) {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
tp := topic.NewTopic("test", "t")
b.topicCache = map[string]*topicCacheEntry{tp.String(): {expiresAt: time.Now().Add(time.Hour)}}
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{
Topic: &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name},
Partition: &schema_pb.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520},
StartOffset: 10,
})
if err != nil {
t.Fatal(err)
}
if resp.Error == "" {
t.Fatal("fetch from a missing topic succeeded")
}
if resp.NextOffset != 10 {
t.Errorf("next offset %d after a failed fetch at 10", resp.NextOffset)
}
}
// A fetch below the earliest retained offset is out of range, not a storage
// error to retry, and the range info reports where the retained log starts.
func TestFetchBelowRetentionIsOutOfRange(t *testing.T) {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
tp := topic.NewTopic("test", "t")
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
b.topicCache = map[string]*topicCacheEntry{tp.String(): {conf: &mq_pb.ConfigureTopicResponse{}, expiresAt: time.Now().Add(time.Hour)}}
lp := topic.NewLocalPartition(partition, 3600, nil, nil)
defer lp.Shutdown()
if err := lp.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) { return 41, nil }); err != nil {
t.Fatal(err)
}
// a purge left offsets 30..41 on disk
lp.LogBuffer.SetLogStartOffset(30)
b.localTopicManager.AddLocalPartition(tp, lp)
pbTopic := &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name}
pbPartition := &schema_pb.Partition{RingSize: partition.RingSize, RangeStart: partition.RangeStart, RangeStop: partition.RangeStop, UnixTimeNs: partition.UnixTimeNs}
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{Topic: pbTopic, Partition: pbPartition, StartOffset: 10})
if err != nil {
t.Fatal(err)
}
if resp.ErrorCode != BrokerErrorOffsetOutOfRange || resp.LogStartOffset != 30 || resp.NextOffset != 10 || len(resp.Messages) != 0 {
t.Errorf("fetch at 10: code %d (%q), log start %d, next %d, %d messages; want out of range, log start 30, next 10",
resp.ErrorCode, resp.Error, resp.LogStartOffset, resp.NextOffset, len(resp.Messages))
}
info, err := b.GetPartitionRangeInfo(context.Background(), &mq_pb.GetPartitionRangeInfoRequest{Topic: pbTopic, Partition: pbPartition})
if err != nil {
t.Fatal(err)
}
if info.Error != "" || info.OffsetRange.GetEarliestOffset() != 30 || info.OffsetRange.GetHighWaterMark() != 42 {
t.Errorf("range info %v, want earliest 30, high water mark 42", info)
}
}
+126
View File
@@ -0,0 +1,126 @@
package broker
import (
"context"
"errors"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// EndPartitionGeneration gives a partition whose leader/follower pair broke a new
// pair. A report for an epoch that already moved on is ignored, so both halves of
// a broken pair can report it.
func (b *MessageQueueBroker) EndPartitionGeneration(ctx context.Context, req *mq_pb.EndPartitionGenerationRequest) (resp *mq_pb.EndPartitionGenerationResponse, err error) {
if !b.isLockOwner() {
err = b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.EndPartitionGeneration(ctx, req)
return err
})
return resp, err
}
if !b.balancerSettled() {
// a new pair is picked from the brokers it has heard from, so wait until all have reconnected
return nil, status.Error(codes.Unavailable, "broker balancer is still settling")
}
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
t := topic.FromPbTopic(req.Topic)
conf, err := b.fca.ReadTopicConfFromFiler(t)
if err != nil {
return nil, fmt.Errorf("read topic %s: %w", t, err)
}
for _, assignment := range conf.BrokerPartitionAssignments {
if !b.partitionsMatch(assignment.Partition, req.Partition) {
continue
}
if assignment.Epoch != req.Epoch {
return &mq_pb.EndPartitionGenerationResponse{}, nil
}
previousLeader, previousFollower := assignment.LeaderBroker, assignment.FollowerBroker
pub_balancer.ReassignPartition(b.PubBalancer.Brokers, assignment)
if err := b.fca.SaveTopicConfToFiler(t, conf); err != nil {
return nil, fmt.Errorf("save topic %s: %w", t, err)
}
b.invalidateTopicCache(t)
glog.V(0).Infof("topic %s partition %v epoch %d ended (reported by %s): %s/%s -> %s/%s at epoch %d", t, topic.FromPbPartition(req.Partition), req.Epoch, req.Broker,
previousLeader, previousFollower, assignment.LeaderBroker, assignment.FollowerBroker, assignment.Epoch)
return &mq_pb.EndPartitionGenerationResponse{}, nil
}
return nil, status.Errorf(codes.NotFound, "topic %s has no partition %v", t, topic.FromPbPartition(req.Partition))
}
// watchReplica ends this leader's generation when its follower is lost. It starts
// once lp is registered, so the generation never ends under an unlisted partition.
func (b *MessageQueueBroker) watchReplica(t topic.Topic, p topic.Partition, lp *topic.LocalPartition, epoch int64) {
if lp.Replica == nil {
return
}
<-lp.Replica.Broken()
if err := lp.Replica.Err(); errors.Is(err, topic.ErrReplicaClosed) || errors.Is(err, topic.ErrReplicaAbandoned) {
return
}
glog.Warningf("topic %s partition %v epoch %d lost follower %s: %v", t, p, epoch, lp.Follower, lp.Replica.Err())
b.endLeaderGeneration(t, lp, epoch)
}
// endLeaderGeneration stores what this leader holds, seals its fence and reports
// the generation ended. The fence is kept renewed meanwhile, so a new leader waits.
func (b *MessageQueueBroker) endLeaderGeneration(t topic.Topic, lp *topic.LocalPartition, epoch int64) {
ctx := context.Background()
p, fence := lp.Partition, lp.Fence
stopRenewing := b.keepFenceRenewed(fence)
b.localTopicManager.RemoveLocalPartition(t, lp)
b.localTopicManager.WaitRetired(ctx, t, p)
stopRenewing()
b.sealAndReportGeneration(ctx, t, p, fence, epoch)
}
func (b *MessageQueueBroker) sealAndReportGeneration(ctx context.Context, t topic.Topic, p topic.Partition, fence *topic.PartitionFence, epoch int64) {
if fence != nil && !fence.IsLost() {
if err := b.renewPartitionFence(ctx, fence, true); err != nil {
glog.Warningf("seal topic %s partition %v epoch %d: %v", t, p, epoch, err)
}
}
go b.reportGenerationEnded(t, p, epoch)
}
const generationReportTimeout = 30 * time.Second
// reportGenerationEnded retries until a balancer takes the report: the lost broker
// may have been the balancer, and the partition stays unserved until one does.
func (b *MessageQueueBroker) reportGenerationEnded(t topic.Topic, p topic.Partition, epoch int64) {
req := &mq_pb.EndPartitionGenerationRequest{
Topic: t.ToPbTopic(),
Partition: p.ToPbPartition(),
Epoch: epoch,
Broker: string(b.option.BrokerAddress()),
}
parent := context.Background()
if b.ctx != nil {
parent = b.ctx
}
for wait := time.Second; ; wait = min(2*wait, 10*time.Second) {
// a balancer that stops answering must not hold the retries; a repeat after a
// save that landed finds the epoch moved on and returns without writing
ctx, cancel := context.WithTimeout(parent, generationReportTimeout)
_, err := b.EndPartitionGeneration(ctx, req)
cancel()
if err == nil {
return
}
glog.Warningf("report topic %s partition %v epoch %d ended: %v", t, p, epoch, err)
select {
case <-parent.Done():
return
case <-time.After(wait):
}
}
}
+8 -11
View File
@@ -19,7 +19,7 @@ import (
// LookupTopicBrokers returns the brokers that are serving the topic
func (b *MessageQueueBroker) LookupTopicBrokers(ctx context.Context, request *mq_pb.LookupTopicBrokersRequest) (resp *mq_pb.LookupTopicBrokersResponse, err error) {
if !b.isLockOwner() {
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.LookupTopicBrokers(ctx, request)
return nil
})
@@ -52,8 +52,7 @@ func (b *MessageQueueBroker) ListTopics(ctx context.Context, request *mq_pb.List
glog.V(4).Infof("📋 ListTopics called, isLockOwner=%v", b.isLockOwner())
if !b.isLockOwner() {
glog.V(4).Infof("📋 ListTopics proxying to lock owner: %s", b.lockAsBalancer.LockOwner())
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.ListTopics(ctx, request)
return nil
})
@@ -190,7 +189,7 @@ func (b *MessageQueueBroker) TopicExists(ctx context.Context, request *mq_pb.Top
if !b.isLockOwner() {
var resp *mq_pb.TopicExistsResponse
var err error
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.TopicExists(ctx, request)
return nil
})
@@ -276,7 +275,7 @@ func (b *MessageQueueBroker) TopicExists(ctx context.Context, request *mq_pb.Top
// GetTopicConfiguration returns the complete configuration of a topic including schema and partition assignments
func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request *mq_pb.GetTopicConfigurationRequest) (resp *mq_pb.GetTopicConfigurationResponse, err error) {
if !b.isLockOwner() {
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.GetTopicConfiguration(ctx, request)
return nil
})
@@ -290,6 +289,8 @@ func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request
var conf *mq_pb.ConfigureTopicResponse
var createdAtNs, modifiedAtNs int64
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
if conf, createdAtNs, modifiedAtNs, err = b.fca.ReadTopicConfFromFilerWithMetadata(t); err != nil {
glog.V(0).Infof("get topic configuration %s: %v", request.Topic, err)
return nil, fmt.Errorf("failed to read topic configuration: %w", err)
@@ -320,7 +321,7 @@ func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request
// GetTopicPublishers returns the active publishers for a topic
func (b *MessageQueueBroker) GetTopicPublishers(ctx context.Context, request *mq_pb.GetTopicPublishersRequest) (resp *mq_pb.GetTopicPublishersResponse, err error) {
if !b.isLockOwner() {
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.GetTopicPublishers(ctx, request)
return nil
})
@@ -374,7 +375,7 @@ func (b *MessageQueueBroker) GetTopicPublishers(ctx context.Context, request *mq
// GetTopicSubscribers returns the active subscribers for a topic
func (b *MessageQueueBroker) GetTopicSubscribers(ctx context.Context, request *mq_pb.GetTopicSubscribersRequest) (resp *mq_pb.GetTopicSubscribersResponse, err error) {
if !b.isLockOwner() {
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.GetTopicSubscribers(ctx, request)
return nil
})
@@ -435,7 +436,3 @@ func (b *MessageQueueBroker) GetTopicSubscribers(ctx context.Context, request *m
Subscribers: subscribers,
}, nil
}
func (b *MessageQueueBroker) isLockOwner() bool {
return pb.ServerAddress(b.lockAsBalancer.LockOwner()).Equals(b.option.BrokerAddress())
}
+55 -59
View File
@@ -2,15 +2,15 @@ package broker
import (
"context"
"errors"
"fmt"
"io"
"math/rand/v2"
"net"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/grpc/peer"
@@ -61,8 +61,7 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
return stream.Send(response)
}
currentBrokerAddress := fmt.Sprintf("%s:%d", b.option.Ip, b.option.Port)
if leaderBroker != currentBrokerAddress {
if !pb.ServerAddress(leaderBroker).Equals(b.option.BrokerAddress()) {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("not the leader for this partition, leader is: %s", leaderBroker))
glog.V(1).Infof("rejecting publish request: not the leader for partition, leader is: %s", leaderBroker)
return stream.Send(response)
@@ -71,16 +70,35 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
// get or generate a local partition
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
localTopicPartition, getOrGenErr := b.GetOrGenerateLocalPartition(t, p)
if localTopicPartition == nil && (getOrGenErr == nil || errors.Is(getOrGenErr, errFenceLost)) {
// the balancer named this broker from a newer topic.conf than the cached one
b.invalidateTopicCache(t)
localTopicPartition, getOrGenErr = b.GetOrGenerateLocalPartition(t, p)
}
if errors.Is(getOrGenErr, errFenceLost) {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, getOrGenErr.Error())
return stream.Send(response)
}
if errors.Is(getOrGenErr, errGenerationEnded) {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, getOrGenErr.Error())
return stream.Send(response)
}
if getOrGenErr != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorTopicNotFound, fmt.Sprintf("topic %v not found: %v", t, getOrGenErr))
glog.Errorf("topic %v not found: %v", t, getOrGenErr)
return stream.Send(response)
}
// connect to follower brokers
if followerErr := localTopicPartition.MaybeConnectToFollowers(initMessage, b.grpcDialOption); followerErr != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorFollowerConnectionFailed, followerErr.Error())
glog.Errorf("MaybeConnectToFollowers: %v", followerErr)
if localTopicPartition == nil {
// topic.conf does not name this broker, though the balancer just did
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is not assigned to this broker", t, p))
return stream.Send(response)
}
if localTopicPartition.IsFenced() {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p))
return stream.Send(response)
}
if replica := localTopicPartition.Replica; replica != nil && replica.Err() != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, fmt.Sprintf("topic %v partition %v: %v", t, p, replica.Err()))
return stream.Send(response)
}
@@ -89,49 +107,12 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
publisher := topic.NewLocalPublisher()
localTopicPartition.Publishers.AddPublisher(clientName, publisher)
// DISABLED: Periodic ack goroutine not needed with immediate per-message acks
// Immediate acks provide correct offset information for Kafka Gateway
var receivedSequence, acknowledgedSequence int64
var isClosed bool
if false {
ackInterval := int64(1)
if initMessage.AckInterval > 0 {
ackInterval = int64(initMessage.AckInterval)
}
go func() {
defer func() {
// println("stop sending ack to publisher", initMessage.PublisherName)
}()
lastAckTime := time.Now()
for !isClosed {
receivedSequence = atomic.LoadInt64(&localTopicPartition.AckTsNs)
if acknowledgedSequence < receivedSequence && (receivedSequence-acknowledgedSequence >= ackInterval || time.Since(lastAckTime) > 100*time.Millisecond) {
acknowledgedSequence = receivedSequence
response := &mq_pb.PublishMessageResponse{
AckTsNs: acknowledgedSequence,
}
if err := stream.Send(response); err != nil {
glog.Errorf("Error sending response %v: %v", response, err)
}
// Update acknowledged offset for this publisher
publisher.UpdateAckedOffset(acknowledgedSequence)
// println("sent ack", acknowledgedSequence, "=>", initMessage.PublisherName)
lastAckTime = time.Now()
} else {
time.Sleep(10 * time.Millisecond) // Reduced from 1s to 10ms for faster acknowledgments
}
}
}()
}
defer func() {
// remove the publisher
localTopicPartition.Publishers.RemovePublisher(clientName)
// Use topic-aware shutdown logic to prevent aggressive removal of system topics
if localTopicPartition.MaybeShutdownLocalPartitionForTopic(t.Name) {
b.localTopicManager.RemoveLocalPartition(t, p)
b.localTopicManager.RemoveLocalPartition(t, localTopicPartition)
glog.V(0).Infof("Removed local topic %v partition %v", initMessage.Topic, initMessage.Partition)
}
}()
@@ -139,10 +120,6 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
// send a hello message
stream.Send(&mq_pb.PublishMessageResponse{})
defer func() {
isClosed = true
}()
// process each published messages
for {
// receive a message
@@ -179,16 +156,22 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
// The control message should still be sent to the follower
// to avoid timing issue when ack messages.
// Send to the local partition with offset assignment
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
// Create offset assignment function for this partition
assignOffsetFn := func() (int64, error) {
return b.offsetManager.AssignOffset(t, p)
if localTopicPartition.IsFenced() {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p))
return stream.Send(response)
}
// Use offset-aware publishing
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage, assignOffsetFn)
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage)
if replica := localTopicPartition.Replica; replica != nil {
// acked only once the follower holds it too
if err == nil {
err = replica.WaitAcked(assignedOffset)
}
if replicaErr := replica.Err(); replicaErr != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, fmt.Sprintf("topic %v partition %v: %v", t, p, replicaErr))
return stream.Send(response)
}
}
if err != nil {
return fmt.Errorf("topic %v partition %v publish error: %w", initMessage.Topic, initMessage.Partition, err)
}
@@ -267,6 +250,19 @@ func (b *MessageQueueBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_
t := topic.FromPbTopic(req.Topic)
p := topic.FromPbPartition(req.Partition)
// A broker that no longer leads the partition would answer with its stale range.
localPartition, err := b.GetOrGenerateLocalPartition(t, p)
if err != nil {
return &mq_pb.GetPartitionRangeInfoResponse{
Error: fmt.Sprintf("partition not found: %v", err),
}, nil
}
if localPartition == nil {
return &mq_pb.GetPartitionRangeInfoResponse{
Error: "partition not found",
}, nil
}
// Get offset information from the broker's internal method
info, err := b.GetPartitionOffsetInfoInternal(t, p)
if err != nil {
+93 -123
View File
@@ -1,152 +1,122 @@
package broker
import (
"context"
"encoding/binary"
"fmt"
"io"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util/buffered_queue"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
type memBuffer struct {
buf []byte
startTime time.Time
stopTime time.Time
}
func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) (err error) {
var req *mq_pb.PublishFollowMeRequest
req, err = stream.Recv()
// PublishFollowMe holds a leader's entries that are not stored yet, acking each,
// until the leader closes the stream after storing everything.
func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
req, err := stream.Recv()
if err != nil {
return err
}
initMessage := req.GetInit()
if initMessage == nil {
init := req.GetInit()
if init == nil {
return fmt.Errorf("missing init message")
}
t, p := topic.FromPbTopic(init.Topic), topic.FromPbPartition(init.Partition)
// create an in-memory queue of buffered messages
inMemoryBuffers := buffered_queue.NewBufferedQueue[memBuffer](4)
logBuffer := b.buildFollowerLogBuffer(inMemoryBuffers)
lastFlushTsNs := time.Now().UnixNano()
// follow each published messages
var held []*filer_pb.LogEntry
acked := int64(-1)
for {
// receive a message
req, err = stream.Recv()
req, err := stream.Recv()
if err != nil {
if err == io.EOF {
err = nil
break
}
glog.V(0).Infof("topic %v partition %v publish stream error: %v", initMessage.Topic, initMessage.Partition, err)
break
// the leader went without closing the stream, so it may not have stored these
glog.Warningf("follow stream of %v %v from %s at epoch %d broke with %d unstored entries: %v", t, p, init.Leader, init.Epoch, len(held), err)
b.takeOverPartition(t, p, init, held)
return nil
}
// Process the received message
if dataMessage := req.GetData(); dataMessage != nil {
// TODO: change this to DataMessage
// log the message
if addErr := logBuffer.AddToBuffer(dataMessage); addErr != nil {
err = fmt.Errorf("failed to add message to log buffer: %w", addErr)
glog.Errorf("Failed to add message to log buffer: %v", addErr)
break
}
// send back the ack
if err := stream.Send(&mq_pb.PublishFollowMeResponse{
AckTsNs: dataMessage.TsNs,
}); err != nil {
glog.Errorf("Error sending response %v: %v", dataMessage, err)
}
// println("ack", string(dataMessage.Key), dataMessage.TsNs)
} else if closeMessage := req.GetClose(); closeMessage != nil {
glog.V(0).Infof("topic %v partition %v publish stream closed: %v", initMessage.Topic, initMessage.Partition, closeMessage)
break
} else if flushMessage := req.GetFlush(); flushMessage != nil {
glog.V(0).Infof("topic %v partition %v publish stream flushed: %v", initMessage.Topic, initMessage.Partition, flushMessage)
lastFlushTsNs = flushMessage.TsNs
// drop already flushed messages
for mem, found := inMemoryBuffers.PeekHead(); found; mem, found = inMemoryBuffers.PeekHead() {
if mem.stopTime.UnixNano() <= flushMessage.TsNs {
inMemoryBuffers.Dequeue()
// println("dropping flushed messages: ", mem.startTime.UnixNano(), mem.stopTime.UnixNano(), len(mem.buf))
} else {
break
}
}
} else {
glog.Errorf("unknown message: %v", req)
}
}
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
logBuffer.ShutdownLogBuffer()
// wait until all messages are sent to inMemoryBuffers
for !logBuffer.IsAllFlushed() {
time.Sleep(113 * time.Millisecond)
}
partitionDir := topic.PartitionDir(t, p)
// flush the remaining messages
inMemoryBuffers.CloseInput()
for mem, found := inMemoryBuffers.Dequeue(); found; mem, found = inMemoryBuffers.Dequeue() {
if len(mem.buf) == 0 {
switch m := req.Message.(type) {
case *mq_pb.PublishFollowMeRequest_Entry:
held = append(held, m.Entry)
acked = m.Entry.Offset
case *mq_pb.PublishFollowMeRequest_Heartbeat:
case *mq_pb.PublishFollowMeRequest_Flush:
held = dropStored(held, m.Flush.Offset)
continue
case *mq_pb.PublishFollowMeRequest_Close:
return nil
default:
continue
}
startTime, stopTime := mem.startTime.UTC(), mem.stopTime.UTC()
if stopTime.UnixNano() <= lastFlushTsNs {
glog.V(0).Infof("dropping remaining data at %v %v", t, p)
continue
if err := stream.Send(&mq_pb.PublishFollowMeResponse{AckOffset: acked}); err != nil {
glog.Warningf("follow stream of %v %v from %s at epoch %d failed to ack with %d unstored entries: %v", t, p, init.Leader, init.Epoch, len(held), err)
b.takeOverPartition(t, p, init, held)
return nil
}
// TODO trim data earlier than lastFlushTsNs
targetFile := fmt.Sprintf("%s/%s", partitionDir, startTime.Format(topic.TIME_FORMAT))
for {
if err := b.appendToFile(targetFile, mem.buf); err != nil {
glog.V(0).Infof("metadata log write failed %s: %v", targetFile, err)
time.Sleep(737 * time.Millisecond)
} else {
break
}
}
glog.V(0).Infof("flushed remaining data at %v to %s size %d", mem.stopTime.UnixNano(), targetFile, len(mem.buf))
}
glog.V(0).Infof("shut down follower for %v %v", t, p)
return err
}
func (b *MessageQueueBroker) buildFollowerLogBuffer(inMemoryBuffers *buffered_queue.BufferedQueue[memBuffer]) *log_buffer.LogBuffer {
lb := log_buffer.NewLogBuffer("follower",
5*time.Second, func(logBuffer *log_buffer.LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
if len(buf) == 0 {
// dropStored keeps the entries above offset; held is in offset order.
func dropStored(held []*filer_pb.LogEntry, offset int64) []*filer_pb.LogEntry {
i := sort.Search(len(held), func(i int) bool { return held[i].Offset > offset })
return append([]*filer_pb.LogEntry(nil), held[i:]...)
}
// takeOverPartition moves the fence from a lost leader to this follower, stores the
// entries the leader had not, and ends the generation. Every acked entry is here,
// since the leader acks only what this follower holds.
func (b *MessageQueueBroker) takeOverPartition(t topic.Topic, p topic.Partition, init *mq_pb.PublishFollowMeRequest_InitMessage, held []*filer_pb.LogEntry) {
ctx := context.Background()
if b.ctx != nil {
ctx = b.ctx
}
// these entries may be the only copy left, so a filer error is retried until the fence moves on
var fence *topic.PartitionFence
if err := retryLogWrite(ctx, topic.PartitionFencePath(t, p), func() (err error) {
fence, err = b.takeOverPartitionFence(ctx, t, p, init.Epoch, init.Leader)
return err
}); err != nil {
glog.V(0).Infof("not taking over %v %v epoch %d: %v", t, p, init.Epoch, err)
return
}
stopRenewing := b.keepFenceRenewed(fence)
defer stopRenewing()
// with the fence moved, nothing else adds to what is stored
var stored mq.OffsetRange
if err := retryLogWrite(ctx, topic.PartitionDir(t, p), func() (err error) {
stored, err = b.getOffsetRangeFromChunkMetadata(t, p)
return err
}); err != nil {
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
return
}
fence.NoteLogFileTime(stored.NewestLogFileTime())
_, highWaterMark := stored.Bounds()
held = dropStored(held, highWaterMark-1)
if len(held) > 0 {
var data []byte
minTsNs, maxTsNs := held[0].TsNs, held[0].TsNs
for _, entry := range held {
encoded, err := entry.MarshalVT()
if err != nil {
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
return
}
inMemoryBuffers.Enqueue(memBuffer{
buf: buf,
startTime: startTime,
stopTime: stopTime,
})
glog.V(0).Infof("queue up %d~%d size %d", startTime.UnixNano(), stopTime.UnixNano(), len(buf))
}, nil, func() {
})
return lb
data = binary.BigEndian.AppendUint32(data, uint32(len(encoded)))
data = append(data, encoded...)
minTsNs, maxTsNs = min(minTsNs, entry.TsNs), max(maxTsNs, entry.TsNs)
}
first, last := held[0], held[len(held)-1]
startTime, stopTime := time.Unix(0, minTsNs).UTC(), time.Unix(0, maxTsNs).UTC()
targetFile := topic.PartitionDir(t, p) + "/" + topic.LogFileName(fence.LogFileTime(startTime), first.Offset)
if err := b.writeLogFile(ctx, fence, targetFile, startTime, stopTime, data, first.Offset, last.Offset); err != nil {
glog.Errorf("take over %v %v epoch %d: store offsets %d-%d: %v", t, p, init.Epoch, first.Offset, last.Offset, err)
return
}
}
glog.V(0).Infof("took over %v %v epoch %d from %s, stored %d entries", t, p, init.Epoch, init.Leader, len(held))
stopRenewing()
b.sealAndReportGeneration(ctx, t, p, fence, init.Epoch)
}
+1 -2
View File
@@ -280,8 +280,7 @@ func (b *MessageQueueBroker) findBrokerForTopicPartition(topic *schema_pb.Topic,
if !b.isLockOwner() {
// Redirect to balancer to get topic broker assignments
balancerAddress := pb.ServerAddress(b.lockAsBalancer.LockOwner())
err = b.withBrokerClient(false, balancerAddress, func(client mq_pb.SeaweedMessagingClient) error {
err = b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
lookupResp, err = client.LookupTopicBrokers(ctx, lookupReq)
return err
})
+37
View File
@@ -0,0 +1,37 @@
package broker
import (
"context"
"runtime/debug"
"github.com/seaweedfs/seaweedfs/weed/glog"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// GrpcServerOptions turns a panic in one broker RPC into an error for that
// call, so it cannot take down the process the broker runs in.
func GrpcServerOptions() []grpc.ServerOption {
return []grpc.ServerOption{
grpc.ChainUnaryInterceptor(recoverUnary),
grpc.ChainStreamInterceptor(recoverStream),
}
}
func recoverUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
defer recoverRpc(info.FullMethod, &err)
return handler(ctx, req)
}
func recoverStream(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
defer recoverRpc(info.FullMethod, &err)
return handler(srv, ss)
}
func recoverRpc(method string, err *error) {
if r := recover(); r != nil {
glog.Errorf("broker %s panic: %v\n%s", method, r, debug.Stack())
*err = status.Errorf(codes.Internal, "broker %s: internal error", method)
}
}
@@ -0,0 +1,29 @@
package broker
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestBrokerRpcPanicBecomesError(t *testing.T) {
_, err := recoverUnary(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/test/Unary"},
func(ctx context.Context, req any) (any, error) {
var p *mq_pb.BrokerPartitionAssignment
return p.LeaderBroker, nil
})
require.Error(t, err)
assert.Equal(t, codes.Internal, status.Code(err))
err = recoverStream(nil, nil, &grpc.StreamServerInfo{FullMethod: "/test/Stream"},
func(srv any, stream grpc.ServerStream) error {
panic("boom")
})
assert.Equal(t, codes.Internal, status.Code(err))
}
+2 -60
View File
@@ -9,7 +9,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/sub_coordinator"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
@@ -68,45 +67,10 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
glog.V(0).Infof("Subscriber %s on %v %v disconnected, sent %d", clientName, t, partition, counter)
// Use topic-aware shutdown logic to prevent aggressive removal of system topics
if localTopicPartition.MaybeShutdownLocalPartitionForTopic(t.Name) {
b.localTopicManager.RemoveLocalPartition(t, partition)
b.localTopicManager.RemoveLocalPartition(t, localTopicPartition)
}
}()
// connect to the follower
var subscribeFollowMeStream mq_pb.SeaweedMessaging_SubscribeFollowMeClient
glog.V(0).Infof("follower broker: %v", req.GetInit().FollowerBroker)
if req.GetInit().FollowerBroker != "" {
follower := req.GetInit().FollowerBroker
if followerGrpcConnection, err := pb.GrpcDial(ctx, follower, true, b.grpcDialOption); err != nil {
return fmt.Errorf("fail to dial %s: %v", follower, err)
} else {
defer func() {
println("closing SubscribeFollowMe connection", follower)
if subscribeFollowMeStream != nil {
subscribeFollowMeStream.CloseSend()
}
// followerGrpcConnection.Close()
}()
followerClient := mq_pb.NewSeaweedMessagingClient(followerGrpcConnection)
if subscribeFollowMeStream, err = followerClient.SubscribeFollowMe(ctx); err != nil {
return fmt.Errorf("fail to subscribe to %s: %v", follower, err)
} else {
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
Message: &mq_pb.SubscribeFollowMeRequest_Init{
Init: &mq_pb.SubscribeFollowMeRequest_InitMessage{
Topic: req.GetInit().Topic,
Partition: req.GetInit().GetPartitionOffset().Partition,
ConsumerGroup: req.GetInit().ConsumerGroup,
},
},
}); err != nil {
return fmt.Errorf("fail to send init to %s: %v", follower, err)
}
}
}
glog.V(0).Infof("follower %s connected", follower)
}
// Channel to handle seek requests - signals Subscribe loop to restart from new offset
seekChan := make(chan *mq_pb.SubscribeMessageRequest_SeekMessage, 1)
@@ -162,19 +126,8 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
// Update acknowledged offset and last seen time for this subscriber when it sends an ack
subscriber.UpdateAckedOffset(currentLastOffset)
// fmt.Printf("%+v recv (%s,%d), oldest %d\n", partition, string(ack.GetAck().Key), ack.GetAck().TsNs, currentLastOffset)
if subscribeFollowMeStream != nil && currentLastOffset > lastOffset {
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
Message: &mq_pb.SubscribeFollowMeRequest_Ack{
Ack: &mq_pb.SubscribeFollowMeRequest_AckMessage{
TsNs: currentLastOffset,
},
},
}); err != nil {
glog.Errorf("Error sending ack to follower: %v", err)
break
}
if currentLastOffset > lastOffset {
lastOffset = currentLastOffset
// fmt.Printf("%+v forwarding ack %d\n", partition, lastOffset)
}
}
if lastOffset > 0 {
@@ -183,17 +136,6 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
glog.Errorf("saveConsumerGroupOffset partition %v lastOffset %d: %v", partition, lastOffset, err)
}
}
if subscribeFollowMeStream != nil {
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
Message: &mq_pb.SubscribeFollowMeRequest_Close{
Close: &mq_pb.SubscribeFollowMeRequest_CloseMessage{},
},
}); err != nil {
if err != io.EOF {
glog.Errorf("Error sending close to follower: %v", err)
}
}
}
}()
// Create a goroutine to handle context cancellation and wake up the condition variable
-253
View File
@@ -1,253 +0,0 @@
package broker
import (
"context"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// SubscribeWithOffset handles subscription requests with offset-based positioning
// TODO: This extends the broker with offset-aware subscription support
// ASSUMPTION: This will eventually be integrated into the main SubscribeMessage method
func (b *MessageQueueBroker) SubscribeWithOffset(
ctx context.Context,
req *mq_pb.SubscribeMessageRequest,
stream mq_pb.SeaweedMessaging_SubscribeMessageServer,
offsetType schema_pb.OffsetType,
startOffset int64,
) error {
initMessage := req.GetInit()
if initMessage == nil {
return fmt.Errorf("missing init message")
}
// Extract partition information from the request
t := topic.FromPbTopic(initMessage.Topic)
// Get partition from the request's partition_offset field
if initMessage.PartitionOffset == nil || initMessage.PartitionOffset.Partition == nil {
return fmt.Errorf("missing partition information in request")
}
// Use the partition information from the request
p := topic.Partition{
RingSize: initMessage.PartitionOffset.Partition.RingSize,
RangeStart: initMessage.PartitionOffset.Partition.RangeStart,
RangeStop: initMessage.PartitionOffset.Partition.RangeStop,
UnixTimeNs: initMessage.PartitionOffset.Partition.UnixTimeNs,
}
// Create offset-based subscription
subscriptionID := fmt.Sprintf("%s-%s-%d", initMessage.ConsumerGroup, initMessage.ConsumerId, startOffset)
subscription, err := b.offsetManager.CreateSubscription(subscriptionID, t, p, offsetType, startOffset)
if err != nil {
return fmt.Errorf("failed to create offset subscription: %w", err)
}
defer func() {
if closeErr := b.offsetManager.CloseSubscription(subscriptionID); closeErr != nil {
glog.V(0).Infof("Failed to close subscription %s: %v", subscriptionID, closeErr)
}
}()
// Get local partition for reading
localTopicPartition, err := b.GetOrGenerateLocalPartition(t, p)
if err != nil {
return fmt.Errorf("topic %v partition %v not found: %v", t, p, err)
}
// Subscribe to messages using offset-based positioning
return b.subscribeWithOffsetSubscription(ctx, localTopicPartition, subscription, stream, initMessage)
}
// subscribeWithOffsetSubscription handles the actual message consumption with offset tracking
func (b *MessageQueueBroker) subscribeWithOffsetSubscription(
ctx context.Context,
localPartition *topic.LocalPartition,
subscription *offset.OffsetSubscription,
stream mq_pb.SeaweedMessaging_SubscribeMessageServer,
initMessage *mq_pb.SubscribeMessageRequest_InitMessage,
) error {
clientName := fmt.Sprintf("%s-%s", initMessage.ConsumerGroup, initMessage.ConsumerId)
// TODO: Implement offset-based message reading
// ASSUMPTION: For now, we'll use the existing subscription mechanism and track offsets separately
// This should be replaced with proper offset-based reading from storage
// Convert the subscription's current offset to a proper MessagePosition
startPosition, err := b.convertOffsetToMessagePosition(subscription)
if err != nil {
return fmt.Errorf("failed to convert offset to message position: %w", err)
}
glog.V(0).Infof("[%s] Starting Subscribe for topic %s partition %d-%d at offset %d",
clientName, subscription.TopicName, subscription.Partition.RangeStart, subscription.Partition.RangeStop, subscription.CurrentOffset)
return localPartition.Subscribe(clientName,
startPosition,
func() bool {
// Check if context is cancelled (client disconnected)
select {
case <-ctx.Done():
glog.V(0).Infof("[%s] Context cancelled, stopping", clientName)
return false
default:
}
// Check if subscription is still active and not at end
if !subscription.IsActive {
glog.V(0).Infof("[%s] Subscription not active, stopping", clientName)
return false
}
atEnd, err := subscription.IsAtEnd()
if err != nil {
glog.V(0).Infof("[%s] Error checking if subscription at end: %v", clientName, err)
return false
}
if atEnd {
glog.V(4).Infof("[%s] At end of subscription, stopping", clientName)
return false
}
// Add a small sleep to avoid CPU busy-wait when checking for new data
time.Sleep(10 * time.Millisecond)
return true
},
func(logEntry *filer_pb.LogEntry) (bool, error) {
// Check if this message matches our offset requirements
currentOffset := subscription.GetNextOffset()
if logEntry.Offset < currentOffset {
// Skip messages before our current offset
return false, nil
}
// Send message to client
if err := stream.Send(&mq_pb.SubscribeMessageResponse{
Message: &mq_pb.SubscribeMessageResponse_Data{
Data: &mq_pb.DataMessage{
Key: logEntry.Key,
Value: logEntry.Data,
TsNs: logEntry.TsNs,
},
},
}); err != nil {
glog.Errorf("Error sending data to %s: %v", clientName, err)
return false, err
}
// Advance subscription offset
subscription.AdvanceOffset()
// Check context for cancellation
select {
case <-ctx.Done():
return true, ctx.Err()
default:
return false, nil
}
})
}
// GetSubscriptionInfo returns information about an active subscription
func (b *MessageQueueBroker) GetSubscriptionInfo(subscriptionID string) (map[string]interface{}, error) {
subscription, err := b.offsetManager.GetSubscription(subscriptionID)
if err != nil {
return nil, err
}
lag, err := subscription.GetLag()
if err != nil {
return nil, err
}
atEnd, err := subscription.IsAtEnd()
if err != nil {
return nil, err
}
return map[string]interface{}{
"subscription_id": subscription.ID,
"start_offset": subscription.StartOffset,
"current_offset": subscription.CurrentOffset,
"offset_type": subscription.OffsetType.String(),
"is_active": subscription.IsActive,
"lag": lag,
"at_end": atEnd,
}, nil
}
// ListActiveSubscriptions returns information about all active subscriptions
func (b *MessageQueueBroker) ListActiveSubscriptions() ([]map[string]interface{}, error) {
subscriptions, err := b.offsetManager.ListActiveSubscriptions()
if err != nil {
return nil, err
}
result := make([]map[string]interface{}, len(subscriptions))
for i, subscription := range subscriptions {
lag, _ := subscription.GetLag()
atEnd, _ := subscription.IsAtEnd()
result[i] = map[string]interface{}{
"subscription_id": subscription.ID,
"start_offset": subscription.StartOffset,
"current_offset": subscription.CurrentOffset,
"offset_type": subscription.OffsetType.String(),
"is_active": subscription.IsActive,
"lag": lag,
"at_end": atEnd,
}
}
return result, nil
}
// SeekSubscription seeks an existing subscription to a specific offset
func (b *MessageQueueBroker) SeekSubscription(subscriptionID string, offset int64) error {
subscription, err := b.offsetManager.GetSubscription(subscriptionID)
if err != nil {
return err
}
return subscription.SeekToOffset(offset)
}
// convertOffsetToMessagePosition converts a subscription's current offset to a MessagePosition for log_buffer
func (b *MessageQueueBroker) convertOffsetToMessagePosition(subscription *offset.OffsetSubscription) (log_buffer.MessagePosition, error) {
currentOffset := subscription.GetNextOffset()
// Handle special offset cases
switch subscription.OffsetType {
case schema_pb.OffsetType_RESET_TO_EARLIEST:
return log_buffer.NewMessagePosition(1, -3), nil
case schema_pb.OffsetType_RESET_TO_LATEST:
return log_buffer.NewMessagePosition(time.Now().UnixNano(), -4), nil
case schema_pb.OffsetType_EXACT_OFFSET:
// Use proper offset-based positioning that provides consistent results
// This uses the same approach as the main subscription handler in broker_grpc_sub.go
return log_buffer.NewMessagePositionFromOffset(currentOffset), nil
case schema_pb.OffsetType_EXACT_TS_NS:
// For exact timestamps, use the timestamp directly
return log_buffer.NewMessagePosition(currentOffset, -2), nil
default:
// Default to starting from current time for unknown offset types
return log_buffer.NewMessagePosition(time.Now().UnixNano(), -2), nil
}
}
@@ -1,707 +0,0 @@
package broker
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
func TestConvertOffsetToMessagePosition(t *testing.T) {
broker := &MessageQueueBroker{}
tests := []struct {
name string
offsetType schema_pb.OffsetType
currentOffset int64
expectedBatch int64
expectError bool
}{
{
name: "reset to earliest",
offsetType: schema_pb.OffsetType_RESET_TO_EARLIEST,
currentOffset: 0,
expectedBatch: -3,
expectError: false,
},
{
name: "reset to latest",
offsetType: schema_pb.OffsetType_RESET_TO_LATEST,
currentOffset: 0,
expectedBatch: -4,
expectError: false,
},
{
name: "exact offset zero",
offsetType: schema_pb.OffsetType_EXACT_OFFSET,
currentOffset: 0,
expectedBatch: 0, // NewMessagePositionFromOffset stores offset directly in Offset field
expectError: false,
},
{
name: "exact offset non-zero",
offsetType: schema_pb.OffsetType_EXACT_OFFSET,
currentOffset: 100,
expectedBatch: 100, // NewMessagePositionFromOffset stores offset directly in Offset field
expectError: false,
},
{
name: "exact timestamp",
offsetType: schema_pb.OffsetType_EXACT_TS_NS,
currentOffset: 50,
expectedBatch: -2,
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a mock subscription
subscription := &offset.OffsetSubscription{
ID: "test-subscription",
CurrentOffset: tt.currentOffset,
OffsetType: tt.offsetType,
IsActive: true,
}
position, err := broker.convertOffsetToMessagePosition(subscription)
if tt.expectError && err == nil {
t.Error("Expected error but got none")
return
}
if !tt.expectError && err != nil {
t.Errorf("Unexpected error: %v", err)
return
}
if position.Offset != tt.expectedBatch {
t.Errorf("Expected batch index %d, got %d", tt.expectedBatch, position.Offset)
}
// Verify that the timestamp is reasonable (not zero for most cases)
// Note: EXACT_OFFSET uses epoch time (zero) with NewMessagePositionFromOffset
if tt.offsetType != schema_pb.OffsetType_RESET_TO_EARLIEST &&
tt.offsetType != schema_pb.OffsetType_EXACT_OFFSET &&
position.Time.IsZero() {
t.Error("Expected non-zero timestamp")
}
})
}
}
func TestConvertOffsetToMessagePosition_OffsetEncoding(t *testing.T) {
broker := &MessageQueueBroker{}
// Test that offset-based positions encode the offset correctly in Offset field
testCases := []struct {
offset int64
expectedBatch int64
expectedIsSentinel bool // Should timestamp be the offset sentinel value?
}{
{10, 10, true},
{100, 100, true},
{0, 0, true},
{42, 42, true},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("offset_%d", tc.offset), func(t *testing.T) {
subscription := &offset.OffsetSubscription{
ID: fmt.Sprintf("test-%d", tc.offset),
CurrentOffset: tc.offset,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
IsActive: true,
}
pos, err := broker.convertOffsetToMessagePosition(subscription)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Check Offset encoding
if pos.Offset != tc.expectedBatch {
t.Errorf("Expected batch index %d, got %d", tc.expectedBatch, pos.Offset)
}
// Verify the offset can be extracted correctly using IsOffsetBased/GetOffset
if !pos.IsOffsetBased {
t.Error("Position should be detected as offset-based")
}
// Check that IsOffsetBased flag is set correctly
if tc.expectedIsSentinel && !pos.IsOffsetBased {
t.Error("Expected offset-based position but IsOffsetBased=false")
}
if extractedOffset := pos.GetOffset(); extractedOffset != tc.offset {
t.Errorf("Expected extracted offset %d, got %d", tc.offset, extractedOffset)
}
})
}
}
func TestConvertOffsetToMessagePosition_ConsistentResults(t *testing.T) {
broker := &MessageQueueBroker{}
subscription := &offset.OffsetSubscription{
ID: "consistent-test",
CurrentOffset: 42,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
IsActive: true,
}
// Call multiple times within a short period
positions := make([]log_buffer.MessagePosition, 5)
for i := 0; i < 5; i++ {
pos, err := broker.convertOffsetToMessagePosition(subscription)
if err != nil {
t.Fatalf("Unexpected error on iteration %d: %v", i, err)
}
positions[i] = pos
time.Sleep(1 * time.Millisecond) // Small delay
}
// All positions should have the same Offset
for i := 1; i < len(positions); i++ {
if positions[i].Offset != positions[0].Offset {
t.Errorf("Inconsistent Offset: %d vs %d", positions[0].Offset, positions[i].Offset)
}
}
// With NewMessagePositionFromOffset, timestamps should be identical (zero time for offset-based)
expectedTime := time.Time{}
for i := 0; i < len(positions); i++ {
if !positions[i].Time.Equal(expectedTime) {
t.Errorf("Expected all timestamps to be sentinel time (%v), got %v at index %d",
expectedTime, positions[i].Time, i)
}
}
}
func TestConvertOffsetToMessagePosition_FixVerification(t *testing.T) {
// This test specifically verifies that the fix addresses the issue mentioned:
// "The calculated timestamp for a given offset will change every time the function is called"
broker := &MessageQueueBroker{}
subscription := &offset.OffsetSubscription{
ID: "fix-verification",
CurrentOffset: 123,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
IsActive: true,
}
// Call the function multiple times with delays to simulate real-world usage
var positions []log_buffer.MessagePosition
var timestamps []int64
for i := 0; i < 10; i++ {
pos, err := broker.convertOffsetToMessagePosition(subscription)
if err != nil {
t.Fatalf("Unexpected error on iteration %d: %v", i, err)
}
positions = append(positions, pos)
timestamps = append(timestamps, pos.Time.UnixNano())
time.Sleep(2 * time.Millisecond) // Small delay to ensure time progression
}
// Verify ALL timestamps are identical (no time-based variance)
expectedTimestamp := timestamps[0]
for i, ts := range timestamps {
if ts != expectedTimestamp {
t.Errorf("Timestamp variance detected at call %d: expected %d, got %d", i, expectedTimestamp, ts)
}
}
// Verify ALL Offset values are identical
expectedBatch := positions[0].Offset
for i, pos := range positions {
if pos.Offset != expectedBatch {
t.Errorf("Offset variance detected at call %d: expected %d, got %d", i, expectedBatch, pos.Offset)
}
}
// Verify the offset can be consistently extracted
expectedOffset := subscription.CurrentOffset
for i, pos := range positions {
if extractedOffset := pos.GetOffset(); extractedOffset != expectedOffset {
t.Errorf("Extracted offset variance at call %d: expected %d, got %d", i, expectedOffset, extractedOffset)
}
}
}
func TestPartitionIdentityConsistency(t *testing.T) {
// Test that partition identity is preserved from request to avoid breaking offset manager keys
// Create a mock init message with specific partition info
partition := &schema_pb.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: 1234567890123456789, // Fixed timestamp
}
initMessage := &mq_pb.SubscribeMessageRequest_InitMessage{
ConsumerGroup: "test-group",
ConsumerId: "test-consumer",
PartitionOffset: &schema_pb.PartitionOffset{
Partition: partition,
},
}
// Simulate the partition creation logic from SubscribeWithOffset
p := topic.Partition{
RingSize: initMessage.PartitionOffset.Partition.RingSize,
RangeStart: initMessage.PartitionOffset.Partition.RangeStart,
RangeStop: initMessage.PartitionOffset.Partition.RangeStop,
UnixTimeNs: initMessage.PartitionOffset.Partition.UnixTimeNs,
}
// Verify that the partition preserves the original UnixTimeNs
if p.UnixTimeNs != partition.UnixTimeNs {
t.Errorf("Partition UnixTimeNs not preserved: expected %d, got %d",
partition.UnixTimeNs, p.UnixTimeNs)
}
// Verify partition key consistency
expectedKey := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
partition.RingSize, partition.RangeStart, partition.RangeStop, partition.UnixTimeNs)
actualKey := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
p.RingSize, p.RangeStart, p.RangeStop, p.UnixTimeNs)
if actualKey != expectedKey {
t.Errorf("Partition key mismatch: expected %s, got %s", expectedKey, actualKey)
}
}
func TestBrokerOffsetManager_GetSubscription_Fixed(t *testing.T) {
// Test that GetSubscription now works correctly after the fix
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
// Create test topic and partition
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Test getting non-existent subscription
_, err := offsetManager.GetSubscription("non-existent")
if err == nil {
t.Error("Expected error for non-existent subscription")
}
// Create a subscription
subscriptionID := "test-subscription-fixed"
subscription, err := offsetManager.CreateSubscription(
subscriptionID,
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription: %v", err)
}
// Test getting existing subscription (this should now work)
retrievedSub, err := offsetManager.GetSubscription(subscriptionID)
if err != nil {
t.Fatalf("GetSubscription failed after fix: %v", err)
}
if retrievedSub.ID != subscription.ID {
t.Errorf("Expected subscription ID %s, got %s", subscription.ID, retrievedSub.ID)
}
if retrievedSub.OffsetType != subscription.OffsetType {
t.Errorf("Expected offset type %v, got %v", subscription.OffsetType, retrievedSub.OffsetType)
}
}
func TestBrokerOffsetManager_ListActiveSubscriptions_Fixed(t *testing.T) {
// Test that ListActiveSubscriptions now works correctly after the fix
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
// Create test topic and partition
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Initially should have no subscriptions
subscriptions, err := offsetManager.ListActiveSubscriptions()
if err != nil {
t.Fatalf("ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptions) != 0 {
t.Errorf("Expected 0 subscriptions, got %d", len(subscriptions))
}
// Create multiple subscriptions (use RESET types to avoid HWM validation issues)
subscriptionIDs := []string{"sub-fixed-1", "sub-fixed-2", "sub-fixed-3"}
offsetTypes := []schema_pb.OffsetType{
schema_pb.OffsetType_RESET_TO_EARLIEST,
schema_pb.OffsetType_RESET_TO_LATEST,
schema_pb.OffsetType_RESET_TO_EARLIEST, // Changed from EXACT_OFFSET
}
for i, subID := range subscriptionIDs {
_, err := offsetManager.CreateSubscription(
subID,
testTopic,
testPartition,
offsetTypes[i],
0, // Use 0 for all to avoid validation issues
)
if err != nil {
t.Fatalf("Failed to create subscription %s: %v", subID, err)
}
}
// List all subscriptions (this should now work)
subscriptions, err = offsetManager.ListActiveSubscriptions()
if err != nil {
t.Fatalf("ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptions) != len(subscriptionIDs) {
t.Errorf("Expected %d subscriptions, got %d", len(subscriptionIDs), len(subscriptions))
}
// Verify all subscriptions are active
for _, sub := range subscriptions {
if !sub.IsActive {
t.Errorf("Subscription %s should be active", sub.ID)
}
}
}
func TestMessageQueueBroker_ListActiveSubscriptions_Fixed(t *testing.T) {
// Test that the broker-level ListActiveSubscriptions now works correctly
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
broker := &MessageQueueBroker{
offsetManager: offsetManager,
}
// Create test topic and partition
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Initially should have no subscriptions
subscriptionInfos, err := broker.ListActiveSubscriptions()
if err != nil {
t.Fatalf("Broker ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptionInfos) != 0 {
t.Errorf("Expected 0 subscription infos, got %d", len(subscriptionInfos))
}
// Create subscriptions with different offset types (use RESET types to avoid HWM validation issues)
testCases := []struct {
id string
offsetType schema_pb.OffsetType
startOffset int64
}{
{"broker-earliest-sub", schema_pb.OffsetType_RESET_TO_EARLIEST, 0},
{"broker-latest-sub", schema_pb.OffsetType_RESET_TO_LATEST, 0},
{"broker-reset-sub", schema_pb.OffsetType_RESET_TO_EARLIEST, 0}, // Changed from EXACT_OFFSET
}
for _, tc := range testCases {
_, err := broker.offsetManager.CreateSubscription(
tc.id,
testTopic,
testPartition,
tc.offsetType,
tc.startOffset,
)
if err != nil {
t.Fatalf("Failed to create subscription %s: %v", tc.id, err)
}
}
// List subscription infos (this should now work)
subscriptionInfos, err = broker.ListActiveSubscriptions()
if err != nil {
t.Fatalf("Broker ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptionInfos) != len(testCases) {
t.Errorf("Expected %d subscription infos, got %d", len(testCases), len(subscriptionInfos))
}
// Verify subscription info structure
for _, info := range subscriptionInfos {
// Check required fields
requiredFields := []string{
"subscription_id", "start_offset", "current_offset",
"offset_type", "is_active", "lag", "at_end",
}
for _, field := range requiredFields {
if _, ok := info[field]; !ok {
t.Errorf("Missing field %s in subscription info", field)
}
}
// Verify is_active is true
if isActive, ok := info["is_active"].(bool); !ok || !isActive {
t.Errorf("Expected is_active to be true, got %v", info["is_active"])
}
}
}
func TestSingleWriterPerPartitionCorrectness(t *testing.T) {
// Test that demonstrates correctness under single-writer-per-partition model
// Simulate two brokers with separate offset managers but same partition
storage1 := NewInMemoryOffsetStorageForTesting()
storage2 := NewInMemoryOffsetStorageForTesting()
offsetManager1 := NewBrokerOffsetManagerWithStorage(storage1)
offsetManager2 := NewBrokerOffsetManagerWithStorage(storage2)
broker1 := &MessageQueueBroker{offsetManager: offsetManager1}
broker2 := &MessageQueueBroker{offsetManager: offsetManager2}
// Same partition identity (this is key for correctness)
fixedTimestamp := time.Now().UnixNano()
testTopic := topic.Topic{Namespace: "test", Name: "shared-topic"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: fixedTimestamp, // Same timestamp = same partition identity
}
// Broker 1 is the leader for this partition - assigns offsets
baseOffset, lastOffset, err := broker1.offsetManager.AssignBatchOffsets(testTopic, testPartition, 10)
if err != nil {
t.Fatalf("Failed to assign offsets on broker1: %v", err)
}
if baseOffset != 0 || lastOffset != 9 {
t.Errorf("Expected offsets 0-9, got %d-%d", baseOffset, lastOffset)
}
// Get HWM from leader
hwm1, err := broker1.offsetManager.GetHighWaterMark(testTopic, testPartition)
if err != nil {
t.Fatalf("Failed to get HWM from broker1: %v", err)
}
if hwm1 != 10 {
t.Errorf("Expected HWM 10 on leader, got %d", hwm1)
}
// Broker 2 is a follower - should have HWM 0 (no local assignments)
hwm2, err := broker2.offsetManager.GetHighWaterMark(testTopic, testPartition)
if err != nil {
t.Fatalf("Failed to get HWM from broker2: %v", err)
}
if hwm2 != 0 {
t.Errorf("Expected HWM 0 on follower, got %d", hwm2)
}
// Create subscription on leader (where offsets were assigned)
subscription1, err := broker1.offsetManager.CreateSubscription(
"leader-subscription",
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription on leader: %v", err)
}
// Verify subscription can see the correct HWM
lag1, err := subscription1.GetLag()
if err != nil {
t.Fatalf("Failed to get lag on leader subscription: %v", err)
}
if lag1 != 10 {
t.Errorf("Expected lag 10 on leader subscription, got %d", lag1)
}
// Create subscription on follower (should have different lag due to local HWM)
subscription2, err := broker2.offsetManager.CreateSubscription(
"follower-subscription",
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription on follower: %v", err)
}
lag2, err := subscription2.GetLag()
if err != nil {
t.Fatalf("Failed to get lag on follower subscription: %v", err)
}
if lag2 != 0 {
t.Errorf("Expected lag 0 on follower subscription (no local data), got %d", lag2)
}
}
func TestEndToEndWorkflowAfterFixes(t *testing.T) {
// Test the complete workflow with all fixes applied
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
broker := &MessageQueueBroker{
offsetManager: offsetManager,
}
// Create test topic and partition with fixed timestamp
fixedTimestamp := time.Now().UnixNano()
testTopic := topic.Topic{Namespace: "test", Name: "e2e-topic"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: fixedTimestamp,
}
subscriptionID := "e2e-test-sub"
// 1. Create subscription (use RESET_TO_EARLIEST to avoid HWM validation issues)
subscription, err := broker.offsetManager.CreateSubscription(
subscriptionID,
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription: %v", err)
}
// 2. Verify GetSubscription works
retrievedSub, err := broker.offsetManager.GetSubscription(subscriptionID)
if err != nil {
t.Fatalf("GetSubscription failed: %v", err)
}
if retrievedSub.ID != subscription.ID {
t.Errorf("GetSubscription returned wrong subscription: expected %s, got %s",
subscription.ID, retrievedSub.ID)
}
// 3. Verify it appears in active list
activeList, err := broker.ListActiveSubscriptions()
if err != nil {
t.Fatalf("Failed to list active subscriptions: %v", err)
}
found := false
for _, info := range activeList {
if info["subscription_id"] == subscriptionID {
found = true
break
}
}
if !found {
t.Error("New subscription not found in active list")
}
// 4. Get subscription info
info, err := broker.GetSubscriptionInfo(subscriptionID)
if err != nil {
t.Fatalf("Failed to get subscription info: %v", err)
}
if info["subscription_id"] != subscriptionID {
t.Errorf("Wrong subscription ID in info: expected %s, got %v", subscriptionID, info["subscription_id"])
}
// 5. Assign some offsets to create data for seeking
_, _, err = broker.offsetManager.AssignBatchOffsets(testTopic, testPartition, 50)
if err != nil {
t.Fatalf("Failed to assign offsets: %v", err)
}
// 6. Seek subscription
newOffset := int64(42)
err = broker.SeekSubscription(subscriptionID, newOffset)
if err != nil {
t.Fatalf("Failed to seek subscription: %v", err)
}
// 7. Verify seek worked
updatedInfo, err := broker.GetSubscriptionInfo(subscriptionID)
if err != nil {
t.Fatalf("Failed to get updated subscription info: %v", err)
}
if updatedInfo["current_offset"] != newOffset {
t.Errorf("Seek didn't work: expected offset %d, got %v", newOffset, updatedInfo["current_offset"])
}
// 8. Test offset to timestamp conversion with fixed partition identity
updatedSub, err := broker.offsetManager.GetSubscription(subscriptionID)
if err != nil {
t.Fatalf("Failed to get updated subscription: %v", err)
}
position, err := broker.convertOffsetToMessagePosition(updatedSub)
if err != nil {
t.Fatalf("Failed to convert offset to position: %v", err)
}
if position.Time.IsZero() {
t.Error("Expected non-zero timestamp from conversion")
}
// 9. Verify partition identity consistency throughout
partitionKey1 := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
testPartition.RingSize, testPartition.RangeStart, testPartition.RangeStop, testPartition.UnixTimeNs)
partitionKey2 := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
testPartition.RingSize, testPartition.RangeStart, testPartition.RangeStop, fixedTimestamp)
if partitionKey1 != partitionKey2 {
t.Errorf("Partition key inconsistency: %s != %s", partitionKey1, partitionKey2)
}
}
+17 -126
View File
@@ -1,107 +1,33 @@
package broker
import (
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// OffsetAssignmentFunc is a function type for assigning offsets to messages
type OffsetAssignmentFunc func() (int64, error)
// AddToBufferWithOffset adds a message to the log buffer with offset assignment
// TODO: This is a temporary solution until LogBuffer can be modified to accept offset assignment
// ASSUMPTION: This function will be integrated into LogBuffer.AddToBuffer in the future
func (b *MessageQueueBroker) AddToBufferWithOffset(
logBuffer *log_buffer.LogBuffer,
message *mq_pb.DataMessage,
t topic.Topic,
p topic.Partition,
) error {
// Assign offset for this message
offset, err := b.offsetManager.AssignOffset(t, p)
if err != nil {
return err
}
// PERFORMANCE OPTIMIZATION: Pre-process expensive operations OUTSIDE the lock
processingTsNs := message.TsNs
if processingTsNs == 0 {
processingTsNs = time.Now().UnixNano()
}
// Create LogEntry with assigned offset
logEntry := &filer_pb.LogEntry{
TsNs: processingTsNs,
PartitionKeyHash: util.HashToInt32(message.Key),
Data: message.Value,
Key: message.Key,
Offset: offset, // Add the assigned offset
}
// Use the existing LogBuffer infrastructure for the rest
// TODO: This is a workaround - ideally LogBuffer should handle offset assignment
// For now, we'll add the message with the pre-assigned offset
return b.addLogEntryToBuffer(logBuffer, logEntry)
}
// addLogEntryToBuffer adds a pre-constructed LogEntry to the buffer
// This is a helper function that directly uses LogBuffer.AddLogEntryToBuffer
func (b *MessageQueueBroker) addLogEntryToBuffer(
logBuffer *log_buffer.LogBuffer,
logEntry *filer_pb.LogEntry,
) error {
// Use the AddLogEntryToBuffer method to preserve offset information
// This ensures the offset is maintained throughout the entire data flow
return logBuffer.AddLogEntryToBuffer(logEntry)
}
// GetPartitionOffsetInfoInternal returns offset information for a partition (internal method)
// GetPartitionOffsetInfoInternal reports offsets from the loaded partition's buffer, which
// assigns them and tracks the earliest one retained, or from the ranges stored on disk
// when this broker has not loaded it.
func (b *MessageQueueBroker) GetPartitionOffsetInfoInternal(t topic.Topic, p topic.Partition) (*PartitionOffsetInfo, error) {
info, err := b.offsetManager.GetPartitionOffsetInfo(t, p)
if err != nil {
return nil, err
}
// CRITICAL FIX: Also check LogBuffer for in-memory messages
// The offset manager only tracks assigned offsets from persistent storage
// But the LogBuffer contains recently written messages that haven't been flushed yet
localPartition := b.localTopicManager.GetLocalPartition(t, p)
logBufferHWM := int64(-1)
if localPartition != nil && localPartition.LogBuffer != nil {
logBufferHWM = localPartition.LogBuffer.GetOffset()
var earliestOffset, highWaterMark, activeSubscriptions int64
if localPartition := b.localTopicManager.GetLocalPartition(t, p); localPartition != nil {
earliestOffset = localPartition.LogBuffer.GetLogStartOffset()
highWaterMark = localPartition.LogBuffer.GetOffset()
activeSubscriptions = int64(localPartition.Subscribers.Size())
} else {
r, err := b.getOffsetRangeFromChunkMetadata(t, p)
if err != nil {
return nil, err
}
earliestOffset, highWaterMark = r.Bounds()
}
// Use the MAX of offset manager HWM and LogBuffer HWM
// This ensures we report the correct HWM even if data hasn't been flushed to disk yet
// IMPORTANT: Use >= not > because when they're equal, we still want the correct value
highWaterMark := info.HighWaterMark
if logBufferHWM >= 0 && logBufferHWM > highWaterMark {
highWaterMark = logBufferHWM
} else if logBufferHWM >= 0 && logBufferHWM == highWaterMark && highWaterMark > 0 {
} else if logBufferHWM >= 0 {
}
// Latest offset is HWM - 1 (last assigned offset)
latestOffset := highWaterMark - 1
if highWaterMark == 0 {
latestOffset = -1 // No records
}
// Convert to broker-specific format
return &PartitionOffsetInfo{
Topic: t,
Partition: p,
EarliestOffset: info.EarliestOffset,
LatestOffset: latestOffset,
EarliestOffset: earliestOffset,
LatestOffset: highWaterMark - 1,
HighWaterMark: highWaterMark,
RecordCount: highWaterMark, // HWM equals record count (offsets 0 to HWM-1)
ActiveSubscriptions: info.ActiveSubscriptions,
RecordCount: highWaterMark - earliestOffset,
ActiveSubscriptions: activeSubscriptions,
}, nil
}
@@ -115,38 +41,3 @@ type PartitionOffsetInfo struct {
RecordCount int64
ActiveSubscriptions int64
}
// CreateOffsetSubscription creates an offset-based subscription through the broker
func (b *MessageQueueBroker) CreateOffsetSubscription(
subscriptionID string,
t topic.Topic,
p topic.Partition,
offsetType string, // Will be converted to schema_pb.OffsetType
startOffset int64,
) error {
// TODO: Convert string offsetType to schema_pb.OffsetType
// ASSUMPTION: For now using RESET_TO_EARLIEST as default
// This should be properly mapped based on the offsetType parameter
_, err := b.offsetManager.CreateSubscription(
subscriptionID,
t,
p,
0, // schema_pb.OffsetType_RESET_TO_EARLIEST
startOffset,
)
return err
}
// GetOffsetMetrics returns offset metrics for monitoring
func (b *MessageQueueBroker) GetOffsetMetrics() map[string]interface{} {
metrics := b.offsetManager.GetOffsetMetrics()
return map[string]interface{}{
"partition_count": metrics.PartitionCount,
"total_offsets": metrics.TotalOffsets,
"active_subscriptions": metrics.ActiveSubscriptions,
"average_latency": metrics.AverageLatency,
}
}
@@ -0,0 +1,137 @@
package broker
import (
"encoding/binary"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// A loaded partition starts its log at the earliest offset still stored, so a
// read below it is out of range rather than answered from a later file.
func TestLoadedPartitionStartsAtTheEarliestStoredOffset(t *testing.T) {
f, b := newFencingFiler(t)
b.localTopicManager = topic.NewLocalTopicManager()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start, 100, 199, start)
f.putLogFile(start.Add(time.Minute), 200, 299, start.Add(time.Minute))
lp, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
if err != nil {
t.Fatal(err)
}
defer lp.LogBuffer.ShutdownLogBuffer()
b.localTopicManager.AddLocalPartition(fenceTestTopic, lp)
info, err := b.GetPartitionOffsetInfoInternal(fenceTestTopic, fenceTestPartition)
if err != nil {
t.Fatal(err)
}
if info.EarliestOffset != 100 || info.HighWaterMark != 300 || info.RecordCount != 200 {
t.Fatalf("info = %+v, want earliest 100, hwm 300, count 200", info)
}
if _, _, _, _, err := lp.LogBuffer.ReadMessagesAtOffset(50, 10, 1<<20); !errors.Is(err, log_buffer.ErrOffsetOutOfRange) {
t.Fatalf("read below the earliest stored offset: %v", err)
}
}
// A leader whose clock is behind the stored messages stamps new ones after them, so
// a timestamp resume from the last stored message still reads what it publishes. An
// older file recording no message times is bounded by when it was written.
func TestLoadedPartitionStampsAfterTheNewestStoredMessage(t *testing.T) {
for _, recordsTimes := range []bool{true, false} {
f, b := newFencingFiler(t)
// the flush on shutdown notifies the partition through the topic manager
b.localTopicManager = topic.NewLocalTopicManager()
stored := time.Now().Add(time.Hour)
name := f.putLogFile(stored.Truncate(time.Second), 0, 9, stored)
if recordsTimes {
entry := f.entry(topic.PartitionDir(fenceTestTopic, fenceTestPartition) + "/" + name)
f.mu.Lock()
entry.Extended[mq.ExtendedAttrTimestampMin] = binary.BigEndian.AppendUint64(nil, uint64(stored.Truncate(time.Second).UnixNano()))
entry.Extended[mq.ExtendedAttrTimestampMax] = binary.BigEndian.AppendUint64(nil, uint64(stored.UnixNano()))
f.mu.Unlock()
}
lp, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
if err != nil {
t.Fatal(err)
}
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("new"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
var got []string
if _, _, err := lp.LogBuffer.LoopProcessLogData("test", log_buffer.NewMessagePosition(stored.UnixNano(), -2), 0, func() bool { return false }, func(logEntry *filer_pb.LogEntry) (bool, error) {
got = append(got, string(logEntry.Data))
return true, nil
}); err != nil {
t.Fatal(err)
}
lp.Shutdown()
if len(got) != 1 || got[0] != "new" {
t.Errorf("file records message times %v: resumed after the stored messages, read %q, want the new message", recordsTimes, got)
}
}
}
// A loaded partition's buffer assigns offsets, so it is the high water mark.
func TestPartitionOffsetInfoFromLoadedBuffer(t *testing.T) {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
tp := topic.NewTopic("test", "t")
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
lp := topic.NewLocalPartition(partition, 3600, nil, nil)
defer lp.Shutdown()
b.localTopicManager.AddLocalPartition(tp, lp)
for i := 0; i < 3; i++ {
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
}
info, err := b.GetPartitionOffsetInfoInternal(tp, partition)
if err != nil {
t.Fatal(err)
}
if info.HighWaterMark != 3 || info.LatestOffset != 2 || info.RecordCount != 3 {
t.Fatalf("info = %+v, want hwm 3, latest 2, count 3", info)
}
}
// A subscriber or fetch naming a stale generation of an assigned range loads
// the assigned generation and continues its stored offsets.
func TestStaleGenerationRequestLoadsTheAssignedPartition(t *testing.T) {
tp := topic.NewTopic("test", "t")
assigned := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
f, b := newFencingFiler(t)
offsetMax := make([]byte, 8)
binary.BigEndian.PutUint64(offsetMax, 41)
f.entries[topic.PartitionDir(tp, assigned)+"/segment"] = &filer_pb.Entry{Name: "segment", Extended: map[string][]byte{mq.ExtendedAttrOffsetMax: offsetMax}}
b.localTopicManager = topic.NewLocalTopicManager()
conf := &mq_pb.ConfigureTopicResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
LeaderBroker: string(b.option.BrokerAddress()),
Partition: &schema_pb.Partition{RingSize: assigned.RingSize, RangeStart: assigned.RangeStart, RangeStop: assigned.RangeStop, UnixTimeNs: assigned.UnixTimeNs},
}}}
stale := assigned
stale.UnixTimeNs = 0
lp, generated, err := b.doGetOrGenLocalPartition(tp, stale, conf)
if err != nil || !generated {
t.Fatalf("generated=%v err=%v", generated, err)
}
defer lp.Shutdown()
if lp.Partition.UnixTimeNs != assigned.UnixTimeNs {
t.Errorf("loaded generation %d, assigned %d", lp.Partition.UnixTimeNs, assigned.UnixTimeNs)
}
if next := lp.LogBuffer.GetOffset(); next != 42 {
t.Errorf("next offset %d, want 42 after the stored offsets", next)
}
}
+3 -152
View File
@@ -2,173 +2,24 @@ package broker
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// BrokerOffsetManager manages offset assignment for all partitions in a broker
// BrokerOffsetManager keeps consumer-group positions. Publish offsets are
// assigned by each partition's log buffer.
type BrokerOffsetManager struct {
mu sync.RWMutex
offsetIntegration *offset.SMQOffsetIntegration
storage offset.OffsetStorage
consumerGroupStorage offset.ConsumerGroupOffsetStorage
}
// NewBrokerOffsetManagerWithFilerAccessor creates a new broker offset manager using existing filer client accessor
func NewBrokerOffsetManagerWithFilerAccessor(filerAccessor *filer_client.FilerClientAccessor) *BrokerOffsetManager {
// Create filer storage using the accessor directly - no duplicate connection management
filerStorage := offset.NewFilerOffsetStorageWithAccessor(filerAccessor)
// Create consumer group storage using the accessor directly
consumerGroupStorage := offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filerAccessor)
return &BrokerOffsetManager{
offsetIntegration: offset.NewSMQOffsetIntegration(filerStorage),
storage: filerStorage,
consumerGroupStorage: consumerGroupStorage,
consumerGroupStorage: offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filerAccessor),
}
}
// AssignOffset assigns the next offset for a partition
func (bom *BrokerOffsetManager) AssignOffset(t topic.Topic, p topic.Partition) (int64, error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer's offset assigner to ensure consistency with subscriptions
result := bom.offsetIntegration.AssignSingleOffset(t.Namespace, t.Name, partition)
if result.Error != nil {
return 0, result.Error
}
return result.Assignment.Offset, nil
}
// AssignBatchOffsets assigns a batch of offsets for a partition
func (bom *BrokerOffsetManager) AssignBatchOffsets(t topic.Topic, p topic.Partition, count int64) (baseOffset, lastOffset int64, err error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer's offset assigner to ensure consistency with subscriptions
result := bom.offsetIntegration.AssignBatchOffsets(t.Namespace, t.Name, partition, count)
if result.Error != nil {
return 0, 0, result.Error
}
return result.Batch.BaseOffset, result.Batch.LastOffset, nil
}
// GetHighWaterMark returns the high water mark for a partition
func (bom *BrokerOffsetManager) GetHighWaterMark(t topic.Topic, p topic.Partition) (int64, error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer's offset assigner to ensure consistency with subscriptions
return bom.offsetIntegration.GetHighWaterMark(t.Namespace, t.Name, partition)
}
// CreateSubscription creates an offset-based subscription
func (bom *BrokerOffsetManager) CreateSubscription(
subscriptionID string,
t topic.Topic,
p topic.Partition,
offsetType schema_pb.OffsetType,
startOffset int64,
) (*offset.OffsetSubscription, error) {
partition := topicPartitionToSchemaPartition(t, p)
return bom.offsetIntegration.CreateSubscription(subscriptionID, t.Namespace, t.Name, partition, offsetType, startOffset)
}
// GetSubscription retrieves an existing subscription
func (bom *BrokerOffsetManager) GetSubscription(subscriptionID string) (*offset.OffsetSubscription, error) {
return bom.offsetIntegration.GetSubscription(subscriptionID)
}
// CloseSubscription closes a subscription
func (bom *BrokerOffsetManager) CloseSubscription(subscriptionID string) error {
return bom.offsetIntegration.CloseSubscription(subscriptionID)
}
// ListActiveSubscriptions returns all active subscriptions
func (bom *BrokerOffsetManager) ListActiveSubscriptions() ([]*offset.OffsetSubscription, error) {
return bom.offsetIntegration.ListActiveSubscriptions()
}
// GetPartitionOffsetInfo returns comprehensive offset information for a partition
func (bom *BrokerOffsetManager) GetPartitionOffsetInfo(t topic.Topic, p topic.Partition) (*offset.PartitionOffsetInfo, error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer to ensure consistency with subscriptions
return bom.offsetIntegration.GetPartitionOffsetInfo(t.Namespace, t.Name, partition)
}
// topicPartitionToSchemaPartition converts topic.Topic and topic.Partition to schema_pb.Partition
func topicPartitionToSchemaPartition(t topic.Topic, p topic.Partition) *schema_pb.Partition {
return &schema_pb.Partition{
RingSize: int32(p.RingSize),
RangeStart: int32(p.RangeStart),
RangeStop: int32(p.RangeStop),
UnixTimeNs: p.UnixTimeNs,
}
}
// OffsetAssignmentResult contains the result of offset assignment for logging/metrics
type OffsetAssignmentResult struct {
Topic topic.Topic
Partition topic.Partition
BaseOffset int64
LastOffset int64
Count int64
Timestamp int64
Error error
}
// AssignOffsetsWithResult assigns offsets and returns detailed result for logging/metrics
func (bom *BrokerOffsetManager) AssignOffsetsWithResult(t topic.Topic, p topic.Partition, count int64) *OffsetAssignmentResult {
baseOffset, lastOffset, err := bom.AssignBatchOffsets(t, p, count)
result := &OffsetAssignmentResult{
Topic: t,
Partition: p,
Count: count,
Error: err,
}
if err == nil {
result.BaseOffset = baseOffset
result.LastOffset = lastOffset
result.Timestamp = time.Now().UnixNano()
}
return result
}
// GetOffsetMetrics returns metrics about offset usage across all partitions
func (bom *BrokerOffsetManager) GetOffsetMetrics() *offset.OffsetMetrics {
// Use the integration layer to ensure consistency with subscriptions
return bom.offsetIntegration.GetOffsetMetrics()
}
// Shutdown gracefully shuts down the offset manager
func (bom *BrokerOffsetManager) Shutdown() {
bom.mu.Lock()
defer bom.mu.Unlock()
// Reset the underlying storage to ensure clean restart behavior
// This is important for testing where we want offsets to start from 0 after shutdown
if bom.storage != nil {
if resettable, ok := bom.storage.(interface{ Reset() error }); ok {
resettable.Reset()
}
}
// Reset the integration layer to ensure clean restart behavior
bom.offsetIntegration.Reset()
}
// Consumer Group Offset Management
// SaveConsumerGroupOffset saves the committed offset for a consumer group
func (bom *BrokerOffsetManager) SaveConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string, offset int64) error {
if bom.consumerGroupStorage == nil {
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff. Show more