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
Tiago PosseandClaude Opus 5.5 0964dd7713 filer: put a finished download on the budget's idle list before waking readers (#13147)
A download closed done and then moved its reservation to the budget's
idle list, so a reader woken by done could ask the budget for room
before the chunk it had just read was evictable.
TestReaderCacheBudgetLendsScratchToHedges failed this way about 1 in
1000 runs under -race ("hedge buffers did not evict the idle chunks").
The download now completes in the budget first.

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:27:33 -08:00
guagucai 53206f16be fix: reject NaN minimum free-space percentages (#13153)
Signed-off-by: guagucai <guagucai@outlook.com>
2026-11-30 13:25:40 -08:00
Song Bian 0025e7177f fix(filer): preserve chunk ordering on 32-bit systems (#13175) 2026-11-30 13:24:21 -08:00
1a2be918bf s3api: reset the circuit breaker when its config is deleted (#13148)
* s3api: reset the circuit breaker when its config is deleted

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

Without the flag the mount behaves as before.

* mount: resubscribe metadata with a replaced filer token

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

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

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

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

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

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

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

* mount: review fixes for the filer token file

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

* mount: review fixes for the mutation stream handover

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

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

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

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

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

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

* mount: drop kernel listings after a subscription gap too

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:02:28 -08:00
05d9242f3c s3api: answer NoSuchBucket to a denied authenticated request on a missing bucket (#13139)
* s3api: optionally answer NoSuchBucket to a denied signed request on a missing bucket

## Problem

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

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

## Fix

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

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

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

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

With the option off nothing changes.

## Tests

`weed/s3api/auth_no_such_bucket_test.go`:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* s3api: fold the NoSuchBucket answer into refineDenialForBucketName

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:00:01 -08:00
Chris LuandClaude Opus 5.5 2b0bff0135 filer.sync: warn when the source metadata log no longer covers the sync (#13143)
* filer.sync: warn when the source metadata log no longer covers the sync

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

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

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

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

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

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

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

---------

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

## Problem

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

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

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

## Fix

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

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

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

## Tests

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:53:24 -08:00
dependabot[bot]andChris Lu faffb0d291 build(deps): bump github.com/jackc/pgx/v5 from 5.10.0 to 5.13.0 (#13164)
Bumps [github.com/jackc/pgx/v5](https://github.com/jackc/pgx) from 5.10.0 to 5.13.0.
- [Release notes](https://github.com/jackc/pgx/releases)
- [Changelog](https://github.com/jackc/pgx/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jackc/pgx/compare/v5.10.0...v5.13.0)

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:15 -08:00
dependabot[bot] a07f774e6f build(deps): bump github/codeql-action from 4.39.4 to 4.39.5 (#13170)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.4 to 4.39.5.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v4.39.4...v4.39.5)

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

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

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

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

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

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

Changes:

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

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

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

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

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

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

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

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

* iceberg: shorten the metadata cache comments

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:50:59 -08:00
a2d6b07d3c filer: refuse a non-recursive delete of a bucket that has children (#13122)
* filer: refuse a non-recursive delete of a bucket that has children

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

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

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

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

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

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

---------

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

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

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

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

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

* iceberg: a create may name a fresh location

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

* iceberg maintenance: raise the descriptor version with row_group_size_mb

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:33:32 -08:00
4cda7ca0a4 iceberg: a transaction's rollback never overwrites a later write (#13162)
* iceberg: a transaction's rollback never overwrites a later write

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

* lance: a register needs _versions to be a directory

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

## Problem

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

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

## Fix

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

## Tests

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

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

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

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

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

---------

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

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

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

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

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

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

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

Tests:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:51:16 -08:00
ec2d96888d pb: use the slot allocator as gRPC's buffer pool (#13136)
* pb: power-of-two gRPC buffer tiers up to 1 MB

## Problem

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

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

## Fix

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

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

## Tests

`weed/pb/grpc_buffer_pool_test.go`:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:50:31 -08:00
Yip LeoandClaude Opus 5.5 c3f7f24684 mount: wake an upload parked on a read when the read ends (#13123)
* mount: wake an upload parked on a read when the read ends

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

Review follow-ups.

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

* mount: keep the resolveCacheDirs doc comment on resolveCacheDirs

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

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

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

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

---------

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

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

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

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

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

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

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

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

Review of the previous commit found two gaps.

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:41:22 -08:00
Chris LuandClaude Opus 5.5 d4a21cef59 weed: flush buffered log lines when a command exits (#13151)
exit() ends the process with os.Exit, which skips deferred calls, and
glog writes its files only every 30s. A short-lived command such as a
piped weed shell session lost every log line it buffered, including the
daily_run summary of s3.lifecycle.run-shard.

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

## Problem

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

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

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

## Fix

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

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

## Tests

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

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

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

* iceberg: refuse commits to catalog-only tables

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

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

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

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

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

* iceberg: apply the metadata size limit to inline content

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

---------

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

## Problem

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

## Fix

Those three refusals now carry a message:

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

Status and code are unchanged (403 AccessDenied).

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

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

## Tests

`weed/s3api/table_bucket_layout_message_test.go`:

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:33:15 -08:00
bf14326c3c iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files (#13131)
* iceberg maintenance: recognise deletion vectors whose format is written in lowercase

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

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

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

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

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

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

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

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

Changes:

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

Tests (`deletion_vector_test.go`):

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

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

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

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

* iceberg detection: key the cached compaction plan on apply_deletes

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

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

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

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

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

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

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

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

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

* iceberg compact: compare the delete ratio in whole rows

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:22:30 -08:00
347f1cf705 deps: bump parquet-go to v0.33.0 (#13130)
* deps: bump parquet-go to v0.33.0

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

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

Changes that follow from the bump:

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

Tests:

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:18:24 -08:00
5017a07475 iceberg maintenance: whole-pass tests of equality deletes on a partitioned table (#13132)
* iceberg maintenance: whole-pass tests of equality deletes on a partitioned table

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:17:18 -08:00
Chris LuandClaude Opus 5.5 2acd49ba27 s3api: end a vended table session no later than the caller's credential (#13161)
* s3api: record the verified credential's expiry in the request context

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

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

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

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

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

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

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

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

---------

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

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

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

* master: carry StartedAt through raft apply and snapshots

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

* master: leader records StartedAt once per cluster

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

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

* test: use current StartedAt values

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

* topology: never lower the mirrored max volume id

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

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

* topology: let the latest applied StartedAt win

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

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

---------

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

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

* abstract_sql: read KV keys with one query

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

* redis: read KV keys in one pipeline

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

* etcd: read KV keys in read-only transactions

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

* mongodb: read KV keys with one query

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

* cassandra: read KV keys concurrently

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

* hbase: read KV keys concurrently

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

* elastic: read KV keys concurrently

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

* arangodb: read KV keys with one request

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

* foundationdb: read KV keys in one transaction

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

* ydb: read KV keys with one query

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

* tarantool: send KV reads before waiting for any

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

* filer: every filer store reads KV keys in batches

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:10:49 -08:00
463 changed files with 33234 additions and 7750 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ runs:
using: composite
steps:
- name: Install cosign
uses: sigstore/cosign-installer@v4.1.3
uses: sigstore/cosign-installer@v4.1.4
- name: Sign
shell: bash
+3 -3
View File
@@ -33,7 +33,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4.39.4
uses: github/codeql-action/init@v4.39.5
# Override language selection by uncommenting this and choosing your languages
with:
languages: go
@@ -41,7 +41,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v4.39.4
uses: github/codeql-action/autobuild@v4.39.5
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -55,4 +55,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4.39.4
uses: github/codeql-action/analyze@v4.39.5
+1 -1
View File
@@ -434,7 +434,7 @@ jobs:
output: trivy-results.sarif
exit-code: '0'
- name: Upload Trivy scan results to GitHub Security
uses: github/codeql-action/upload-sarif@v4.39.4
uses: github/codeql-action/upload-sarif@v4.39.5
if: always()
with:
sarif_file: trivy-results.sarif
@@ -515,7 +515,7 @@ jobs:
- name: Upload Trivy scan results to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v4.39.4
uses: github/codeql-action/upload-sarif@v4.39.5
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
+1 -1
View File
@@ -169,7 +169,7 @@ jobs:
sed -i "s/assert prefixes == \['foo%2B1\/', 'foo\/', 'quux%20ab\/'\]/assert prefixes == \['foo\/', 'foo%2B1\/', 'quux%20ab\/'\]/" s3-tests/s3tests/functional/test_s3.py
sed -i "/# request PartNumber out of range/,+4{s/assert status == 400/assert status == 416/; s/assert error_code == 'InvalidPart'/assert error_code == 'InvalidPartNumber'/}" s3-tests/s3tests/functional/test_s3.py
- uses: actions/download-artifact@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
@@ -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
+15 -13
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
@@ -21,12 +22,12 @@ require (
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/aws/aws-sdk-go v1.55.8
github.com/aws/aws-sdk-go-v2 v1.48.0
github.com/aws/aws-sdk-go-v2 v1.48.1
github.com/aws/aws-sdk-go-v2/config v1.33.9
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.9
github.com/aws/smithy-go v1.28.10
github.com/bwmarrin/snowflake v0.3.0
github.com/cenkalti/backoff/v4 v4.3.0
github.com/cespare/xxhash/v2 v2.3.0
@@ -52,13 +53,13 @@ require (
github.com/hashicorp/raft v1.8.0
github.com/hashicorp/raft-boltdb/v2 v2.4.2
github.com/hashicorp/vault/api v1.23.0
github.com/jackc/pgx/v5 v5.10.0
github.com/jhump/protoreflect v1.18.1
github.com/jackc/pgx/v5 v5.13.0
github.com/jhump/protoreflect v1.19.0
github.com/jinzhu/copier v0.4.0
github.com/json-iterator/go v1.1.12
github.com/k0kubun/pp v3.0.1+incompatible
github.com/karlseguin/ccache/v2 v2.0.8
github.com/klauspost/compress v1.20.3
github.com/klauspost/compress v1.20.5
github.com/klauspost/reedsolomon v1.14.2
github.com/kurin/blazer v0.5.3
github.com/linkedin/goavro/v2 v2.15.0
@@ -67,7 +68,7 @@ require (
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
github.com/olivere/elastic/v7 v7.0.32
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.32.0
github.com/parquet-go/parquet-go v0.33.0
github.com/peterh/liner v1.2.3
github.com/pierrec/lz4/v4 v4.1.33
github.com/pkg/sftp v1.13.12
@@ -99,6 +100,7 @@ require (
github.com/tikv/client-go/v2 v2.0.7
github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365
github.com/twmb/avro v1.9.0
github.com/twpayne/go-geom v1.6.1
github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43
github.com/valyala/bytebufferpool v1.0.0
github.com/viant/ptrie v1.0.1
@@ -110,7 +112,7 @@ require (
go.etcd.io/etcd/api/v3 v3.7.3
go.etcd.io/etcd/client/pkg/v3 v3.7.4
go.etcd.io/etcd/client/v3 v3.7.3
go.mongodb.org/mongo-driver v1.17.9
go.mongodb.org/mongo-driver v1.17.10
go.uber.org/atomic v1.12.0
go.yaml.in/yaml/v3 v3.0.6
gocloud.dev v0.49.0
@@ -120,7 +122,7 @@ require (
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
golang.org/x/image v0.46.0
golang.org/x/net v0.62.0
golang.org/x/oauth2 v0.37.0
golang.org/x/oauth2 v0.38.0
golang.org/x/sync v0.25.0
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0
@@ -171,7 +173,7 @@ require (
github.com/abbot/go-http-auth v0.4.0 // indirect
github.com/adrg/xdg v0.5.3 // indirect
github.com/anchore/go-lzo v0.1.1 // indirect
github.com/andybalholm/brotli v1.2.8 // indirect
github.com/andybalholm/brotli v1.3.0 // indirect
github.com/andybalholm/cascadia v1.3.4 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/thrift v0.25.0 // indirect
@@ -308,7 +310,7 @@ require (
github.com/internxt/rclone-adapter v0.0.0-20260708165336-dd6561bacfa2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/jaegertracing/jaeger v1.47.0 // indirect
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
@@ -374,9 +376,10 @@ require (
github.com/openzipkin/zipkin-go v0.4.3 // indirect
github.com/oracle/oci-go-sdk/v65 v65.121.0 // indirect
github.com/panjf2000/ants/v2 v2.12.1 // indirect
github.com/parquet-go/bitpack v1.0.0 // indirect
github.com/parquet-go/jsonlite v1.0.0 // indirect
github.com/parquet-go/bitpack v1.1.1 // indirect
github.com/parquet-go/jsonlite v1.5.7 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/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
@@ -434,7 +437,6 @@ require (
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/twmb/murmur3 v1.1.8 // indirect
github.com/twpayne/go-geom v1.6.1 // indirect
github.com/twpayne/go-kml/v3 v3.2.1 // indirect
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
+28 -24
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=
@@ -142,8 +144,8 @@ github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktp
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/anchore/go-lzo v0.1.1 h1:IwL/fvkdtlIrYIXck6WxZ3nb8WjjHziYYmGxlooyOnM=
github.com/anchore/go-lzo v0.1.1/go.mod h1:3kLx0bve2oN1iDwgM1U5zGku1Tfbdb0No5qp1eL1fIk=
github.com/andybalholm/brotli v1.2.8 h1:H9F6r7RNwzSRsx/lytpIYkbjNFMt2yNBwsJ2+0gpx78=
github.com/andybalholm/brotli v1.2.8/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
@@ -171,8 +173,8 @@ github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJ
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
github.com/aws/aws-sdk-go-v2 v1.48.1 h1:j6ro6IvbxUe8BCulc/6uWMrhmx6+i5HNIc1GZEJRT9k=
github.com/aws/aws-sdk-go-v2 v1.48.1/go.mod h1:HP8Jzg1FDurJomtx40YM0eiLoJrwjjZ9X+4BNpy4OXc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
@@ -213,8 +215,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEB
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
@@ -722,10 +724,10 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
github.com/jaegertracing/jaeger v1.47.0/go.mod h1:mHU/OHFML51CijQql4+rLfgPOcIb9MhxOMn+RKQwrJc=
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
@@ -740,8 +742,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/jhump/protoreflect v1.18.1 h1:h4odAaLg9wyn7yHxMF7sSkJ7JfLwK1oy37/1Pi212GE=
github.com/jhump/protoreflect v1.18.1/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
github.com/jhump/protoreflect v1.19.0 h1:YhKbE78JrjfngcCZfZTIV7rQQGndyqll6fXfaqiOEg4=
github.com/jhump/protoreflect v1.19.0/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 h1:Dw1rslK/VotaUGYsv53XVWITr+5RCPXfvvlGrM/+B6w=
github.com/jhump/protoreflect/v2 v2.0.0-beta.1/go.mod h1:D9LBEowZyv8/iSu97FU2zmXG3JxVTmNw21mu63niFzU=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
@@ -782,8 +784,8 @@ github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXw
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4=
github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/reedsolomon v1.14.2 h1:SafJYwpBBQBI6amHUygcjxZjXeN2HpiENHQDwuPWCCQ=
@@ -955,15 +957,17 @@ github.com/orcaman/concurrent-map/v2 v2.0.1 h1:jOJ5Pg2w1oeB6PeDurIYf6k9PQ+aTITr/
github.com/orcaman/concurrent-map/v2 v2.0.1/go.mod h1:9Eq3TG2oBe5FirmYWQfYO5iH1q0Jv47PLaNK++uCdOM=
github.com/panjf2000/ants/v2 v2.12.1 h1:BWvU2wHpyXWxhhNXsGB6JXLCNbshyLd1QxvoAmZnu10=
github.com/panjf2000/ants/v2 v2.12.1/go.mod h1:tSQuaNQ6r6NRhPt+IZVUevvDyFMTs+eS4ztZc52uJTY=
github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxPcQA=
github.com/parquet-go/bitpack v1.0.0/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZdd7VU=
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
github.com/parquet-go/parquet-go v0.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
github.com/parquet-go/bitpack v1.1.1 h1:mygqlCBk/rnvtqqP5Oy7IkIPAxZ3bDM7V4yce/ms6pE=
github.com/parquet-go/bitpack v1.1.1/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.5.7 h1:FxIrc2MBZ9QLpljM1+3F3JuCuug+BWOt8Yx+S4o3bl8=
github.com/parquet-go/jsonlite v1.5.7/go.mod h1:ZIyft0+sSdvgTu2m6RpqxWx/F3UBNtF3ammevxDJcoE=
github.com/parquet-go/parquet-go v0.33.0 h1:iDe13lcW6t0mnZWPqKqWccNa5GdP/L9GNNyzlr8JqNY=
github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMPJ6I+/zmNnsOSh4=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
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=
@@ -1355,8 +1359,8 @@ go.etcd.io/etcd/client/pkg/v3 v3.7.4 h1:633yLMDAQHWqLTRMxUNuZfOy6a4REJPcA3juoMRx
go.etcd.io/etcd/client/pkg/v3 v3.7.4/go.mod h1:I1lMmoiq2SF4Wg0Gru7uXMovS1eEo6wwAxcFPFPk/v0=
go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q=
go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE=
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
go.mongodb.org/mongo-driver v1.17.10 h1:kdAgQvu8TROXZpSkJQd5wzfaNCCrMbpZyKFtQ6qkPCE=
go.mongodb.org/mongo-driver v1.17.10/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
@@ -1501,8 +1505,8 @@ golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+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.
@@ -187,6 +187,10 @@ func (store *MockFoundationDBStore) KvGet(ctx context.Context, key []byte) ([]by
return value, nil
}
func (store *MockFoundationDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *MockFoundationDBStore) KvDelete(ctx context.Context, key []byte) error {
delete(store.kvStore, string(key))
return nil
+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()
}
}
}
+2 -1
View File
@@ -572,7 +572,8 @@ func runInitialSnapshot(
// still gets seeded (only its children would be skipped by the parent
// check).
if parent == filer.SystemLogDir || strings.HasPrefix(parent, filer.SystemLogDir+"/") ||
source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") {
source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") ||
isSyncCursor(sourceKey) {
return nil
}
if matchesExcludePath(parent, excludePaths) || matchesExcludePath(source, excludePaths) {
@@ -0,0 +1,74 @@
package command
import (
"net"
"sort"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/replication/source"
"google.golang.org/grpc"
)
type snapshotListFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
dirs map[string][]*filer_pb.Entry
}
func (f *snapshotListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
for _, entry := range f.dirs[req.Directory] {
if req.StartFromFileName != "" && (entry.Name < req.StartFromFileName || entry.Name == req.StartFromFileName && !req.InclusiveStartFrom) {
continue
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
return err
}
}
return nil
}
func TestInitialSnapshotSkipsSyncCursors(t *testing.T) {
dir := func(name string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}
}
file := func(name string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{}}
}
fake := &snapshotListFiler{dirs: map[string][]*filer_pb.Entry{
"/": {dir("data"), dir("etc")},
"/data": {file("a.txt")},
"/etc": {dir("seaweedfs")},
"/etc/seaweedfs": {file("filer.conf"), dir("filer_sync")},
filer.SyncCursorDir: {file("0000000a-0000000000000001.json")},
}}
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, fake)
go server.Serve(lis)
defer server.Stop()
filerSource := &source.FilerSource{}
if err := filerSource.DoInitialize("localhost:1", lis.Addr().String(), "/", false); err != nil {
t.Fatal(err)
}
sink := &recordSink{created: map[string]*filer_pb.Entry{}}
if _, err := runInitialSnapshot(lis.Addr().String(), filerSource, "/", "/", nil, nil, nil, nil, sink, false, nil); err != nil {
t.Fatal(err)
}
var created []string
for key := range sink.created {
created = append(created, key)
}
sort.Strings(created)
want := []string{"/data", "/data/a.txt", "/etc", "/etc/seaweedfs", "/etc/seaweedfs/filer.conf"}
if strings.Join(created, ",") != strings.Join(want, ",") {
t.Fatalf("seeded %v, want %v", created, want)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"sort"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
@@ -69,6 +70,7 @@ func (c *lookupEntrySeaweedClient) ListEntries(_ context.Context, in *filer_pb.L
}
type recordSink struct {
mu sync.Mutex
created map[string]*filer_pb.Entry
deleted []string
}
@@ -78,10 +80,14 @@ func (s *recordSink) Initialize(configuration util.Configuration, prefix string)
return nil
}
func (s *recordSink) DeleteEntry(key string, isDirectory, deleteIncludeChunks bool, signatures []int32) error {
s.mu.Lock()
defer s.mu.Unlock()
s.deleted = append(s.deleted, key)
return nil
}
func (s *recordSink) CreateEntry(key string, entry *filer_pb.Entry, signatures []int32) error {
s.mu.Lock()
defer s.mu.Unlock()
s.created[key] = entry
return nil
}
+4
View File
@@ -27,6 +27,10 @@ func (s *kvOnlyStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
return value, nil
}
func (s *kvOnlyStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *kvOnlyStore) KvPut(_ context.Context, key []byte, value []byte) error {
s.kv[string(key)] = value
return nil
+48 -3
View File
@@ -25,6 +25,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
util_http_client "github.com/seaweedfs/seaweedfs/weed/util/http/client"
"github.com/seaweedfs/seaweedfs/weed/util/version"
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
"google.golang.org/grpc"
)
@@ -142,6 +143,9 @@ var cmdFilerSynchronize = &Command{
If restarted, the synchronization will resume from the previous checkpoints, persisted every minute.
A fresh sync will start from the earliest metadata logs.
The position is also saved hourly on the source filer under /etc/seaweedfs/filer_sync, so fs.log.purge
there keeps the logs the sync still needs, until the sync has been stopped for 7 days. That copy also
describes the sync (paths, target, host, progress) for display; the checkpoint on the target stays authoritative.
`,
}
@@ -374,6 +378,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
}
glog.V(0).Infof("start sync %s(%d) => %s(%d) from %v(%d)", sourceFiler, sourceFilerSignature, targetFiler, targetFilerSignature, time.Unix(0, sourceFilerOffsetTsNs), sourceFilerOffsetTsNs)
go warnMetadataLogGap(sourceGrpcDialOption, sourceFiler, sourceTokenSource, sourcePath, sourceExcludePaths, targetFiler, sourceFilerOffsetTsNs)
// create filer sink
filerSource := &source.FilerSource{}
@@ -419,6 +424,34 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
processor := NewMetadataProcessor(processEventFn, concurrency, sourceFilerOffsetTsNs)
processor.SetMetrics(sourceFiler.String(), targetFiler.String(), clientName, sourcePath)
cursorName := syncCursorName(targetFilerSignature, signaturePrefix)
var storedOffsetTsNs, firstSeenTsNs atomic.Int64
storedOffsetTsNs.Store(sourceFilerOffsetTsNs)
host, _ := os.Hostname()
cursor := filer.SyncCursor{
SourceFiler: string(sourceFiler),
SourcePath: sourcePath,
ExcludePaths: sourceExcludePaths,
TargetFiler: string(targetFiler),
TargetPath: targetPath,
TargetSignature: targetFilerSignature,
Host: host,
Version: strings.TrimSpace(version.Version()),
SyncStartedNs: time.Now().UnixNano(),
}
stopCursorSaves := make(chan struct{})
defer close(stopCursorSaves)
firstSeen := make(chan struct{})
cursorTicker := time.NewTicker(time.Minute)
defer cursorTicker.Stop()
go keepSyncCursor(stopCursorSaves, firstSeen, cursorTicker.C, &storedOffsetTsNs, &firstSeenTsNs, func(tsNs int64, checkpointed bool) error {
cursor.TsNs = tsNs
cursor.Checkpointed = checkpointed
cursor.ProcessedTsNs = processor.processedTsWatermark.Load()
cursor.OldestFailedTsNs = processor.OldestFailedTsNs()
return saveSyncCursor(sourceGrpcDialOption, sourceFiler, sourceTokenSource, cursorName, cursor)
})
// update sync state for graceful shutdown checkpoint saving
if statePtr != nil {
statePtr.Store(&syncState{
@@ -465,6 +498,9 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
var lastLogTsNs = time.Now().UnixNano()
var lastProgressedTsNs int64
processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error {
if resp.TsNs > 0 && firstSeenTsNs.CompareAndSwap(0, resp.TsNs) {
close(firstSeen)
}
processor.AddSyncJob(resp)
return nil
}, 3*time.Second, func(counter int64, lastTsNs int64) error {
@@ -490,7 +526,12 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
lastProgressedTsNs = offsetTsNs
// collect synchronous offset
statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(offsetTsNs))
return setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor))
resumeTsNs := resumeTsNsFor(processor)
if err := setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNs); err != nil {
return err
}
storedOffsetTsNs.Store(resumeTsNs)
return nil
})
prefix := sourcePath
@@ -726,8 +767,8 @@ func genProcessFunction(sourcePath string, targetPath string, excludePaths []str
// Compute per-side exclusion so that rename events crossing an
// exclude boundary are handled as delete + create rather than
// being entirely skipped.
oldExcluded := oldDirExcluded || isEntryExcluded(resp.Directory, message.OldEntry, reExcludeFileName, excludeFileNames, excludePathPatterns)
newExcluded := newDirExcluded || isEntryExcluded(targetDir, message.NewEntry, reExcludeFileName, excludeFileNames, excludePathPatterns)
oldExcluded := oldDirExcluded || isSyncCursor(sourceOldKey) || isEntryExcluded(resp.Directory, message.OldEntry, reExcludeFileName, excludeFileNames, excludePathPatterns)
newExcluded := newDirExcluded || isSyncCursor(sourceNewKey) || isEntryExcluded(targetDir, message.NewEntry, reExcludeFileName, excludeFileNames, excludePathPatterns)
if oldExcluded && newExcluded {
return nil
@@ -896,6 +937,10 @@ func destKey(dataSink sink.ReplicationSink, targetPath, sourcePath string, sourc
return util.Join(targetPath, dateKey, relative)
}
func isSyncCursor(key util.FullPath) bool {
return key != "" && util.IsEqualOrUnder(string(key), filer.SyncCursorDir)
}
// isEntryExcluded checks whether a single side (old or new) of an event is excluded
// by the deprecated filename regexp, the wildcard file-name matchers, or the
// wildcard path-pattern matchers.
+73
View File
@@ -0,0 +1,73 @@
package command
import (
"context"
"encoding/json"
"fmt"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
)
const syncCursorSaveInterval = time.Hour
func syncCursorName(targetFilerSignature int32, signaturePrefix string) string {
return fmt.Sprintf("%08x-%016x.json", uint32(targetFilerSignature), uint64(util.HashStringToLong(signaturePrefix)))
}
// saveSyncCursor keeps the sync position on the source filer as a replay
// cursor, so a metadata log purge there keeps the logs the sync has yet to read.
func saveSyncCursor(sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourceTokenSource security.FilerTokenSource, name string, cursor filer.SyncCursor) error {
if cursor.TsNs <= 0 {
return nil
}
cursor.SavedNs = time.Now().UnixNano()
content, err := json.Marshal(cursor)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = pb.WithGrpcFilerClient(false, 0, sourceFiler, sourceGrpcDialOption, sourceTokenSource, func(client filer_pb.SeaweedFilerClient) error {
return filer.SaveInsideFiler(ctx, client, filer.SyncCursorDir, name, content)
})
if err != nil {
glog.V(1).Infof("save sync position on %s: %v", sourceFiler, err)
}
return err
}
// keepSyncCursor saves the cursor once the sync has a position, retries a
// failed save on the next tick, and then rewrites it hourly even when the
// position is stuck, so the purge keeps honoring a running sync and lets a
// stopped one expire. A fresh sync has no checkpoint until its oldest event
// finishes, and a restart replays everything it has received.
func keepSyncCursor(stop, firstSeen <-chan struct{}, tick <-chan time.Time, storedOffsetTsNs, firstSeenTsNs *atomic.Int64, save func(tsNs int64, checkpointed bool) error) {
var lastSaveTime time.Time
for {
tsNs := storedOffsetTsNs.Load()
checkpointed := tsNs > 0
if !checkpointed {
tsNs = firstSeenTsNs.Load() - 1
}
if tsNs > 0 && (lastSaveTime.IsZero() || time.Since(lastSaveTime) >= syncCursorSaveInterval) {
if save(tsNs, checkpointed) == nil {
lastSaveTime = time.Now()
}
}
select {
case <-stop:
return
case <-firstSeen:
firstSeen = nil
case <-tick:
}
}
}
+88
View File
@@ -0,0 +1,88 @@
package command
import (
"errors"
"sync/atomic"
"testing"
"time"
)
type cursorSave struct {
tsNs int64
checkpointed bool
}
func startKeepSyncCursor(t *testing.T, stored int64, failures int) (firstSeenTsNs *atomic.Int64, firstSeen chan struct{}, tick chan time.Time, saves chan cursorSave) {
var storedOffsetTsNs atomic.Int64
storedOffsetTsNs.Store(stored)
firstSeenTsNs = &atomic.Int64{}
firstSeen = make(chan struct{})
tick = make(chan time.Time)
saves = make(chan cursorSave, 16)
stop := make(chan struct{})
done := make(chan struct{})
t.Cleanup(func() {
close(stop)
<-done
})
go func() {
defer close(done)
keepSyncCursor(stop, firstSeen, tick, &storedOffsetTsNs, firstSeenTsNs, func(tsNs int64, checkpointed bool) error {
saves <- cursorSave{tsNs, checkpointed}
if failures > 0 {
failures--
return errors.New("filer unavailable")
}
return nil
})
}()
return
}
func expectCursorSave(t *testing.T, saves chan cursorSave, want cursorSave) {
t.Helper()
select {
case got := <-saves:
if got != want {
t.Fatalf("saved %+v, want %+v", got, want)
}
case <-time.After(5 * time.Second):
t.Fatalf("no cursor save, want %+v", want)
}
}
func expectNoCursorSave(t *testing.T, saves chan cursorSave) {
t.Helper()
select {
case got := <-saves:
t.Fatalf("unexpected cursor save %+v", got)
default:
}
}
func TestKeepSyncCursorSavesOnFirstEvent(t *testing.T) {
firstSeenTsNs, firstSeen, tick, saves := startKeepSyncCursor(t, 0, 0)
tick <- time.Now()
expectNoCursorSave(t, saves)
firstSeenTsNs.Store(100)
close(firstSeen)
expectCursorSave(t, saves, cursorSave{99, false})
tick <- time.Now()
tick <- time.Now()
expectNoCursorSave(t, saves)
}
func TestKeepSyncCursorRetriesFailedSave(t *testing.T) {
_, _, tick, saves := startKeepSyncCursor(t, 500, 2)
expectCursorSave(t, saves, cursorSave{500, true})
tick <- time.Now()
expectCursorSave(t, saves, cursorSave{500, true})
tick <- time.Now()
expectCursorSave(t, saves, cursorSave{500, true})
tick <- time.Now()
tick <- time.Now()
expectNoCursorSave(t, saves)
}
+124
View File
@@ -0,0 +1,124 @@
package command
import (
"context"
"errors"
"math"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
)
const (
metadataLogGapProbeLimit = 1024
logDayLayout = "2006-01-02"
)
// oldestMetadataLogTime is the start of the oldest metadata log file the
// filer still keeps, or zero when it keeps none.
func oldestMetadataLogTime(ctx context.Context, client filer_pb.SeaweedFilerClient) (time.Time, error) {
var oldestDay string
err := filer_pb.SeaweedList(ctx, client, filer.SystemLogDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if _, parseErr := time.Parse(logDayLayout, entry.Name); parseErr == nil && entry.IsDirectory && (oldestDay == "" || entry.Name < oldestDay) {
oldestDay = entry.Name
}
return nil
}, "", false, math.MaxInt32)
if errors.Is(err, filer_pb.ErrNotFound) || (err == nil && oldestDay == "") {
return time.Time{}, nil
}
if err != nil {
return time.Time{}, err
}
dayStart, _ := time.Parse(logDayLayout, oldestDay)
var oldest time.Time
err = filer_pb.SeaweedList(ctx, client, string(util.NewFullPath(filer.SystemLogDir, oldestDay)), "", func(entry *filer_pb.Entry, isLast bool) error {
hourMinute, _, _ := strings.Cut(entry.Name, ".")
if t, parseErr := time.Parse(logDayLayout+" 15-04", oldestDay+" "+hourMinute); parseErr == nil && (oldest.IsZero() || t.Before(oldest)) {
oldest = t
}
return nil
}, "", false, math.MaxInt32)
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return time.Time{}, err
}
if oldest.IsZero() {
return dayStart, nil
}
return oldest, nil
}
// entryChangedBefore is a synced child of dir whose last change is older than
// t, so a replay of the log from t never writes it.
func entryChangedBefore(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string, excludePaths []string, t time.Time) (*filer_pb.Entry, error) {
var found *filer_pb.Entry
err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error {
if found != nil || isNotSynced(string(util.NewFullPath(dir, entry.Name)), excludePaths) {
return nil
}
if entryLastChange(entry).Before(t) {
found = entry
}
return nil
}, "", false, metadataLogGapProbeLimit)
if errors.Is(err, filer_pb.ErrNotFound) {
return nil, nil
}
return found, err
}
func entryLastChange(entry *filer_pb.Entry) time.Time {
if entry.CommitTsNs > 0 {
return time.Unix(0, entry.CommitTsNs)
}
return time.Unix(entry.GetAttributes().GetMtime(), 0)
}
func isNotSynced(p string, excludePaths []string) bool {
return util.IsEqualOrUnder(p, filer.SystemLogDir) || strings.HasPrefix(filer.SystemLogDir, p+"/") ||
isSyncCursor(util.FullPath(p)) || isMultipartUploadDir(p+"/") || matchesExcludePath(p, excludePaths)
}
// metadataLogGap describes what a sync starting at offsetTsNs cannot replay
// because the source no longer keeps the metadata log for it, or "".
func metadataLogGap(ctx context.Context, client filer_pb.SeaweedFilerClient, sourcePath string, excludePaths []string, offsetTsNs int64) (string, error) {
logStart, err := oldestMetadataLogTime(ctx, client)
if err != nil || logStart.IsZero() {
return "", err
}
if offsetTsNs > 0 {
if logStart.UnixNano() <= offsetTsNs {
return "", nil
}
return "its metadata log starts at " + logStart.UTC().Format(time.RFC3339) + ", after the saved sync position " + time.Unix(0, offsetTsNs).UTC().Format(time.RFC3339) + "; changes made in between, if any, were purged and are not replicated", nil
}
entry, err := entryChangedBefore(ctx, client, sourcePath, excludePaths, logStart)
if err != nil || entry == nil {
return "", err
}
return "there is no saved sync position, so the sync replays its metadata log from its oldest file at " + logStart.UTC().Format(time.RFC3339) + ", but " + string(util.NewFullPath(sourcePath, entry.Name)) + " was last changed at " + entryLastChange(entry).UTC().Format(time.RFC3339) + "; entries not changed since the log was purged are not copied, so seed the target with the existing data first", nil
}
func warnMetadataLogGap(sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourceTokenSource security.FilerTokenSource, sourcePath string, excludePaths []string, targetFiler pb.ServerAddress, offsetTsNs int64) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
var gap string
err := pb.WithGrpcFilerClient(false, 0, sourceFiler, sourceGrpcDialOption, sourceTokenSource, func(client filer_pb.SeaweedFilerClient) (err error) {
gap, err = metadataLogGap(ctx, client, sourcePath, excludePaths, offsetTsNs)
return err
})
if err != nil {
glog.V(1).Infof("check the metadata log of %s: %v", sourceFiler, err)
return
}
if gap != "" {
glog.Warningf("sync %s%s => %s may be incomplete: on %s, %s", sourceFiler, sourcePath, targetFiler, sourceFiler, gap)
}
}
+77
View File
@@ -0,0 +1,77 @@
package command
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func TestMetadataLogGap(t *testing.T) {
logStart := time.Date(2026, 11, 30, 3, 7, 0, 0, time.UTC)
logs := map[string][]*filer_pb.Entry{
filer.SystemLogDir: {
{Name: "2026-12-01", IsDirectory: true},
{Name: "2026-11-30", IsDirectory: true},
{Name: "not-a-day", IsDirectory: true},
},
filer.SystemLogDir + "/2026-11-30": {
{Name: "05-00.0000000a"},
{Name: "03-07.0000000b"},
},
}
child := func(name string, commitTsNs int64, mtime time.Time) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, IsDirectory: true, CommitTsNs: commitTsNs, Attributes: &filer_pb.FuseAttributes{Mtime: mtime.Unix()}}
}
before, after := logStart.Add(-time.Hour), logStart.Add(time.Hour)
tests := []struct {
name string
dirs map[string][]*filer_pb.Entry
sourcePath string
exclude []string
offsetTsNs int64
want string
}{
{name: "no metadata log", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("old", before.UnixNano(), before)}}, sourcePath: "/buckets"},
{name: "position inside the log", offsetTsNs: after.UnixNano()},
{name: "position at the oldest file", offsetTsNs: logStart.UnixNano()},
{name: "position before the log", offsetTsNs: before.UnixNano(), want: "after the saved sync position 2026-11-30T02:07:00Z"},
{name: "fresh sync, every entry in the log", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("recent", after.UnixNano(), before)}}, sourcePath: "/buckets"},
{name: "fresh sync, entry changed before the log", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("recent", after.UnixNano(), after), child("historical", before.UnixNano(), before)}}, sourcePath: "/buckets", want: "/buckets/historical was last changed at 2026-11-30T02:07:00Z"},
{name: "fresh sync, entry without commit time", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("historical", 0, before)}}, sourcePath: "/buckets", want: "/buckets/historical"},
{name: "fresh sync of the root skips the log directory", dirs: map[string][]*filer_pb.Entry{"/": {child("topics", before.UnixNano(), before)}}, sourcePath: "/"},
{name: "fresh sync skips excluded entries", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("archive", before.UnixNano(), before), child("recent", after.UnixNano(), after)}}, sourcePath: "/buckets", exclude: []string{"/buckets/archive"}},
{name: "fresh sync skips the sync cursors", dirs: map[string][]*filer_pb.Entry{"/etc/seaweedfs": {child("filer_sync", before.UnixNano(), before)}}, sourcePath: "/etc/seaweedfs"},
{name: "fresh sync skips multipart uploads", dirs: map[string][]*filer_pb.Entry{"/buckets/b": {child(".uploads", before.UnixNano(), before)}}, sourcePath: "/buckets/b"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dirs := map[string][]*filer_pb.Entry{}
if tt.name != "no metadata log" {
for k, v := range logs {
dirs[k] = v
}
}
for k, v := range tt.dirs {
dirs[k] = v
}
got, err := metadataLogGap(context.Background(), &verifyTestInnerClient{entriesByDir: dirs}, tt.sourcePath, tt.exclude, tt.offsetTsNs)
if err != nil {
t.Fatalf("metadataLogGap: %v", err)
}
if tt.want == "" {
if got != "" {
t.Fatalf("got gap %q, want none", got)
}
return
}
if !strings.Contains(got, tt.want) {
t.Fatalf("got gap %q, want it to mention %q", got, tt.want)
}
})
}
}
+56
View File
@@ -6,6 +6,7 @@ import (
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
"github.com/seaweedfs/seaweedfs/weed/replication/sink/localsink"
@@ -378,3 +379,58 @@ func TestGenProcessFunctionLocalSinkStaysInsideTarget(t *testing.T) {
t.Fatalf("local sink wrote outside %s: %v", target, err)
}
}
func TestGenProcessFunctionSkipsSyncCursors(t *testing.T) {
dataSink := &recordingSyncSink{}
processFn := genProcessFunction("/", "/", nil, nil, nil, nil, dataSink, true, false)
for _, key := range []util.FullPath{util.FullPath(filer.SyncCursorDir), util.FullPath(filer.SyncCursorDir).Child("cursor.json"), util.FullPath(filer.DirectoryEtcSeaweedFS).Child("cursor.json")} {
dir, name := key.DirAndName()
err := processFn(&filer_pb.SubscribeMetadataResponse{
Directory: dir,
EventNotification: &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{Name: name},
NewParentPath: dir,
},
})
if err != nil {
t.Fatalf("processFn %s: %v", key, err)
}
}
if want := []string{filer.DirectoryEtcSeaweedFS + "/cursor.json"}; !equalSyncStrings(dataSink.createKeys, want) {
t.Fatalf("create keys = %v, want %v", dataSink.createKeys, want)
}
}
func TestGenProcessFunctionSyncCursorRenames(t *testing.T) {
event := func(oldDir, oldName, newDir, newName string) *filer_pb.SubscribeMetadataResponse {
resp := &filer_pb.SubscribeMetadataResponse{Directory: oldDir, EventNotification: &filer_pb.EventNotification{NewParentPath: newDir}}
if oldName != "" {
resp.EventNotification.OldEntry = &filer_pb.Entry{Name: oldName}
}
if newName != "" {
resp.EventNotification.NewEntry = &filer_pb.Entry{Name: newName}
}
return resp
}
tests := []struct {
name string
resp *filer_pb.SubscribeMetadataResponse
wantCreate, wantDelete []string
}{
{name: "into the cursor directory", resp: event("/data", "file", filer.SyncCursorDir, "file"), wantDelete: []string{"/data/file"}},
{name: "out of the cursor directory", resp: event(filer.SyncCursorDir, "file", "/data", "file"), wantCreate: []string{"/data/file"}},
{name: "inside the cursor directory", resp: event(filer.SyncCursorDir, "a.json", filer.SyncCursorDir, "b.json")},
{name: "cursor deleted", resp: event(filer.SyncCursorDir, "a.json", "", "")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dataSink := &recordingSyncSink{}
if err := genProcessFunction("/", "/", nil, nil, nil, nil, dataSink, true, false)(tt.resp); err != nil {
t.Fatalf("processFn: %v", err)
}
if !equalSyncStrings(dataSink.createKeys, tt.wantCreate) || !equalSyncStrings(dataSink.deleteKeys, tt.wantDelete) || len(dataSink.updateKeys) > 0 {
t.Fatalf("create %v delete %v update %v, want create %v delete %v", dataSink.createKeys, dataSink.deleteKeys, dataSink.updateKeys, tt.wantCreate, tt.wantDelete)
}
})
}
}
+9
View File
@@ -125,6 +125,8 @@ func runFuse(cmd *Command, args []string) bool {
mountOptions.filer = &parameter.value
case "filer.path":
mountOptions.filerMountRootPath = &parameter.value
case "filer.tokenFile":
mountOptions.filerTokenFile = &parameter.value
case "volumeName":
mountOptions.volumeName = &parameter.value
case "dirAutoCreate":
@@ -191,6 +193,8 @@ func runFuse(cmd *Command, args []string) bool {
}
case "cacheDirWrite":
mountOptions.cacheDirForWrite = &parameter.value
case "cacheMinFreeSpace":
mountOptions.cacheMinFreeSpace = &parameter.value
case "writeBufferSizeMB":
if parsed, err := strconv.ParseInt(parameter.value, 0, 64); err == nil {
mountOptions.writeBufferSizeMB = &parsed
@@ -328,6 +332,11 @@ func runFuse(cmd *Command, args []string) bool {
if err := checkIdmap(runtime.GOOS, *mountOptions.idmap, *mountOptions.defaultPermissions); err != nil {
panic(err)
}
// The child checks it as well, but by then the parent only waits for
// its signal, so a bad value has to fail here.
if _, err := parseCacheMinFreeSpace(&mountOptions); err != nil {
panic(err)
}
util_http.InitGlobalHttpClient()
+25
View File
@@ -65,3 +65,28 @@ func TestRunFuseSetsVolumeName(t *testing.T) {
"volumeName=MyDisk,concurrentReaders=bad",
})
}
func TestRunFuseSetsFilerTokenFile(t *testing.T) {
oldTokenFile := mountOptions.filerTokenFile
oldConcurrentReaders := mountOptions.concurrentReaders
oldDir := mountOptions.dir
defer func() {
got := mountOptions.filerTokenFile
mountOptions.filerTokenFile = oldTokenFile
mountOptions.concurrentReaders = oldConcurrentReaders
mountOptions.dir = oldDir
if recover() == nil {
t.Fatal("expected invalid concurrentReaders option to be parsed")
}
if got == nil || *got != "/run/seaweedfs/token" {
t.Fatalf("-o filer.tokenFile did not set mountOptions.filerTokenFile, got %v", got)
}
}()
runFuse(cmdMount, []string{
"/mnt",
"-o",
"filer.tokenFile=/run/seaweedfs/token,concurrentReaders=bad",
})
}
+6 -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")
@@ -544,6 +544,7 @@ func initMiniS3Flags() {
miniS3Options.portLance = cmdMini.Flag.Int("s3.port.lance", 9101, "Lance Namespace server listen port (0 to disable)")
miniS3Options.icebergCredentialRole = cmdMini.Flag.String("s3.iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
miniS3Options.icebergCredentialDuration = cmdMini.Flag.Int("s3.iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
miniS3Options.icebergCredentialMinDuration = cmdMini.Flag.Int("s3.iceberg.credentialMinDurationSeconds", 900, "shortest session a client may ask the Iceberg catalog to vend (header X-SeaweedFS-Credential-Duration-Seconds); 1-900, other STS actions keep 900")
miniS3Options.domainName = cmdMini.Flag.String("s3.domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
miniS3Options.allowedOrigins = cmdMini.Flag.String("s3.allowedOrigins", "*", "comma separated list of allowed origins")
miniS3Options.tlsPrivateKey = cmdMini.Flag.String("s3.key.file", "", "path to the TLS private key file")
@@ -1489,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)
@@ -1740,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)
}
}
}
+5 -1
View File
@@ -8,6 +8,7 @@ import (
type MountOptions struct {
filer *string
filerMountRootPath *string
filerTokenFile *string
dir *string
volumeName *string
dirAutoCreate *bool
@@ -28,6 +29,7 @@ type MountOptions struct {
cacheDirForRead *string
cacheDirForWrite *string
cacheSizeMBForRead *int64
cacheMinFreeSpace *string
writeBufferSizeMB *int64
dataCenter *string
allowOthers *bool
@@ -103,6 +105,7 @@ func init() {
cmdMount.Run = runMount // break init cycle
mountOptions.filer = cmdMount.Flag.String("filer", "localhost:8888", "comma-separated weed filer location")
mountOptions.filerMountRootPath = cmdMount.Flag.String("filer.path", "/", "mount this remote path from filer server")
mountOptions.filerTokenFile = cmdMount.Flag.String("filer.tokenFile", "", "file holding a pre-issued filer gRPC token, re-read for every filer call so a replaced file takes effect without a restart; a missing or empty file fails the call. Cannot be combined with -peer.enable or -dlm. copy_file_range's server-side copy signs its filer HTTP request with jwt.filer_signing.key, not this token, and is unsupported with it")
mountOptions.dir = cmdMount.Flag.String("dir", ".", "mount weed filer to this directory")
mountOptions.volumeName = cmdMount.Flag.String("volumeName", "", "name the mount shown by the platform (Finder/Explorer, or \"mount\"/\"df\" on Linux and FreeBSD), overriding the name taken from -filer.path or -dir")
mountOptions.dirAutoCreate = cmdMount.Flag.Bool("dirAutoCreate", false, "auto create the directory to mount to")
@@ -116,10 +119,11 @@ 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")
mountOptions.cacheMinFreeSpace = cmdMount.Flag.String("cacheMinFreeSpace", "1", "free space the chunk cache leaves on the disk holding -cacheDir, as a percentage like 1 or a size like 10GiB: the cache shrinks to fit above it and takes no new disk space while the disk is under it")
mountOptions.cacheDirForWrite = cmdMount.Flag.String("cacheDirWrite", "", "buffer writes mostly for large files")
mountOptions.writeBufferSizeMB = cmdMount.Flag.Int64("writeBufferSizeMB", 0, "global cap on the per-mount write buffer (memory + swap) in MB, 0 means unlimited. Bounds /tmp growth when volume uploads stall")
mountOptions.cacheMetaTtlSec = cmdMount.Flag.Int("cacheMetaTtlSec", 60, "metadata cache validity seconds")
+43 -1
View File
@@ -149,7 +149,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr
var err error
var digest string
for i := 0; i < 10; i++ {
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error {
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, mountFilerTokenSource(option), func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err)
@@ -180,6 +180,31 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr
return filerAddresses, grpcDialOption, cipher, bucketRootPath, true
}
// mountFilerTokenSource reads -filer.tokenFile for each filer call, or is nil
// without it so the mount keeps its existing credentials.
func mountFilerTokenSource(option *MountOptions) security.FilerTokenSource {
if option.filerTokenFile == nil || *option.filerTokenFile == "" {
return nil
}
return security.FilerTokenFile(util.ResolvePath(*option.filerTokenFile))
}
// checkFilerTokenFile refuses options a filer token cannot serve. A filer
// refuses MountRegister, MountList and distributed locks to a scoped token,
// so peer chunk sharing and -dlm would fail at run time instead of at start.
func checkFilerTokenFile(option *MountOptions) error {
if option.filerTokenFile == nil || *option.filerTokenFile == "" {
return nil
}
if option.peerEnabled != nil && *option.peerEnabled {
return fmt.Errorf("-filer.tokenFile cannot be used with -peer.enable: the filer refuses MountRegister and MountList to scoped tokens")
}
if option.distributedLock != nil && *option.distributedLock {
return fmt.Errorf("-filer.tokenFile cannot be used with -dlm: the filer refuses distributed locks to scoped tokens")
}
return nil
}
// fileSystemParams are the pieces of a mount that each platform works out for
// itself: where it is attached, and whose identity the entries carry.
type fileSystemParams struct {
@@ -198,6 +223,7 @@ type fileSystemParams struct {
chunkSizeLimitMB int
cacheDirForRead string
cacheDirForWrite string
cacheMinFree *util.MinFreeSpace // the parsed -cacheMinFreeSpace
// eagerFilerCreate persists a created file's entry at create time rather
// than at flush. A platform sets it when it cannot run the flush before
@@ -218,6 +244,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
GrpcDialOption: p.grpcDialOption,
FilerSigningKey: security.SigningKey(util.GetViper().GetString("jwt.filer_signing.key")),
FilerSigningExpiresAfterSec: util.GetViper().GetInt("jwt.filer_signing.expires_after_seconds"),
FilerTokenSource: mountFilerTokenSource(option),
FilerMountRootPath: p.mountRoot,
VolumeReadAuth: option.volumeReadAuth != nil && *option.volumeReadAuth,
Collection: *option.collection,
@@ -230,6 +257,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
ReaderCacheSizeMB: readerCacheSizeMB,
CacheDirForRead: p.cacheDirForRead,
CacheSizeMBForRead: *option.cacheSizeMBForRead,
CacheMinFreeSpace: p.cacheMinFree,
CacheDirForWrite: p.cacheDirForWrite,
WriteBufferSizeMB: *option.writeBufferSizeMB,
CacheMetaTTlSec: *option.cacheMetaTtlSec,
@@ -362,6 +390,19 @@ func resolveMountRoot(filerMountRootPath string) string {
return mountRoot
}
// parseCacheMinFreeSpace reads -cacheMinFreeSpace, written like the volume
// server's -minFreeSpace.
func parseCacheMinFreeSpace(option *MountOptions) (*util.MinFreeSpace, error) {
if option.cacheMinFreeSpace == nil {
return nil, nil
}
minFreeSpace, err := util.ParseMinFreeSpace(*option.cacheMinFreeSpace)
if err != nil {
return nil, fmt.Errorf("cacheMinFreeSpace %q: want a percentage like 1 or a size like 10GiB", *option.cacheMinFreeSpace)
}
return minFreeSpace, nil
}
// resolveCacheDirs falls back to the read cache when no write cache is set.
func resolveCacheDirs(option *MountOptions) (string, string) {
cacheDirForRead := util.ResolvePath(*option.cacheDirForRead)
@@ -410,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
+33
View File
@@ -471,3 +471,36 @@ func Test_ensureMountRootDirectory(t *testing.T) {
}
})
}
func Test_parseCacheMinFreeSpace(t *testing.T) {
for _, tc := range []struct {
value string
want string
wantErr bool
}{
{value: "1", want: "1.00%"},
{value: "0", want: "0.00%"},
{value: "10GiB", want: "10GiB"},
{value: "101", wantErr: true},
{value: "lots", wantErr: true},
} {
value := tc.value
got, err := parseCacheMinFreeSpace(&MountOptions{cacheMinFreeSpace: &value})
if tc.wantErr {
if err == nil {
t.Errorf("-cacheMinFreeSpace=%s: no error", tc.value)
}
continue
}
if err != nil {
t.Errorf("-cacheMinFreeSpace=%s: %v", tc.value, err)
continue
}
if got.String() != tc.want {
t.Errorf("-cacheMinFreeSpace=%s: %s, want %s", tc.value, got, tc.want)
}
}
if got, err := parseCacheMinFreeSpace(&MountOptions{}); got != nil || err != nil {
t.Errorf("unset -cacheMinFreeSpace: %v, %v; want no floor", got, err)
}
}
+11 -1
View File
@@ -30,6 +30,11 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
fmt.Println(err)
return false
}
cacheMinFree, parseErr := parseCacheMinFreeSpace(option)
if parseErr != nil {
fmt.Println(parseErr)
return false
}
// basic checks
chunkSizeLimitMB := *mountOptions.chunkSizeLimitMB
@@ -41,6 +46,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
fmt.Println(err)
return false
}
if err := checkFilerTokenFile(option); err != nil {
fmt.Println(err)
return false
}
filerAddresses, grpcDialOption, cipher, bucketRootPath, ok := connectToFiler(option)
if !ok {
@@ -69,7 +78,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
}
}
var err error
sseReader, err = mount.NewSSES3Reader(context.Background(), bucketPath, filerAddresses, grpcDialOption)
sseReader, err = mount.NewSSES3Reader(context.Background(), bucketPath, filerAddresses, grpcDialOption, mountFilerTokenSource(option))
if err != nil {
glog.Errorf("configure SSE-S3 reads: %v", err)
return false
@@ -264,6 +273,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
chunkSizeLimitMB: chunkSizeLimitMB,
cacheDirForRead: cacheDirForRead,
cacheDirForWrite: cacheDirForWrite,
cacheMinFree: cacheMinFree,
})
if !createMountRoot(seaweedFileSystem, mountRoot, bucketRootPath, filerAddresses) {
+118
View File
@@ -0,0 +1,118 @@
//go:build linux || darwin || freebsd || windows
package command
import (
"context"
"net"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func TestCheckFilerTokenFileRefusesUnsupportedOptions(t *testing.T) {
on, off := true, false
tokenFile, none := "/run/filer-token", ""
tests := []struct {
name string
tokenFile *string
peer, dlm *bool
want string
}{
{name: "no token file", tokenFile: &none, peer: &on, dlm: &on},
{name: "unset token file", peer: &on, dlm: &on},
{name: "token file alone", tokenFile: &tokenFile, peer: &off, dlm: &off},
{name: "token file, options unset", tokenFile: &tokenFile},
{name: "peer sharing", tokenFile: &tokenFile, peer: &on, dlm: &off, want: "-peer.enable"},
{name: "distributed lock", tokenFile: &tokenFile, peer: &off, dlm: &on, want: "-dlm"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := checkFilerTokenFile(&MountOptions{filerTokenFile: tt.tokenFile, peerEnabled: tt.peer, distributedLock: tt.dlm})
if tt.want == "" {
if err != nil {
t.Fatalf("checkFilerTokenFile = %v, want nil", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tt.want) || !strings.Contains(err.Error(), "-filer.tokenFile") {
t.Fatalf("checkFilerTokenFile = %v, want a refusal naming -filer.tokenFile and %s", err, tt.want)
}
})
}
}
func TestMountFilerTokenSourceIsNilWithoutFlag(t *testing.T) {
empty := ""
for _, option := range []*MountOptions{{}, {filerTokenFile: &empty}} {
if mountFilerTokenSource(option) != nil {
t.Fatal("a mount without -filer.tokenFile has a token source")
}
}
}
type configurationFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
mu sync.Mutex
tokens [][]string
}
func (f *configurationFiler) GetFilerConfiguration(ctx context.Context, _ *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
md, _ := metadata.FromIncomingContext(ctx)
f.mu.Lock()
f.tokens = append(f.tokens, md.Get("authorization"))
f.mu.Unlock()
return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets"}, nil
}
// The startup handshake runs before the file system exists and must already
// present the token file, or a filer that requires tokens refuses the mount.
func TestConnectToFilerPresentsTokenFile(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
fake := &configurationFiler{}
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, fake)
go server.Serve(listener)
t.Cleanup(server.Stop)
address := string(pb.NewServerAddressWithGrpcPort("127.0.0.1:1", listener.Addr().(*net.TCPAddr).Port))
tokenPath := filepath.Join(t.TempDir(), "token")
if err := os.WriteFile(tokenPath, []byte("bootstrap-token\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
name string
tokenFile string
want []string
}{
{name: "without token file", want: nil},
{name: "with token file", tokenFile: tokenPath, want: []string{"Bearer bootstrap-token"}},
} {
t.Run(tt.name, func(t *testing.T) {
fake.mu.Lock()
fake.tokens = nil
fake.mu.Unlock()
filer, tokenFile := address, tt.tokenFile
_, _, _, bucketRoot, ok := connectToFiler(&MountOptions{filer: &filer, filerTokenFile: &tokenFile})
if !ok || bucketRoot != "/buckets" {
t.Fatalf("connectToFiler ok=%v bucketRoot=%q", ok, bucketRoot)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.tokens) != 1 || strings.Join(fake.tokens[0], ",") != strings.Join(tt.want, ",") {
t.Fatalf("authorization = %q, want %q", fake.tokens, tt.want)
}
})
}
}
+10
View File
@@ -34,6 +34,11 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
fmt.Println(err)
return false
}
cacheMinFree, parseErr := parseCacheMinFreeSpace(option)
if parseErr != nil {
fmt.Println(parseErr)
return false
}
chunkSizeLimitMB := *mountOptions.chunkSizeLimitMB
if chunkSizeLimitMB <= 0 {
@@ -44,6 +49,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
fmt.Println("-idmap is only supported on Linux")
return false
}
if err := checkFilerTokenFile(option); err != nil {
fmt.Println(err)
return false
}
dir := *option.dir
if dir == "" {
@@ -105,6 +114,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
chunkSizeLimitMB: chunkSizeLimitMB,
cacheDirForRead: cacheDirForRead,
cacheDirForWrite: cacheDirForWrite,
cacheMinFree: cacheMinFree,
// WinFsp posts the cleanup and close that carry the flush after
// CloseHandle has already returned, so entry creation cannot wait
// for the flush the way it does when close(2) runs it synchronously.
+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 {
+32 -4
View File
@@ -19,6 +19,7 @@ import (
"google.golang.org/grpc/reflection"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
@@ -58,6 +59,11 @@ type S3Options struct {
portLance *int
icebergCredentialRole *string
icebergCredentialDuration *int
// icebergCredentialMinDuration is the floor of a catalog-vended session
// that asked for a shorter lifetime (-iceberg.credentialMinDurationSeconds).
icebergCredentialMinDuration *int
config *string
iamConfig *string
domainName *string
@@ -108,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() {
@@ -122,6 +131,7 @@ func init() {
s3StandaloneOptions.portLance = cmdS3.Flag.Int("port.lance", 9101, "Lance Namespace server listen port (0 to disable); credential vending uses -iceberg.credentialRole")
s3StandaloneOptions.icebergCredentialRole = cmdS3.Flag.String("iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
s3StandaloneOptions.icebergCredentialDuration = cmdS3.Flag.Int("iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
s3StandaloneOptions.icebergCredentialMinDuration = cmdS3.Flag.Int("iceberg.credentialMinDurationSeconds", 900, "shortest session a client may ask the Iceberg catalog to vend (header X-SeaweedFS-Credential-Duration-Seconds); 1-900, other STS actions keep 900")
s3StandaloneOptions.domainName = cmdS3.Flag.String("domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
s3StandaloneOptions.allowedOrigins = cmdS3.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
s3StandaloneOptions.dataCenter = cmdS3.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
@@ -679,6 +689,14 @@ func (s3opt *S3Options) setCredentialRole(s3ApiServer *s3api.S3ApiServer) {
duration = int64(*s3opt.icebergCredentialDuration)
}
s3ApiServer.SetIcebergCredentialRole(*s3opt.icebergCredentialRole, duration)
if s3opt.icebergCredentialMinDuration != nil {
minDuration := int64(*s3opt.icebergCredentialMinDuration)
if minDuration <= 0 || minDuration > sts.MinSessionDurationSeconds {
glog.Warningf("Iceberg: credentialMinDurationSeconds=%d is outside 1-%d; vended sessions keep a %d s floor",
minDuration, sts.MinSessionDurationSeconds, sts.MinSessionDurationSeconds)
}
s3ApiServer.SetIcebergCredentialMinDuration(minDuration)
}
}
// startIcebergServer starts the Iceberg REST Catalog server on a separate port.
@@ -733,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})
}
@@ -948,8 +975,8 @@ type icebergCredentialVendor struct {
server *s3api.S3ApiServer
}
func (v icebergCredentialVendor) VendTableCredentials(ctx context.Context, principal, bucket, prefix string, readOnly bool) (*iceberg.VendedCredentials, error) {
credentials, err := v.server.VendTableCredentials(ctx, principal, bucket, prefix, readOnly)
func (v icebergCredentialVendor) VendTableCredentials(ctx context.Context, principal, bucket, prefix string, readOnly bool, requestedSeconds int64) (*iceberg.VendedCredentials, error) {
credentials, err := v.server.VendTableCredentials(ctx, principal, bucket, prefix, readOnly, requestedSeconds)
if err != nil || credentials == nil {
return nil, err
}
@@ -968,7 +995,8 @@ type lanceCredentialVendor struct {
}
func (v lanceCredentialVendor) VendTableCredentials(ctx context.Context, principal, bucket, prefix string, readOnly bool) (*lance.VendedCredentials, error) {
credentials, err := v.server.VendTableCredentials(ctx, principal, bucket, prefix, readOnly)
// Lance has no way to ask for a shorter session: the configured lifetime.
credentials, err := v.server.VendTableCredentials(ctx, principal, bucket, prefix, readOnly, 0)
if err != nil || credentials == nil {
return nil, err
}
+1 -1
View File
@@ -86,7 +86,7 @@ func TestCredentialRoleIsSetForBothCatalogs(t *testing.T) {
t.Fatal("a role is configured but vending is reported off")
}
// With no role, vending is off and answers nil without checking anything.
if _, err := s3a.VendTableCredentials(context.Background(), "", "bkt", "vector/x", true); err == nil {
if _, err := s3a.VendTableCredentials(context.Background(), "", "bkt", "vector/x", true, 0); err == nil {
t.Fatal("vending is off: the credential role was not set")
}
}
+2 -1
View File
@@ -45,7 +45,8 @@ bucket = "your_bucket_name" # an existing bucket
endpoint = ""
storage_class = "STANDARD_IA"
# optional HTTP client tuning for S3-compatible services:
# disable_http2 = false # true keeps the client on HTTP/1.1, one connection per concurrent request
# disable_http2 = false # true keeps the client on HTTP/1.1, one connection per concurrent request,
# # with a 30s response header timeout and 5 retries
# max_connections = 0 # cap on connections to the endpoint, 0 = no cap
# idle_connection_timeout_seconds = 0 # close idle connections sooner, 0 = Go default (90s)
+2 -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")
@@ -184,6 +184,7 @@ func init() {
s3Options.portLance = cmdServer.Flag.Int("s3.port.lance", 9101, "Lance Namespace server listen port (0 to disable)")
s3Options.icebergCredentialRole = cmdServer.Flag.String("s3.iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
s3Options.icebergCredentialDuration = cmdServer.Flag.Int("s3.iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
s3Options.icebergCredentialMinDuration = cmdServer.Flag.Int("s3.iceberg.credentialMinDurationSeconds", 900, "shortest session a client may ask the Iceberg catalog to vend (header X-SeaweedFS-Credential-Duration-Seconds); 1-900, other STS actions keep 900")
s3Options.domainName = cmdServer.Flag.String("s3.domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
s3Options.allowedOrigins = cmdServer.Flag.String("s3.allowedOrigins", "*", "comma separated list of allowed origins")
s3Options.dataCenter = cmdServer.Flag.String("s3.dataCenter", "", "prefer to read and write to volumes in this data center")
+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.
@@ -19,6 +19,9 @@ type SqlGenerator interface {
GetSqlInsert(tableName string) string
GetSqlUpdate(tableName string) string
GetSqlFind(tableName string) string
// GetSqlFindBatch selects dirhash, name, directory and meta of the rows
// matching count (dirhash, name, directory) triples, as GetSqlFind does one.
GetSqlFindBatch(tableName string, count int) string
GetSqlDelete(tableName string) string
GetSqlDeleteFolderChildren(tableName string) string
GetSqlListExclusive(tableName string) string
@@ -76,6 +76,51 @@ func (store *AbstractSqlStore) KvGet(ctx context.Context, key []byte) (value []b
return
}
// kvBatchGetSize bounds the keys of one query, well under the bind parameter
// limit of every SQL store.
const kvBatchGetSize = 256
func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
db := store.kvDB(ctx)
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
type row struct {
dirHash int64
name, directory string
}
asked := make(map[row][]string, len(batch))
args := make([]interface{}, 0, 3*len(batch))
for _, key := range batch {
dirStr, dirHash, name := GenDirAndName(key)
r := row{dirHash, name, dirStr}
asked[r] = append(asked[r], string(key))
args = append(args, dirHash, name, dirStr)
}
if err := func() error {
rows, err := db.QueryContext(ctx, store.GetSqlFindBatch(DEFAULT_TABLE, len(batch)), args...)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var r row
var value []byte
if err := rows.Scan(&r.dirHash, &r.name, &r.directory, &value); err != nil {
return err
}
for _, key := range asked[r] {
values[key] = value
}
}
return rows.Err()
}(); err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
}
return values, nil
}
func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err error) {
db := store.kvDB(ctx)
+26
View File
@@ -44,6 +44,32 @@ func (store *ArangodbStore) KvGet(ctx context.Context, key []byte) (value []byte
return arrayToBytes(model.Meta), nil
}
func (store *ArangodbStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
if len(keys) == 0 {
return values, nil
}
docKeys := make([]string, len(keys))
for i, key := range keys {
docKeys[i] = hashString(".kvstore." + string(key))
}
models := make([]Model, len(keys))
_, errs, err := store.kvCollection.ReadDocuments(ctx, docKeys, models)
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
for i, key := range keys {
if i < len(errs) && errs[i] != nil {
if driver.IsNotFound(errs[i]) {
continue
}
return nil, fmt.Errorf("kv batch get: %w", errs[i])
}
values[string(key)] = arrayToBytes(models[i].Meta)
}
return values, nil
}
func (store *ArangodbStore) KvDelete(ctx context.Context, key []byte) (err error) {
_, err = store.kvCollection.RemoveDocument(ctx, hashString(".kvstore."+string(key)))
if err != nil {
@@ -0,0 +1,39 @@
package arangodb
import (
"context"
"crypto/rand"
"fmt"
"testing"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
var keys [][]byte
want := map[string][]byte{}
for i := 0; i < 30; i++ {
key := make([]byte, 16)
rand.Read(key)
keys = append(keys, key)
if i%3 != 0 {
want[string(key)] = []byte(fmt.Sprintf("value-%d", i))
if err := store.KvPut(ctx, key, want[string(key)]); err != nil {
t.Fatal(err)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != len(want) {
t.Fatalf("%d values, want %d", len(values), len(want))
}
for key, value := range want {
if string(values[key]) != string(value) {
t.Fatalf("key %x: %q, want %q", key, values[key], value)
}
}
}
@@ -41,6 +41,14 @@ func (store *CassandraStore) KvGet(ctx context.Context, key []byte) (data []byte
return data, nil
}
// KvBatchGet runs the reads concurrently: CQL has no read of several
// partitions that is cheaper than one query each.
func (store *CassandraStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *CassandraStore) KvDelete(ctx context.Context, key []byte) (err error) {
dir, name := genDirAndName(key)
@@ -42,6 +42,14 @@ func (store *Cassandra2Store) KvGet(ctx context.Context, key []byte) (data []byt
return data, nil
}
// KvBatchGet runs the reads concurrently: CQL has no read of several
// partitions that is cheaper than one query each.
func (store *Cassandra2Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *Cassandra2Store) KvDelete(ctx context.Context, key []byte) (err error) {
dir, name := genDirAndName(key)
@@ -50,6 +50,15 @@ func (store *ElasticStore) KvGet(ctx context.Context, key []byte) (value []byte,
return value, filer.ErrKvNotFound
}
// KvBatchGet runs the reads concurrently. A multi-get sends the ids in its
// JSON body, which does not carry a key that is not UTF-8 the way the URL of
// KvGet and KvPut does.
func (store *ElasticStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *ElasticStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
esEntry := &ESKVEntry{value}
val, err := jsoniter.Marshal(esEntry)
@@ -0,0 +1,52 @@
//go:build elastic
package elastic
import (
"context"
"crypto/rand"
"fmt"
"os"
"testing"
elastic "github.com/olivere/elastic/v7"
)
func TestKvBatchGetReadsWhatKvGetReads(t *testing.T) {
url := os.Getenv("ELASTIC_URL")
if url == "" {
t.Skip("set ELASTIC_URL to an Elasticsearch server to run")
}
store := &ElasticStore{}
if err := store.initialize([]elastic.ClientOptionFunc{elastic.SetURL(url), elastic.SetSniff(false)}); err != nil {
t.Fatal(err)
}
ctx := context.Background()
keys := [][]byte{[]byte("plain-key")}
for i := 0; i < 20; i++ {
key := make([]byte, 17)
rand.Read(key)
keys = append(keys, key)
}
for i, key := range keys {
if i%3 != 2 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
for i, key := range keys {
value, kvErr := store.KvGet(ctx, key)
if got, found := values[string(key)]; string(got) != string(value) || found != (kvErr == nil) {
t.Fatalf("key %d: batch read %q (found %v), KvGet read %q (%v)", i, got, found, value, kvErr)
}
}
if string(values["plain-key"]) != "value-0" {
t.Fatalf("plain-key: %q", values["plain-key"])
}
}
+29
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"github.com/seaweedfs/seaweedfs/weed/filer"
clientv3 "go.etcd.io/etcd/client/v3"
)
// KvPut has no request deadline, like InsertEntry: the filer stores a hard-linked
@@ -38,6 +39,34 @@ func (store *EtcdStore) KvGet(ctx context.Context, key []byte) (value []byte, er
return resp.Kvs[0].Value, nil
}
// kvBatchGetSize keeps a transaction within etcd's default --max-txn-ops.
const kvBatchGetSize = 128
// KvBatchGet reads the keys with one read-only transaction per kvBatchGetSize.
func (store *EtcdStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
opCtx, cancel := store.withTimeout(ctx)
defer cancel()
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
ops := make([]clientv3.Op, len(batch))
for i, key := range batch {
ops[i] = clientv3.OpGet(store.etcdKeyPrefix+string(key), atScanRevision(ctx)...)
}
resp, err := store.client.Txn(opCtx).Then(ops...).Commit()
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
for i, r := range resp.Responses {
if kvs := r.GetResponseRange().GetKvs(); len(kvs) > 0 {
values[string(batch[i])] = kvs[0].Value
}
}
}
return values, nil
}
func (store *EtcdStore) KvDelete(ctx context.Context, key []byte) (err error) {
opCtx, cancel := store.withTimeout(ctx)
defer cancel()
@@ -0,0 +1,65 @@
package etcd
import (
"context"
"fmt"
"os"
"testing"
"time"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
addr := os.Getenv("ETCD_ADDR")
if addr == "" {
t.Skip("set ETCD_ADDR to an etcd server to run")
}
store := &EtcdStore{etcdKeyPrefix: fmt.Sprintf("kvbatch%d/", time.Now().UnixNano()), timeout: 3 * time.Second}
if err := store.initialize(addr, "", "", 3*time.Second, nil); err != nil {
t.Fatal(err)
}
defer store.Shutdown()
ctx := context.Background()
var keys [][]byte
for i := 0; i < 300; i++ {
key := []byte(fmt.Sprintf("hardlink-%04d", i))
keys = append(keys, key)
if i%3 != 0 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
if len(values) != 200 {
t.Fatalf("%d values, want 200", len(values))
}
for i := 0; i < 300; i++ {
value, found := values[fmt.Sprintf("hardlink-%04d", i)]
if i%3 == 0 {
if found {
t.Fatalf("key %d was never written but read %q", i, value)
}
} else if want := fmt.Sprintf("value-%d", i); string(value) != want {
t.Fatalf("key %d: %q, want %q", i, value, want)
}
}
rev, err := store.client.Get(ctx, store.etcdKeyPrefix+"hardlink-0001")
if err != nil {
t.Fatal(err)
}
if err := store.KvPut(ctx, keys[1], []byte("newer")); err != nil {
t.Fatal(err)
}
values, err = store.KvBatchGet(context.WithValue(ctx, scanRevisionKey{}, rev.Header.Revision), keys[1:3])
if err != nil {
t.Fatal(err)
}
if string(values["hardlink-0001"]) != "value-1" {
t.Fatalf("read %q at the scan revision, want value-1", values["hardlink-0001"])
}
}
+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")
}
})
}
}
}
}
+3 -2
View File
@@ -1,6 +1,7 @@
package filer
import (
"cmp"
"container/list"
"slices"
@@ -37,10 +38,10 @@ func readResolvedChunks(chunks []*filer_pb.FileChunk, startOffset int64, stopOff
}
slices.SortFunc(points, func(a, b *Point) int {
if a.x != b.x {
return int(a.x - b.x)
return cmp.Compare(a.x, b.x)
}
if a.ts != b.ts {
return int(a.ts - b.ts)
return cmp.Compare(a.ts, b.ts)
}
if a.order != b.order {
return a.order - b.order
+88
View File
@@ -0,0 +1,88 @@
package filer_test
import (
"context"
"math"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func TestSparseChunkViewsPreserveOffsetOrder(t *testing.T) {
for _, offset := range []int64{1 << 30, (1 << 31) - 1, 1 << 31, (1 << 31) + 1, 3 << 30, 1 << 32, math.MaxInt64 - 1} {
chunks := []*filer_pb.FileChunk{
{FileId: "1,0000000100000001", Offset: 0, Size: 1, ModifiedTsNs: 1},
{FileId: "1,0000000200000002", Offset: offset, Size: 1, ModifiedTsNs: 2},
}
views, err := filer.ViewFromChunks(context.Background(), nil, chunks, 0, math.MaxInt64)
if err != nil {
t.Fatal(err)
}
var starts []int64
for x := views.Front(); x != nil; x = x.Next {
starts = append(starts, x.StartOffset)
}
if len(starts) != 2 || starts[0] != 0 || starts[1] != offset {
t.Errorf("offset=%d: views at %v, want [0 %d]", offset, starts, offset)
}
}
}
type chunkOrderByteCache struct{}
func (*chunkOrderByteCache) ReadChunkAt(data []byte, fileID string, _ uint64) (int, error) {
value := byte(0xCD)
if fileID == "1,0000000100000001" {
value = 0xAB
}
for i := range data {
data[i] = value
}
return len(data), nil
}
func (*chunkOrderByteCache) SetChunk(string, []byte) {}
func (*chunkOrderByteCache) IsInCache(string, bool) bool { return true }
func (*chunkOrderByteCache) GetMaxFilePartSizeInCache() uint64 { return 1 << 20 }
func TestSparseChunkReadPreservesFirstByte(t *testing.T) {
const farOffset = int64(3 << 30)
chunks := []*filer_pb.FileChunk{
{FileId: "1,0000000100000001", Offset: 0, Size: 1, ModifiedTsNs: 1},
{FileId: "1,0000000200000002", Offset: farOffset, Size: 1, ModifiedTsNs: 2},
}
views, err := filer.ViewFromChunks(context.Background(), nil, chunks, 0, math.MaxInt64)
if err != nil {
t.Fatal(err)
}
cache := filer.NewReaderCache(1, &chunkOrderByteCache{}, nil, nil)
reader := filer.NewChunkReaderAtFromClient(context.Background(), cache, views, farOffset+1, 0)
defer reader.Close()
buf := []byte{0xFF}
n, err := reader.ReadAt(buf, 0)
if err != nil || n != 1 || buf[0] != 0xAB {
t.Fatalf("first stored byte must be 0xAB; got n=%d err=%v data=%x", n, err, buf)
}
}
func TestChunkViewsPreserveTimestampPriority(t *testing.T) {
for _, timestamps := range [][2]int64{{1, 1 + (3 << 30)}, {math.MinInt64, math.MaxInt64}} {
chunks := []*filer_pb.FileChunk{
{FileId: "1,0000000100000001", Offset: 0, Size: 2, ModifiedTsNs: timestamps[0]},
{FileId: "1,0000000200000002", Offset: 0, Size: 1, ModifiedTsNs: timestamps[1]},
}
views, err := filer.ViewFromChunks(context.Background(), nil, chunks, 0, 2)
if err != nil {
t.Fatal(err)
}
var ids []string
var offsets []int64
for view := views.Front(); view != nil; view = view.Next {
ids = append(ids, view.Value.FileId)
offsets = append(offsets, view.StartOffset)
}
if len(ids) != 2 || ids[0] != chunks[1].FileId || ids[1] != chunks[0].FileId || offsets[0] != 0 || offsets[1] != 1 {
t.Fatalf("timestamps=%v: got file IDs %v at offsets %v; newer chunk must cover [0,1), older chunk [1,2)", timestamps, ids, offsets)
}
}
}
+1
View File
@@ -26,6 +26,7 @@ const (
DirectoryEtcRoot = "/etc/"
DirectoryEtcSeaweedFS = "/etc/seaweedfs"
DirectoryEtcRemote = "/etc/remote"
SyncCursorDir = DirectoryEtcSeaweedFS + "/filer_sync"
FilerConfName = "filer.conf"
IamConfigDirectory = "/etc/iam"
IamIdentityFile = "identity.json"
+7 -4
View File
@@ -200,7 +200,10 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
var chunksToDelete, fsyncChunksToDelete []*filer_pb.FileChunk
lastFileName := ""
includeLastFile := false
listedChildren := !isDeletingBucket || !f.Store.CanDropWholeBucket()
// A store that keeps each bucket apart drops a deleted bucket whole, so
// only a non-recursive delete lists it, to refuse one that has children.
dropsWholeBucket := isDeletingBucket && f.Store.CanDropWholeBucket()
listedChildren := !dropsWholeBucket || !isRecursive
if listedChildren {
for {
entries, _, err := f.ListDirectoryEntries(ctx, entry.FullPath, lastFileName, includeLastFile, PaginationSize, "", "", "")
@@ -265,9 +268,9 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
glog.V(3).InfofCtx(ctx, "deleting directory %v delete chunks: %v", entry.FullPath, shouldDeleteChunks)
// a non-recursive delete already proved the folder empty above, so sweeping the
// children now can only remove entries that raced in after that listing
if isRecursive || !listedChildren {
// a non-recursive delete proved the folder empty above and sweeps only to
// free an empty bucket the store keeps apart
if isRecursive || dropsWholeBucket {
if storeDeletionErr := f.Store.DeleteFolderChildren(ctx, entry.FullPath); storeDeletionErr != nil {
return fmt.Errorf("filer store delete: %w", storeDeletionErr)
}
@@ -0,0 +1,150 @@
package filer
import (
"context"
"errors"
"os"
"reflect"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// wholeBucketStore drops a deleted bucket's entries in one call, the way
// leveldb3 and the SQL stores with a table per bucket do.
type wholeBucketStore struct {
*hookedStore
mu sync.Mutex
dropped []util.FullPath
}
func (s *wholeBucketStore) OnBucketCreation(string) {}
func (s *wholeBucketStore) OnBucketDeletion(string) {}
func (s *wholeBucketStore) CanDropWholeBucket() bool {
return true
}
func (s *wholeBucketStore) DeleteFolderChildren(ctx context.Context, p util.FullPath) error {
s.mu.Lock()
s.dropped = append(s.dropped, p)
s.mu.Unlock()
return s.hookedStore.DeleteFolderChildren(ctx, p)
}
func (s *wholeBucketStore) droppedFolders() []util.FullPath {
s.mu.Lock()
defer s.mu.Unlock()
return append([]util.FullPath(nil), s.dropped...)
}
func newFilerOnWholeBucketStore(t *testing.T) (*Filer, *wholeBucketStore, *collectionDeleteMaster) {
t.Helper()
f, store, master := newFilerWithFakeMaster(t)
bucketStore := &wholeBucketStore{hookedStore: store}
f.Store = NewFilerStoreWrapper(bucketStore)
return f, bucketStore, master
}
func seedObject(t *testing.T, store *wholeBucketStore, path util.FullPath) {
t.Helper()
if err := store.InsertEntry(context.Background(), &Entry{
FullPath: path,
Attr: Attr{Mode: 0644},
}); err != nil {
t.Fatalf("seed object %s: %v", path, err)
}
}
// A non-recursive delete of a bucket that still holds objects is refused on a
// store that drops whole buckets, as on every other store. rmdir on a mount,
// fs.rm without -r and an HTTP DELETE without recursive=true all send one.
// The store's whole-bucket drop used to skip the listing that refuses it, so
// the delete went through: the objects' entries went with the bucket, then the
// bucket's collection was deleted, volumes and all.
func TestNonRecursiveDeleteKeepsNonEmptyBucketOnWholeBucketStore(t *testing.T) {
f, store, master := newFilerOnWholeBucketStore(t)
seedBucket(t, store.hookedStore, "/buckets/photos")
seedObject(t, store, "/buckets/photos/cat.jpg")
err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/photos", false, false, true, false, nil, time.Time{})
if !errors.Is(err, ErrNonEmptyFolder) {
t.Fatalf("non-recursive delete of a non-empty bucket = %v, want ErrNonEmptyFolder", err)
}
for _, p := range []string{"/buckets/photos", "/buckets/photos/cat.jpg"} {
if store.getEntry(p) == nil {
t.Errorf("%s is gone after the refused delete", p)
}
}
if dropped := store.droppedFolders(); len(dropped) != 0 {
t.Errorf("the refused delete dropped %v", dropped)
}
select {
case call := <-master.calls:
t.Errorf("the refused delete deleted collection %q", call.name)
default:
}
}
// An empty bucket still goes the store's way: one drop of the bucket, which
// also frees whatever the store keeps per bucket, then its collection.
func TestNonRecursiveDeleteDropsEmptyBucketOnWholeBucketStore(t *testing.T) {
f, store, master := newFilerOnWholeBucketStore(t)
seedBucket(t, store.hookedStore, "/buckets/empty")
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/empty", false, false, true, false, nil, time.Time{}); err != nil {
t.Fatalf("non-recursive delete of an empty bucket: %v", err)
}
if store.getEntry("/buckets/empty") != nil {
t.Error("the bucket entry is still there")
}
if got, want := store.droppedFolders(), []util.FullPath{"/buckets/empty"}; !reflect.DeepEqual(got, want) {
t.Errorf("dropped %v, want %v", got, want)
}
select {
case call := <-master.calls:
if call.name != "empty" {
t.Errorf("CollectionDelete = %q, want %q", call.name, "empty")
}
case <-time.After(20 * time.Second):
t.Fatal("CollectionDelete never reached the master")
}
}
// A recursive delete keeps the shortcut: the store drops the bucket with its
// objects, without the filer walking them first.
func TestRecursiveDeleteDropsNonEmptyBucketOnWholeBucketStore(t *testing.T) {
f, store, master := newFilerOnWholeBucketStore(t)
seedBucket(t, store.hookedStore, "/buckets/logs")
if err := store.InsertEntry(context.Background(), &Entry{
FullPath: "/buckets/logs/2026",
Attr: Attr{Mode: os.ModeDir | 0755},
}); err != nil {
t.Fatalf("seed directory: %v", err)
}
seedObject(t, store, "/buckets/logs/2026/app.log")
if err := f.DeleteEntryMetaAndData(context.Background(), "/buckets/logs", true, false, true, false, nil, time.Time{}); err != nil {
t.Fatalf("recursive delete of a non-empty bucket: %v", err)
}
for _, p := range []string{"/buckets/logs", "/buckets/logs/2026", "/buckets/logs/2026/app.log"} {
if store.getEntry(p) != nil {
t.Errorf("%s is still there", p)
}
}
if got, want := store.droppedFolders(), []util.FullPath{"/buckets/logs"}; !reflect.DeepEqual(got, want) {
t.Errorf("dropped %v, want the bucket alone, without a walk of its children: %v", got, want)
}
select {
case call := <-master.calls:
if call.name != "logs" {
t.Errorf("CollectionDelete = %q, want %q", call.name, "logs")
}
case <-time.After(20 * time.Second):
t.Fatal("CollectionDelete never reached the master")
}
}
+4
View File
@@ -671,6 +671,10 @@ func (s *versionedStore) KvGet(ctx context.Context, key []byte) ([]byte, error)
return value, err
}
func (s *versionedStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *versionedStore) KvPut(ctx context.Context, key []byte, value []byte) error {
if txn := s.txn(ctx); txn != nil {
txn.keys[string(key)] = append([]byte{}, value...)
+65 -38
View File
@@ -14,9 +14,10 @@ import (
)
// What a listing reads the store for besides the listing itself: the shared
// record of every hard-linked entry. A store that reads KV keys in batches is
// asked for the records of the waiting entries together; the caller of the
// listing must not be able to tell, except by how long it takes.
// record of every hard-linked entry. The store is asked for the records of the
// waiting entries together; the caller of the listing must not be able to tell
// that from a listing that reads each record as its entry arrives, except by
// how long it takes.
// rowListingStore hands over an entry of its own for each name it lists, as a
// store that decodes rows does. It can fail a listing part of the way.
@@ -62,7 +63,7 @@ func (s *rowListingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirP
}, eachEntryFunc)
}
// batchReadingStore also reads KV keys in batches.
// batchReadingStore also records the batches it is asked for.
type batchReadingStore struct {
*rowListingStore
batches [][]string // the keys of each batch it was asked for
@@ -89,9 +90,9 @@ func (s *batchReadingStore) KvBatchGet(_ context.Context, keys [][]byte) (map[st
return values, nil
}
// linkListingStores returns the same directory in a store that reads records
// one at a time and in one that reads them in batches, each with a count of
// the single reads it serves.
// linkListingStores returns the same directory in two stores, one to list with
// oneAtATime and one that records its batches, each with a count of the single
// reads it serves.
func linkListingStores(t *testing.T, fill func(store *stubFilerStore)) (oneByOne *rowListingStore, oneReads *int, batched *batchReadingStore, batchedReads *int) {
t.Helper()
build := func() (*rowListingStore, *int) {
@@ -148,9 +149,31 @@ func see(entry *Entry) listed {
}
}
func listAll(t *testing.T, store FilerStore, dir string, startFileName string, limit int64) (entries []listed, lastFileName string) {
type lister func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error)
// throughWrapper lists as the filer does.
func throughWrapper(store FilerStore) lister {
return func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error) {
return NewFilerStoreWrapper(store).ListDirectoryEntries(ctx, dir, startFileName, false, limit, each)
}
}
// oneAtATime lists reading each record as its entry arrives, and hands the
// entry on before the store lists the next one.
func oneAtATime(store FilerStore) lister {
fsw := NewFilerStoreWrapper(store)
return func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error) {
return store.ListDirectoryEntries(ctx, dir, startFileName, false, limit, func(entry *Entry) (bool, error) {
fsw.maybeReadHardLink(ctx, entry)
filer_pb.AfterEntryDeserialization(entry.GetChunks())
return each(entry)
})
}
}
func listAll(t *testing.T, list lister, dir string, startFileName string, limit int64) (entries []listed, lastFileName string) {
t.Helper()
lastFileName, err := NewFilerStoreWrapper(store).ListDirectoryEntries(context.Background(), util.FullPath(dir), startFileName, false, limit, func(entry *Entry) (bool, error) {
lastFileName, err := list(context.Background(), util.FullPath(dir), startFileName, limit, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return true, nil
})
@@ -175,8 +198,8 @@ func mixedDirectory(t *testing.T) func(store *stubFilerStore) {
func TestListingReadsHardLinkRecordsTogether(t *testing.T) {
oneByOne, oneReads, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
want, wantLast := listAll(t, oneByOne, "/d", "", 100)
got, gotLast := listAll(t, batched, "/d", "", 100)
want, wantLast := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
got, gotLast := listAll(t, throughWrapper(batched), "/d", "", 100)
require.Equal(t, []string{"a", "b", "c", "d", "e", "f", "g"}, namesOf(want))
require.Equal(t, listed{Name: "b", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}, want[1], "a linked name lists what its record holds")
@@ -227,8 +250,8 @@ func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
}
})
want, _ := listAll(t, oneByOne, "/d", "", names+1)
got, lastFileName := listAll(t, batched, "/d", "", names+1)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", names+1)
got, lastFileName := listAll(t, throughWrapper(batched), "/d", "", names+1)
require.Len(t, got, names)
require.Equal(t, want, got)
@@ -244,7 +267,7 @@ func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
const pageSize = hardLinkBatchSize + 100
var paged []listed
for start := ""; ; {
page, last := listAll(t, batched, "/d", start, pageSize)
page, last := listAll(t, throughWrapper(batched), "/d", start, pageSize)
paged = append(paged, page...)
if len(page) < pageSize {
break
@@ -260,7 +283,7 @@ func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
// is given back has every one of them.
func TestListingEndedByItsCallerContinuesFromWhereItEnded(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
want, _ := listAll(t, oneByOne, "/d", "", 100)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
for stopAt := 1; stopAt <= len(want); stopAt++ {
var got []listed
@@ -272,7 +295,7 @@ func TestListingEndedByItsCallerContinuesFromWhereItEnded(t *testing.T) {
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
rest, _ := listAll(t, batched, "/d", lastFileName, 100)
rest, _ := listAll(t, throughWrapper(batched), "/d", lastFileName, 100)
require.Equal(t, want[stopAt:], append([]listed{}, rest...), "continued after entry %d", stopAt)
}
}
@@ -297,13 +320,13 @@ func TestListingReturnsItsCallersError(t *testing.T) {
}
}
// The records are then read one at a time, as from a store without batches.
// The records are then read one at a time.
func TestListingReadsRecordsOneByOneWhenTheBatchFails(t *testing.T) {
oneByOne, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
batched.batchErr = errors.New("region unavailable")
want, _ := listAll(t, oneByOne, "/d", "", 100)
got, _ := listAll(t, batched, "/d", "", 100)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
got, _ := listAll(t, throughWrapper(batched), "/d", "", 100)
require.Equal(t, want, got)
require.Equal(t, 4, *batchedReads)
@@ -315,7 +338,7 @@ func TestListingReadsRecordsOneByOneWhenTheBatchFails(t *testing.T) {
func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
broken := errors.New("iterator closed")
want, _ := listAll(t, oneByOne, "/d", "", 100)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
for failAfter := 0; failAfter <= 6; failAfter++ {
batched.failAfter, batched.listErr = failAfter, broken
@@ -330,8 +353,8 @@ func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
}
// listUntil lists dir and ends the listing at its entry numbered stopAt.
func listUntil(store FilerStore, dir string, stopAt int) (entries []listed, lastFileName string, err error) {
lastFileName, err = NewFilerStoreWrapper(store).ListDirectoryEntries(context.Background(), util.FullPath(dir), "", false, 100000, func(entry *Entry) (bool, error) {
func listUntil(list lister, dir string, stopAt int) (entries []listed, lastFileName string, err error) {
lastFileName, err = list(context.Background(), util.FullPath(dir), "", 100000, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return len(entries) < stopAt, nil
})
@@ -344,17 +367,17 @@ func listUntil(store FilerStore, dir string, stopAt int) (entries []listed, last
// ends where the caller ended it, and its own failure is the one it gets.
func TestListingEndedByItsCallerIsNotFailedByWhatTheStoreMetBehind(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
want, _ := listAll(t, oneByOne, "/d", "", 100)
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
broken := errors.New("iterator closed")
// the store hands over a to e and then fails; b to e wait for their records
oneByOne.failAfter, oneByOne.listErr = 5, broken
batched.failAfter, batched.listErr = 5, broken
for stopAt := 1; stopAt <= 5; stopAt++ {
_, _, err := listUntil(oneByOne, "/d", stopAt)
_, _, err := listUntil(oneAtATime(oneByOne), "/d", stopAt)
require.NoError(t, err, "one at a time, ended at entry %d", stopAt)
got, lastFileName, err := listUntil(batched, "/d", stopAt)
got, lastFileName, err := listUntil(throughWrapper(batched), "/d", stopAt)
require.NoError(t, err, "ended at entry %d", stopAt)
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
@@ -392,8 +415,8 @@ func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
batched.failStopAt, batched.stopErr = hardLinkBatchSize, broken
for _, stopAt := range []int{1, 10, hardLinkBatchSize - 1, hardLinkBatchSize, hardLinkBatchSize + 1, names} {
want, wantLast, wantErr := listUntil(oneByOne, "/d", stopAt)
got, gotLast, gotErr := listUntil(batched, "/d", stopAt)
want, wantLast, wantErr := listUntil(oneAtATime(oneByOne), "/d", stopAt)
got, gotLast, gotErr := listUntil(throughWrapper(batched), "/d", stopAt)
require.Equal(t, stopAt == hardLinkBatchSize, wantErr != nil, "one at a time, ended at entry %d", stopAt)
require.Equal(t, wantErr, gotErr, "ended at entry %d", stopAt)
@@ -404,17 +427,18 @@ func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
}
}
// The records are in the default store. A directory another store lists keeps
// the read per entry: nothing says that store's listing hands over entries
// that can wait.
func TestListingOfAPathSpecificStoreReadsRecordsOneByOne(t *testing.T) {
// The records are in the default store, and a directory another store lists
// reads them from there together too.
func TestListingOfAPathSpecificStoreReadsRecordsTogether(t *testing.T) {
_, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
other := &rowListingStore{stubFilerStore: newStubFilerStore()}
// the store keeps its paths without the prefix it is mounted at
other.entries["/d/n"] = &Entry{
FullPath: "/d/n",
Attr: Attr{Mode: 0o644},
HardLinkId: HardLinkId("link-x-0123456789"),
for _, name := range []string{"/d/m", "/d/n"} {
other.entries[name] = &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o644},
HardLinkId: HardLinkId("link-x-0123456789"),
}
}
wrapper := NewFilerStoreWrapper(batched)
wrapper.AddPathSpecificStore("/other/", "other", other)
@@ -426,9 +450,12 @@ func TestListingOfAPathSpecificStoreReadsRecordsOneByOne(t *testing.T) {
})
require.NoError(t, err)
require.Equal(t, []listed{{Name: "n", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}}, got)
require.Equal(t, 1, *batchedReads)
require.Empty(t, batched.batches)
linked := listed{Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}
m, n := linked, linked
m.Name, n.Name = "m", "n"
require.Equal(t, []listed{m, n}, got)
require.Zero(t, *batchedReads)
require.Equal(t, [][]string{{"link-x-0123456789"}}, batched.batches)
}
func namesOf(entries []listed) (names []string) {
+6 -2
View File
@@ -107,6 +107,10 @@ func (s *stubFilerStore) KvGet(_ context.Context, key []byte) ([]byte, error) {
}
return append([]byte(nil), value...), nil
}
func (s *stubFilerStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return KvGetEach(ctx, s.KvGet, keys, 1)
}
func (s *stubFilerStore) KvDelete(_ context.Context, key []byte) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -205,7 +209,7 @@ func (s *stubFilerStore) InsertEntry(_ context.Context, entry *Entry) error {
if s.insertErr != nil {
return s.insertErr
}
s.entries[string(entry.FullPath)] = entry
s.entries[string(entry.FullPath)] = entry.ShallowClone()
return nil
}
@@ -215,7 +219,7 @@ func (s *stubFilerStore) UpdateEntry(_ context.Context, entry *Entry) error {
if s.updateErr != nil {
return s.updateErr
}
s.entries[string(entry.FullPath)] = entry
s.entries[string(entry.FullPath)] = entry.ShallowClone()
return nil
}
+3
View File
@@ -39,6 +39,9 @@ func (s *bucketTrackingStore) KvPut(context.Context, []byte, []byte) error { ret
func (s *bucketTrackingStore) KvGet(context.Context, []byte) ([]byte, error) {
return nil, ErrKvNotFound
}
func (s *bucketTrackingStore) KvBatchGet(context.Context, [][]byte) (map[string][]byte, error) {
return map[string][]byte{}, nil
}
func (s *bucketTrackingStore) KvDelete(context.Context, []byte) error { return nil }
func (s *bucketTrackingStore) Shutdown() {}
func (s *bucketTrackingStore) OnBucketCreation(bucket string) { s.created = append(s.created, bucket) }
+24
View File
@@ -0,0 +1,24 @@
package filer
// SyncCursor is what a filer.sync keeps on its source filer under
// SyncCursorDir. TsNs holds back the metadata log purge there; the other
// fields describe the sync for display. The checkpoint stored on the target
// filer stays the authoritative sync position.
type SyncCursor struct {
TsNs int64 `json:"ts_ns"`
SavedNs int64 `json:"saved_ns"`
// Checkpointed is false while a fresh sync has no target checkpoint yet
// and TsNs is held just before the first event it received.
Checkpointed bool `json:"checkpointed"`
ProcessedTsNs int64 `json:"processed_ts_ns,omitempty"`
OldestFailedTsNs int64 `json:"oldest_failed_ts_ns,omitempty"`
SourceFiler string `json:"source_filer"`
SourcePath string `json:"source_path"`
ExcludePaths []string `json:"exclude_paths,omitempty"`
TargetFiler string `json:"target_filer"`
TargetPath string `json:"target_path"`
TargetSignature int32 `json:"target_signature"`
Host string `json:"host,omitempty"`
Version string `json:"version,omitempty"`
SyncStartedNs int64 `json:"sync_started_ns"`
}
+46 -13
View File
@@ -4,8 +4,10 @@ import (
"context"
"errors"
"io"
"sync"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/sync/errgroup"
)
const CountEntryChunksForGzip = 50
@@ -44,11 +46,55 @@ type FilerStore interface {
KvPut(ctx context.Context, key []byte, value []byte) (err error)
KvGet(ctx context.Context, key []byte) (value []byte, err error)
// KvBatchGet returns the values of the keys the store holds, by key. A
// key it does not hold is left out.
KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error)
KvDelete(ctx context.Context, key []byte) (err error)
Shutdown()
}
// KvGetEach reads the keys with kvGet, up to concurrency of them at a time,
// for a store without a batch read of its own. A key not found is left out.
func KvGetEach(ctx context.Context, kvGet func(context.Context, []byte) ([]byte, error), keys [][]byte, concurrency int) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
if concurrency <= 1 {
for _, key := range keys {
value, err := kvGet(ctx, key)
if errors.Is(err, ErrKvNotFound) {
continue
}
if err != nil {
return nil, err
}
values[string(key)] = value
}
return values, nil
}
var mu sync.Mutex
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(concurrency)
for _, key := range keys {
g.Go(func() error {
value, err := kvGet(gCtx, key)
if errors.Is(err, ErrKvNotFound) {
return nil
}
if err != nil {
return err
}
mu.Lock()
values[string(key)] = value
mu.Unlock()
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return values, nil
}
// ErrUnsupportedEntryScan is returned by EntryScanner.ScanEntries, before
// any entry is visited, when the store cannot serve the scan.
var ErrUnsupportedEntryScan = errors.New("entry scan not supported by this filer store")
@@ -72,19 +118,6 @@ type EntryScanner interface {
ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error
}
// KvBatchReader is implemented by a store that reads several KV keys in one
// round trip. A directory listing reads the shared record of every hard-linked
// entry it lists; from such a store it reads the records of a run of entries
// together, instead of one at a time while the store iterates.
//
// The listing keeps the entries the store hands over until their records are
// read, so each of them is an *Entry of its own.
type KvBatchReader interface {
// KvBatchGet returns the values of the keys the store holds, by key. A
// key it does not hold is left out.
KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error)
}
type BucketAware interface {
OnBucketCreation(bucket string)
OnBucketDeletion(bucket string)
+13 -25
View File
@@ -467,36 +467,27 @@ const hardLinkBatchSize = 256
// Read as each entry arrives, that is a round trip to the store for every
// hard-linked name, made one after the other while the store iterates: a
// directory of hard-linked files lists many times slower than one of plain
// files. Where the store that lists is the default store, which holds the
// records, and reads KV keys in batches (KvBatchReader), the entries from the
// first hard-linked one on wait, up to hardLinkBatchSize of them, and their
// records are read together. The caller gets the entries in the order the
// store lists them either way.
// files. Instead the entries from the first hard-linked one on wait, up to
// hardLinkBatchSize of them, and their records are read together with
// KvBatchGet. Every store's listing hands over an *Entry of its own for each
// name, so the entries can wait. The caller gets them in the order the store
// lists them.
type hardLinkListing struct {
fsw *FilerStoreWrapper
ctx context.Context
each ListEachEntryFunc
reader KvBatchReader // nil: a record is read when its entry arrives
held []*Entry // waiting for their records; the first has a hard link
last string // the name of the last entry handed on
ended bool // each ended the listing or failed
passed bool // each ended it at an entry with others waiting behind
held []*Entry // waiting for their records; the first has a hard link
last string // the name of the last entry handed on
ended bool // each ended the listing or failed
passed bool // each ended it at an entry with others waiting behind
}
func (fsw *FilerStoreWrapper) newHardLinkListing(ctx context.Context, actualStore FilerStore, eachEntryFunc ListEachEntryFunc) *hardLinkListing {
listing := &hardLinkListing{fsw: fsw, ctx: ctx, each: eachEntryFunc}
if actualStore == fsw.defaultStore {
listing.reader, _ = actualStore.(KvBatchReader)
}
return listing
func (fsw *FilerStoreWrapper) newHardLinkListing(ctx context.Context, eachEntryFunc ListEachEntryFunc) *hardLinkListing {
return &hardLinkListing{fsw: fsw, ctx: ctx, each: eachEntryFunc}
}
// add takes the next entry of the store's listing.
func (l *hardLinkListing) add(entry *Entry) (bool, error) {
if l.reader == nil {
l.fsw.maybeReadHardLink(l.ctx, entry)
return l.handOn(entry)
}
if len(l.held) == 0 && len(entry.HardLinkId) == 0 {
return l.handOn(entry)
}
@@ -523,14 +514,14 @@ func (l *hardLinkListing) release() (bool, error) {
keys = append(keys, entry.HardLinkId)
}
}
records, batchErr := l.reader.KvBatchGet(l.ctx, keys)
records, batchErr := l.fsw.KvBatchGet(l.ctx, keys)
if batchErr != nil {
glog.ErrorfCtx(l.ctx, "read %d hard link records together: %v", len(keys), batchErr)
}
for i, entry := range held {
if len(entry.HardLinkId) != 0 {
if batchErr != nil {
// one at a time, as from a store without batches
// one at a time
l.fsw.maybeReadHardLink(l.ctx, entry)
} else if record, found := records[string(entry.HardLinkId)]; found {
if err := entry.DecodeAttributesAndChunks(record); err != nil {
@@ -567,9 +558,6 @@ func (l *hardLinkListing) handOn(entry *Entry) (bool, error) {
// error the store ran into past that entry is not the caller's either: handed
// each entry as it arrived, the caller would have stopped the store before.
func (l *hardLinkListing) finish(lastFileName string, err error) (string, error) {
if l.reader == nil {
return lastFileName, err
}
if !l.ended && len(l.held) > 0 {
// The store handed these over and went on, to the end of its listing
// or to an error. Where the caller ends the listing among them, or
+55
View File
@@ -0,0 +1,55 @@
package filer
import (
"context"
"errors"
"sync/atomic"
"testing"
)
func TestKvGetEachLeavesOutMissingKeys(t *testing.T) {
held := map[string][]byte{"a": []byte("1"), "c": []byte("3")}
var running, most atomic.Int32
kvGet := func(_ context.Context, key []byte) ([]byte, error) {
n := running.Add(1)
defer running.Add(-1)
for {
m := most.Load()
if n <= m || most.CompareAndSwap(m, n) {
break
}
}
if v, ok := held[string(key)]; ok {
return v, nil
}
return nil, ErrKvNotFound
}
for _, concurrency := range []int32{1, 2} {
most.Store(0)
values, err := KvGetEach(context.Background(), kvGet, [][]byte{[]byte("a"), []byte("b"), []byte("c"), []byte("a")}, int(concurrency))
if err != nil {
t.Fatal(err)
}
if len(values) != 2 || string(values["a"]) != "1" || string(values["c"]) != "3" {
t.Fatalf("concurrency %d: values = %q", concurrency, values)
}
if most.Load() > concurrency {
t.Fatalf("%d reads at a time, want at most %d", most.Load(), concurrency)
}
}
}
func TestKvGetEachFailsOnAReadError(t *testing.T) {
failure := errors.New("store down")
kvGet := func(_ context.Context, key []byte) ([]byte, error) {
if string(key) == "b" {
return nil, failure
}
return key, nil
}
for _, concurrency := range []int{1, 2} {
if _, err := KvGetEach(context.Background(), kvGet, [][]byte{[]byte("a"), []byte("b")}, concurrency); !errors.Is(err, failure) {
t.Fatalf("concurrency %d: err = %v, want %v", concurrency, err, failure)
}
}
}
+4
View File
@@ -154,6 +154,10 @@ func (t *FilerStorePathTranslator) KvPut(ctx context.Context, key []byte, value
func (t *FilerStorePathTranslator) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
return t.actualStore.KvGet(ctx, key)
}
func (t *FilerStorePathTranslator) KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error) {
return t.actualStore.KvBatchGet(ctx, keys)
}
func (t *FilerStorePathTranslator) KvDelete(ctx context.Context, key []byte) (err error) {
return t.actualStore.KvDelete(ctx, key)
}
+6 -2
View File
@@ -389,7 +389,7 @@ func (fsw *FilerStoreWrapper) ListDirectoryEntries(ctx context.Context, dirPath
stats.FilerStoreHistogram.WithLabelValues(actualStore.GetName(), "list").Observe(time.Since(start).Seconds())
}()
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
listing := fsw.newHardLinkListing(ctx, eachEntryFunc)
defer func() {
lastFileName, err = listing.finish(lastFileName, err)
}()
@@ -411,7 +411,7 @@ func (fsw *FilerStoreWrapper) ListDirectoryPrefixedEntries(ctx context.Context,
if limit > math.MaxInt32-1 {
limit = math.MaxInt32 - 1
}
listing := fsw.newHardLinkListing(ctx, actualStore, eachEntryFunc)
listing := fsw.newHardLinkListing(ctx, eachEntryFunc)
defer func() {
lastFileName, err = listing.finish(lastFileName, err)
}()
@@ -569,6 +569,10 @@ func (fsw *FilerStoreWrapper) KvGet(ctx context.Context, key []byte) (value []by
ctx = context.WithoutCancel(ctx)
return fsw.getDefaultStore().KvGet(ctx, key)
}
func (fsw *FilerStoreWrapper) KvBatchGet(ctx context.Context, keys [][]byte) (values map[string][]byte, err error) {
ctx = context.WithoutCancel(ctx)
return fsw.getDefaultStore().KvBatchGet(ctx, keys)
}
func (fsw *FilerStoreWrapper) KvDelete(ctx context.Context, key []byte) (err error) {
if err := ctx.Err(); err != nil {
return err
@@ -766,6 +766,39 @@ func (store *FoundationDBStore) KvGet(ctx context.Context, key []byte) ([]byte,
return data, nil
}
// KvBatchGet issues every read of one transaction before it waits for any.
func (store *FoundationDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
read := func(rtr fdb.ReadTransaction) (interface{}, error) {
futures := make([]fdb.FutureByteSlice, len(keys))
for i, key := range keys {
futures[i] = rtr.Get(store.kvDir.Pack(tuple.Tuple{key}))
}
values := make(map[string][]byte, len(keys))
for i, future := range futures {
data, err := future.Get()
if err != nil {
return nil, err
}
if data != nil {
values[string(keys[i])] = data
}
}
return values, nil
}
var result interface{}
var err error
if tx, exists := store.getTransactionFromContext(ctx); exists {
result, err = read(tx)
} else {
result, err = store.database.ReadTransact(read)
}
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
return result.(map[string][]byte), nil
}
func (store *FoundationDBStore) KvDelete(ctx context.Context, key []byte) error {
fdbKey := store.kvDir.Pack(tuple.Tuple{key})
@@ -0,0 +1,72 @@
//go:build foundationdb
package foundationdb
import (
"context"
"fmt"
"os"
"testing"
"time"
)
func TestKvBatchGetReadsTheKeysHeld(t *testing.T) {
clusterFile := getTestClusterFile()
if _, err := os.Stat(clusterFile); os.IsNotExist(err) {
t.Skip("FoundationDB cluster file not found, skipping")
}
store := &FoundationDBStore{}
if err := store.initialize(clusterFile, 740); err != nil {
t.Skipf("Failed to initialize FoundationDB store: %v", err)
}
defer store.Shutdown()
ctx := context.Background()
prefix := fmt.Sprintf("kvbatch-%d-", time.Now().UnixNano())
var keys [][]byte
for i := 0; i < 50; i++ {
key := []byte(fmt.Sprintf("%s%02d", prefix, i))
keys = append(keys, key)
if i%3 != 0 {
if err := store.KvPut(ctx, key, []byte(fmt.Sprintf("value-%d", i))); err != nil {
t.Fatal(err)
}
}
}
check := func(values map[string][]byte, rewritten string) {
t.Helper()
for i := 0; i < 50; i++ {
value, found := values[fmt.Sprintf("%s%02d", prefix, i)]
want := fmt.Sprintf("value-%d", i)
if i == 1 && rewritten != "" {
want = rewritten
}
if i%3 == 0 {
if found {
t.Fatalf("key %d was never written but read %q", i, value)
}
} else if string(value) != want {
t.Fatalf("key %d: %q, want %q", i, value, want)
}
}
}
values, err := store.KvBatchGet(ctx, keys)
if err != nil {
t.Fatal(err)
}
check(values, "")
txCtx, err := store.BeginTransaction(ctx)
if err != nil {
t.Fatal(err)
}
defer store.RollbackTransaction(txCtx)
if err := store.KvPut(txCtx, keys[1], []byte("in transaction")); err != nil {
t.Fatal(err)
}
if values, err = store.KvBatchGet(txCtx, keys); err != nil {
t.Fatal(err)
}
check(values, "in transaction")
}
+8
View File
@@ -20,6 +20,14 @@ func (store *HbaseStore) KvGet(ctx context.Context, key []byte) (value []byte, e
return store.doGet(ctx, store.cfKv, key)
}
// KvBatchGet runs the reads concurrently; the client sends the ones bound for
// one region server together.
func (store *HbaseStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, kvBatchGetConcurrency)
}
const kvBatchGetConcurrency = 16
func (store *HbaseStore) KvDelete(ctx context.Context, key []byte) (err error) {
return store.doDelete(ctx, store.cfKv, key)
}
+5
View File
@@ -50,6 +50,11 @@ func (store *LevelDBStore) VisitKvPrefix(ctx context.Context, prefix []byte, vis
return iter.Error()
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *LevelDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *LevelDBStore) KvDelete(ctx context.Context, key []byte) (err error) {
err = store.db.Delete(key, nil)
+5
View File
@@ -38,6 +38,11 @@ func (store *LevelDB2Store) KvGet(ctx context.Context, key []byte) (value []byte
return
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *LevelDB2Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *LevelDB2Store) KvDelete(ctx context.Context, key []byte) (err error) {
partitionId := bucketKvKey(key, store.dbCount)
+5
View File
@@ -34,6 +34,11 @@ func (store *LevelDB3Store) KvGet(ctx context.Context, key []byte) (value []byte
return
}
// KvBatchGet reads the keys one at a time: the reads are local.
func (store *LevelDB3Store) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
}
func (store *LevelDB3Store) KvDelete(ctx context.Context, key []byte) (err error) {
err = store.dbs[DEFAULT].Delete(key, nil)
@@ -2,11 +2,13 @@ package leveldb
import (
"context"
"errors"
"math"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
@@ -275,3 +277,29 @@ func TestUnavailableDatabaseFailsListAndDelete(t *testing.T) {
t.Fatal("delete children on a closed database succeeded")
}
}
// leveldb3 keeps each bucket in a database of its own and drops it whole when
// the bucket is deleted. A non-recursive delete of a bucket that still holds
// objects must be refused all the same, as on the other stores, and leave the
// objects where they are.
func TestNonRecursiveDeleteOfNonEmptyBucketIsRefused(t *testing.T) {
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
testFiler.DirBucketsPath = "/buckets"
store := &LevelDB3Store{}
store.initialize(t.TempDir())
testFiler.SetStore(store)
ctx := context.Background()
object := util.FullPath("/buckets/photos/2026/cat.jpg")
if err := testFiler.CreateEntry(ctx, &filer.Entry{FullPath: object, Attr: filer.Attr{Mode: 0644}}, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil {
t.Fatalf("create %s: %v", object, err)
}
err := testFiler.DeleteEntryMetaAndData(ctx, "/buckets/photos", false, false, true, false, nil, time.Time{})
if !errors.Is(err, filer.ErrNonEmptyFolder) {
t.Fatalf("non-recursive delete of a non-empty bucket = %v, want ErrNonEmptyFolder", err)
}
if _, err := testFiler.FindEntry(ctx, object); err != nil {
t.Fatalf("%s after the refused delete: %v", object, err)
}
}
+36
View File
@@ -56,6 +56,42 @@ func (store *MongodbStore) KvGet(ctx context.Context, key []byte) (value []byte,
return data.Meta, nil
}
func (store *MongodbStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
values := make(map[string][]byte, len(keys))
if len(keys) == 0 {
return values, nil
}
asked := make(map[[2]string][]string, len(keys))
match := make([]bson.M, 0, len(keys))
for _, key := range keys {
dir, name := genDirAndName(key)
pair := [2]string{dir, name}
asked[pair] = append(asked[pair], string(key))
match = append(match, bson.M{"directory": dir, "name": name})
}
cur, err := store.connect.Database(store.database).Collection(store.collectionName).Find(ctx, bson.M{"$or": match})
if err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var data Model
if err := cur.Decode(&data); err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
if len(data.Meta) == 0 {
continue
}
for _, key := range asked[[2]string{data.Directory, data.Name}] {
values[key] = data.Meta
}
}
if err := cur.Err(); err != nil {
return nil, fmt.Errorf("kv batch get: %w", err)
}
return values, nil
}
func (store *MongodbStore) KvDelete(ctx context.Context, key []byte) (err error) {
dir, name := genDirAndName(key)
Loaded 100 of 463 files, more files were not shown because too many files have changed in this diff. Show more