Compare commits

..
Author SHA1 Message Date
D.Maier 8afef5166b sftp: serve reads on read-write opens instead of writing zeros (#13343) 2026-12-03 07:59:06 -08:00
0daa7558e2 filer: propagate HBase and remote child deletion errors (#13328)
* test/s3: FsMkdir no longer fails on its own in the rclone fstests

expected_failures.txt listed the test itself because DeleteBucket answered
BucketNotEmpty at the end of the run. Since #13311 a null delete marker can
be deleted, the bucket ends up empty, and the check has failed on master and
on every pull request the workflow runs for:

  TestIntegration/FsMkdir: now fails only through its subtests, remove it
  from expected_failures.txt

* filer/hbase: propagate errors when deleting directory children

* filer: reclaim HBase chunks after each confirmed row deletion

* filer: return a child's remote delete error from a recursive delete

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

* filer: drop the per-row folder delete store capability

Keep the HBase scan and row-delete errors reaching the caller without a
new FilerStore capability. A store that fails partway through
DeleteFolderChildren leaves already-removed rows' chunks to volume.fsck,
as every non-transactional store already does.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:15:42 -08:00
f4290b5ec2 kms/local: resolve key and alias ARNs (#13331)
* kms/local: resolve key and alias ARNs

AWS KMS takes a key's or an alias's ARN wherever it takes a key ID or an
alias, and the local provider hands out ARNs in DescribeKey, but it looked
them up as plain names, so an ARN named no key. A local ARN now resolves to
the key or alias it names, in requests, in the keys list's key_id and
aliases, and in CreateKey's aliases. An ARN with an empty key ID names no
key.

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

* kms/local: register a key created by ARN under its key ID

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

* kms/local: refuse a key ARN listed as an alias

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

* kms/local: refuse a key ID that is an ARN of an ARN

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

* kms/local: resolve a key ARN only to the key with that ID

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

* kms/local: create an on-demand key under the ID its ARN names

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

* kms/local: decrypt keeps the key ARN a ciphertext was wrapped under

A key configured by its ARN had that ARN as its ID before key ARNs
resolved, and S3 stored it with each object and compares it with the
ID Decrypt returns.

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-03 01:12:44 -08:00
63e15ce1ea kms: take the default provider from the config being loaded (#13332)
* kms: take the default provider from the config being loaded

S3 wraps and unwraps data keys with the default provider alone. Without
default_provider, the loader made the first provider the manager listed
the global one, and the manager still holds the providers earlier loads
listed, so a reload could leave S3 on a provider the config dropped. The
manager's own default, which buckets without a mapping use, was left
unset. The default is now the first provider by name in the config being
loaded, for both. A default_provider that isn't listed under providers
fails the load before any provider changes, where before it could name a
provider left over from an earlier load. With more than one provider and
no default_provider the load logs a warning, as adding a provider whose
name sorts first would switch S3 to it.

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

* kms: load the default provider first and fail the load if it can't be loaded

A load whose default provider failed replaced and closed the other providers first, so S3
could be left on a closed instance of one of them as the global provider.

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-03 00:48:29 -08:00
Chris LuandClaude Opus 5.5 a7c1cc32ec s3api: fail closed when the directory marker lock check cannot read the marker (#13326)
* s3api: refuse a directory marker PUT when the existing marker cannot be read

Only a missing marker skips the Object Lock check. Any other lookup
error now fails the request instead of letting mkdir replace a marker
that may be under retention or legal hold.

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

* s3api: create the Extended map before applying upload ACL metadata

A directory extracted from a zip without an owner header reached
applyPutObjectACL with a nil Extended map and panicked.

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

* s3api: refuse extracting over a marker that cannot be read

The zip extract mkdir path had the same fail-open lookup as the
directory marker PUT; a failed read now reports InternalError for the
member.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:51:58 -08:00
Chris LuandClaude Opus 5.5 d6d5e99f9b s3api: limit service account keys to their stored actions (#13325)
* s3api: limit service account keys to their stored actions

A service account created with an action subset authenticated as its
parent and was authorized with the parent's full permissions. Map each
restricted service account key to a copy of the parent that carries the
subset as a boundary, and check it in the S3, bucket listing and IAM
authorization paths. An empty action list still inherits the parent.

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

* s3api: drop restricted service account keys with their removed parent

RemoveIdentity only dropped keys that mapped to the parent itself, so a
restricted service account key, which maps to its own bounded copy, kept
authenticating after the parent was deleted.

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

* sts: keep restricted service account keys out of their parent's roles

A named role is admitted by its trust policy alone, so a service account
key limited to Read could assume any role trusting its parent and use the
role's permissions. Require the key's action subset to allow
sts:AssumeRole.

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

* s3api: let a service account's scoped upload listing grant pass its boundary

The upload and part listing routes are authorized as Read, and the
legacy path falls back to the listing grant. The boundary check now does
the same, so a service account limited to ListBucketMultipartUploads can
still list uploads without being allowed object reads.

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

* sts: refuse self sessions for restricted service account keys

AssumeRole without a RoleArn and GetFederationToken issue sessions that
carry the caller's own policies, which for a service account are its
parent's. A restricted key would shed its action subset that way, so
refuse both for it.

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

* sts: give the restricted service account role test its own role

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

* s3api: check a restricted key's parent grants apart from its boundary

The boundary is checked against the request first, so the legacy action
check only has to cover the parent's grants. Checking the boundary there
again without the request denied a Read parent's upload listing to a key
limited to ListBucketMultipartUploads.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:50:44 -08:00
Chris LuandClaude Opus 5.5 515b905011 s3notification: lose the test lock on the fetch of the records' partition (#13324)
TestALeadThatLostItsLockDoesNotSend dropped the forwarder lock on the
first fetch of any partition, then waited for a fetch of partition 0.
When another partition's goroutine fetched first, the lead stopped before
partition 0 was fetched and the wait timed out (seen on the 32-bit job).
The hook now gets the request and drops the lock on partition 0's fetch.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:47:50 -08:00
1606fe4f39 operation: resend an upload that hits a broken pipe on a stale connection (#13322)
* operation: resend an upload that hits a broken pipe on a stale connection

A pooled connection the server has closed fails an upload in one of three
ways, depending on when the close reaches the client. Two of them, a reset
and a closed connection, already get the request resent once with its body
rewound. A broken pipe did not.

A volume server closes a connection idle for 30 seconds and the client keeps
idle ones for 90, so a request that reuses a connection as it turns 30 seconds
old races with the close. The forward of a write to a replica makes a single
attempt: there the write failed with a 500, and the needle already stored on
the primary stayed on that one replica.

* seaweed-volume: resend a replica forward that hits a reset on a stale connection

The Rust replica forward made one attempt, so a pooled connection the peer
closed at its idle timeout failed the write with a broken pipe or a reset,
as the Go forward did before. Resend it once on a new connection, as Go's
upload_content does.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:47:12 -08:00
Chris LuandClaude Opus 5.5 2f300c2969 s3api: keep the in-flight upload counters 64-bit aligned on 32-bit (#13321)
The recursiveListDeclined sync.Map placed ahead of inFlightDataSize and
inFlightUploads moved them off 8-byte alignment on 386, so the first
throttled upload panicked with "unaligned 64-bit atomic operation".
atomic.Int64 is aligned wherever it sits in the struct.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:46:20 -08:00
006885232e master: start file ids past the ones a previous master may have handed out (#13320)
* master: start file ids past the ones a previous master may have handed out

The file id sequence lives in memory. A master that starts, or takes over
as leader, continues it from what the volume servers report: the largest
needle id each of them holds. That is the largest id written, not the
largest one handed out, so the ids of uploads that had not landed when the
previous master was lost are handed out a second time.

Two uploads then hold one needle id in one volume with different cookies.
The one that lands second is refused, and deleting its file id, which goes
by needle id, removes the needle of the other: a file the filer had
answered 201 for lost its chunk on every replica that way.

A volume server's first report to a master now sets the sequence past its
largest needle id by a margin instead of right after it. Later reports
count as before, and a server that holds nothing adds no margin.

* master: shorten the unwritten file id margin comments

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

* master: record the file ids handed out through raft

Starting a margin past a volume server's first report does not hold for
two masters lost in a row: with nothing written in between, the second one
gets the same report and hands out the same id.

The master now records through raft how far it may hand file ids out
before it does (MaxVolumeIdCommand.FileIdCeiling, a step of 2^20 ids at a
time), and every master moves its sequence past what another one recorded,
from the log or from a snapshot. An id goes out only when it was drawn
under a ceiling this master recorded itself: recording one applies what
the masters before recorded first, so an id drawn after that is past all
of theirs, and one drawn before it is dropped.

A master that does not know the field ignores it. Snowflake ids are made
from the clock and are left alone.

* master: leave room for a file id draw larger than the ceiling step

A draw of more ids than fileIdCeilingStep never fit under the ceiling
recorded after it, so the assignment kept recording ceilings through raft.
The record now covers the dropped draw and the next one, and a count past
2^32 is refused before the additions can wrap.

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

* master: tell a recorded file id ceiling apart from another master's

A master that took over could propose the same ceiling the one before it
recorded and it had not applied yet. Applying that entry then looked like
applying its own, so its sequence stayed below ids the other master had
handed out. Each record now carries an id of the master process, and only
an entry with that id and value leaves the sequence where it is.

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

* master: charge assigned bytes only once the file id is recorded

An assignment that failed to record its file ids kept the bytes charged to
the volume, which could mark a volume near its limit full for an upload
that never came.

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

* master: move the sequence before publishing a file id ceiling

An assignment that loaded a ceiling another master recorded, before the
sequence had moved past it, could draw an id below it when this master had
proposed the same value.

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

* master: test that a failed file id record charges the volume nothing

The order c40e01786 set. Before it, an assignment that could not record its
file ids left the volume charged for them: 1 MB for an id never handed out.

* sequence: stop the memory sequencer at the largest file id instead of wrapping

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

* master: refuse a file id draw whose ceiling would wrap past the largest id

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:45:31 -08:00
217795e34c Continue prefix listings on unordered filer stores (#13330)
* filer: continue prefix listings on unordered stores

* test/s3: FsMkdir no longer fails on its own in the rclone fstests

expected_failures.txt listed the test itself because DeleteBucket answered
BucketNotEmpty at the end of the run. Since #13311 a null delete marker can
be deleted, the bucket ends up empty, and the check has failed on master and
on every pull request the workflow runs for:

  TestIntegration/FsMkdir: now fails only through its subtests, remove it
  from expected_failures.txt

(cherry picked from commit b248167800)

* filer: read unordered stores in full pages when filtering a prefix

An unordered store can have to be read to its end for a prefix, and
reading it in pages of the caller's limit (max-keys + 2 for S3) turned
one listing into a store query per few entries.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:31:01 -08:00
MapleWhiteZZZandMapleWhiteZZZ 390c5acc00 test/s3: FsMkdir no longer fails on its own in the rclone fstests (#13323)
expected_failures.txt listed the test itself because DeleteBucket answered
BucketNotEmpty at the end of the run. Since #13311 a null delete marker can
be deleted, the bucket ends up empty, and the check has failed on master and
on every pull request the workflow runs for:

  TestIntegration/FsMkdir: now fails only through its subtests, remove it
  from expected_failures.txt

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
2026-12-02 23:29:28 -08:00
github-actions[bot] 605b5f7f79 docs: regenerate star history chart 2026-12-03 01:53:42 +00:00
Chris LuandClaude Opus 5.5 3c9bdaca86 sftp: create uploaded files 0644, keep modes on overwrite, and support put -p (#13319)
* sftp: create uploaded files with mode 0644

The upload writer carried a 0644 mode that never reached the filer, so the
PUT fell back to the filer default of 0660. Pass the mode on the PUT, as
OpenSSH's sftp-server creates new files 0666 minus a 022 umask.

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

* sftp: keep an existing file's mode when an upload overwrites it

An overwrite went through the same PUT as a new file, so a 0600 file came
back with the default mode. Send the stored mode instead, as open(2) on an
existing file keeps it.

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

* sftp: apply an fsetstat sent while an upload is still buffering

"put -p" sets the mode and times on the open handle before closing it, but
the upload only reaches the filer on close, so the setstat found no entry and
the client failed with "No such file or directory". Keep such attributes on
the open upload: a size cuts the buffered bytes, the mode goes on the PUT,
and the rest is set once the file is stored.

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

* sftp: clear the sub-second part of an mtime a setstat replaces

SFTP times are whole seconds, but the stored nanoseconds of the old mtime
stayed, so a touched or "put -p" file showed a time the client never set.

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

* sftp: set the attributes queued on an upload in its post-upload update

A new file can be under its bucket's default retention as soon as the PUT
stores it, and a setstat after that is refused, so "put -p" into such a
bucket stored the file and then failed the close. Apply the queued
attributes in the update that already sets the owner after the upload.

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

* sftp: leave a setstat alone when two uploads share its path

A setstat carries only the path, so with two uploads of one path open in a
session it went to whichever opened last, and a size cut the other upload's
bytes. Route it to an upload only when that upload is the only one open.

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

* sftp: fail the close when an upload's queued attributes are not stored

The setstat already answered success, so a failed post-upload update was
only logged and "put -p" lost the times without the client knowing.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:56:45 -08:00
5038508fd9 shell: volume.fsck says how many chunks its cutoff left out of the missing-chunk check (#13318)
* shell: volume.fsck says how many chunks its cutoff left out of the missing-chunk check

volume.fsck -findMissingChunksInFiler leaves out every filer chunk written
within -cutoffTimeAgo, five hours by default, and did not say so. Run after
volume servers lost power, it found nothing missing for exactly the files
at risk: the ones written last.

The check now counts the chunks it leaves out for the cutoff and ends with
one line that gives the number and points at -cutoffTimeAgo. The default
cutoff stays, and the orphan check is not touched.

* shell: volume.fsck counts only the chunks its run would have checked

The walk reads the whole filer, so a recent chunk on a volume that
-volumeId or -collection left out of the run was counted too, and the
report said a shorter cutoff would check it. Count a chunk only when its
volume is one of the run's, or one the master does not list and -volumeId
does not leave out, which is what the check itself looks at.

* shell: volume.fsck applies -modifyTimeAgo before counting chunks the cutoff left out

A chunk older than -modifyTimeAgo is not checked at any cutoff, so it
does not belong in the count a shorter -cutoffTimeAgo would check.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:21:42 -08:00
MapleWhiteZZZandMapleWhiteZZZ a89971ff66 filer: delete the chunks a failed copy wrote (#13316)
* filer: delete the chunks a failed copy wrote

A copy through the filer (POST dst?cp.from=src) writes the destination's
chunks first and its entry last. When it ended before the entry was written
(the client gave up, a chunk failed to copy, the entry write failed), the
chunks already on the volume servers stayed there, with no entry to
reference them and nothing to delete them.

The fan-out now waits for the copies it started, starts no further one
after a failure or once the request has ended, and deletes what the
completed ones wrote. A chunk copy that fails deletes the file id it was
assigned, as a failed write can still have stored the needle. A failed
entry write deletes only the chunks the destination does not hold, since
CreateEntry can fail after storing the entry.

#13217 did the same for the S3 copy paths.

* filer: keep the copied chunks when the entry write fails

CreateEntry can fail after it stored the entry: the entry stays when only
its parent folders could not be created. Reading the destination afterwards
does not settle whether the chunks are live, since an entry that was stored
may have been renamed by then, and deleting on a miss would take its data.

So a failed entry write keeps the chunks, as it did before. Only the
failures that come before the entry write delete what the copy wrote.

* filer: fail a copy whose request ended after its last chunk

A request cancelled once every chunk copy had returned still handed the
chunks on, to an entry write that the cancelled context then fails, and
that write keeps them. The end of the request now fails the fan-out
whether or not a copy was left to start, so the chunks are deleted there.

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
2026-12-02 14:10:27 -08:00
ca4e568832 volume.check.disk: resurrect needles a vacuumed replica provably never had (#13304)
* volume.check.disk: resurrect needles a vacuumed replica provably never had

-resurrectMissingNeedles copies a needle that is live on one replica and
absent on the other only into a replica that was never vacuumed: a vacuum
erases deleted needles together with their delete markers, so on a
vacuumed replica an absent needle may be a delete. Once every replica has
been vacuumed, a replica that lost writes, the tail of its volume after a
crash for one, has no repair but copying the whole volume.

A vacuum erases only among the needles the index holds when it commits.
The volume now records the largest needle id it held then, deleted ones
included, in its .vif (VolumeInfo.vacuumed_max_file_key), before the
vacuumed files replace the old ones. A needle with a larger id that the
replica has no index entry for was never deleted there, since no vacuum
has touched its marker: it was never written there. volume.check.disk
-resurrectMissingNeedles reads the record with the compaction revision
and copies such needles back; absent needles up to the recorded id are
left alone as before.

The record is only good if no vacuum went unrecorded, so it starts at a
volume's first vacuum and is kept through each one after it. A volume
vacuumed before it had a record never gets one and keeps the present
rule. A copy of a volume takes the record along in the .vif.

* volume.check.disk: look at vacuumed replicas whose live counts match, and judge only what stays unrepaired

Two replicas at different compaction revisions with equal live counts were
skipped under -resurrectMissingNeedles when both had been vacuumed, since
neither could take a needle back. One that recorded its vacuums can, and a
missed write plus a missed delete leave the live counts equal. Under the
flag such a pair is now compared.

A run without -apply ends with a verdict on the needles one replica has
and the other lacks. It counted the ones the run would have resurrected
with -apply, so two replicas each missing needles above the other's
recorded id were called a split brain not to be repaired. Needles above
the recorded id of the replica lacking them are left out of the verdict.

* volume: trust the vacuum record only at the revision it was written for

A vacuum by a volume server that does not keep vacuumed_max_file_key (an
older Go one, or the Rust one) erases delete markers above the record but
leaves the .vif as it was. Once a server that reads the record serves the
volume again, volume.check.disk -resurrectMissingNeedles takes those ids
for missing writes and raises deleted needles.

The record now names the compaction revision its vacuum produced. It is
saved after the swap, so a vacuum that fails to record it leaves a
revision that no longer matches, and check.disk and later vacuums only
take it up while it equals the volume's live revision.

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

* volume: number the vacuum record fields 12 and 13

VolumeInfo 10 and 11 already carry other bool fields in a downstream
build. A volume server of that build answering ReadVolumeFileStatus would
read here as vacuumed_max_file_key 1 at revision 1, a record that lets
check.disk resurrect every absent needle. The .vif is keyed by name, so
only the wire numbers move.

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

* volume(rs): record the largest needle id a vacuum could have erased

Mirror the Go volume server: VolumeInfo carries vacuumed_max_file_key and
the compaction revision it was taken at (fields 12 and 13). commit_compact
keeps the record through every vacuum once the volume has one, saves it
after the swap, and drops it once a vacuum went unrecorded.

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

* volume(rs): keep the ids of cut tail needles in the decoded index

The EC decoder dropped the .idx row of a deleted needle past the decoded
.dat, so the compaction that follows recorded a vacuumed max needle id
below it. volume.check.disk -resurrectMissingNeedles could then copy that
deleted needle back from a stale replica. Write the row as a tombstone
without the offset instead, as Go keeps every .ecx row.

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

* volume(rs): count tombstone keys toward the max file key on redb loads

metrics_from_idx skipped the max-key update for tombstone rows, unlike
Go's needleMapMetricFromIndexFile and the in-memory replay. A deleted
tail needle then left a redb volume's vacuum record below its id.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:08:37 -08:00
Chris LuandClaude Opus 5.5 add9d60378 s3api: list a versioned key whose .versions folder streams past the page (#13317)
* s3api: list a versioned key whose .versions folder streams past the page

A key's .versions folder sorts after the longer keys it prefixes:
"a.pom.versions" follows "a.pom.sha1.versions" although the key
"a.pom" sorts before "a.pom.sha1". A ListObjects page that filled in
between returned the longer key and resumed past the folder name, so
the shorter key was never listed.

When a versioned page is truncated, look up the .versions folder of
each proper prefix of the page's last item that would still stream
after it, add the live keys found, drop as many items off the end,
and resume from the last key kept instead of a .versions folder name.

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

* s3api: test versioned listing pages that end between a key and its .versions folder

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

* s3api: test encoded versioned listing pages with spaces and plus signs

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

* s3api: keep recovered versioned keys in raw key order

Encoded keys do not sort like raw ones ("a%20b-1/x" before "a+b"), so
a key recovered past the page boundary is placed by its raw key before
the page is trimmed.

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

* s3api: order a versioned page by raw key when listing with encoding-type=url

The in-page insert compared encoded keys, which sort differently from
raw ones once a directory and a file name escape a space differently.

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

* s3api: test encoded directory keys at a versioned page boundary

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

* s3api: scan raw keys when retracting a delete-marked null object

The page is now ordered by raw key, so the backward scan that finds the
null object to retract stops on raw keys too.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:52:05 -08:00
Chris LuandClaude Opus 5.5 8a6c948b12 s3api: delete a null delete marker named by versionId=null (#13311)
* s3api: split the .versions file delete out of deleteSpecificObjectVersion

deleteVersionFile deletes a version stored under .versions and repoints
the latest pointer past it. deleteSpecificObjectVersion keeps "null" as
the plain object entry, which the suspended delete and lifecycle paths
rely on, and calls deleteVersionFile for every other version id.

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

* s3api: delete a null delete marker named by versionId=null

A suspended-versioning delete stores its marker as .versions/v_null, but
DELETE ?versionId=null only looked at the plain object entry. With no
null object there, it answered 204 without x-amz-delete-marker and left
the marker in place, so the bucket could never be emptied.

When the plain null object is missing and a null marker exists, delete
the marker file and repoint the latest pointer to the prior version.
The routed specific-version delete leaves that case to the lock path,
which already handles batch deletes the same way.

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

* s3api: order the repoint past a deleted null delete marker by the versions left

A null delete marker's id has no format, so the routed version delete
read the recompute order from the first remaining version file.

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

* s3api: delete a null delete marker on the key's owner

The marker is read from the owner, so deleting it through the gateway's
own filer could answer success while the owner kept it. Both the routed
DELETE and the lock path delete it with a routed transaction instead.

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

* s3api: rank the versions left by time when deleting a null delete marker

Mixed legacy and inverted ids made the first file name a wrong guide to
the repoint order. The routed delete now finds the newest remaining
version and picks the name order that reaches it; when neither end of
the order is the newest, it leaves the delete to the lock path.

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

* s3api: keep only the ends and the newest while scanning for the null marker repoint

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

* s3api: choose the null marker repoint from the owner's own listing

A filer other than the key's owner can lag it, and the recompute runs over
the owner's full directory, so a direction picked from a replica's partial
listing could repoint the object to an older version. Scan .versions on the
owner only; when the owner cannot answer, leave the delete to the lock path.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:18:23 -08:00
3764534dd1 kms: read filer.toml and the identities file with one parser (#13313)
* kms: read filer.toml and the identities file with one parser

The KMS settings from filer.toml and from the identities file went through
two paths: the JSON one was wrapped in an adapter so it could be read like
viper. Both are now parsed into the same settings and loaded by the same
code. Viper lowercases the provider tables in filer.toml but not the values
that name a provider, so a mixed-case default_provider or bucket provider
never matched and failed the load. Those values are now lowercased for
filer.toml. Providers load in name order, a providers or buckets section
that isn't a table fails the load instead of being ignored, and so does a
default_provider that isn't a string.

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

* kms: test the parser's section types and JSON provider names

A providers or buckets section that isn't a table and a default_provider
that isn't a string fail the parse, and a JSON config keeps the case of
the provider names it uses. The check-once test now loads through the
whole loader, which sets the global provider, so it clears it after.

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

* kms: pick the first provider by name when no default is set

ListKMSProviders iterated the provider map, so with several providers
and no default_provider the global SSE-KMS provider changed between
loads, and objects written under one could not be read after a restart.

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

* s3api: report KMS load errors from the identities file

Any failure loading the identities file's kms block was logged at V(2)
as no KMS configuration, which hid the parser's errors and a
default_provider that does not exist. Only a missing block is quiet now.

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-02 13:16:52 -08:00
a16ca18ae0 kms/local: load master keys from the provider config (#13312)
* kms/local: load master keys from the provider config

The local provider generated its master keys in memory, so a restart or a
reload lost them, and with them every object they encrypted. It now reads a
keys list from its config. Each entry has a key_id, 32 bytes of key_material
in hex or base64, and optional aliases and description. A reload reads the
list again, so objects encrypted under a listed key stay readable.

A name that's already taken, key material that isn't 32 bytes, or
enableOnDemandCreate together with keys fails the provider, and the keys it
loaded before the error are cleared. No default key is generated when keys
are listed, since whatever it wrapped would be lost on a restart. CreateKey
and CreateKeyWithID refuse a name that's taken instead of replacing that key.

GetStringMap copies a list of tables like the other nested values it hands
out.

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

* kms/local: give a racing on-demand request the key the first one created

CreateKeyWithID refuses a key ID that's taken now, and the on-demand path
looked the key up and created it under separate locks. Two requests for
the same new key could both miss it, and the second then failed with
KMSInternalFailure. The on-demand path checks for the key under the lock
it stores it with, and returns the one stored in the meantime, so the
first request's data key stays readable.

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

* kms/local: serve requests that name no key with the configured aws/s3 key

With keys configured there is no generated default key, so an SSE-KMS
request without a key ID failed even when the bucket-default path
(which already resolves to alias/aws/s3) would work. Resolve an empty
key ID to alias/aws/s3, as AWS does, so an operator picks the default
by giving a configured key that alias instead of a new setting.

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

* kms/local: refuse a master key that Close cleared mid-request

A reload replaces the provider and closes the old one, which zeroes its
key material in place. A request that looked up a key before the close
could then build its cipher from zeros and store a data key no provider
can unwrap. Build the cipher under the provider lock and refuse a key
that is no longer registered.

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-02 13:14:11 -08:00
2938037cae filer: end a subscriber's stall when memory serves its cursor (#13310)
* filer: end a subscriber's stall when memory serves its cursor

A metadata subscriber that finds nothing in the ring yet parks until data
arrives ("no readable in-memory entries yet"), which starts its stall
clock. When data arrives the ring serves the cursor and the read goes on,
but nothing stopped the clock: only the paths that leave a gap do.

The clock is what bounds the wait on a gap. With it still running from
that first park, the first real gap the subscriber meets, hours later,
looks older than maxGapStall the moment it parks: the park gives up at
once and skips to the eviction watermark, and the events a peer would have
flushed within the flush interval are never delivered. The log shows a
subscriber "parked" for hours at a cursor a few seconds old, and the gap
skipped in the same millisecond. A mount keeps the stale listing it has
for those events, and filer.sync loses them.

resolve now ends the stall when it sends the read to memory.

* filer: age the first stall in the memory-serves test instead of shrinking maxGapStall

With maxGapStall at 50ms, a scheduler pause between the fresh park and its
give-up check expired the new stall and failed the test against the fixed
code. Keep the real bound and backdate the first park's clock.

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

* filer: shorten the comment on ending the stall in resolve

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:12:20 -08:00
Chris LuandClaude Opus 5.5 c7ba8bd079 sftp: give user store accounts without a Uid a non-root id (#13309)
* sftp: give user store accounts without a Uid a non-root id

An entry that leaves out Uid decoded to 0, and Uid 0 skips every
Permissions check, so a read-only account could write and delete.
Generate a regular id for it the way NewUser does, and default an
omitted Gid to the Uid.

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

* sftp: test that an omitted Uid or Gid does not load as root

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

* sftp: keep the default Uid of an account stable across loads

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

* sftp: test that a default Uid survives Reload and a new store

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

* sftp: keep a default Uid off the ids other accounts use

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

* sftp: test that a default Uid skips ids other accounts use

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

* sftp: refuse a user store with no free id for an omitted Uid

When every id in the default range is taken, loadUsers now fails instead
of reusing a taken id, and it fails before replacing the loaded users so
a Reload keeps the previous accounts.

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

* sftp: test that a full id range rejects the store and keeps old users

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:49:44 -08:00
b445228794 volume: read the fields it knows from a .vif a later version wrote (#13305)
* volume: read the fields it knows from a .vif a later version wrote

The .vif is parsed as strict JSON, so one field this version does not
know fails the whole file. The volume server only logs that and serves the
volume with an empty VolumeInfo: a read-only mark is gone, and so is the
remote file of a tiered volume. Every field added to VolumeInfo makes the
.vif files written from then on unreadable to the versions before it, which
is what a rollback runs into.

When neither the strict parse nor the old format's reads the file, it is
now parsed once more with unknown fields ignored. The fields this version
knows apply, and a warning names the file. The old format is still tried
first, since read this way it would lose its DestroyTime, and a file that
is not a VolumeInfo is still an error.

* volume(rs): read an old-format .vif before the current format

VifVolumeInfo ignores fields it does not know, so an old-format .vif
parsed as it too: its DestroyTime and BytesOffset were dropped and the
old-format fallback never ran. The Go server tries the old format before
reading a file with unknown fields ignored, which keeps the destroy time.
The old format is now taken only when every field in the file is one of
its own, and a file that is not old-format reads as before.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:48:05 -08:00
d05cb0d308 volume: keep the largest needle id of a leveldb-indexed volume through a vacuum (#13306)
* volume: keep the largest needle id of a leveldb-indexed volume through a vacuum

The index a vacuum builds for a volume with a leveldb needle map is loaded
by LevelDbNeedleMap.DoOffsetLoading, which counted the files and tracked
the end of the data but not the largest needle id, as the in-memory map's
loader does. After the commit the volume reported 0 as its largest id until
a needle with a larger one was written, and after each vacuum again.

The volume server sends the largest id over its volumes in every heartbeat,
and the master keeps its id sequence above it. A server whose largest ids
sit in volumes that were vacuumed since they were last written reported too
small a value, which is all the master has to go by when its own sequence
is behind.

* volume: test the largest needle id when nothing lands during the vacuum

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:45:23 -08:00
d0b431b192 filer: pace the deletion ledger's snapshots to a byte budget (#13301)
* filer: pace the deletion ledger's snapshots to a byte budget

The durable deletion ledger is written as a snapshot of the whole pending
set, and the snapshotter is woken by every queued and every finished
delete. A filer deleting a hundred chunks a second rewrote the set a
hundred times a second, close to 4KB written to the store per deleted
chunk. The cost of each snapshot is the size of the set, so a filer that
holds deletes it cannot finish yet, the ones it retries, rewrote that whole
backlog on every other change as fast as the store took it.

A snapshot is now followed by a pause in proportion to the bytes it wrote
(filer.deleteQueue.persistBytesPerSecond, 64KiB a second by default, and
4KiB charged per snapshot), never longer than the periodic interval. The
first change after a quiet spell is still written at once; the changes made
during the pause go into the next snapshot. A crash therefore loses the ids
queued since the last write instead of those of the write in flight.

* filer: fix the deletion ledger's write budget instead of a config key

The pacing needs no operator knob: 64KiB a second keeps a large backlog's
snapshots at the periodic interval and a small ledger's at a few a second.
The snapshotter reads the budget and the interval once when it starts, so a
test that pins the budget does not race a running snapshotter.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:16:02 -08:00
75ba2b125c filer: count the store's KV requests in the store metrics (#13302)
* filer: count the store's KV requests in the store metrics

FilerStoreWrapper counts and times InsertEntry, UpdateEntry, FindEntry,
DeleteEntry and the listings, but passed KvPut, KvGet, KvBatchGet and
KvDelete straight to the store. Hard link records, the deletion ledger and
the per-path commit records are all kept in KV, so that part of what a
filer asks of its store did not show in SeaweedFS_filerStore_request_total
or in the request duration histogram.

The four KV calls are now counted and timed like the others, as kvPut,
kvGet, kvBatchGet and kvDelete.

* filer: shorten the KV metrics helper comment

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:14:38 -08:00
Chris LuandClaude Opus 5.5 5c36ee70ee master: sign a LookupVolume token for the file id asked for (#13300)
* master: sign a LookupVolume token for the file id asked for

LookupVolume signed the token with the bare volume id, and the volume
server checks the token's fid against vid,key, so every token it handed
out was refused. /dir/lookup signs the file id. operation.LookupJwt goes
through LookupVolume, so the expired-token renewals of the S3 PutObject
and copy cleanup deletes, the admin file browser and weed benchmark all
got a token the volume server refused.

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

* master: sign lookup tokens for the base file id

The volume server checks a token's fid against the file id with its
_<delta> suffix stripped, so a token minted for vid,key_N, over gRPC or
/dir/lookup, was refused. Sign baseFid of the file id in both paths.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:13:16 -08:00
Chris LuandClaude Opus 5.5 dc15685282 filer: rename a postgres_flat scan test bucket codespell flags (#13314)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:13:00 -08:00
Chris LuandClaude Opus 5.5 ae99aae2cb mq: report the caller's deadline when a broker sees it first (#13303)
* mq: report the caller's deadline when a broker sees it first

doConfigureTopic checked ctx.Err() to tell the caller's deadline from a
broker failure. A broker's DeadlineExceeded status (or its RST_STREAM,
which gRPC maps to DeadlineExceeded once the deadline has passed) can
arrive before the context's own timer has run, so ctx.Err() was still nil
and NewTopicPublisher returned the wrapped gRPC error instead of
context.DeadlineExceeded. Once the deadline is behind us, wait for the
context's timer before reading ctx.Err().

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

* mq: let the configure call start before its deadline passes in the test

The deadline the test reported had already passed when NewTopicPublisher
started, so the check before the first broker caught it and the check after
the call was never exercised. The fake broker now moves the deadline behind
us only once it has the call, and answers with its own DeadlineExceeded.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:12:07 -08:00
Chris LuandClaude Opus 5.5 f599f870a8 s3: list without a delimiter from one range of the filer store (#13263)
* s3: -s3.listRecursiveFromStore, on by default

Lets an operator keep recursive listings on the directory walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3: list without a delimiter from one range of the filer store

A bucket that never had versioning is listed with ListEntriesRecursive:
one read of the bucket's path range per page instead of one directory
listing per directory. A folder object's "<dir>/" key waits for its place in
key order, and the folder objects whose rows sort before the range (the one
the prefix names, those the marker ends inside of) are looked up. .uploads
is skipped; a .versions folder hands the page to the walk, as does a filer
that answers Unimplemented, which is then not asked again for a minute.

The test pages through both ways over the same tree, for prefixes, markers
and page sizes, and expects the same keys, sizes, ETags and markers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: a range-read gateway lists what the walking one does

A second S3 gateway with -listRecursiveFromStore=false runs on the same
filer. ListObjectsV2 and V1 pages agree for prefixes, markers and page sizes
over folder objects, a prefix object, an unfinished upload and +/-/0
neighbours. Listing 60 keys five directories deep scans the bucket table 2
times from the range read and 302 times from the walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3: range-read listings without the -s3.listRecursiveFromStore flag

A filer whose store cannot list a range answers Unimplemented and the
gateway already walks that bucket's directories instead, so the flag only
switched off a path that falls back by itself. The unit test forces the
walk through the decline cache, and the postgres_flat test checks pages
against the keys in byte order rather than against a second gateway.

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

* s3: step a range-read listing over the bucket's upload parts

The walk skips the bucket's .uploads folder as one entry, but a range read
from the bucket root streamed every part of every unfinished upload and
dropped them, one 1024-row window after another, on each first page.
Every path under .uploads/ sorts before ".uploads0", so the read resumes
there and looks up the one key with that name.

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

* s3: list a waiting folder object once a row passes its key

A range-read page queued every childless folder object until a file row
arrived, so max-keys=1 over a bucket of empty folders read the whole
bucket before answering.

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

* s3: forget a deleted bucket's recursive-listing decline

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:10:19 -08:00
Yip LeoandClaude Opus 5.5 77a070fe0a s3api: tell a symlink apart from an empty object on GET and HEAD (#13299)
A symlink made through weed mount holds no data, so GET and HEAD
answered for it as for an empty file: Content-Length 0 and a type
guessed from its name. An S3 client could not tell it from an empty
file, nor see where it pointed.

For an entry with the symlink mode bit, send the target as user
metadata, x-amz-meta-seaweedfs-symlink-target, escaped like a key under
encoding-type=url, and use Content-Type inode/symlink (what file(1)
reports) when none is stored. User metadata is the one place AWS has for
an object's own fields, so SDKs and the AWS CLI show it as they are. The
link is not followed: the target is a path on the client that made it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:05:12 -08:00
Chris LuandClaude Opus 5.5 acb7728915 filer: ListEntriesRecursive RPC (#13262)
* filer: name the check that a listing expires an entry

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: StreamListRecursiveEntries lists a subtree in path order

It pages through the store's RecursiveLister until the limit, leaves out
and deletes expired entries as a directory listing does, and declines a
subtree in or holding a remote mount.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer.proto: ListEntriesRecursive

A new RPC rather than a field on ListEntries: a filer that predates it
answers Unimplemented instead of listing one directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: serve ListEntriesRecursive

Unimplemented when the store cannot list the subtree in path order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: a scoped token is refused ListEntriesRecursive

Classified with TraverseBfsMetadata: it lists a whole subtree, past the
per-directory checks a scoped ListEntries gets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: trim a trailing slash before checking a recursive listing for remote mounts

An empty directory lists from the root.

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

* filer: keep the recursive listing cursor when a page comes back empty

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:04:27 -08:00
a9d4714aed s3api, filer: keep a symlink a symlink when CopyObject copies it (#13298)
* s3api, filer: keep a symlink a symlink when CopyObject copies it

A symlink made through weed mount is an entry with the symlink mode bit,
a SymlinkTarget and no data. CopyObject builds the destination's
attributes afresh, with the permission bits from the request, so a copy
to another key dropped both and landed as an empty regular file. A
metadata-only self-copy (REPLACE) kept the target but reset the mode,
leaving the link an empty regular file in place.

Keep the symlink mode bit and the target on both paths. The permission
bits still come from the request, as for any other copy. The filer's own
copy (copyEntry) already carries the source's whole attribute set.

A copy into a new prefix creates the symlink in a missing directory, and
the filer gave each parent it created the entry's whole mode plus
ModeDir. With the symlink bit as well, a mount shows those directories
as regular files, and nothing under them can be reached. Parents now
take the entry's permission bits only.

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

* filer: drop the symlink type when promoting an entry to a directory

A key nested under a symlink promotes the symlink's entry to a
directory. The promotion added ModeDir and kept the symlink bit, so a
mount showed the directory as a regular file and could not reach the
nested key. Keep only the permission bits there too, with the same
restorableModeBits a missing parent now takes from its entry.

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

* s3api: keep a self-copied prefix object a directory when it was a symlink

A prefix object promoted from a symlink before the filer change still has
the symlink bit. A routed self-copy of it restored ModeDir and then
keepSymlink added the symlink bit back, leaving a directory a mount shows
as a regular file. keepSymlink now leaves directory destinations alone.

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

* filer_pb: a prefix object keeps no type bit but the directory's

MarkPrefixObject added ModeDir and the execute bits to whatever mode the
object had. A symlink copied onto a key that other keys are nested
under, or a self-copy outside the owner route of a prefix object
promoted from a symlink before the filer change, kept the symlink bit
next to ModeDir, which a mount shows as a regular file. Clear the other
type bits first.

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-02 12:04:04 -08:00
85b783cc0d s3api: copy a chunk to another volume when its volume fails the write (#13297)
* s3api: copy a chunk to another volume when its volume fails the write

CopyObject and UploadPartCopy assigned one volume to each copied chunk and
failed the whole copy when that volume failed the write: a streamed copy
sent a single POST, and a buffered copy retried only the same fid.
PutObject asks for a fresh assignment instead (upload_chunked.go), so a
volume that filled up, went away or was overloaded failed a copy that a
PUT would have survived. In production, a CopyObject failed with 500
because the destination volume server broke the connection mid-upload,
and only the client's retry completed it.

Every chunk copy now writes through uploadCopiedChunk: streamed, buffered,
range, and the five SSE re-encryption paths. When a volume fails the write
in a way another volume would not, the copy deletes whatever the failed
write may have stored, asks for another volume and writes the chunk again,
as PutObject does: up to three volumes, and only one more after an
overload. The uploader's errors are judged by
operation.ShouldReassignUpload, and a streamed POST by its status (no
response, a 5xx, or an overload refusal). A streamed retry reads the
source again, and a range copy digests only the bytes of the attempt that
landed. A failed source read is not retried on another volume: a streamed
copy now records the source's read error apart from the POST's.

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

* s3api: delete a failed copy chunk only when its write reached the volume

A streamed copy reads its source inside the write, so a source that could
not be read also came back through uploadCopiedChunk, which then deleted a
fid nothing had been written to. Only a failure of the volume itself
(copyUploadError) is followed by the delete now; the tests check that a
source failure sends none.

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

* s3api: reassign copy writes refused before the append, bound the cleanup

A streamed copy's POST dropped the volume's X-Seaweed-Write-Outcome header,
so a 409 from a volume that turned read-only before the append, or a 401 for
a token that expired in the queue, failed the copy where the uploader's
ShouldReassignUpload tries another volume. The POST now keeps the header and
reassigns on the same marked answers; unmarked 409 and 401 stay final.

The delete of a failed chunk read its answer with no deadline, so a volume
that sent the headers and stalled the body held the copy up for good. Each
delete now runs within copyCleanupTimeout (10s), its answer included, and
still logs the status and up to 4 KiB of the body.

Tests: the fake volume keeps the file it was sent, and each retry case checks
that the second volume stored the copied bytes. An SSE-C chunk copied under a
new key decrypts with the key and IV its chunk names. Marked 409 and 401
answers reassign, unmarked ones do not, and a stalled cleanup delays the copy
by the timeout only.

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

* s3api: renew an expired token for a failed copy chunk's delete

A copy's write token is minted at the assignment, before the source is
read, and lasts 10s by default. A write that failed after that left the
cleanup delete refused with 401 and the needle orphaned. PutObject's
cleanup renews the token from the master on a 401; do the same.

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

* s3api: log the status and body of a cleanup delete whose read failed

A delete whose answer began but whose body read failed, such as one cut
off by copyCleanupTimeout, was logged with the error only. Log its status
and the part of the body that arrived as well.

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-02 12:03:40 -08:00
Chris LuandClaude Opus 5.5 38422bd1fa filer: RecursiveLister, a subtree in path order from one range of postgres_flat (#13261)
* filer: RecursiveLister, a store capability to list a subtree in path order

The wrapper hands it to the default store, reading hard links as listings
do, and declines it when path-specific stores could hold part of the
subtree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: list a subtree with one range scan when rows are keyed by path

AbstractSqlStore lists recursively when its generator implements
RecursiveListSqlGenerator. The range runs from the directory and prefix to
the least string past every path starting with them. A directory whose
subtree spans the bucket tables is declined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: the postgres_flat generator lists a path range

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/store_test: check recursive listings

Byte order across +, -, / and non-ASCII names, prefixes holding a slash,
literal % and _, resuming after a path, pages of one and three, a
directory outside the buckets, and the directories that span bucket
tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: a recursive listing's start path outside the bucket table bounds it by full path

A start path in another bucket was trimmed as if it were inside this one, so
a start path past the bucket listed it all again, and one before it could
skip entries.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:03:18 -08:00
Chris LuandClaude Opus 5.5 b7536bd6f6 test: S3, versioning and FUSE integration tests for the postgres_flat filer store (#13255)
* test/postgres_flat: S3 against a filer on the postgres_flat store

A weed mini whose filer.toml enables postgres_flat in a schema of its own.
Objects, listings, copies, multipart uploads, versions and bucket deletion
are checked through S3 and against the rows of the bucket's table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: a FUSE mount against the postgres_flat store

Files, a directory longer than a listing page, renames, hard and symbolic
links, tree removal and a bucket made through the mount, checked against the
rows, then read back by a second mount with an empty metadata cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: run the postgres_flat S3 and FUSE tests against Postgres

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: run the postgres_flat tests on pull requests to any branch

Like the S3 workflows, so a stacked pull request runs them too, and only
when the code they reach changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: fail fast when weed mini or the mount exits

ProcessState is only set by Wait, which ran only at cleanup, so a mini
or mount that died at startup was noticed only at the 45s or 90s
deadline. Reap each command as it starts and check for its exit while
waiting.

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

* ci: run the postgres_flat tests on changes anywhere under weed/

The tests run master, volume, filer, S3 and a mount, so changes in
packages such as weed/pb, weed/wdclient or weed/credential reach them
too. Match the FUSE integration workflow and also trigger on the
fusermount action the job uses.

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

* test/postgres_flat: versioned buckets on the postgres_flat store

Versions and delete markers are rows under the key's .versions folder in
the bucket's table. Covers version listings in one page and one version a
page, delete markers, promoting the previous version, the null version
under suspended versioning, and dropping the table once every version and
the bucket are deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: run the S3 versioning suite on a postgres_flat filer

The whole test/s3/versioning suite, stress tests included, against a weed
mini whose filer.toml enables postgres_flat. The job first checks that
filemeta has the flat layout, so a filer on its default store cannot pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: set up shared objects before the subtests

The S3 and versioning suites wrote their objects and the second bucket
inside the first subtest, so running one later subtest with -run left
the version ids empty and panicked. The parent test now writes them and
the subtests only check.

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

* test/postgres_flat: helpers fail the test that calls them

paths, tableExists, count, filerList, start and mount take the caller's
*testing.T, so a failure inside a subtest fails that subtest instead of
calling FailNow on the parent and stopping its siblings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: wait for the filemeta table before the versioning suite

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

* test/postgres_flat: POSIX subtests set up their own fixtures

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

* test/postgres_flat: absent versions must answer 404

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:42:13 -08:00
b5a7d9600e kms: read provider settings as TOML gives them (#13294)
* kms: read provider settings as TOML gives them

Provider settings were read with plain type assertions, so a setting
of another type read as its zero value. TOML decodes integers as
int64, which GetInt ignored, so max_cache_size from filer.toml never
applied, and Viper lowercases TOML keys, so the local provider never
saw enableOnDemandCreate. A cache_ttl that didn't parse fell back to
an hour without a word.

Settings are now read through one typed getter. An int64 or a whole
float64 reads as an int, a key matches ignoring case when it isn't
found as given, and a provider that reads a setting of the wrong type
fails to load and is closed. The loader reads the cache settings the
same way and fails a provider whose cache settings don't parse.

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

* kms: apply the cache defaults to a setting given as null

A JSON null for cache_enabled or cache_ttl counted as set, so it turned
caching off or failed the provider on an empty duration, where it used
to read as the default.

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-02 07:15:51 -08:00
ed177d31e3 kms: run provider health checks without the manager's lock (#13295)
* kms: run provider health checks without the manager's lock

GetKMSHealth held the manager's read lock while it asked every provider for
a key, and a remote KMS can take its whole timeout to answer. A provider
change waited behind it for the write lock, and every request looking up a
provider then waited behind the change. The checks now run on a copy of the
providers. SetDefaultKMSProvider and SetBucketKMSProvider check that the
provider exists and set it under one lock, so a provider removed in between
can't be left as the default or as a bucket's provider.

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

* kms: health-check only the provider a load adds

Loading a provider checked every provider loaded so far, so a configuration
with N providers made N(N+1)/2 remote calls at startup, and one slow provider
could spend the shared 10s budget and get the new provider reported unhealthy.

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

* kms: run provider health checks concurrently

The checks shared one deadline and ran one after another, so a provider
stuck until the deadline got every provider checked after it reported
unhealthy, and startup waited for the checks in turn.

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-02 07:11:17 -08:00
Chris LuandClaude Opus 5.5 acff807879 filer: postgres_flat store keyed by the full path (#13253)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of directory statements

Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: batch lookup takes row keys and matches rows by name and directory

A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: build the connection string with pgxutil.BuildDSN

The credential store already does; it quotes values per libpq, so a
password or certificate path with spaces or quotes no longer breaks the
connection string. The OpenPGXDB alias has no callers left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: scan pages take the row key of the last row as their cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: postgres and postgres2 share their connection setup

ReadConnection reads the settings and their defaults, Connection.Open
opens the store's pools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: key-value records may live in a table of their own

A store whose entry tables have another layout keeps its key-value
records in KvTable, written by KvSqlGenerator; its scans then read only
entries and need not tell the records apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: SQL generator keyed by the full path

Rows have path as their primary key; a (directory, name) unique
constraint serves the directory listings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: postgres_flat store

Entries are keyed by their full path, the object key inside a bucket's
table; buckets get tables of their own as in postgres2. Key-value
records keep the postgres2 layout in filemeta_kv. The store refuses a
filemeta table of another layout, so it needs a schema of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: register postgres_flat and add it to the filer.toml scaffold

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: test the arguments each generator binds

Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

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

* filer/postgres_flat: name a missing filemeta table instead of a foreign layout

With createTable = false and no filemeta table, the layout check said the
table had no path column and blamed a postgres2 layout. Report the missing
table and the key-value table that also has to be created.

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

* filer/postgres: postgres_flat escapes the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one, but the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: escape the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: postgres_flat shares the generator's tableIdent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

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

* filer/postgres_flat: find filemeta along the search path when checking its layout

The store's queries name filemeta unqualified, so with schema = "a,b" they
reach a table in b; the layout check looked in current_schema() only and
refused it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres_flat: force byte order when the path column is locale-ordered

Directory listings order and bound rows by path, but only the name
column's collation was checked. A createTable with a locale-ordered path
column listed in locale order, and byte-order bounds missed entries.

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

* filer/postgres: read the ordered columns' collation along the search path

The collation check looked for filemeta in current_schema() only. With the
tables in a later schema of the search path it found no column and took the
database's order, so a locale-ordered path column next to a C database went
unforced, and byte-ordered columns in a locale database got a needless sort.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres_flat: list a directory from its path range

A directory's children are the rows of its path range whose directory is
the listed one. The listing reads that range in growing batches and skips
the rows of the children's subtrees in Go, so a versioned object's
.versions rows cost no query of their own. Past 64 rows of one subtree it
queries again from that subtree's end. A name prefix narrows the range.

Listing no longer reads the (directory, name) index.

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

* filer/postgres_flat: find a folder's children in its path range

Deleting a folder's children looked them up by directory alone, which
only the (directory, name) index serves. Bound the delete by the
folder's path range as well.

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

* filer/postgres_flat: key the table by path alone

Listing and deleting a folder's children both read the path range now,
so the (directory, name) unique index only cost writes and storage:
flatPath already makes the path unique per (directory, name).

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

* filer/postgres: read the ICU or builtin database locale before datcollate

An ICU-default database can report datcollate 'C' while its default
collation orders by the ICU locale, so a name column on the database
default looked byte-ordered and the listing kept locale order. Read
datlocprovider and the provider locale (via to_jsonb, so servers before
Postgres 15 still answer) and treat an ICU default as locale-ordered.

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

* filer/postgres_flat: list a folder's children from its path range

The bucket enumeration listed /buckets by directory and ordered by name,
a sequential scan and sort now that path is the only index. Read the
folder's path range in path order instead.

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

* filer/postgres_flat: only the path column needs byte order

Listings now order and range by path alone, and directory and name are
only compared for equality, which no deterministic collation changes.
Drop their COLLATE "C" and check only the path column's order.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 07:05:13 -08:00
Tiago PosseandClaude Opus 5.5 ce7b6c93b2 filer: read the views of the chunk a boundary read leaves in one goroutine (#13293)
A read across a chunk boundary started a goroutine for each view of the
chunk the stream leaves, outside the limit on chunks read at once, so a
compressed chunk written over in many places could start any number of
them. One goroutine started before the others now reads those views one
after another, and the other views are back under the errgroup limit. It
reads every view from the held download before a view the download can't
serve falls back to a read of its own, as that read can make room and
evicting the chunk waits for the holds.

The test of a boundary read that doesn't wait for the chunk it leaves now
has four times as many views of that chunk as chunks run at once, and
checks that the read starts fewer goroutines than that.

The waits for a prefetch to reserve and for a boundary read to fetch its
last chunk are bounded, so a failing test reports instead of hanging.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 07:04:19 -08:00
Martijn HoekstraandClaude Opus 5.5 411ab1d920 worker(rs): refuse short JWT keys under fips.mode strict (#13284)
* worker(rs): refuse short JWT keys under fips.mode strict

weed-worker, weed-vector and weed-vector-cli now check the JWT keys of the
security.toml they read, as every Go process does: under fips.mode strict
each exits at startup naming every key shorter than the 14 characters FIPS
140 needs for HMAC keys, with the rule and messages of
seaweed_common::jwt_keys (#13206); outside strict mode each such key but a
previous_key gets a warning. A filer signing key given on the command line
(--filer-signing-key, WEED_FILER_SIGNING_KEY) is checked the same way.

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

* worker(rs): warn about a short signing key flag outside strict mode

A filer signing key given by --filer-signing-key or WEED_FILER_SIGNING_KEY
was checked only under fips.mode strict; outside it, a key strict mode
would refuse now gets the warning a short key in security.toml gets.

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

* test: start the worker binaries with short keys under fips.mode strict

Integration tests start the built weed-worker, weed-vector and
weed-vector-cli under WEED_FIPS_MODE=strict with a 10-byte key in
security.toml, or a short --filer-signing-key, and check that each exits
naming the key. They run in the existing cargo test jobs and need no
cluster: the check comes before the binaries dial anything.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 06:24:14 -08:00
6a67fe503e vacuum: compact copies held read-only by a readonlyCanDelete mark (#13283)
* vacuum: compact copies held read-only by a readonlyCanDelete mark

A volume marked with volume.mark -readonlyCanDelete takes no new writes
but keeps taking deletes, so it can drain instead of holding a volume
slot (#10688). The automatic vacuum never reclaims those deletes: it
skips every read-only copy unless low disk space is the only cause, and
a mark clears that exception (#11519). The space comes back only once
the last needle is deleted (deleteEmpty) or through volume.vacuum
-volumeId, one volume at a time, so a volume that never drains
completely keeps its garbage.

VacuumVolumeCheck now also reports can_delete_mark: the copy is
read-only through a readonlyCanDelete mark and nothing that refuses
deletes (no plain read-only mark, no I/O quarantine, not tiered to
remote storage). The sweep compacts such a copy like a writable one,
except when the master pushed the mark itself to quarantine a duplicate
volume id. The mark survives the compaction, so the copy stays
read-only, keeps taking deletes and stays out of the writables. A
read-only volume reserves no headroom, so the space it gives back
becomes free volume slots.

The Rust volume server reports the same field. In volume.vacuum, the
help text and the list of read-only volumes the sweep skips leave out
copies that still take deletes. For the unnamed collection, which the
shell vacuums volume by volume, such volumes are left to the sweep: an
explicit request would also compact a quarantined copy.

An older volume server does not set the field and an older master
ignores it, so a mixed cluster keeps skipping these copies.

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

* shell: say which marked volumes volume.vacuum leaves to the sweep

For the unnamed collection, volume.vacuum sends one request per volume
and skips a volume held by a readonlyCanDelete mark, while the "skipped
by the sweep" hint leaves such volumes out because the sweep compacts
them. With a filter matching only those volumes, the command returned
without a request and without a word. It now lists the marked volumes
over the threshold that it leaves to the automatic sweep.

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

* storage: drop the compacted needle map a read-only commit leaves unused

CommitCompact reloads a read-only volume into a sorted map, so the
compacted map built for the reload is never consumed: it stays in
v.tmpNm with every needle of the volume, and with a leveldb index its
.cpldb stays on disk. The next compaction reopens that .cpldb as is, so
needles deleted between the two compactions come back in the leveldb
map with stale offsets once the volume is writable again, and reads of
them fail with EOF instead of not found.

The sweep now compacts readonlyCanDelete volumes, so this path is no
longer limited to an explicit volume.vacuum -volumeId.

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

* storage: do not tie the canDelete compaction test to random needle sizes

newRandomNeedle sizes its data at random, so three deleted needles out
of six left under 30% garbage about once in twenty runs and failed the
precondition. The test only needs the deletes to leave some garbage.

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

* shell: say the sweep skips quarantined copies in the left-to-sweep note

The note named unnamed-collection volumes as left to the automatic
sweep, but the sweep skips a copy the master holds for a duplicate
volume id under the same mark, and the topology does not show that
quarantine. The note now says so. It also describes the copies by what
the topology shows, read-only but still taking deletes, since a copy
read-only only for low disk space looks the same when its probe fails.

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-02 04:23:39 -08:00
c96636ecd0 filer: fold chunk lists for scoped commits (#13281)
* filer: fold chunk lists for scoped commits

A filer serving a keep-only scoped token never folded chunk lists, and
refused any new chunk for an entry holding manifests, so scoped clients
kept their lists flat. On a store with a value size limit, such as
FoundationDB, a scoped file stopped fitting at about 1000 chunks.

The filer now folds scoped commits and reuses stored manifests as it does
for unscoped ones. Folding runs after the retained-data check, so the only
manifests a scoped commit stores are ones the filer wrote:

- a scoped request may keep a manifest stored at the target, sent as
  stored; any other manifest is refused, with or without a proof, and a
  stored manifest cannot be kept as a data chunk;
- the chunks held by the stored manifests count as stored at the target
  and join the identity map, so they may be retained flat but not under
  another spelling of their file id;
- those chunks are read under the handler's path lock, not at admission;
  admission still refuses a manifest the target does not store and leaves
  the checks that depend on the held chunks to the locked check. A
  manifest that cannot be read refuses the write as Unavailable. An update
  rechecking inside its store transaction reuses the chunks it already
  read, so it does no volume I/O there.

Appends to a folded entry are allowed under the same rules: an append
keeps every stored chunk, and the locked check refuses aliases of the
chunks the stored manifests hold.

* mount: explain why a scoped mount keeps chunk lists flat

A filer serving a scoped token now folds scoped commits itself and keeps
only the manifests it wrote. The mount's flat rule is unchanged; only the
reason given for it was out of date.

* filer: test a scoped truncate through a stored manifest

* filer: refuse manifest chunks in a scoped append

An append moves each chunk it carries to the end of the file. A manifest
cannot be moved that way: the chunks it holds keep their own offsets, so
the appended range would read no data and the manifest's bytes would still
read at their old place. Before this series a scoped request could carry no
manifest at all; now that a scoped commit may keep a stored manifest, an
append still takes data chunks only.

* filer: read only the stored manifests a scoped commit drops

The locked retained-data check read every stored manifest whenever a
scoped request had chunks, so each flush of a folded file and each append
cost one volume read per manifest under the path lock. The unscoped path
reads only the manifests a commit drops.

Read the same way for a keep-only scope: only the stored manifests the
request does not keep unchanged, and none for an append, which keeps every
stored chunk. A kept manifest keeps its chunks referenced, and garbage
comparisons match chunk identities, so another spelling of one of its
chunks cannot get the needle deleted; such a chunk now needs its own proof
like any new chunk. Truncating through a manifest and listing its chunks
flat still work, since both drop it.

* filer: find the dropped manifests of a scoped commit in one pass

Index the manifests the request keeps by file id instead of scanning the
request for each stored manifest, which compared and cloned chunks
quadratically in the number of manifests.

* filer: rewrap the scopeManifestReader comment

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-02 04:22:12 -08:00
Chris LuandClaude Opus 5.5 4cb096e32f filer, s3: report a failed read as an error, not as a missing entry (#13289)
* filer/mongodb: report a failed read as an error, not as a missing entry

FindEntry logged any read error other than ErrNoDocuments and returned
filer_pb.ErrNotFound, so a lookup that could not reach MongoDB answered
that an existing entry was gone.

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

* filer/arangodb: report a failed read as an error, not as a missing entry

FindEntry logged any ReadDocument error other than not-found and
returned filer_pb.ErrNotFound, so a lookup that could not reach ArangoDB
answered that an existing entry was gone.

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

* filer/rocksdb: report a failed read as an error, not as a missing entry

FindEntry and KvGet checked for a missing value before the read error,
and the value is nil after any failed read, so every read error came back
as not found.

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

* s3: a versioned read whose lookup fails is not NoSuchKey

In a versioned bucket, GetObject, HeadObject and GetObjectAttributes
answered NoSuchKey for any error from getLatestObjectVersion, so a filer
or store outage told clients that existing objects were gone. They now
classify the error the way CopyObject's source lookup does: NoSuchKey
only when the object is missing, 503 for transient failures and 500
otherwise.

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

* s3: keep the cause when the latest version file cannot be read

doGetLatestObjectVersion formatted a failed read of the version file the
pointer names with %v, so a transient failure there answered 500 instead
of 503.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:20:06 -08:00
Chris LuandClaude Opus 5.5 1f65d9e708 s3api: answer GetBucketLocation with a LocationConstraint document (#13292)
GetBucketLocation wrote the CreateBucket request body
(CreateBucketConfiguration), so clients that check the root element, such
as the AWS Rust SDK, failed with "expected LocationConstraint tag". Reply
with an empty LocationConstraint in the S3 namespace, which is what AWS
sends for us-east-1 buckets.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:10:17 -08:00
Chris LuandClaude Opus 5.5 97cac5f5e5 test: fix mq tests broken by separately merged changes (#13285)
* mq/logstore: rename the tiered copy of a duplicated test name

TestTimeReadWithNothingNewKeepsItsPosition was added in both
merged_read_test.go and merged_read_table_test.go by changes that
merged separately, so the package's tests stopped compiling. The
table-backed one becomes TestTieredTimeReadWithNothingNewKeepsItsPosition.

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

* query engine: make the topic table test's control entry a close marker

The test's offset 5 had no key but kept its value, which was a control
entry before keyless messages became data. Now only an entry with
neither key nor value is skipped, so the baseline scanned that message
in both partitions and counted 22 rows instead of 20. Offset 5 drops its
value too, so it is the close marker the test means.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:07:51 -08:00
Yip LeoandClaude Opus 5.5 13d65deb3a filer/tikv: report a failed read as an error, not as a missing entry (#13287)
FindEntry turned every failed read into filer_pb.ErrNotFound, because
the value it checks is still nil after any error. While TiKV cannot be
reached, or a region has lost its leader, a lookup of an existing entry
answers "not found" once the client library gives up its backoff (about
40 s): the S3 gateway returns 404 NoSuchKey to HEAD and CopyObject,
weed mount returns ENOENT and the filer HTTP API 404. Writes in the same
outage fail with an error, so only reads report the entry as gone.

A read that TiKV answers with "not exist" is still a missing entry; any
other error is returned to the caller.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:07:00 -08:00
Chris LuandClaude Opus 5.5 b1f86ddfa2 s3: support PutBucketDefaultStorageClass and GetBucketDefaultStorageClass (#13282)
* s3: add PutBucketDefaultStorageClass and GetBucketDefaultStorageClass

The setting is kept in the bucket entry's extended attributes next to
the other bucket configuration, so every gateway sees it through the
bucket config cache. Only STANDARD and INTELLIGENT_TIERING are accepted,
matching the AWS model; STANDARD clears the stored value.

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

* s3: give new objects the bucket default storage class

PutObject, POST uploads, CreateMultipartUpload and CopyObject store the
bucket default when the request names no storage class. The request
headers are left alone, so bucket-policy storage-class conditions and
the self-copy change check still see only what the client sent. Upload
parts are not tagged; a completed upload takes the class recorded when
it was initiated.

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

* s3: test the bucket default storage class APIs and write default

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

* s3: fail a write whose bucket default storage class cannot be read

A failed bucket config lookup used to fall back to STANDARD, so a write
could store a different class than the bucket default asks for. The
write now returns the lookup error instead. A request that names its
own class still needs no lookup.

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

* s3: give extracted ZIP directory members the bucket default storage class

Directory members are created through mkdir rather than putToFiler, so
they stored no class while the files next to them did.

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

* s3: reject a default storage class body with trailing data

The decoder stopped after the first element, so a valid configuration
followed by another element or stray bytes was accepted. The body is
now read with a size bound and only whitespace, comments or processing
instructions may follow the configuration.

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

* go.mod: bump aws-sdk-go-v2/service/s3 to v1.117.1

The release adds the PutBucketDefaultStorageClass and
GetBucketDefaultStorageClass client operations.

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

* s3: test the bucket default storage class through the AWS SDK

Covers get/set, an unsupported class, the setting stored in the bucket
entry and read back by a fresh bucket config, PUT, explicit classes,
multipart initiation, copy, existing objects, and per-API grants.

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

* s3: let each default storage class subtest set up its own state

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

* s3: assert the explicit STANDARD class exactly in the default class test

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

* s3: note that the bucket default storage class is a label only

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:05:48 -08:00
6b402aa87c sftp: serve one session on stdin/stdout when run as an OpenSSH Subsystem (#13278)
* sftp: add -stdio to run as an OpenSSH Subsystem

weed sftp -stdio serves one SFTP session on stdin/stdout, so sshd can run it
as its sftp subsystem and handle authentication itself (PAM, SSSD, 2FA,
AllowUsers, Match blocks):

    Subsystem sftp /usr/local/bin/weed sftp -stdio -filer=filer:8888

The session belongs to the OS user sshd started it as. With -userStoreFile
that user must be in the store, and its HomeDir and Permissions apply as
over SSH; without one, the session reaches the whole filer, which the
process's filer access allows anyway. The SSH listener options are ignored
and nothing but SFTP is written to stdout.

Checked with OpenSSH's sftp -D: put/ls/rm on the whole filer without a
store; with a store the user is jailed to its home, and a user missing from
the store is refused.

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

* sftp -stdio: explain an unreadable user store, test the stream

The session runs as the logged-in OS user, who must read the store; a
store without passwords or keys can be shared with them. Tell that user
why the store is refused instead of a bare permission error.

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

* sftp: stdio sessions reuse handleSFTP

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

* sftp: a refused -stdio session exits 1 without printing usage

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

* sftp -stdio: give up after 30s when the filer is unreachable

The listener keeps waiting for the filer; a stdio session is one login and
should not hold a process for the whole outage.

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

* sftp -stdio: bound the filer configuration request by the wait

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

* sftpd: skip the unreadable-store test on Windows

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

* sftp: detect the sshd Subsystem launch instead of a -stdio flag

weed sftp serves one session on stdin/stdout when sshd starts it: SSH_CONNECTION
is set and stdin and stdout are both pipes or sockets. A listener started by
systemd, a container, nohup or a shell has a terminal, /dev/null or a file
there, so it keeps listening.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 04:02:12 -08:00
f88ca328da sftp: answer md5sum, sha1sum, df and echo exec requests (#13277)
* sftp: answer md5sum, sha1sum, df and echo exec requests

SFTP clients such as rclone verify transfers and show free space by running
md5sum/sha1sum/df over an SSH exec request. weed sftp rejected every exec
request, so rclone fell back to comparing sizes and could not report usage.

Answer the few commands those clients send, without a shell:

- echo <text>: prints text (rclone's shell detection)
- md5sum/sha1sum [path]: the file's hash in coreutils format, or the
  empty-input hash without a path (the support probe). The path is resolved
  inside the user's home and needs read permission. MD5 uses the hash the
  filer stored when there is one, otherwise the content is read.
- df [-k] [path]: the filer's volume capacity in df -k format

Anything else fails with exit status 1. Checked with rclone: hashes md5 and
sha1 detected, md5sum/sha1sum match local files, `rclone about` works.

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

* sftp: describe exec commands without naming one client

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

* sftp: exec hashes cover sparse files and stop with the connection

- md5sum/sha1sum read a file's whole logical content, with zeros for the
  holes and tail no chunk stores, through the same sparse-aware stream an
  in-place SFTP write uses; it ends with the SSH connection
- a trailing escaped space stays part of the file name
- df checks that the path exists

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

* sftp: relative exec operands, hashes of holes stop, setstat size clears MD5

- a command's relative path is relative to the home, as over SFTP, so df
  and the hashes of a root-home user look up the right entry
- writes into the hash check the connection, so a large file that is all
  holes stops too
- a size change through SETSTAT drops the stored MD5, which md5sum reports

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

* sftp: an exec ends when the client closes its channel

The command's context ended only with the SSH connection, so a client that
closed one exec channel and kept the connection left a hash running. The
channel's request stream closes with the channel, which now cancels it.
A second exec on the same channel is refused, as OpenSSH does.

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

* sftp: a channel runs one exec or one SFTP session

With the exec running beside the request loop, a subsystem request after
it would have started SFTP on the same channel while the command was still
writing to it.

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

* sftp: refuse a subsystem request without a name instead of panicking

The subsystem name was read as Payload[4:], so a request with fewer than
four payload bytes panicked the channel goroutine and stopped the server.
Decode the name like the exec command.

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

* sftp: test that a running exec keeps its channel from starting sftp

Also say in handleExec that its context ends with the channel.

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

* sftp: df drops -k only as a whole option

"df -kfoo" was read as "df foo"; now -kfoo is the path, which fails
unless such a file exists.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 03:54:26 -08:00
e32f1aa20e filer: don't evict a chunk a stream is still reading (#13276)
* filer: don't evict a chunk a stream is still reading

The reader cache map and the budget fell back to evicting a chunk a
stream was in as soon as they found no idle one, even while a running
download held the rest and would become evictable once it finished. The
stream then fetched its chunk again. They now evict a pinned chunk only
once pinned chunks alone fill the limit or the budget. A budget wait
wakes when a stream enters or leaves a chunk, and when a pinned
download reserves.

A read across a chunk boundary leaves the stream's chunk before making
room, or its pin would count against another stream's chunk, and carries
the stream to its last chunk. Its reads of the chunk it leaves hold that
download, start first and take no concurrency slot, as evicting the
chunk waits for them.

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

* filer: wait for the budget waiter in reader cache tests instead of sleeping

A reservation that reaches the budget only after the sleep sees the new
state on its first check, so these tests could pass with the wakeup or
the wait rule they cover removed. Wait until the reservation is parked
in reserve, and fail at once if it finishes without waiting.

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

* filer: release blocked test fetches when a boundary read test fails

A t.Fatal before the gate closed left the deferred cache destroy waiting
for the blocked fetch, so the test hung instead of failing. The wait for
the head read to pin chunk0 is now bounded too.

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

* filer: hold the chunk a boundary read leaves from one look at the stream

The hold pass looked up the stream's chunk per task and the leave looked
again, so a concurrent read on the same reader that moved the stream in
between got its new chunk detached and unheld, and the boundary read could
download that chunk again. Take the stream's chunk once, hold it for the
views reading it, and detach only that chunk.

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

* filer: tie the budget-wait test check to the test's own reservation

waitForBudgetWaiter now starts the reservation itself and only accepts a
goroutine parked in reserve that is that goroutine or a download it
started, so an unrelated waiter cannot let a test move on early. The
direct budget tests cancel their waiter on cleanup, since destroy() does
not reach a cacher outside the map.

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-02 03:52:46 -08:00
Chris LuandClaude Opus 5.5 ca09dae400 filer/postgres: postgres and postgres2 share their connection setup (#13252)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of directory statements

Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: batch lookup takes row keys and matches rows by name and directory

A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: build the connection string with pgxutil.BuildDSN

The credential store already does; it quotes values per libpq, so a
password or certificate path with spaces or quotes no longer breaks the
connection string. The OpenPGXDB alias has no callers left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: scan pages take the row key of the last row as their cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: postgres and postgres2 share their connection setup

ReadConnection reads the settings and their defaults, Connection.Open
opens the store's pools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: test the arguments each generator binds

Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

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

* filer/postgres: escape the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:46:57 -08:00
Chris LuandClaude Opus 5.5 abe623c570 filer/sql: generators bind their own statement arguments (#13251)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of directory statements

Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: batch lookup takes row keys and matches rows by name and directory

A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: scan pages take the row key of the last row as their cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: test the arguments each generator binds

Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

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

* filer/postgres: escape the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:45:44 -08:00
889d15b8de sftp: refuse paths that are not valid UTF-8 (#13279)
* sftp: refuse paths that are not valid UTF-8

Filer entry names are proto strings and must be valid UTF-8.
util.FullPath.DirAndName replaces invalid bytes in the last path element
with "_", but leaves the directory part as is. So an SFTP request naming
"bad\xfe" silently acted on "bad_": Mkdir created a directory "bad_",
Rename moved the source to "bad_", Open/Put uploaded to "bad_", and
Stat/Setstat matched an unrelated "bad_" entry. Any later request using
the name as a directory then failed to marshal, so the mangled entry
could not be removed under the name the client used. rclone's
FsEncoding/invalid_UTF-8 test hits this and leaves "invalid utf-8_"
behind, breaking every later listing check.

Reject such paths in toAbsolutePath, which every request (including the
rename target) goes through, with SSH_FX_BAD_MESSAGE, so nothing is
created or changed.

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

* sftp: shorten the invalid UTF-8 path comments

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 03:43:49 -08:00
ca4d7939ab sftp: fail listing a missing directory (#13280)
The filer streams nothing for ListEntries on a directory that does not
exist, or on a file, so OPENDIR succeeded and READDIR returned an empty
listing. Clients could not tell a missing directory from an empty one:
`rclone lsf remote:does-not-exist` exited 0, and rclone's
FsListDirNotFound test got nil instead of "directory not found".

When the first page comes back empty, look the path up and return
os.ErrNotExist unless it is a directory, which the request server sends
as SSH_FX_NO_SUCH_FILE. Non-empty listings pay no extra lookup.

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:43:25 -08:00
Chris LuandClaude Opus 5.5 2574cedfd3 s3: publish a recovered PUT's event at its commit stamp (#13265)
* s3: publish a recovered PUT's event at the stored entry's commit stamp

A PUT whose create committed but lost its answer, and that recovery
then found stored, published its event at the gateway's clock. A later
write to the same key that carries its filer stamp could then sort
before it. Both recovery paths now take the stamp the committing filer
gave the stored entry, as recovered multipart completions do.

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

* mq: return the context error when it ends a topic configure

A start whose context ended during ConfigureTopic on the last broker
answered with the RPC's text, so errors.Is(err, context.Canceled) did
not hold for it as it does for a context that ends before an attempt.

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

* mq: name the broker whose topic configure failed

doConfigureTopic built lastErr with the broker address but returned the
bare RPC error, so a failed configure did not say which broker refused.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:38:58 -08:00
5a8e774e36 shell: harden volume.tier.upload for unattended batch runs (#13254)
* shell: harden volume.tier.upload for unattended batch runs

- validate -dest against the master's storage backends before any volume
  is marked read-only, instead of failing per volume after the freeze
- mark replicas read-only with canDelete so TTL expiry keeps draining the
  volume during the upload, and restore writable marks when the upload or
  metadata replication fails partway
- keep going after a per-volume failure in batch mode and report all
  errors at the end
- treat an unset -disk as "any disk"; flag.String never returns nil and
  ToDiskType("") is the hdd type, so the batch silently skipped ssd and
  tagged volumes

Refs #13223

* shell: keep deletes refused while volume.tier.upload copies a volume

A delete accepted during the copy appends a tombstone to the source .dat,
so the attach refuses the upload, and one accepted after a replica's .idx
snapshot is dropped when that replica installs the copy.

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

* shell: leave replicas that were read-only alone when a tier upload fails

VolumeMarkWritable persists ReadOnly=false, so the rollback cleared an
operator's read-only mark on any replica that was frozen before the run.

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

* shell: roll back the replica whose read-only mark failed in volume.tier.upload

VolumeMarkReadonly freezes the volume locally before its second master
notification, so an error there leaves the replica read-only although it
never joined the marked list. Also name that replica in the error.

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

* shell: let the tiered source accept deletes once every replica has its index

The copies load as tiered volumes that accept deletes, but the source kept
the no-delete mark until its next reload, so a delete applied on a copy
then failed on the source.

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

* shell: bound each rollback mark in volume.tier.upload

A stalled VolumeMarkWritable held up the upload error and, in a batch run,
every later volume.

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

* shell: keep replicas frozen when the tier upload attached before failing

A stream that breaks after the volume server attached the remote copy
returns an error, and reopening the other replicas then let them take
writes the remote copy lacks. Ask the source first; a rerun finishes the
upload from its remote copy.

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

* shell: bound the final delete mark in volume.tier.upload

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-02 03:38:02 -08:00
e10cf7fd85 shell: a moved volume does not keep its source disk id in the model (#13275)
* shell: a moved volume does not keep its source disk id in the model

adjustAfterMove added the moved volume to the target's VolumeInfos with the
source's DiskId. volumeServer.evacuate moves the normal volumes first and then
plans the EC shards on the same topology, where the disk ids of a node come
from its volume and shard records. A volume moved off disk 3 of a four-disk
server therefore gave its one-disk target a disk 3, the planner sent EC shards
there, and the target refused every such move with "invalid disk_id 3: only
have 1 disks".

The target server picks the disk for a moved volume, so record it with disk id
0 (unknown) on a copy, leaving the source's record as it is.

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

* shell: test the EC phase of evacuate on the model the volume phase left

Drive evacuateNormalVolumes and then evacuateEcVolumes, the two phases
the command runs on one topology, instead of calling adjustAfterMove
directly, and check the disk each planned shard move names.

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

* shell: trim comments on the moved volume record

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-02 03:32:44 -08:00
Chris LuandClaude Opus 5.5 2b157f2ef1 test: clear the codespell hits left after #13290 (#13264)
* test: use a codespell-clean non-ASCII key in TestEncodeKey

Codespell reads caf%C3%A9 as the misspelling caf.

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

* topictable: reword want's in the CheckSchema comment

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:28:00 -08:00
Yip LeoandClaude Opus 5.5 22abfe2d1b shell: leave emptier servers without free slots out of the -byDiskUsage ideal (#13247)
* shell: leave emptier servers without free slots out of the -byDiskUsage ideal

volume.balance -byDiskUsage never picks a server without a free volume
slot as a move target, but planBalance counted every server in the ideal
ratio. A server that is emptier than the rest but has no free slot, as
happens to an auto-sized disk (no -max) whose free space is held as
growth room for its partly written volumes, pulled the ideal below the
usage of the servers that could take a volume. Every target's next
ratio then exceeded the ideal, planBalanceMove stopped at the first one,
and the run planned no move while the fullest servers kept filling.

The ideal of a -byDiskUsage run now leaves those servers out: a server
without a free slot below the ideal is dropped and the ideal recomputed
over the rest, until none is below it. A server without a free slot
above the ideal still counts, as it is drained as a source.

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

* shell: leave servers out of the -byDiskUsage ideal by their raw ratio

idealRatioOfReceivingServers compared a server with DensityRatio, which
gives a server with no whole volume used a floor of half a volume over
its capacity. A small disk without free slots then compared above the
ideal and stayed in it, holding the ideal under the targets' next ratio
as before. Compare the raw used/capacity ratio, the one the ideal is
made of.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:22:35 -08:00
Chris Lu 081218bf8a test: reword misspelled fixtures that trip codespell (#13290) 2026-12-02 03:21:01 -08:00
9f9c28471f s3api: free the parts a multipart completion does not name (#13248)
* s3api: free the parts a multipart completion does not name

prepareMultipartCompletionState skipped every entry of the upload
directory whose part number the request does not name: it was neither a
part of the object nor one of the unused entries freed with their data.
The completion then removes the upload directory metadata-only, since
the object's chunks are its parts' chunks, so the skipped parts' chunks
stayed on the volume servers with nothing referencing them until a
volume.fsck purge. Once the upload is completed they cannot be listed,
completed or aborted any more.

The completion now keeps those entries aside and, once its object is
committed and the upload directory is gone, deletes their chunks by
file id, resolving manifest chunks first. They are not freed before the
commit, as the unused attempts are on the routed paths: until a
completion succeeds the upload stays open with all its parts, and the
commit transaction can still refuse the write. When another completion
of the upload owns the commit (metadataOnlyCleanup), its object can hold
them, and they are kept.

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

* s3api: give the unrequested-part cleanup one deadline and check the committed object first

The client waits for the completion it already committed, so the cleanup
of the parts the request did not name gets one deadline,
unrequestedPartsCleanupTimeout, instead of a lookup timeout for each part
with manifests: the chunks of the parts without manifests are deleted
first, then manifests are resolved part by part while time is left.
deleteOrphanedChunksWithContext passes the deadline to the volume lookups
and deletes; deleteOrphanedChunks keeps its behaviour.

A completion without a ring owner commits under the object lock without
the upload-directory precondition, so a routed completion of the same
upload can commit after it with a list that names those parts, and
remove the directory. The cleanup now frees them only when the key's
current object is this completion's commit (this upload, the same
chunks), checked once the directory is gone, when no routed completion
can commit any more.

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

* s3api: deleteOrphanedChunks takes the context its lookups and deletes use

Fold deleteOrphanedChunksWithContext into deleteOrphanedChunks instead of
keeping a second name; the existing callers pass context.Background().

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

* s3api: check the entry the completion wrote, under the cleanup deadline

The check before freeing the unrequested parts resolved the object by
its key, outside the cleanup deadline. A key ending in "/" is written
inside the directory it names ("dir/" at dir/dir), so the check read
another entry and kept the parts, and a filer that stopped answering
after the commit could hold the completion without a limit. The
completion now records where it writes its object (the version file on a
versioned bucket), and the cleanup reads that entry back, from the write
owner when there is one, under the same deadline as the deletes.

Each part whose manifests resolve is deleted before the next manifest is
read, so a read that runs out the deadline no longer strands the parts
resolved before it.

The cleanup's filer reads, that check and deleteOrphanedChunks' volume
lookup, go through withFilerClient with the deadline, so the deadline
running out is not booked as a failure of the filer and does not open
its circuit for other requests.

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-02 03:18:04 -08:00
Chris LuandClaude Opus 5.5 ab6b1598b9 mq/offset: fix a flaky partial-listing test (#13288)
mq/offset: fail the test lookup the way a filer store does

TestListConsumerGroupPositionsReturnsWhatItReadOnAFailure flaked (about
1 in 60 runs): its fake filer failed the unreadable position with
codes.Unavailable and no details, which pb treats as a dead channel. The
shared ClientConn was closed and the concurrent loads of the other
partitions failed with it, so the listing returned one position, not two.

A real filer answers a store read error with a plain error (codes.Unknown),
which keeps the channel. The fake now does the same.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:15:58 -08:00
Chris LuandClaude Opus 5.5 9e4e1ade67 filer: conformance suite for filer stores, run against Postgres and MySQL in CI (#13250)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/store_test: create the shared fixtures before the subtests

The scan and delete-folder-children subtests read the order directory that
only the list subtest created, so selecting either one with -run failed on
a conforming store.

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

* filer/store_test: roll back a transaction an assertion abandons

A failed assertion between BeginTransaction and the commit left the
transaction open with its locks, and the cleanup's DROP SCHEMA then waited
on them until the go test timeout.

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

* filer/store_test: check limited listings without trimming the result

The limit-1 checks sliced the listing to one name, so a store that ignored
the limit passed, and one that returned nothing panicked. Allow only the one
look-ahead entry the SQL stores return and compare the first name.

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

* filer/store_test: give the exclusive limit check three eligible names

Starting after a%b left only two names under the prefix, so a store that
ignored the limit still met the one look-ahead bound.

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

* filer/store_test: check that a bucket drop removes nested entries

A store that reports CanDropWholeBucket gets no recursive walk from the
filer, so its DeleteFolderChildren on the bucket has to remove every
descendant. With only a direct child in bkt2, a store that deleted the
direct children and kept the table passed.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:13:02 -08:00
Chris LuandClaude Opus 5.5 51d2b2b712 mq: read a table-backed topic's history from its Iceberg table (#13260)
* mq: read a topic table's data files back as log entries

A view of a topic's table holds the current snapshot's offset map and, per
_partition, its data files with the _offset and _ts_ns bounds from the
manifests. A partition's rows are read by offset or by time, skipping files
and then row groups whose bounds miss the read, and come back as the log
entries they were copied from: key, timestamp, offset, and the message as
_value or as the record re-encoded from its columns. Views are cached per
topic, rechecked every few seconds, rebuilt only when the metadata location
moves, reuse already-parsed manifests, and are evicted past a bound on the
data files they hold. A table that is gone or replaced by another UUID reads
as empty; one with delete files is refused.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a table-backed partition below its table's high-water mark from the table

The merged reader takes the partition's table, looked up on every read so a
table attached later is seen. An offset read below the mark reads the table
up to the mark and continues into the log files and compacted parquet from
the mark; a time read takes the table's rows after the time and then the
files' entries at or above the mark. Log files left below the mark by a
crash between the writer's commit and its delete are never read. The broker
hands its partitions' disk reads to the table through the topic's cached
view; a topic without a table, or whose topic.conf is gone, reads its files
as before.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: start a table-backed partition's offsets at its table

A partition whose log files below the table's high-water mark were deleted
would reload with a high-water mark and log start taken from the files that
are left. Loading it now continues its offsets no lower than the table's
mark and starts its log at the table's lowest offset, or, when the table
holds nothing of it, at the first file offset at or above the mark. A
retired range of a repartitioned topic is read and bounded the same way,
and a retention purge raises the log start likewise, so purging hot log
files never makes the table's offsets out of range.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: keep a flushed data source's finished flag atomic

The streaming goroutine sets finished while the merge loop reads it through
HasMore, which the race detector reports on any scan that reads flushed
data.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: scan a table-backed topic's history from its table

The hybrid scanner hands each partition's merged read the topic's table,
so a scan reads the table's data files below the partition's high-water
mark, pruned by _partition, _offset and _ts_ns, and log files from the mark
on, skipping any a crash left below it. Aggregations no longer answer such
a topic from parquet statistics and log counts, which hold none of its
table's rows; they scan instead.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a schematized row's raw _value back as its message

A schematized topic's table can keep a message that is not a record, a
tombstone or an undecodable value, as raw bytes in an optional _value with
the record columns null. Such a row now reads back as those bytes; a row
whose _value is null reads back as its record, and a schemaless topic's row
as its _value as before.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: delete log files a topic table already holds

A log file or compacted parquet whose every offset is below a partition's
table high-water mark is never read again, so it can go. The mark used is
that of the newest snapshot at least a minute old: a reader's view of the
table is at most a few seconds old, so it already reads those offsets from
the table and never from a file being deleted. Files without an offset
range and the file holding the partition's highest offset are always kept.
DeleteCoveredLogFiles is for the topic's writer after its commit; a leader
also deletes them under its fence on load and on each retention pass,
covering a writer that crashed between its commit and its delete.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: report a topic table's rows as parquet_archive

A table-backed topic's scan labelled every row live_log, its table's
included. The flushed data source now records the high-water mark of the
table its merged read was handed and reports the rows below it, which come
only from the table's parquet data files, as parquet_archive.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: delete the log files a topic table holds after each run

Every mq_topic_table run now ends by deleting, in each partition, the log
files wholly below the offsets of the newest snapshot at least
LogDeleteGrace old, never the leader's newest file. A commit is never old
enough on the run that makes it, so each run deletes what earlier ones
copied; the partition's leader deletes the same files when no run follows.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a time read's position when nothing on disk follows it

A time read that found nothing after its position returned a position at
time zero: the parquet reader reports the newest time it delivered, which
is none. A loop over an empty memory buffer then read the whole partition
from the start, came back to the same empty read, and started over, so a
query asking a broker for its unflushed messages streamed the partition
forever. The merged and the table-tiered readers now keep the position
when they deliver nothing past it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: publish a topic table view under the lock eviction reads it with

A loaded view was stored under its entry's loading lock while eviction,
run by another topic's load, read every entry's view under the cache's
lock, so two topics refreshing at once raced. A view is now stored holding
both locks: a load reads it under the first, eviction under the second.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep no topic table view larger than the whole view cache

Eviction never dropped the view just loaded, so one topic whose table had
more data files than the cache's bound stayed cached past it, and evicted
every other topic's view on the way. Such a view is now answered and not
kept; the others stay.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: look up a topic table's mark again where a read leaves the table

A read kept the table mark it started with. One slow over the table's
rows could outlast the grace: the writer commits past that mark, the logs
below the new mark are deleted, and the read then lists the logs from its
old mark and passes over the deleted offsets without a word. The read now
asks for the table again each time it leaves it and reads on in the table
up to the mark it finds, until the mark stops moving; a time read takes
the rows between the marks by offset. A gap where the logs begin is
checked against the table once more, and read from the table if it took
it meanwhile.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a topic table's timestamps back without going through nanoseconds

A timestamp or time column was turned into micros by way of nanoseconds,
which overflow for dates before 1678 or after 2261, so a year 1 or year
9999 value came back as another date. Each unit now converts to micros
directly. The table fixture wrote every topic's rows whole into _value
once every table had that column, so the record columns these reads take
went untested; it now writes a schematized topic's rows as columns.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* iceberg: order a compaction bin by the first sort field that varies in it

A topic table sorts by _partition, then _offset, and is partitioned by
_partition, so every file of a bin holds one _partition. Ordering the bin
by it kept the files in manifest order, and a merged file's offsets came
out of order for the topic table reader, which delivers a data file's rows
as offsets in order.

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

* mq broker: list a retired range from its table's lowest offset

A topic lookup lists each retired range with the bounds of its own files,
so once the table held a range's history and its log files went, the range
was listed from its newest file on, while its reader serves the table's
offsets below it.

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

* iceberg: never merge compaction inputs across a file left out of the merge

A file already at the target size takes no part in compaction, yet small
files on both sides of it in sort order went into one bin, so the merged
file's bounds spanned it. For a topic table that is a data file whose
_offset range overlaps another's, which a reader finishing one file before
the next cannot read in order. An ordered bin is now cut wherever a file
left out of the merge falls between two of its files, so every merged file
covers a range no file outside its run lies in.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: merge a topic table's overlapping data files by offset when reading

A partition's data files were read one after another by their lowest
offset, which only reads in offset order while no two ranges overlap. A
rewrite by another engine can leave a file spanning another one, and then
a read from inside the overlap delivered the spanning file's later rows
first, and a read that stopped early left the rows in between behind.
Files whose offset ranges overlap are now read together, their rows merged
by offset and an offset held twice delivered once.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: open a topic table's data files only as a read reaches them

A merged read opened every file of an overlapping group before it
delivered a row, and a file the manifest records no offset bounds for
overlaps every other one, so a short fetch held a reader for each file of
the partition's history. The files of a read now wait in a heap keyed by
the lowest offset each can hold, and a file is opened only once nothing
before that offset is left to deliver; a file without bounds is opened
where the read starts, and its row groups' statistics skip what they rule
out.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: retire no log file a topic's table does not hold yet

Retention deleted a table-backed topic's log files by age alone, so with
the table writer behind it deleted messages the table did not hold, and
they were gone from both. On such a topic a file now expires only once
all it holds is below the table's mark of a grace-old snapshot, the same
files the leader deletes as covered; what the table holds ages out with
table retention.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound a table-backed range's bounds by its caller's deadline

The table lookup that widens a partition's bounds ran under a background
context, so a retention pass or a retired-range lookup with a deadline
waited on a stalled table catalog for as long as it stalled. It now runs
under the caller's context.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check a topic table's mark again when a time read reaches its files

A time read caught up with the table and then read the files above the
mark it last saw. A view that had moved on meanwhile, with the logs below
its new mark deleted before the files were listed, left the offsets
between the two marks to neither. The time read now asks for the table
again at the first file entry it would deliver, or after the files if they
held none, and on a moved mark reads the table up to it before reading the
files again.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: bound the topic table views kept, empty ones included, and keep those in use

Eviction only counted data files, so views of tables holding none, and
entries a failed first load left behind, were never dropped; and it could
drop an entry while a caller was loading it, so the next caller loaded the
same table again alongside. A failed first load now leaves no entry, at
most maxCachedTopics views are kept, and an entry a caller still holds is
never evicted. The eviction test now requires exactly the one eviction
that makes room.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check a topic table afresh before deleting the logs below its mark

A leader's covered-log delete and log retention took the table's mark
from the cached view, up to a few seconds old, so a table rolled back to a
lower mark meanwhile had its logs above that mark deleted although it no
longer held them. Both now check the table before acting: the cache takes
a maximum age, a read passes ViewRefresh and a delete zero. A cached view
is also reused only for the same table state, since a commit that rewrote
the metadata in place keeps its location.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* iceberg: leave a sort field holding nulls to order a compaction bin

A sort field whose bounds are one value in every file was taken as
constant and the bin ordered by the next field, yet bounds leave nulls and
NaNs out, so a column holding them besides its one value is not constant.
A field is now skipped only when the files also record no null in it, and
no NaN for a floating point one.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: delete a topic's covered logs only while it still names the table

A run's log cleanup used the table metadata the run started with, so after
the topic left the table, or the run lost its lock, it still deleted the
logs below that table's marks. The cleanup now checks, when it runs, that
it still holds the topic's lock and that topic.conf still names the table
with its recorded UUID, and reads the marks from the table as it is then.
It still runs after a run that failed otherwise.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: check a topic table again before each covered log it deletes

The leader read the table's mark once, listed the files below it, then
deleted them one by one, so a rollback or a detach landing in between went
unseen and files the table no longer held were deleted. The delete now
holds the table writer's lock, so the topic cannot leave the table
meanwhile, and before each file reads topic.conf and the table afresh,
stopping at the first file not below the mark it finds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: let a caller waiting on a topic table's load give up at its deadline

A caller wanting the view a stalled load of the same table was making
waited on a mutex, past its own deadline, for as long as the load stalled.
The entry is now held by a one-token channel a waiter selects on with its
context, so it returns at its deadline and lets go of the entry.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: give up a scan's table lookup when the query is cancelled

The table a scan reads below each partition's mark was looked up under a
background context, and the flushed data source waited on its channels
alone, so a cancelled query stayed blocked on a stalled table catalog. The
scan's context now reaches the topic.conf read and the table lookup, and
the data source returns once it is done.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: take a topic table's lock only when a covered log is left to delete

The leader's covered-log pass took the table writer's lock for every
table-backed partition it leads once the table had a mark, every five
minutes, even with nothing to delete. While a copy run held the lock, each
such partition waited out the lock wait and logged a failure, holding up
the rest of the retention tick. List the covered files first and take the
lock only when there are some; the per-file checks under the lock stay.

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

* mq: drop a topic table view only with the last caller holding it

An oversized view was removed while other callers still held it, so the
next caller loaded it again alongside; an entry no load filled was removed
only by a failing load that was its sole holder, so one whose callers
failed or gave up in another order stayed; and eviction that found every
candidate held left the cache above its bounds with nothing to evict
again. Callers now let go through one release: the last one removes an
entry no load filled or one marked to drop, as an oversized view is, and
each release runs eviction again.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: check a topic's table again before each covered log the cleanup deletes

The cleanup checked the lock, topic.conf and the table once, then deleted
every file below the marks it read, so a detach, a dropped or replaced
table, or a lapsed lease landing during the deletes went unseen. The
deletes now check all three again before each file, with the mark of the
table as it is then, and stop at the first file not below it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: let a flushed data source's producer close its own channels

Next can return on the query's cancellation while the producer is still
sending, and the merge then closes the source, which closed the result
and error channels under that send. The producer now owns them: Close
only signals it to stop, every send also selects on that signal, and the
producer closes the result channel when it exits, after sending its one
error if it has one.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: fail a scan whose data source fails after its first row

The merge only logged an error from a source past its first row, the
query's cancellation included, and returned the rows read so far, so a
cancelled or timed-out COUNT or SUM answered with a wrong number. It now
closes its sources and returns the error, and the scan wraps it, so a
caller can tell the context's error from others.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: check a topic table again before each group retention deletes

Retention read a table-backed partition's deletable mark once, chose its
expired groups, then deleted them with no further look, as the covered-log
delete did before it rechecked; a rollback in between left groups deleted
that the table no longer held. The live and retired purges and the
covered-log delete now share one guard: it holds the table writer's lock
and, before each group or file, reads topic.conf and the table afresh,
stopping at the first one not below the mark it finds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound a partition load's reads of what it already stores

Loading a partition reads its files' offset range and, for a table-backed
topic, the table's, while holding accessLock, under a background context,
so a stalled filer or table catalog held every other partition operation
for as long as it stalled. The reads now get the bound a load's fence
take has; past it the load fails, as it does when the stored offsets
cannot be read, and the caller retries. Falling back to the log files'
bounds would start the log above the table's offsets with no later
refresh to lower it, so consumers resetting to the earliest offset would
skip the table's history.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: count a flushed source's pending error as more to read

The merge asks HasMore before reading a source again, and HasMore looked
only at buffered rows and whether the producer finished, so a producer
that failed after its last row and finished before the merge asked had
its error never read, and the scan returned the rows so far as its
answer. An error waiting counts as more to read now, so Next returns it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: keep the table's files of a topic that left it before the delete

A topic that left its table between the listing of what the table held
and the guard the delete takes got no guard, which let every listed file
go, though readers take those offsets from the logs again. Files chosen
by the table's rules, the covered logs and the groups retention trimmed
to the table's mark, are now kept when no table remains; files of a topic
that had no table when the pass began still expire as before.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: order the pending-error merge test's row before its error

The test's producer could send its error before the first Next took the
row, and Next then picked either one, so on some runs the error came
through the first read and the test passed without exercising HasMore.
The producer now holds its error until the first Next has the row, and
the merge asks again only after the producer has finished, so the test
fails every time without the pending-error fix.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a topic table's chunk-backed files under the caller's context

A manifest or manifest list stored in chunks was read through a stream
reader built without a context, and the stream reader looked up and
fetched each chunk under a background context even when built with one,
so a stalled volume server held a partition load past its bound while it
held accessLock. A chunk stream reader now looks up and fetches its chunks
under the context it was built with, and a table's chunk-backed files are
read with the caller's.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: keep the expiredLogFiles doc comment on expiredLogFiles

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

* mq broker: let the table catalog read chunk-backed table metadata

The broker's table catalog reached its filers through a client with no
way to look up chunk locations, so a table whose catalog record holds
only the location of its metadata, as one whose metadata outgrew a
request does, failed to load once that file was stored in chunks: the
topic's history could not be read. The client now resolves chunks the
way the broker's own filer client does.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* iceberg: read chunk-backed table metadata under the caller's context

A catalog record holding only a metadata location had its chunk-backed
file read by StreamContent, whose lookups and fetches run under a
background context, so a stalled volume server held a table load past its
caller's deadline: a broker loading a table-backed partition under
accessLock past its bound. The read now streams under the read's own
context, which already bounds its other filer calls.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* filer: give up a LookupFn volume lookup's retries at its caller's deadline

LookupFn retried a failed volume lookup through util.Retry, which sleeps
its backoff without looking at the caller's context, so a lookup failing
near a deadline outlived it by up to the whole backoff; a table load under
a broker's accessLock held it that long. The lookup now retries through
util.RetryWithBackoff with the same transient-error rule and about the
same total wait, which stops when the context is done.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:48:04 -08:00
Chris LuandClaude Opus 5.5 284d491587 s3: forward notification topics to webhook targets (#13245)
* util: move the guarded dialer out of the volume server

The deny list and the dialer that re-checks every resolved address at
connect time move into weed/util/netguard, with the allow-private knob as a
policy, so other outbound clients can dial through the same guard.

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

* mq: fence consumer group position saves by generation

A position saved with a generation is written only while the stored one
carries no newer generation, or the same generation from another writer:
the save reads the stored position and writes on the condition that it is
unchanged, routed to the entry's owner filer, and re-reads when another
writer got there first. A single consumer that elects itself can then store
its offsets without a deposed predecessor overwriting them. Saves without a
generation keep overwriting as before.

Loading a missing position now reports ErrNotFound instead of trying every
filer and marking each one failed.

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

* s3: post bucket event batches to a webhook target

A webhook destination renders a batch of records as one
{"Records":[...]} body, posts it with the target's bearer token, and takes
any 2xx as delivered. The renderer is a function the destination holds, a
stand-in that refuses until the record renderer lands. It dials through the
guarded dialer under a new Local policy, which refuses metadata-service,
link-local and unspecified addresses at connect time but lets an operator
point a target at a private host or a sidecar on loopback. Redirects are
followed only to the endpoint's own host and never down from https.

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

* s3: forward each target's topic to its destination

A Forwarder runs beside the Publisher on every gateway. Each enabled target
with a destination gets a lock, s3.notify.<target>, held through
LockClient.StartLongLivedLock, so one gateway forwards a target and targets
spread across gateways; a topic target has none.

The holder runs one loop per partition of the target's topic: fetch from the
stored offset at the partition's leader, decode the records, deliver them as
one batch, store the next offset. A fetch that stops short at a segment
boundary just continues from its next offset. A failed send, a rejected one
included, blocks the partition and is retried with capped backoff, and the
offset is stored only after the destination took the batch. An offset that
retention removed skips to the earliest one and counts the gap.

Offsets go to the consumer group offset storage under group forwarder,
fenced by the lock generation. On taking the lock a forwarder stores each
partition's offset back under its generation, so an older holder's saves are
refused and it stops. A stored generation at or above its own means the
lock was lost, unless the forwarder has since held the lock through a full
renewal, which happens only when the lock server's counter restarted; it
then fences above the stored generation.

Metrics per target: records delivered, send retries, retention gaps, and
lag from the forwarding gateway.

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

* s3api: run notification forwarders beside the publisher

Every gateway with filers starts a Forwarder with the publisher. It elects
itself per target through the gateway's object-write lock client, stores
offsets in the filer, reads through the same brokers the publisher uses,
follows the target registry as the publisher does, and releases its locks
on shutdown.

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

* s3: post a test event to a webhook on its own

The renderer refuses an s3:TestEvent that shares a body with other records,
so a webhook splits a batch around each one and posts them in order, the
test event as its own body. The test is a stand-in until the renderer's
lands.

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

* s3: skip a bucket event record that can never be delivered

A record that does not decode, or that the renderer refuses, used to be
retried like a failed send and would block its partition for good. The
webhook now renders a whole batch before posting any of it and names the
records that cannot render; the forwarder drops those, counts them per
target and reason in notification_skipped_records_total, logs each offset
once, and sends the rest. Only transport and HTTP failures are retried.

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

* mq: read a fenced position save at the filer that applies it

The fenced save read the stored position from whichever filer answered and
then sent its conditional write to the key's owner, so with filers that keep
their own stores the condition could be checked against an entry other than
the one read, failing until replication caught up or judging a stale copy.
The storage now takes the ring's owner lookup, the one route-by-key writes
already use, and sends both the read and the write to that filer. The
gateway hands its object-write lock client's PrimaryForKey to the forwarder
offsets.

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

* s3: follow a repartitioned notification topic

A forwarder listed its topic's partitions once, when it took the lock, so a
repartition left the new partitions unforwarded until the lock moved. It now
lists them again every 30 seconds, starts a loop for each new partition, and
marks the loops of partitions no longer listed as replaced; such a loop keeps
delivering what its partition holds and ends once it has caught up. A
failed fetch now looks up the leader of that exact partition, not of any
partition with the same range.

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

* s3: let the first forwarder take the lock before the second asks

The election test synced both gateways at once, and each forwarder asks for
its lock from its own goroutine, so the second could ask first and store the
offsets the test expected from the first.

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

* s3: warn when a partition returns nothing below its high-water mark

A fetch that returned no records and kept its next offset below the
high-water mark looked like an idle partition, so the forwarder waited
without a word while its lag stayed up. It still waits, since skipping would
lose the records, but now warns at most once a minute with the topic,
partition, offset and high-water mark, so the lag has an explanation.

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

* s3: render webhook bodies with the bucket event renderer

The webhook now renders through Render and posts each s3:TestEvent alone by
IsTestEvent, replacing the stand-ins it held until the renderer landed.
The tests send real records and read the object keys and test request ids
back out of the bodies.

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

* netguard: refuse the IPv6 and Alibaba metadata service addresses

AWS's IPv6 metadata address fd00:ec2::254 is unique-local and Alibaba's
100.100.100.200 sits in the CGNAT range, so the Private and Local
policies let a webhook or remote endpoint reach them. Refuse both under
every policy, like 169.254.169.254.

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

* grafana: chart the notification forwarder metrics

Add an S3 Notifications row with delivered records, lag, send retries,
and records skipped or lost to retention per target.

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

* s3: follow only webhook redirects that keep the POST

On a 301, 302 or 303 Go resends the request as a GET without a body, so an
endpoint that redirected and then answered 2xx counted as delivered while
it received no records. Only 307 and 308, which keep the method and resend
the body, are followed now; any other redirect fails the send and is
retried.

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

* s3: keep webhook endpoint secrets out of errors and logs

The guarded dialer names its endpoint in every refusal, and the forwarder
logs that error, so a webhook endpoint carrying credentials in its userinfo
or a token in its query had them written to the log. The dialer now gets
the endpoint as scheme, host and path only, and the parse and request
errors no longer echo the URL.

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

* mq: load a consumer group position from its owner filer

A forwarder taking over read its start offset from whichever filer answered,
while its fenced saves read and write at the key's owner. With filers that
keep their own stores, a replica still holding an older offset handed the
new holder that offset, which it then stored under its higher generation at
the owner, replaying everything delivered since. Loads now go to the owner
too when the storage knows it.

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

* mq: bound consumer group position loads and saves by the caller

LoadConsumerGroupPosition and SaveConsumerGroupPosition ran their filer
calls under context.Background(), so a filer whose store stalled held a
forwarder's save forever: ending the lead waited on it, the lock was never
released, and Close hung while the lock kept renewing. Both now take the
caller's context; the forwarder gives each call its RPC deadline under the
lead's context, so stopping returns and the lock is released. The offset
wrappers the broker uses keep their signatures.

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

* mq: list a consumer group's positions across partition generations

ListConsumerGroupPositions walks every generation and range directory of a
topic and returns the group's stored position in each, keyed by partition
directory, so a consumer can tell which ranges it holds offsets for that
the topic no longer lists.

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

* s3: stop forwarding ranges a repartition removed

A repartition drops the old assignments, and the broker serves only
assigned ranges, so the loop draining a removed range retried a refused
fetch forever, and after a restart nothing looked at it at all. Reading a
removed range's flushed data would need a read-only path in the broker.
Until then a removed range's loop delivers the batch it holds and ends,
and the forwarder logs an error naming each range it stops and, when it
takes the lock, each partition directory holding a stored offset the topic
no longer lists. The fake broker now refuses unassigned ranges as the real
one does.

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

* s3: deliver what a repartition left in the retired ranges

The lookup now offers the sealed ranges a repartition retired, and any
broker serves them from their files, so the forwarder no longer drops
them. On taking the lock and on each re-list it asks for the retired
ranges too and runs a loop for each, from its stored offset up to its
high-water mark, after which the loop ends; a range it was forwarding as
current and that is now retired gets the same end. A read below a retired
range's log start counts as a retention gap, as for a live one.

A key's records in a retired range precede its records in the ranges that
replaced it, and loops running side by side would not keep that order. So
the retired ranges go first, one generation at a time, oldest first, and
the current ranges start only once none is left. A range listed neither as
assigned nor as retired, as while a drained range is not sealed yet, pauses
until it is offered again.

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

* s3: match a retired range to its forwarding loop by directory

The broker lists a retired range at the second its generation directory
is named for, while the assignment the forwarder started its loop from
carried nanoseconds. After a repartition the retired entry missed the
running loop, so a second loop started on the same stored offset and
delivered the batch the first was still retrying. Key the loops by
partition directory; the fake broker now lists retired ranges and the
fake positions store offsets at that resolution, like the real ones.

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

* s3: replace a paused forwarding loop only once it ended

A range drained but not sealed yet is listed neither as assigned nor as
retired, so its loop is paused and dropped from the lead's loops while
it may still be retrying a batch. Once the range was offered as retired
a new loop started at the stored offset and sent that batch again. Keep
a paused loop until it ends, and start the range again only then.

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

* s3: hold the new ranges while a drained one is not sealed yet

A repartition saves the new ranges before it drains and seals the old ones,
so for a while an old range is offered neither as assigned nor as retired,
and the forwarder started the new ranges at once: a key's new records could
go out before its records still waiting in the old range. On each look at
the topic the forwarder now lists the directories holding a stored offset
that the topic does not offer, and probes each at its offset; one that may
still hold records past it, refused because it is not sealed, holds the new
ranges until it is offered as retired and drained. One that answers with
nothing past the stored offset is settled, sealed and empty or already
delivered, and stays so for the lead. While holding, the forwarder logs at
most once a minute and keeps looking even with no loop running.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: have the fake broker serve only the generation a fetch names

The broker now refuses a fetch naming a generation other than the one it
assigns for the range, unless that generation is sealed and read as
retired. The forwarder tests' fake broker matched an assigned range by its
range alone, so it served the live generation to a fetch for an older,
unsealed one; it now matches the generation too, as the broker does.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold the current ranges until the stored offsets can be listed

A lead whose first look at the stored offsets failed took that as no old
range left unsettled and started the current ranges, delivering a key's
newer records ahead of the ones still in a drained range that is not sealed
yet. A failed look now holds the current ranges as an unsettled range does,
and is retried with backoff and on each partition refresh; the current
ranges start only after a look succeeds. Retired ranges and loops already
running carry on meanwhile.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3api: leave forwarding off on an unusable broker TLS config

The forwarder loaded the grpc.msg_broker client TLS config with
LoadClientTLS, which exits the process on a bad one, and every gateway with
filers builds a forwarder whether or not it has webhook targets. It now
loads it as the publisher does: an unusable config is logged and leaves
forwarding off while the gateway keeps serving.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold the new ranges for an unsealed old range with no stored offset

The check for old ranges still unsealed looked only at ranges holding a
forwarder offset. A forwarder starting for the first time while a drained
range was not sealed yet had stored none in it, so it started the new
ranges and delivered a key's newer records ahead of its older ones. The
consumer group listing now names every partition directory of the topic,
with no position where the group stored none, and such a range is probed
from offset 0. A range with nothing left past that offset, including one
whose records retention already removed, is settled.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check the load in the fenced save race test

The test read the stored position back ignoring the load's error, so a
failed load panicked on a nil position instead of reporting the error.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: take a partition over at the offset its last holder committed

A new forwarder generation claimed a partition by writing the offset it
had loaded. When the old generation committed again in between, the claim
rewound the stored offset and the new lead replayed what had been
delivered since. A fenced save that takes over from an older generation
now keeps the offset that generation committed last, rereading it on a
conditional write miss, and hands it back in the position, and the
forwarder starts from it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: wait for a position's owner filer instead of asking another

A position store routed by owner fell back to any filer while the owner
of a key was not known yet, as before the lock ring is learned. That
filer's not-found ended the load there, though it may only not have
caught up, and a claim on it would start the partition over. Loads and
fenced saves now fail until the owner is known, and the forwarder
retries them; a store without an owner routing still uses any filer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: wait for the last checkpoint before a forwarder handoff in tests

The resume, repartition and election tests stopped the first forwarder
once its records were delivered but possibly before their offsets were
stored, so they could pass on a replay rather than on a committed
handoff. They now wait for the final offsets first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: have Close wait for removed targets to release their locks

A target removed from the registry had its forwarder cancelled and
dropped from the targets, so a Close soon after did not wait for it and
returned with that target's lock possibly still held. Removed forwarders
are now kept until they are done, and Close waits for them as well.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold newer retired generations behind an unsealed older one

A range of an old generation still unsealed held back only the current
ranges. A generation retired after it was offered and delivered right
away, ahead of the older generation's records of the same keys. The
unsealed range's generation now counts as the oldest one left, so only
that generation's own sealed ranges are forwarded until it is sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: check the forwarder lock right before each send

A lead checked its lock at the top of each fetch and after a failed send's
backoff, so a lead that lost the lock while it fetched a batch still sent
it, and the next holder sent it again. The lock is now checked right
before each send. Delivery stays at-least-once: a lock lost during a send
cancels that send once the lead notices, which may be after the endpoint
took the batch.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: read a retired range past a broker that answers with an error

Any broker serves a retired range from its files, but a fetch took the
first broker's answer even when it was a storage error, and each retry
asked that broker first again, so one broker that could not read the
files held the range up for good. A retired fetch answered with an error
other than an offset out of range now goes on to the next broker, and
returns the error only when none could read it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count ranges held back behind an older generation in the lag

The lag gauge summed what each running loop reported, so the current
ranges held back while an older generation was still unsealed, and the
retired generations waiting their turn, showed no lag however much piled
up in them. On each partition refresh the lead now reports their lag
from the stored offset to the high-water mark, read from the range's
leader or the retired listing, and drops the lag of ranges it no longer
has.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold retired generations too while stored offsets cannot be listed

A lead whose look at the stored offsets failed held only the current
ranges and went on forwarding retired generations, though an older
generation it could not see might still be unsealed and hold earlier
records of the same keys. A failed look now holds every range not yet
running until a look succeeds; loops already running carry on.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: read stored offsets only of the ranges a lead does not know yet

The check for unsettled ranges listed every partition directory and read
every stored offset in it one by one under one deadline, before dropping
the ranges the topic offers and those already found settled. A topic
with many past generations could take longer than the deadline on every
refresh and hold a new lead for good. The listing now takes the
directories to skip and reads only the remaining offsets, a few at a
time, and the lead skips the offered ranges and those it found settled.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: test the failed-listing hold with no unsealed range

The failed-listing test also had an older generation unsealed, which
holds the newer ranges on its own once a listing succeeds, so it did not
show the listing guard by itself. A second case has no unsealed range:
nothing goes out while the listing fails, and both the retired and the
current range do once it succeeds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: stop the lead before marking a failed loop ended

A forwarding loop that failed, as on being deposed, was marked ended
before it cancelled its lead. A partition refresh in between saw a
retired range's loop ended, took the range as delivered, and started the
next generation's ranges on the lead that was about to stop. The lead is
now cancelled first, so no refresh acts on the failed loop.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count no retention gap below an offset only claimed

A lead claiming a partition with no stored offset wrote offset 0 to fence
it before reading anything. A lead that stopped there left 0 behind, and
the next one, finding the log start past it, counted those offsets as
lost though no forwarder had ever been at them. A claim made before any
read is now marked as such, a takeover keeps the marker of the entry it
replaces, and only an offset a lead read from counts a gap.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: retry a takeover save at the offset it kept

A claim's save that took a partition over from an older generation kept
that generation's last offset, but when its reply was lost the retry
went out with the offset the claim had loaded. The stored entry was by
then the claim's own, so the retry kept nothing and rewound the
partition, replaying what had been delivered since. A failed save now
retries with the offset and marker the attempt settled on.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: store an offset as read from once the first fetch succeeds

A claimed offset lost its claimed marker only when a later save moved it,
so a lead that read an empty partition and stopped left it marked as
never read. Records published and then removed by retention while no
gateway forwarded the target were skipped without a gap counted or
logged. The first successful fetch now stores the offset as read from,
once per claim, even when it has not moved.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: wait for the stalled topic's publisher before reading it in a test

The worker sets the topic publisher up on its own goroutine, which on a
loaded host can start after Publish has stopped waiting.

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

* s3: keep what a timed-out offset check settled for the next one

A check for unsettled ranges that could not read every stored offset
within its deadline returned nothing, so each retry read the same ranges
again and a long enough history kept the new ranges held for good. The
listing now returns the positions it read along with the error and goes
on past one that fails, and the check probes those and keeps the ranges
it finds settled before reporting the failure, so the next check reads
only the rest. The ranges stay held until a check covers them all.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: say which records the notification lag counts

The lag gauge's help, and the dashboard panel with none, read as every
undelivered record, but the records of an old range still being sealed
after a repartition cannot be read and are not counted. Both now say the
gauge covers the current ranges, the ranges held back behind an older
generation, and the sealed retired ranges.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:45:41 -08:00
Chris LuandClaude Opus 5.5 960230f86d mq: keep keyless and valueless messages in compacted parquet (#13258)
* mq: keep keyless and valueless messages in compacted parquet

mq.topic.compact treated every message without a key, every message
without a value, and every value that happened to parse as a
DataMessage with a Ctrl as a control entry, and left it out of the
parquet it wrote. Kafka records with a null key and tombstones were
gone once retention removed their logs, and so was a JSON string value
whose bytes parse that way.

The only control entry a log holds is a publisher's close marker, which
the broker logged without its Ctrl, as an entry with neither key nor
value. That is now the whole rule, for compaction and for reading
parquet back. A schematized topic's message without a value is still
left out, since its row has no column to hold one.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: ack a publisher's close marker without logging it

The marker a publisher sends when it finishes was appended to the
partition log like a message, minus its Ctrl, so it took an offset and
sat in the log as an entry with neither key nor value that every reader
had to recognize and skip. The broker now acks it and moves on. Every
message the publisher sent before it on the stream was acked first, so
the publisher's wait for its last ack is unchanged. Logs written before
still hold markers, which readers keep skipping.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: log a Ctrl message that carries a key or value

The close-marker branch dropped every DataMessage with a Ctrl, though
one carrying a key or value was published before. Only a bare marker,
a Ctrl with neither, is acked without an offset now; anything else is
stored at its offset as it was.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query engine: skip only close markers, as compaction does

Compaction now keeps keyless messages and values that happen to parse as a
DataMessage with a Ctrl, but the SQL engine still dropped both from log scans
and live-log counts, while COUNT(*) took parquet row counts from file stats.
After compaction COUNT(*) included messages SELECT did not show. Scans and
counts now use the same rule as compaction and parquet reads.

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

* query engine: leave out a schematized message without a value, as compaction does

Compaction writes no row for a schematized message without a value, so a live
log count that included one dropped by one once its log was compacted. Scans
and live-log counts now skip what compaction skips.

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

* query engine: count only rows among broker-buffered messages

The COUNT(*) fast path added every unflushed broker message, so a close marker
or a schematized message without a value counted until its flush, when the
live-log count left it out. Unflushed messages now count by the same row rule.

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

* query engine: test the broker-buffered count against the scan

COUNT(*) adds the broker's unflushed messages by the row rule a scan of
them uses, but nothing tested it. The count moves into countRows, and
the scan test checks it gives the number of rows the scan returns for a
schemaless and a schematized topic, so close markers and schematized
messages without a value stay out of both.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:10:22 -08:00
Chris Lu 6a9fe874d7 mq: keep a time read's position when nothing on disk follows it (#13259)
A time read that found nothing after its position returned a position at
time zero, since the parquet reader reports the newest time it delivered.
A loop over an empty memory buffer then read the partition again from the
start. The broker's unflushed-message query does exactly that, so once a
partition's buffer was flushed and empty it streamed every flushed message
as unflushed, and weed sql counted each row twice. The merged reader now
keeps the position when it delivers nothing past it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34
2026-12-01 20:33:02 -08:00
Chris LuandClaude Opus 5.5 bc1b805c82 mq: copy a table-backed topic's sealed log data into its Iceberg table (#13256)
* mq: export logstore's log file offset range and control entry checks

The topic table writer decides what is sealed from a partition's file
offset ranges and drops the same control entries compaction drops, so it
calls these instead of keeping copies.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: tell which of a partition's files its leader will not write again

A topic table may only take what is sealed. The fence names a writer
and an epoch, not a file, and each flushed window lands whole as a new
file under it, so every log file but the one holding the highest offsets
is sealed; the newest may still be followed by a window in flight. A
sealed fence takes no more windows, so all of its files are. Parquet
left by mq.topic.compact rewrites earlier logs and is always sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a topic table's copied offsets in its snapshot summary

Each append records seaweedfs.mq.offsets, the first offset of every
partition not yet in the table. A snapshot that rewrote files without
carrying the map defers to its newest ancestor that has one; a table with
snapshots and no map anywhere holds rows of unknown offsets and is not
written to.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: build a topic table's rows from log entries

A message becomes a row of its table: the system columns from the log
entry, then the record's fields by name, or the whole message in _value
for a schemaless topic. Rows are laid out in the table's current schema
through iceberg-go's Arrow mapping, so the Parquet file they are written
as carries the table's field ids and the types Iceberg readers expect.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: compare topic tables by name in topictable

The table writer in the worker has to tell whether topic.conf still names
the table a job was proposed for, by bucket ARN, namespace and name, the
same way the broker compares a configure request with what is stored. The
comparison moves next to the rest of the topic table layout so both call
it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's offset map through maintenance snapshots

Compaction, delete rewrites and manifest rewrites keep a table's rows,
so the offsets a topic table holds are unchanged by them. Their
snapshots now carry the parent's seaweedfs.mq.offsets, so the topic
writer and readers find the map on the current snapshot rather than
only on an ancestor that snapshot expiry may remove.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: start a table's running totals at its first snapshot

Totals were only carried from a parent that recorded them, so a table
whose first snapshot the worker wrote never got total-records or
total-data-files, and no later snapshot could carry them. A snapshot
without a parent adds to an empty table, whose totals are zero.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's sealed log data into its Iceberg table

copyTopicTable reads each partition from the offset the table's current
snapshot records up to what its leader has sealed, through the merged
reader that already serves log files and compacted parquet, and writes
the rows as data files under data/<_partition>/ named by their offset
range. A file holds one partition value, so it never spans partitions or
days, and its rows are one contiguous offset run in offset order.

The append goes through commitWithRetry and records the advanced offset
map in seaweedfs.mq.offsets. Each attempt re-checks that topic.conf
still names the table and that the table still names the topic, and
re-reads the map: a partition another writer moved since this run
planned keeps that writer's offset, and this run's files for it are
removed, so no offset is appended twice. A run that dies before its
commit leaves only unreferenced files for orphan removal. Log files are
left in place; the broker cannot read the table yet.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: run mq_topic_table for topics that name an Iceberg table

The worker registers an mq_topic_table job beside iceberg_maintenance and
runs it in the Iceberg lane. Detection reads every topic.conf under
/topics; a topic naming a table is due once one of its partitions has
128 MiB sealed past the table's offsets or a sealed file 5 minutes old.
Execution takes the filer lock mq.table.<namespace>.<topic>, so one
writer copies a topic at a time, and copies only while topic.conf still
names the table the job was proposed for; a topic that left it ends the
job without failing it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy only into the table whose UUID topic.conf recorded

A table dropped and replaced at the topic's table name still carries
the name, and may carry the topic's property if its creator copied it.
The broker records the UUID of the table it created or adopted in
topic.conf, so the writer checks it before planning and again before
each commit attempt, and stops rather than append the topic's offsets
to a table that is not the one the topic holds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep keyless and valueless messages in a topic table

The table becomes a topic's only copy once copied logs are deleted, and
the writer dropped what compaction drops: every message without a key
or without a value. Those are data; a Kafka record with a null key is
one. The only control entry the log holds is a publisher's close
marker, which the broker stores without its Ctrl, as an entry with
neither key nor value. IsControlMarker names exactly that, IsControlEntry
keeps its wider rule for compaction, and the writer skips markers only.

A keyless message gets a null _key. A skipped marker's offset stays
below the partition's offset in the map, so the table records it as an
offset that held no message rather than a gap left to fill.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: change a topic's table under its table writer's lock

A configure that left a table checked it for snapshots, then saved
topic.conf. The table writer checks topic.conf before each commit, so a
detach saved between that check and the commit's CAS left a table
holding the topic's data with no topic. The broker now takes the
writer's filer lock, mq.table.<namespace>.<topic>, before the release
check and keeps it through the topic.conf save, so it sees what the
writer committed, and the writer sees the change before committing.

The wait is bounded at 15 seconds: a configure behind a long copy is
Unavailable and retried rather than holding the configure RPC. The lock
key moves to topictable so the broker and the worker share it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: make a topic table's record columns optional

A field's is_required became a required column, so a message missing
that field could not be written and the table writer stopped at its
offset. Once copied logs are deleted the table is the topic's only copy,
so every message needs a row. Record fields now map to optional columns
at every level; the system columns stay required. Adopting a table still
refuses one whose record columns are required, since it could not take
such a message.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a message its topic's record type cannot hold in _value

A schematized topic's tombstone, or a value that is not a RecordValue
of its type, stopped the table writer at its offset, and once copied
logs are deleted the table is the only copy. Every topic table now has
an optional _value column. A message whose value is empty, does not
parse, carries bytes a RecordValue does not have, names a field the
table lacks, or holds a value its column cannot take gets null record
columns and its raw bytes in _value. A decoded message leaves _value
null. A row is checked whole before any column takes it, so a fallback
leaves no partial row behind.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's history into its table in bounded runs

A run read every sealed offset past the table's map and committed only at
the end, so a topic attached with a long history could not finish within
the job's one-hour timeout: each attempt rewrote the same files, removed
them on cancel, and the map never moved. A run now stops at a file boundary
once it has written 4 GiB and commits the offsets its files cover; the next
detection picks up the rest.

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

* mq: decode a record read back from compacted parquet into its columns

logstore's parquet reader hands back a schematized row as its RecordValue,
which still holds the file's _ts_ns, _key and _offset columns. The row
writer took those for fields outside the table, so every message the copy
read from mq.topic.compact's parquet landed as raw _value with null record
columns. Those three fields are the entry's own and are now passed over.

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

* mq: map a repeated field already typed as a list to one list

The Kafka protobuf and JSON Schema decoders describe a repeated field with
both a ListType and IsRepeated, and their values are one ListValue deep.
mapField wrapped the list type again, so the column became list<list<T>>
and every message with a non-empty repeated field fell back to raw _value.
Avro gives the item type with IsRepeated, which still gets wrapped once.
MQ's own parquet schema already ignores IsRepeated on a list type.

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

* mq: keep a decimal past its column's precision in _value

rescaleDecimal checked only that the rescaled value fit 128 bits, so an
unscaled value from 10^38 up to 2^127 was written into the decimal(38,18)
column, which engines then read as an overflow or null. The value is now
checked against the column's precision, so such a message keeps its raw
bytes in _value like any other value the record type cannot hold.

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

* mq: bound a published decimal before rescaling it

A DecimalValue's scale, precision and bytes come from the publisher,
and rescaling to the column built 10^|18-scale| before checking
anything, so one message with an extreme scale could hold a worker's
CPU and memory on every retry of the copy. A scale or precision beyond
the column's 38 digits, or a magnitude longer than 32 bytes, cannot fit
decimal(38, 18) and is refused before any arithmetic; the message keeps
its row with its bytes in _value like any other value its column cannot
take.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's files when its commit's outcome is unknown

A commit whose update of the table entry failed without an answer, a
reset connection or a deadline, may still have been applied by the
filer. The run then deleted its data files and manifests, and
commitWithRetry its new metadata file, leaving a committed snapshot
pointing at files that were gone.

Such a failure is now errCommitOutcomeUnknown, and commitWithRetry keeps
the metadata file for it. The topic table writer reads the table again:
a snapshot it built that is in the current lineage is a commit, kept and
reported as one. Otherwise, or when the table cannot be read, the files
stay for orphan removal, since an update still in flight could land
after the read. Only a refused commit, a conflict or a stopped run,
deletes them.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: count a partition's rows after its last flush

copyPartition returned total and flush() in one statement, and Go does
not order reading total against calling flush, so the rows of the last
file could be left out of the count. The last flush now runs first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: report the rows a topic table commit kept

A run's rows_written was every row it staged, though a commit attempt
drops the files of a partition another writer already moved, and a run
that commits nothing reported its staged rows all the same. It is now
the record count of the files the committed snapshot added.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: wait for a topic's table writer outside topicConfLock

A configure that moved a topic off its table waited up to 15 seconds
for the table writer's lock while holding topicConfLock, which every
configure, lookup cache miss and rebalance of every topic takes, and a
caller that gave up kept waiting.

The configure now reads topic.conf first and, when the request moves
the topic off the table it names, takes the writer's lock before
topicConfLock, the order the writer keeps since it never takes
topicConfLock. The wait ends when the caller's context does, and a grant
that arrives after that is released. A configure that finds the table
changed under topicConfLock without holding the writer's lock is
Unavailable and retried.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound the topic.conf read a table change starts with

The read that decides whether a configure must wait for the table
writer runs before topicConfLock, and so before the 30 second bound
lockTopicConf puts on calls made under it. A caller without a deadline
then hung on a filer that took the read and never answered. The read
now gets the same bound of its own, still outside topicConfLock.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep what an unanswered maintenance commit may reference

Compaction, delete rewrite and manifest rewrite delete everything they
wrote when their commit fails. When the failure is an update of the
table entry that went unanswered, the filer may have applied it, and
the table then points at data files, manifests and a manifest list that
were just deleted. Those are now left for orphan removal on
errCommitOutcomeUnknown, as the topic table writer already does;
conflicts and other definite failures still clean up. Snapshot expiry
deletes nothing before its commit succeeds and needed no change.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: test a topic table retry that keeps only one partition's files

A run whose commit loses to a writer that copied only one of its
partitions keeps the other partition's file. The test checks that the
retry reports only that file's rows and that each offset lands once.

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

* mq broker: wait for the detach's refused lock request in the table lock test

A fixed sleep did not show the detach had reached the table lock, so a
late goroutine let the lookup pass with nothing waiting. The fake filer
now counts refused lock requests and the test waits for the first one.

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

* mq broker: check the table writer's lock before saving a table change

A configure that moves a topic off its table holds the writer's lock
from its release check through the topic.conf save, but never looked at
it again. A lease that lapsed meanwhile, its renewals failing, may
already be the writer's, which can then commit to the table the
configure is about to detach. The configure now checks that it still
holds the lock right before the save and is Unavailable otherwise.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: check a topic table copy's lock and topic last before committing

Each commit attempt checked the lock, topic.conf and the table's owner
before writing its manifests and manifest list, and nothing after, so a
lease that lapsed or a detach that landed while they were written went
unnoticed. The attempt now checks again once they are written, the last
step before commitWithRetry saves the metadata file and updates the
table pointer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: read a topic's conf with the topic table job's context

The table writer and detection read topic.conf with ReadConfFile, which
takes no context, so a filer that took the read and never answered held
the job, its worker slot and its renewed table lock, and held up
detection, past any cancel. They now read through
ReadConfFileWithMetadata with the job's or the detection's context, so
a cancelled job ends and lets its lock go.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:29:34 -08:00
github-actions[bot] 228dadd5c0 docs: regenerate star history chart 2026-12-02 03:54:58 +00:00
Chris LuandClaude Opus 5.5 3f2f625822 s3: publish bucket events to each notification target's MQ topic (#13244)
* mq: report when a published message is acknowledged

Publish now returns a channel the publisher closes once the broker acks
that message, including an ack that arrives on a later stream after a
resend. A caller that has to know its message is stored, such as the S3
gateway answering a request only after its event is durable, can wait on
it with its own bound; callers that do not care ignore it.

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

* s3: build bucket event records in the AWS shape

An Event is what one operation did to one object; Record turns it into
an eventVersion 2.7 record for one rule, and Message wraps that record
in the Records envelope a consumer receives. The key is form-encoded per
path segment as AWS does it, size and eTag are left off removals, and
the sequencer is the filer's commit stamp as 16 hex digits, so one key's
sequencers compare as strings in commit order. The s3:TestEvent message
is built here too.

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

* s3: publish bucket event records to each target's MQ topic

The Publisher runs one worker per enabled target. The worker creates the
target's topic, s3.notify-<target> with 4 partitions and 7 days of
retention, then hands records to the MQ publisher keyed by bucket/key so
one object's events stay in one partition in order. Setup retries with
backoff, so a broker that is down or still taking the balancer lock after
a cold start delays records instead of losing them. A removed or
disabled target's worker stops; its topic is left for retention to age
out, since a forwarder may still be draining it.

Publish queues every record and waits up to 2 seconds, or until the
request ends, for all of them to be acked, and reports whether they
were. A record not acked by then stays queued and is still sent; the MQ
publisher resends it across leader changes. Each target's queue holds
10000 records; past that, and for records whose target has no worker, a
record is dropped. Acked, late and dropped records, the queue depth and
the wait are exported as metrics.

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

* s3api: start a bucket event publisher with the gateway

The gateway creates one event publisher and syncs it with the target
registry whenever the registry loads or changes, so each enabled target
gets its topic and worker. The publisher bootstraps from the broker the
command started beside the gateway, passed in as MqBroker once it bound,
and from every broker the masters list, so a gateway running without its
own broker still finds the cluster's. Broker connections use the
grpc.msg_broker TLS section. Shutdown stops the workers.

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

* s3api: send the test event before storing a notification configuration

Unless x-amz-skip-destination-validation is true, PUT notification
publishes an s3:TestEvent to the topic of every target the configuration
names, in parallel, and fails with InvalidArgument listing the
destinations whose topic did not ack it within the publisher's 2 second
wait. Nothing is stored in that case. The registry checks still run
with the header, and an empty configuration sends nothing.

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

* s3api: publish ObjectCreated events for PUT and POST

A PUT, including a "dir/" marker, publishes ObjectCreated:Put and a POST
upload ObjectCreated:Post, after the filer commit and before the
response, once per matching rule of the bucket's configuration, waiting
for the acks within the publisher's bound. A failed write publishes
nothing and a slow or absent broker never fails the request.

The sequencer is the filer's stamp of the commit. putToFiler records it,
from the routed ObjectTransaction or the lock path's CreateEntry, with
the committed size, into the request so the handler finds it; the marker
write and a create recovered after an ambiguous route return none, and
take the gateway's clock instead.

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

* s3api: publish ObjectCreated events for copy and multipart completion

CopyObject, including a metadata-only copy onto itself, publishes
ObjectCreated:Copy, and CompleteMultipartUpload publishes
ObjectCreated:CompleteMultipartUpload, both after the commit and before
the response; a copy that keeps the connection alive publishes before
its final answer.

The write wrappers these use dropped the transaction response, so they
now return the filer's commit stamp: routedMkFile, writeMultipartObject,
routedVersionedFinalize, routedMultipartFinalize, routedSelfCopy and
finalizeCopyDestination. Writes that go off the owner, through mkFile,
still return none and the event takes the gateway's clock.

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

* s3api: publish ObjectRemoved events for deletes

DeleteObject and DeleteObjects publish ObjectRemoved:DeleteMarkerCreated
when a delete without a version id leaves a marker in place of the key,
in a versioning-enabled or suspended bucket, and ObjectRemoved:Delete
for any other delete, including the delete of a marker by its version
id. The record carries the marker's or the deleted version's id.
DeleteObjects publishes one event per key it deleted and waits for all
of them at once.

The routed delete wrappers now return the filer's commit stamp:
routedDeleteSpecificVersion, routedDeleteNullVersion,
routedDemoteNullVersion and createDeleteMarker; deleteMutationResult
carries it to the handler. A suspended delete uses the stamp of the null
version's delete, since the marker write after it returns none. Deletes
on the lock path go through DeleteEntry, which has no stamp, and take
the gateway's clock.

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

* mq: report the ack of a published record too

PublishRecord now returns the same ack channel as Publish, so a caller
publishing to a topic with a record type can wait for its record to be
stored. Both go through doPublish, which registers the waiter for every
message.

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

* s3: carry bucket events as schematized records

A notification topic now has a record type, EventRecordType, the single
source for its flat snake_case columns: the event, requester, bucket and
object fields, the commit stamp as sequencer, and multipart columns for
later. event_time, event_name and bucket_name are required, the rest
optional, and changes to it are additive only. The topic is configured
with it, with bucket_name and object_key as key columns and the schema
format left empty as for the other schematized topics, and records go
out through PublishRecord.

The record holds raw values: the object key unencoded, the sequencer as
an int64, and nulls where a value is absent, such as size and eTag on
removals. Render turns records into the AWS JSON a destination receives,
the Records envelope with eventVersion 2.7, a form-encoded key and a hex
sequencer, or the test event message for an s3:TestEvent, so forwarders
produce exactly the body the gateway used to publish.

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

* s3: shut a stopped target's publisher down even while it is blocked

With the broker away long enough to fill a partition's unacked buffer,
the worker blocks inside PublishRecord. Removing, disabling or closing
the target only cancelled the worker's context, which the blocked worker
never looked at, so the publisher and its queued records lived on and
resumed sending once the broker came back. Stopping a target now shuts
its MQ publisher down directly, which releases the blocked publish, and
does it in the background so Sync and Close do not wait for the flush. A
publisher that finishes setting up after the stop is shut down at once,
and a worker that dequeues a record after the stop drops it.

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

* s3api: publish nothing for a retried multipart completion

A CompleteMultipartUpload retried after the object committed is answered
from that commit and writes nothing, yet the handler still published an
ObjectCreated:CompleteMultipartUpload, with size 0 since no commit was
noted. AWS sends the event once, for the completion that created the
object, so the handler now publishes only when the request itself
committed.

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

* s3api: take an event's principal from the authenticated identity only

With auth off, the gateway keeps the s3-account-id header the client
sent, and an event's principal_id fell back to it, so any client could
name itself as the requester in the record a destination trusts. The
principal is now the identity name authentication put in the request
context, or anonymous.

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

* s3api: turn notifications off instead of exiting on a bad broker TLS config

The event publisher loaded the grpc.msg_broker client TLS with
LoadClientTLS, which exits the process on a config it cannot use, such
as a cert without its key, so a broker-only TLS mistake took the S3
gateway down even with no notification targets. It now loads it with
TryLoadClientTLS and, on an error, logs it and runs without a
publisher: object writes publish nothing and a notification
configuration's test event fails. It never falls back to an insecure
connection.

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

* s3: count a record dropped while its request waits only as dropped

A record dropped while a request waited for it, by a PublishRecord error
or its target being stopped, was counted dropped where it was dropped,
and then late when the request's wait ran out, which it also sat
through in full. Each queued record now carries a done signal that both
its ack and its drop close, so the wait ends as soon as the record's
fate is known and the drop is not counted again as late. Late still
counts a record that was neither acked nor dropped when the request
answered.

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

* mq: let a caller cancel starting a topic publisher

NewTopicPublisher returned only once a partition lookup succeeded, and
retried the lookup for as long as the broker refused it, with nothing a
caller could stop it with. It now takes a context that bounds the start:
the topic configuration runs under it, and cancelling it stops the
lookup loop and returns an error. A publisher already returned is not
affected. Existing callers pass context.Background().

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

* s3: stop a removed target's publisher that is still starting

A target's MQ publisher was started without the worker's context, so a
target removed while its partitions had no leader kept its publisher
looking them up, and its worker waiting, until a lookup succeeded. The
worker's context now bounds the start, so removing or disabling the
target ends both.

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

* s3: bound each broker's ConfigureTopic during a target's setup

Setup asked each broker in turn to configure the target's topic with
the worker's context alone, so a broker that accepted the call and never
answered held the worker there for good. Each broker now gets 10
seconds before setup moves on to the next, and a stopped worker does not
ask the rest.

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

* s3api: stamp a suspended delete's event with its marker write

A suspended-bucket delete removes the null version, then writes the null
delete marker and points latest at it. Its DeleteMarkerCreated event
took the stamp of the first step, so a write landing between the steps
got a later sequencer although the marker it lost to is what remained.
The event now takes the stamp of the pointer write, the delete's last
commit.

To get it, MkFile, the gateway's mkFile and
updateLatestVersionInDirectory return the CreateEntry stamp, and
createNullDeleteMarker returns it. createDeleteMarker's unrouted path
and writeMultipartObject off the owner now return their write's stamp
too instead of none.

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

* mq: bound each broker's ConfigureTopic when a publisher starts

NewTopicPublisher configures the topic again before its lookups, with
no deadline per broker, so a broker that accepted the call and hung
held the start until the caller gave up, even with a healthy broker
next in the list. Each broker now gets 10s before the next is tried.

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

* s3api: sequence a key's events only with stamps from its owner filer

The previous change stamped a suspended delete's DeleteMarkerCreated
with the null marker's pointer write, but that write goes to the
gateway's default filer, not the key's owner. Filer clocks differ, so a
delete could get a smaller sequencer than the PUT before it, and a
consumer deduplicating on the sequencer would drop it as stale.

Routing the marker write to the owner would move the suspended delete
onto the transaction path, a change to the write itself. Until then the
event goes back to the stamp of the null version's routed delete on the
owner, and gateway clock when the delete is not routed. The same
reasoning applies to the other stamps that change began returning from
off-owner writes, a delete marker or a multipart object written through
mkFile, so those return none again, and MkFile, mkFile and
updateLatestVersionInDirectory go back to returning only an error.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count each queued record once as acked or dropped, and late apart

A drop counted the record as dropped and then closed its done channel,
so a request whose wait ran out between the two still saw it pending and
counted it late in the same counter. Each queued record now has a
terminal outcome, acked or dropped, set once by compare-and-swap, and
notification_records_total counts that outcome alone, so every lost
record shows as dropped exactly once.

Late moves to its own counter, notification_records_late_total, counted
once per record when its request stops waiting on it before it is acked
or dropped; that record is still counted acked or dropped when it
settles.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3api: publish the event of a completion recovered after its commit

When a finalize committed but returned an error, completeMultipartUpload
answered from committedCompletion without noting the commit, so the handler
published no ObjectCreated:CompleteMultipartUpload. A retry is answered as
a replay and publishes nothing either, so the event was lost although the
object exists. The recovery now notes the commit when the stored object
holds this attempt's parts, stamped by the gateway clock as the filer's
stamp is not known. One answered from another attempt's commit stays
silent.

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

* s3api: sequence a recovered completion's event with its entry's commit stamp

A completion whose finalize committed but returned an error is answered
from the stored object, and its event took the gateway clock. The stored
entry carries CommitTsNs, the meta log stamp the committing filer gave
the write, from the same sequence as the stamps the routed write paths
return, and peers that replicate the entry keep it. The event now takes
that stamp, and falls back to the gateway clock only for an entry
written by a filer that predates it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:53:18 -08:00
Chris LuandClaude Opus 5.5 2cde975c25 mq: read, list and purge the ranges a repartition retires (#13249)
* mq: seal a partition's fence when a repartition drains it

Draining a partition shut it down and answered at once: its last window was
still being flushed, and its fence was left unsealed. A publisher still
holding the old assignment could then load the range again on its leader at
the same epoch and append to a range the topic no longer lists, so nothing
could treat a removed range as complete. The drain now waits for the last
flush, waiting out a retirement already pending too, and seals the fence
before it answers; a drained range its leader does not have loaded has its
stored fence sealed as found.

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

* mq: serve a sealed range a repartition removed from its files

A repartition drops the old ranges from the topic, and a fetch for one was
answered partition not found, so whatever a consumer had not read from it
was out of reach. A fetch naming a generation and range the topic no longer
assigns, whose fence is sealed, is now served read-only by any broker:
a stopped log buffer over the range's files, with its log start and
high-water mark read from them, answers through the same stateless read as
a live partition, out-of-range included. A reader is reused for 30 seconds,
so a purge elsewhere shows soon. An unassigned range whose fence is not
sealed may still take writes and keeps the old answer.

The test filer can now keep what is uploaded to it, so flushed windows read
back.

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

* mq: list a topic's retired ranges in the partition lookup

LookupTopicBrokers takes include_retired and then also answers
retired_partitions: each sealed range of an earlier generation the topic no
longer assigns that still holds data, with its log start and high-water
mark, read from the range's files. A consumer can find what a repartition
left behind and fetch it. Unsealed ranges are left out, since they may
still take writes.

The test filer lists the directories an entry's path implies, as the filer
does.

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

* mq: purge retired ranges past retention

The retention pass hands each partition with expired files to its leader,
but it walked only the topic's current assignments, so a range a
repartition retired kept its files forever. The balancer now purges each
sealed retired range itself, deleting its expired files under the sealed
fence as read. As for a live partition the newest file stays, so the range
keeps its high-water mark and a read below the raised log start is out of
range. The purging broker drops its cached reader of the range.

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

* mq: the offset scan of a partition's files stops with its caller

Retired fetches and listings, the retention pass and a follower take-over
now pass their context to the filer scan, so a cancelled lookup or a broker
shutting down does not wait on a filer that stops sending entries.

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

* mq: drain a repartition's old ranges only after saving the new topic.conf

A repartition drained the old ranges before saving the topic.conf that
replaces them, and a drain now seals them. When that save failed, the
ranges topic.conf still assigned were sealed: their leader could not take
their fence again, and with every broker healthy nothing moved the epoch on,
so the topic took no more writes. The old ranges are now drained after the
save, so a failed save leaves them assigned, unsealed and writable.

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

* mq: leave a drained range's fence to a holder still renewing it

A drained range its leader had not loaded had its stored fence sealed as
found. If a follower had taken that fence over and was still storing the
records it acked, the seal replaced its token, so its remaining writes
failed the fence check and those records never reached the range. The drain
now seals a found fence only once nobody has renewed it for fenceSealWait,
the same test a new leader applies; a holder still renewing it seals it
itself when done, and the drain waits for that.

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

* mq: seal a range drained while its broker shuts down

Once a broker shutdown has started it retires every partition itself, so
removing one for a drain reports false, and the drain answered success
without sealing the range. It now waits for the shutdown's last flush of the
partition and seals the fence like any other drain.

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

* mq: read retired ranges without a log buffer, dropping old readers on access

Each retired range's reader was a stopped log buffer, which still allocated
the buffers and windows a writer needs, and cached readers past their time
were dropped only when another was created. A retired range is now read
through ReadFlushedMessagesAtOffset, the stateless disk read with its chunk
cache and nothing else, answering out-of-range and end of partition as a
live buffer does; the disk read helpers take the read function and cache
instead of a buffer. Readers past retiredReaderTTL are dropped on every
lookup.

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

* mq: bound the retention pass over retired ranges

The pass over a topic's retired ranges ran under the broker's own context,
so a filer that stopped answering its listing or offset scan held the
balancer's retention loop for good. Each topic's pass over its retired
ranges now has generationPassTimeout, as handing expired partitions to
their leaders does. The test also covers a fetch of a retired range
returning with its caller.

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

* mq: a drain seals a stale fence only as it read it

A drained range its leader had not loaded is sealed once its fence has gone
fenceSealWait without a renewal. The seal required only the fence's token,
which a renewal keeps, so a holder that renewed between the drain's read and
its seal still had the fence sealed under it, and its remaining writes failed
the fence check. The seal now requires the entry as read, as a new leader's
take does, and a drain that loses that race looks again.

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

* mq: finish the drains a stopped balancer left behind

A repartition saves the new topic.conf and then drains the old ranges. A
balancer that stopped in between left them unsealed, and nothing came back
to them: repair looks only at topic.conf, and retired reads, listing and
retention skip unsealed ranges, so their records were out of reach. The
balancer's periodic pass now also looks for range directories that
topic.conf no longer names and whose fence is unsealed, and asks the
broker holding the fence to drain the range, which flushes what it holds
and seals it. A holder that does not answer is drained by the balancer
itself, which seals the fence only once nobody has renewed it for
fenceSealWait. Each topic's pass is bounded by generationPassTimeout.

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

* mq: finish a predecessor's drains on taking the balancer lock

The pass that finishes drains a stopped balancer left behind ran only with
the retention loop, so after a balancer restart its old ranges could stay
unsealed, and unreadable, for up to five minutes. A broker that finds
itself the balancer now runs the pass once right away in the background,
bounded per topic as the periodic one is, so the wait is down to the
fenceSealWait rule.

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

* mq: report a drain's error on the test goroutine

Two drain tests ran the drain, which fails the test on error, in a
goroutine of their own, where failing only ends that goroutine and leaves
the test waiting or passing on what it saw. The drain's error now comes
back over the channel the test already waits on, and the test fails there.

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

* mq: drain a repartition's replaced ranges outside the topic.conf lock

A repartition drained the replaced ranges while it still held topicConfLock,
under the lock's 30-second deadline, and the drain now waits for each
range's last flush and seal. A slow flush held every cache-miss read of
topic.conf behind the lock, could run the shared deadline out and leave a
range unsealed, and left the new ranges' assignment to a context that had
already expired. The new ranges are now assigned under the lock, and the
replaced ones drained after it is released, with a deadline of their own
sized for a flush and a seal that may wait out fenceSealWait. A range the
drain does not get to is finished by the balancer's pass over orphaned
ranges.

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

* mq: move a retired read past offsets no stored entry holds

A read of a retired range at an offset no stored entry holds, below the
high-water mark, answered no records with the same next offset and no end
of partition, so a consumer asked for that offset again forever. Such a
stretch is a gap in the offsets or entries the log could not place. The
read now looks for the lowest stored offset after it and reads from there,
and when none is held up to the high-water mark it answers the end of the
partition at the high-water mark. Below the log start the read is still
out of range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: serve a client only the partition generation it names

A partition is found by its range alone, so a fetch naming an older
generation of a range the topic still assigns, not sealed and so not read
as retired, was answered from the live partition of the newer generation:
the client read records of a generation it never asked for, at offsets that
mean something else there. A client that names a generation now gets only
that one: one that is not the assigned generation, or not the one loaded,
is refused with the partition not found a removed unsealed range gets. A
client that names none still matches by range. A publisher refused this way
looks the topic up again, as it does when the balancer is ahead of the
cached topic.conf, and the unflushed-message query and the flush
notification check the generation too.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: decide orphaned ranges under the topic.conf lock from the stored conf

The pass that finishes unfinished drains took topic.conf from the cache and
listed the stored ranges without the topic.conf lock. A balancer just
elected with a stale cache, or a repartition saving its new generation
between the read and the listing, made current ranges look orphaned, and
they were drained and sealed. The pass now takes topicConfLock, reads
topic.conf from the filer, lists the stored ranges and decides under it,
then drains what it found once the lock is released; a repartition cannot
assign a generation that is already gone, so the decision holds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: drain only the partition generation a drain names

A drain found the loaded partition by its boundaries alone. A topic
repartitioned 1 -> 2 -> 1 has its first range and its current one on the
same boundaries, so finishing the first one's unfinished drain removed and
sealed the current range instead. A drain naming a generation now takes a
loaded partition only of that generation; otherwise it seals the named
generation's stored fence, as for a range its leader has not loaded.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: leave an orphaned range's own drain time when its holder stalls

Finishing an orphaned range's drain asks the broker holding its fence
first and drains the range itself when that fails. The holder's call had
the whole per-topic deadline, so a holder that took the call and never
answered used it up, and the drain here then ran on an expired context and
did nothing. The holder now gets half the time that is left, keeping the
rest for the drain here.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: end an unflushed query a broker would redirect to itself

A broker still holding an older generation of a range it now leads under
a newer one refuses a query for the newer generation, looks the range up,
finds itself as the leader, and redirected the query to itself, which did
the same again until the caller gave up. When the lookup names this broker
the query now ends with an error saying the generation is assigned here but
not loaded; a lookup naming another broker is still followed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: refuse a loaded generation the topic no longer assigns

After a split the old range stays loaded on its broker until the drain
unloads and seals it. A fetch naming that generation passed the generation
check, since no assignment shares its range any more, and was served from a
buffer that is neither assigned nor sealed. A loaded partition is now served
by generation only while topic.conf assigns it; the cache is reread once
before refusing, so a broker whose cache predates the assignment that loaded
the partition still serves it. Once the drain unloads and seals it, the
retired reader serves it from its files.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq logstore: retry a parquet reader whose topic.conf read failed

The parquet reader reads topic.conf once, when it is built, and a failed
read left it a reader that finds nothing, for good. A merged offset read
then skipped the compacted offsets to the first log file, and a sealed
partition's reader, finding nothing stored, ended the partition at its high
water mark. The reader is now set up on its first read and again on each
read while topic.conf cannot be read, failing those reads; a topic.conf that
does not exist still means no compacted rows.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a drained range from reloading until its seal lands

A drain unlisted the range once its last flush landed, before sealing its
fence. A publisher whose topic.conf cache still assigned the range to this
broker could load it again in between, take the fence at the same epoch,
and make the seal fail, leaving the range unsealed after the repartition.
The drain now holds the range as retiring until its seal returns, so a
loader waits and then finds the fence sealed. A failed seal releases it,
unsealed and unassigned, for the orphan pass.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: seal a drained range only once all it accepted is stored

A drain sealed the fence after the partition's last flush returned, without
asking whether that flush stored anything. A flush abandoned when a broker
stop ran out its flush budget drops the window and breaks the follow stream
so the follower stores its copy, but the seal could land first, and the
follower, finding the fence sealed, gave up records the leader had
acknowledged. The drain now seals only when the flushed watermark reaches
the last accepted offset; otherwise it leaves the fence to the follower and
fails, and a later drain or the orphan pass finds it sealed by the follower
or seals it once it is stale.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:36:14 -08:00
Chris LuandClaude Opus 5.5 d915787cf1 mq: a topic can name an Iceberg table in a table bucket (#13246)
* mq: add a table option to topic configuration

ConfigureTopicRequest, ConfigureTopicResponse and
GetTopicConfigurationResponse carry a TopicTable: the table bucket ARN,
namespace and name of the Iceberg table that holds the topic's compacted
history. A request without it keeps whatever the topic has; one with an
empty table bucket ARN asks to detach it.

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

* mq: map a topic's record type to an Iceberg table layout

The topictable package lays out the table a topic's compacted history
goes into. Its columns are _partition, _offset, _ts_ns, _ts (a
timestamptz copy of _ts_ns to partition on) and _key, then the record's
fields, or _value for a schemaless topic. Scalars map to their Iceberg
counterparts, TIMESTAMP to timestamptz, records to structs and repeated
fields or list types to lists, with required-ness taken from the field.
A DECIMAL field has no precision or scale of its own, so it takes the
decimal(38, 18) the topic's parquet files already use.

The spec is identity(_partition) and day(_ts), the sort order _partition
then _offset, and the seaweedfs.mq.topic property names the owning topic.
CheckSchema says whether an existing table can hold a topic's rows,
matching columns by name so the ids a table assigns do not matter.

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

* iceberg: create and load a table in process

The create handler splits into planCreateTable, which checks the name,
authorizes the create and builds the first metadata, and
registerCreateTable, which stages the metadata file and registers the
table, with stage-create still handled between them in the handler.
Server.CreateTable runs both for a caller inside the cluster, and
Server.LoadTable answers what a load does, sharing the GetTable call and
the metadata parse with the handler. A server-side component that needs
its own table now gets the same location, metadata file, exclusive
staging and cleanup as a REST client, rather than writing metadata by
hand.

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

* mq broker: keep a topic's table in topic.conf

ConfigureTopic stores the requested table with the rest of the topic's
configuration, so it survives restarts and moves to another balancer. A
request that does not name a table keeps the stored one, including one
that changes the partition count, and an empty table bucket ARN detaches
it. GetTopicConfiguration returns it.

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

* mq broker: create or adopt a topic's table on ConfigureTopic

When a configure names a table, or changes the schema of a topic that
has one, the balancer loads the table through the Iceberg catalog the
broker now keeps over its filers. A missing table is created through the
catalog's own create path with the topic's layout and the
seaweedfs.mq.topic property; the table bucket and namespace must already
exist. An existing table is accepted only if that property names this
topic, its location is inside its table bucket, and its columns can hold
the topic's rows, so a topic never takes over a table it did not create
and a schema change the table cannot follow is refused.

The broker creates the table with no caller identity, as trusted
cluster tooling, so the table is owned by its namespace's owner like any
other table there. Deleting a topic only removes /topics and leaves the
table.

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

* mq broker: refuse to leave a topic table that holds data

A configure that detaches a topic from its table, or points it at
another one, first loads the current table, and is refused while that
table has any snapshot: its history would be left with no topic to read
or trim it. A table that is still empty, or that its owner has dropped,
can be left, and stays where it is with its property. Detaching a table
that holds data is left to an explicit command.

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

* mq broker: pass the table catalog's answers through the filer accessor

The filer accessor treats any error as a failed filer: it records the
failure, asks the next filer and wraps the last error with %v. A catalog
answer such as NoSuchTable then reached ConfigureTopic as an opaque
string, so a missing table was reported instead of created. The catalog
now goes through an adapter that returns the catalog's own answers
unwrapped and leaves failover to real filer failures.

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

* mq broker: a table hidden by its policy still holds the topic's history

GetTable answers NoSuchTable both for a table that is gone and for one a
policy denies the caller, so a topic whose table carried snapshots under
a policy denying GetTable could detach as if the table had been
dropped. When the catalog says the table is missing, the broker now
looks for its record in the filer with the new s3tables.TableRegistered,
which finds what GetTable finds before policy, and refuses to leave a
table that is registered but unreadable.

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

* mq broker: fail over the table catalog's internal errors

The adapter between the table catalog and the filer accessor passed
every S3TablesError back as a successful filer call. An InternalError is
what the catalog answers when its own read of the filer fails, so a
broken filer was recorded healthy and no other filer was asked. Only
the catalog's refusals pass through now; an internal error goes back to
the accessor, which marks the filer failed and tries the next one.

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

* mq: name a table's owning topic by its path under /topics

The seaweedfs.mq.topic property was <namespace>.<topic>, and topic names
may hold dots, so a.b/c and a/b.c wrote the same value and either could
adopt the other's table. The value is now <namespace>/<topic>, the
topic's directory under /topics: two topics that write the same value
already share one topic.conf, so they are the same topic.

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

* mq: reserve the day partition field's name in a topic's table layout

The spec partitions by day(_ts) under the name _ts_day, and Iceberg only
lets a partition field share a column's name when it is that column's
identity. A topic with its own _ts_day field mapped fine and then failed
the table create with an invalid partition spec. Schema now refuses the
name up front, with the system columns, saying it is reserved.

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

* mq broker: let the table catalog fail over to every discovered filer

The broker's filer accessor lists only the current filer, so the
failover the catalog adapter relies on had nowhere to go: an internal
error from the current filer failed the catalog call even with another
healthy filer discovered. The catalog now gets an accessor of its own
over every filer the broker has discovered, the current one first, read
under the lock that guards them. The broker's shared accessor stays on
the current filer, so topic.conf, offsets and the subscriber coordinator
keep reading one filer as before.

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

* mq broker: a topic leaves a table that no longer names it

A table dropped and replaced under the same name by one that does not
carry the topic's property holds none of the topic's history, so its
snapshots no longer keep the topic from detaching, switching tables, or
following a schema change.

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

* s3tables: keep tableMetadata's doc comment on tableMetadata

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

* mq broker: walk the table catalog's filers in order, current first

FilerClientAccessor shuffles the filers it is given, so the catalog's
create, load and registration calls each went to a random discovered
filer even while the current one answered. A filer with its own store
may not yet hold what another just wrote. Try the current filer first
and move on to the others only when it fails, as the S3 gateway does.

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

* Revert "mq broker: a topic leaves a table that no longer names it"

The property alone does not show the table was replaced: a
set-properties commit on the same table changes it and keeps the
snapshots, and the topic would then leave its history behind. Telling a
replacement apart needs the table's identity stored with the topic.

This reverts commit ddeb10a89b.

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

* mq broker: tell a replaced topic table from its own by UUID

A topic could not leave a table that was dropped and replaced at its
name by an unrelated table holding data: the snapshot guard refused to
detach or switch, and the ownership check refused to adopt. A changed
seaweedfs.mq.topic property does not prove a replacement, since a
set-properties commit keeps the same table and its snapshots.

TopicTable now carries the Iceberg table UUID, which the broker records
in topic.conf after it creates or adopts the table; a request cannot set
it. Requests are compared by bucket ARN, namespace and name only. When
the topic leaves its table, a loaded table whose UUID differs from the
recorded one is a replacement and is let go without the snapshot guard.
A matching UUID, or a topic.conf written before the UUID was recorded,
stays under the guard. Taking a table at the name still goes through
the ownership and schema checks.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:48:29 -08:00
Chris LuandClaude Opus 5.5 a8f13e7db2 filer: keep a PUT under /etc inline like a POST (#13241)
* filer: keep a PUT under /etc inline like a POST

The write handler marks /etc paths (and saveInside=true) to be stored as
inline content, but only the multipart POST path honoured it. A plain PUT
went through the chunk uploader, which keeps content inline only below
saveToFilerLimit, 0 by default, so `curl -T x.json http://filer/etc/...`
stored chunks and the loaders that read /etc files from inline content saw
nothing.

Both paths now share one saveInside write: read the body, check
Content-Md5, store it as the entry's content. An append to a chunked file
is refused for PUT as it already was for POST, and an offset write is
refused for both instead of being treated as a whole-file write.

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

* filer: skip the saveInside PUT digest checks under fips140=only

GODEBUG=fips140=only refuses MD5: the filer neither checks Content-Md5
nor reports Content-MD5, and crypto/md5 panics. The bad-digest test is
skipped there, and the inline-store test checks the digest only when MD5
is available while always checking the content is inline with no chunks.

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

* filer: answer a malformed write offset with 400

A negative, non-numeric or overflowing ?offset, and an offset with
op=append, were plain errors that the write handler answered with 500,
while a positive offset to inline content got 400. Both the inline and the
chunk path now parse it through one helper whose error carries the
ErrMsgInvalidOffset prefix, mapped to 400. offset=0 stays a whole write.

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

* filer: charge a saveInside PUT its whole body like a POST

A PUT stored inside the entry is now buffered whole by saveInsideEntry,
but uploadCharge still charged it by chunks, so -concurrentUploadLimitMB
no longer bounded the memory it holds. It is charged as the POST is: its
declared length, at most the whole budget, or the whole budget when the
length is unknown.

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

* filer: bound a body stored inside the entry at 16 MiB

A saveInside or /etc upload is read into memory whole, and nothing capped
it: one PUT or POST could grow the filer's memory without bound, as the
upload charge limits concurrency rather than bytes. The read now stops at
16 MiB, far above any config file, and a larger body is answered 413 with
nothing stored, whether or not its length was declared.

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

* filer: keep inline storage to entries inside /etc/

The /etc check was a bare string prefix, so a PUT to /etcd-backup/snap.db
or /etcetera took the saveInside path and a large body was refused with
413 instead of chunked. Match /etc/ as a directory for the write, upload
charge and zip extract paths.

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

* filer: bound a zip member kept inline like a saveInside upload

A zip member extracted under /etc/ (or with saveInside=true) is read into
memory whole, but was bounded only by the 1 TiB archive limit. Refuse a
member over saveInsideMaxBytes, as a PUT or POST body is.

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

* filer: keep a multipart POST to the bare /etc directory inline

A POST to /etc with a file name lands the file inside the /etc directory,
but the /etc/ prefix check missed the bare path and stored it as chunks.
Match /etc itself as well as entries under it.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:46:59 -08:00
d715c4e28f mount: buffer a write in memory when the swap file cannot take it (#13205)
* mount: buffer a write in memory when the swap file cannot take it

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* helm: keep the broker port off the Services

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

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

---------

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

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

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

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

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

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

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

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

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

* filer: fence lookups from the event stamp sequence

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

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

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

* filer: keep the stamp sequence above renumbered log positions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

* log_buffer: queue the final flush from ShutdownLogBuffer itself

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

* s3api: hot-reload the notification target registry

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

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

* s3: parse and validate bucket notification configurations

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

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

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

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

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

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

* s3api: store bucket notification configurations

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

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

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

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

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

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

* s3notification: reject unknown elements inside rules and filters

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

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

* s3notification: URL-decode prefix and suffix filter values

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

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

* s3api: refuse a notification targets file stored in chunks

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

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

* s3notification: refuse overlapping rules as AWS does

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

* mq balancer: load partitions whose files are past retention

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* filer_client: track a filer's backoff atomically

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* mq balancer: register each broker connection separately

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:15:37 -08:00
Chris LuandClaude Opus 5.5 3363f4a318 mq: disk and parquet reads stop when asked, resume inside earlier files, and order new stamps after stored ones (#13230)
* mq logstore: stop a disk read when the callback is done

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* mq logstore: read parquet rows at the stop time

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

* filer: AppendToEntry clears the stored content MD5

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

* mount: copy_file_range clears the MD5 once it buffers bytes

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

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

* filer: an empty AppendToEntry keeps the content MD5

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

---------

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

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

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

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

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

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

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

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

* webdav: ignore a NaN X-OC-Mtime

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

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

* webdav: group the oc test imports

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

---------

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

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

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

* filer: retry deletes refused for an offline replica

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

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

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

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

* filer: move exhausted deletion retries to dead letter queues

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* mq broker: report a balance move the target refused

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:03:20 -08:00
491 changed files with 50852 additions and 5416 deletions

No files matched your search

+24
View File
@@ -125,6 +125,28 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
mysql:
image: mysql:8.4
env:
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
options: >-
--health-cmd "mysqladmin ping -uroot -proot"
--health-interval 10s
--health-timeout 5s
--health-retries 10
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
@@ -136,6 +158,8 @@ jobs:
- name: Test
env:
RUN_REDIS_TESTS: "1"
RUN_POSTGRES_TESTS: "1"
RUN_MYSQL_TESTS: "1"
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
test-32bit:
+138
View File
@@ -0,0 +1,138 @@
name: "postgres_flat Filer Store Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/postgres_flat/**'
- 'test/s3/versioning/**'
- 'test/testutil/**'
- 'test/volume_server/framework/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-flat-tests.yml'
- '.github/actions/fix-fusermount-setuid/**'
pull_request:
paths:
- 'weed/**'
- 'test/postgres_flat/**'
- 'test/s3/versioning/**'
- 'test/testutil/**'
- 'test/volume_server/framework/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-flat-tests.yml'
- '.github/actions/fix-fusermount-setuid/**'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
permissions:
contents: read
jobs:
postgres-flat:
name: S3 and POSIX over postgres_flat
runs-on: ubuntu-24.04
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 20
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Repair the fusermount3 setuid bit
uses: ./.github/actions/fix-fusermount-setuid
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Run tests
env:
RUN_POSTGRES_TESTS: "1"
WEED_BINARY: ${{ github.workspace }}/weed/weed
run: go test -v -count=1 -timeout=20m ./test/postgres_flat/
versioning-suite:
name: S3 versioning suite over postgres_flat
runs-on: ubuntu-24.04
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 20
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Start weed mini on postgres_flat
run: |
mkdir -p "$RUNNER_TEMP/config" "$RUNNER_TEMP/data"
: > "$RUNNER_TEMP/config/security.toml"
cat > "$RUNNER_TEMP/config/filer.toml" <<'EOF'
[postgres_flat]
enabled = true
hostname = "127.0.0.1"
port = 5432
username = "postgres"
password = "postgres"
database = "postgres"
sslmode = "disable"
EOF
weed/weed -config_dir="$RUNNER_TEMP/config" mini -ip=127.0.0.1 -ip.bind=127.0.0.1 \
-dir="$RUNNER_TEMP/data" -s3.config="$GITHUB_WORKSPACE/docker/compose/s3.json" \
-webdav=false -admin.ui=false > "$RUNNER_TEMP/weed.log" 2>&1 &
ready() {
curl -s -o /dev/null http://127.0.0.1:8333 &&
test "$(docker exec ${{ job.services.postgres.id }} psql -U postgres -Atc "SELECT count(*) FROM information_schema.columns WHERE table_name = 'filemeta' AND column_name = 'path'")" = 1
}
for i in $(seq 90); do ready && break; sleep 1; done
ready || { cat "$RUNNER_TEMP/weed.log"; exit 1; }
- name: Run the S3 versioning suite
env:
ENABLE_STRESS_TESTS: "true"
run: go test -v -count=1 -timeout=25m ./test/s3/versioning/
- name: Show the server log
if: failure()
run: tail -200 "$RUNNER_TEMP/weed.log"
+37 -2
View File
@@ -4,8 +4,11 @@ name: "S3 digest and FIPS matrix"
# signing on, so the sha256 digest and GODEBUG=fips140=only stay working:
# md5 GODEBUG=fips140=off, the default digest
# sha256 GODEBUG=fips140=on with the filer's -digest=sha256
# fips140only GODEBUG=fips140=only, built with GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster.
# fips140only GODEBUG=fips140=only and WEED_FIPS_MODE=strict, built with
# GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster. The
# negative-config job checks what strict mode refuses at startup
# (test/s3/digest_matrix/negative_config.sh).
on:
push:
@@ -115,6 +118,38 @@ jobs:
retention-days: 1
path: digest-matrix-binaries.tar
negative-config:
name: Strict FIPS mode refusals
needs: build
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
- name: Restore binaries
run: |
tar xf digest-matrix-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
- name: Short keys refused
env:
WEED: ${{ github.workspace }}/weed/weed
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
WORK_DIR: /tmp/negative-config
run: bash test/s3/digest_matrix/negative_config.sh
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: negative-config-logs
path: /tmp/negative-config/**/*.log
retention-days: 3
suites:
name: S3 suites (${{ matrix.digest }}, ${{ matrix.volume }} volume server)
needs: build
@@ -80,6 +80,13 @@ jobs:
set -x
go test -v -timeout=180s -run TestS3GetPart ./...
- name: Run S3 Bucket Default Storage Class Tests
timeout-minutes: 15
working-directory: test/s3/normal
run: |
set -x
go test -v -timeout=180s -run TestS3BucketDefaultStorageClass ./...
- name: Run IAM Integration Tests
timeout-minutes: 15
working-directory: test/s3/normal
+11 -11
View File
@@ -22,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.1
github.com/aws/aws-sdk-go-v2 v1.49.0
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/s3 v1.117.1
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.10
github.com/aws/smithy-go v1.28.11
github.com/bwmarrin/snowflake v0.3.0
github.com/cenkalti/backoff/v4 v4.3.0
github.com/cespare/xxhash/v2 v2.3.0
@@ -179,16 +179,16 @@ require (
github.com/apache/thrift v0.25.0 // indirect
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.52.4 // indirect
+22 -22
View File
@@ -173,10 +173,10 @@ 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.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 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 h1:LfdRwpJ0Dfh+vpqHevmmnFnMoc3/lfB4pdHOfWpLfH4=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29/go.mod h1:r6fijnrGRQ4OnSGyHYuFcC7G6wdwB4Ld8WhiIaGZHx0=
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
@@ -187,22 +187,22 @@ github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHA
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34/go.mod h1:eToXR/Gk1uqpn04eSmdgVXwfS0WvH8aG4eBFr8ygbpU=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16 h1:q9YuNkYR/7lxflWCcEv3C0cecUt3Zvrh2hn9ZNxieNA=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16/go.mod h1:3BSeJQF55QQI+dDFHx4WTIjTvX/Lvtk8Jaaf/SGAnBM=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 h1:D2smhPZgqVLuc8rmuvb6wrG4sgut9iv1BN8W2twFtfo=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16/go.mod h1:HheOgBYcgoZgeKSLVEmk9whxHERlVXAKTVWK3xizKeo=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 h1:5w2E7ndu7XOt62yvu2vGm/Rv7WDn1oQjrJ7Dt1NTVTM=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15/go.mod h1:1WgfBCsJYL6E7T2QkkE8kQvo7uG+5+z2LpaQ9L6pjZs=
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1 h1:fOeEIKMlgwKbMFSNMM+pLo2NPRJ1dSKbaAuZYGXUVR0=
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1/go.mod h1:xHaAZkbYuIc9UtLZxdoeyhzmx06g1paDjPkHgljJU/I=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 h1:4EezYQsIY0xPbD6u7TbQLfnpicSMQgA8n9paomVV4Zo=
@@ -215,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.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI=
github.com/aws/smithy-go v1.28.11/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=
+19 -3
View File
@@ -267,6 +267,18 @@ filer:
enabled: true
```
### Message queue broker
An S3 gateway can run a message queue broker beside it, on gRPC port 17777 by default. `s3.mqBroker`, `filer.s3.mqBroker` and `allInOne.s3.mqBroker` choose it:
- `auto` (the default) runs it only with `global.seaweedfs.enableSecurity`, where the chart gives it mutual TLS through `[grpc.msg_broker]` in security.toml.
- `true` runs it either way. Without `enableSecurity` it then accepts any client that can reach the port.
- `false` never runs it.
`s3.mqBrokerPort`, `filer.s3.mqBrokerPort` and `allInOne.s3.mqBrokerPort` set the port, and 0 also turns the broker off. The `allInOne.s3` values inherit the `s3` ones when null. The container port and NetworkPolicy entry appear only when the broker runs.
Brokers register with the master under the pod IP, and clients and other brokers find them there and dial that address, so the port is deliberately left off the Services; a LoadBalancer or NodePort Service would only publish it outside the cluster. With `networkPolicy.enabled` the chart admits the port from the release's own pods; publishers and subscribers elsewhere need an `extraIngress` rule for it.
### Enabling Authentication to S3
To enable authentication for S3, you have two options:
@@ -373,9 +385,13 @@ filer:
apply without a restart. Other files in the Secret, such as an audit log config, still
need one, and so do changes to the values the chart generates its own Secret from, such
as `s3.credentials`.
- Every reload also re-creates the KMS providers configured in the identities file. The
`local` provider keeps its keys in memory, so a reload replaces them, as a restart does;
use another provider for objects that must stay readable.
- Every reload also re-creates the KMS providers configured in the identities file. S3
uses `default_provider`, or the first provider by name when it isn't set, so set it when
you list more than one, as adding a provider whose name sorts first would switch S3 to
it. The `local` provider reads its `keys` list again, so objects encrypted under those
keys stay readable. The keys it generates in memory are lost on a reload, as on a
restart, so list every key that protects objects you need to keep, and give the alias
`aws/s3` to the one that should serve requests naming no key.
- The pod shares its process namespace (see [Sharing the process namespace](#sharing-the-process-namespace)),
so the sidecar can see SeaweedFS. It uses the component's image and container security
context, because it must run as the same user as SeaweedFS to signal it. If it can't
@@ -274,6 +274,9 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
-sftp \
@@ -406,6 +409,10 @@ spec:
- containerPort: {{ $httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
- containerPort: {{ .Values.allInOne.sftp.port | default .Values.sftp.port }}
@@ -296,6 +296,9 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
-master={{ include "seaweedfs.masterServerArg" . }} \
{{- range .Values.filer.extraArgs }}
@@ -363,6 +366,10 @@ spec:
- containerPort: {{ .Values.filer.s3.httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- $jwt := (.Values.global.seaweedfs.securityConfig).jwtSigning | default dict }}
{{- $isJwtEnabled := or $jwt.filerWrite $jwt.filerRead }}
@@ -179,6 +179,9 @@ spec:
{{- end }}
{{- /* rendered even when 0: an if would drop the flag and weed would serve its default */}}
-port.lance={{ .Values.s3.lancePort | default 0 }} \
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).args }}
{{ . }} \
{{- end }}
{{- range .Values.s3.extraArgs }}
{{ . }} \
{{- end }}
@@ -233,6 +236,10 @@ spec:
- containerPort: {{ .Values.s3.lancePort }}
name: swfs-lance
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- if .Values.s3.metricsPort }}
- containerPort: {{ .Values.s3.metricsPort }}
name: metrics
@@ -283,6 +283,55 @@ true
{{- end -}}
{{- end -}}
{{/*
The message queue broker beside an S3 gateway, for (list $ "s3"|"filer"|"allInOne"),
as JSON: "args" are its flags and "port" the port it serves, 0 when it cannot run.
Unflagged, weed starts it only with grpc.msg_broker TLS, which enableSecurity
writes, and on 17777; defaults are left out so images without these flags start.
allInOne.s3 inherits s3's mqBroker and mqBrokerPort when null.
*/}}
{{- define "seaweedfs.mqBroker" -}}
{{- $root := index . 0 -}}
{{- $component := index . 1 -}}
{{- $prefix := "" -}}
{{- $name := "s3.mqBroker" -}}
{{- $mode := $root.Values.s3.mqBroker -}}
{{- $port := $root.Values.s3.mqBrokerPort -}}
{{- if eq $component "filer" -}}
{{- $prefix = "s3." -}}
{{- $name = "filer.s3.mqBroker" -}}
{{- $mode = $root.Values.filer.s3.mqBroker -}}
{{- $port = $root.Values.filer.s3.mqBrokerPort -}}
{{- else if eq $component "allInOne" -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBroker) -}}
{{- $name = "allInOne.s3.mqBroker" -}}
{{- $mode = $root.Values.allInOne.s3.mqBroker -}}
{{- end -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBrokerPort) -}}
{{- $port = $root.Values.allInOne.s3.mqBrokerPort -}}
{{- end -}}
{{- end -}}
{{- $mode = ternary "auto" (toString $mode | lower) (kindIs "invalid" $mode) -}}
{{- if not (has $mode (list "auto" "true" "false")) -}}
{{- fail (printf "%s must be auto, true or false, not %q" $name $mode) -}}
{{- end -}}
{{- $port = int ($port | default 0) -}}
{{- $runs := false -}}
{{- if and (gt $port 0) (or (eq $mode "true") (and (eq $mode "auto") $root.Values.global.seaweedfs.enableSecurity)) -}}
{{- $runs = true -}}
{{- end -}}
{{- $args := list -}}
{{- if or (eq $mode "false") (eq $port 0) -}}
{{- $args = append $args (printf "-%smq.broker=false" $prefix) -}}
{{- else if eq $mode "true" -}}
{{- $args = append $args (printf "-%smq.broker=true" $prefix) -}}
{{- end -}}
{{- if and $runs (ne $port 17777) -}}
{{- $args = append $args (printf "-%smq.broker.port=%d" $prefix $port) -}}
{{- end -}}
{{- dict "args" (join " " $args) "port" (ternary $port 0 $runs) | toJson -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -26,6 +26,9 @@
{{- if and $https (gt (int $https) 0) }}
{{- $ports = append $ports $https }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "allInOne") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
{{- $ports = append $ports (.Values.allInOne.sftp.port | default .Values.sftp.port) }}
@@ -62,6 +65,9 @@
{{- if and .Values.filer.s3.httpsPort (gt (int .Values.filer.s3.httpsPort) 0) }}
{{- $ports = append $ports .Values.filer.s3.httpsPort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "filer") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- $targets = append $targets (dict "component" "filer" "ports" $ports) }}
{{- end }}
@@ -76,6 +82,9 @@
{{- if .Values.s3.lancePort }}
{{- $ports = append $ports .Values.s3.lancePort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "s3") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- if .Values.s3.metricsPort }}
{{- $ports = append $ports .Values.s3.metricsPort }}
{{- end }}
@@ -120,6 +120,14 @@ stringData:
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
{{- /* The broker beside each S3 gateway serves with this identity and
dials other brokers with it; weed starts that broker only when this
section has a cert and key. Same internal client cert as grpc.s3, which
every pod running a gateway already mounts. */}}
[grpc.msg_broker]
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
# use this for any place needs a grpc client
# i.e., "weed backup|benchmark|filer.copy|filer.replicate|mount|s3|upload"
[grpc.client]
@@ -0,0 +1,199 @@
package tests
import (
"fmt"
"os/exec"
"strings"
"testing"
)
const security = "global.seaweedfs.enableSecurity=true"
type brokerGateway struct {
name string
settings []string
kind string
object string
prefix string
broker string
port string
}
var brokerGateways = []brokerGateway{
{"s3", []string{"s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-s3", "", "s3.mqBroker", "s3.mqBrokerPort"},
{"filer.s3", []string{"filer.s3.enabled=true"}, "StatefulSet", "vector-test-seaweedfs-filer", "s3.", "filer.s3.mqBroker", "filer.s3.mqBrokerPort"},
{"allInOne", []string{"allInOne.enabled=true", "allInOne.s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-all-in-one", "", "allInOne.s3.mqBroker", "allInOne.s3.mqBrokerPort"},
}
func firstContainer(workload map[string]interface{}) map[string]interface{} {
return workload["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"].([]interface{})[0].(map[string]interface{})
}
// brokerFlags returns the broker flags of the workload's first container.
func brokerFlags(workload map[string]interface{}) []string {
container := firstContainer(workload)
var words []string
for _, key := range []string{"command", "args"} {
if list, ok := container[key].([]interface{}); ok {
for _, word := range list {
words = append(words, strings.Fields(word.(string))...)
}
}
}
var flags []string
for _, word := range words {
if strings.Contains(word, "mq.broker") {
flags = append(flags, word)
}
}
return flags
}
func namedPort(ports []interface{}, name, field string) int {
for _, port := range ports {
if p := port.(map[string]interface{}); p["name"] == name {
return p[field].(int)
}
}
return 0
}
func policyAllows(policy map[string]interface{}, want int) bool {
rules, _ := policy["spec"].(map[string]interface{})["ingress"].([]interface{})
for _, rule := range rules {
ports, _ := rule.(map[string]interface{})["ports"].([]interface{})
for _, port := range ports {
if port.(map[string]interface{})["port"] == want {
return true
}
}
}
return false
}
// checkBroker asserts the flags, that the broker port is declared and
// admitted exactly when the broker runs, so a broker that runs with its port
// blocked fails, and that no Service ever carries it.
func checkBroker(t *testing.T, gateway brokerGateway, label string, settings []string, wantFlags []string, wantPort int) {
t.Helper()
_, documents := render(t, append(append([]string{"networkPolicy.enabled=true"}, gateway.settings...), settings...)...)
label = fmt.Sprintf("%s %s", gateway.name, label)
workload := findDocument(documents, gateway.kind, gateway.object)
if workload == nil {
t.Fatalf("%s: no %s %s", label, gateway.kind, gateway.object)
}
if got := brokerFlags(workload); strings.Join(got, " ") != strings.Join(wantFlags, " ") {
t.Errorf("%s: broker flags %q, want %q", label, got, wantFlags)
}
containerPorts, _ := firstContainer(workload)["ports"].([]interface{})
if got := namedPort(containerPorts, "swfs-mq-broker", "containerPort"); got != wantPort {
t.Errorf("%s: containerPort %d, want %d", label, got, wantPort)
}
// Clients find brokers through the master and dial the pod, so a Service
// port would only publish the broker through a LoadBalancer or NodePort.
for _, document := range documents {
if document["kind"] != "Service" {
continue
}
for _, port := range document["spec"].(map[string]interface{})["ports"].([]interface{}) {
p := port.(map[string]interface{})
if p["name"] == "swfs-mq-broker" || p["port"] == 17777 || p["targetPort"] == 17777 || (wantPort != 0 && (p["port"] == wantPort || p["targetPort"] == wantPort)) {
t.Errorf("%s: Service %v carries the broker port: %v", label, document["metadata"].(map[string]interface{})["name"], p)
}
}
}
policy := findDocument(documents, "NetworkPolicy", gateway.object)
if policy == nil {
t.Fatalf("%s: no NetworkPolicy %s", label, gateway.object)
}
if wantPort != 0 && !policyAllows(policy, wantPort) {
t.Errorf("%s: NetworkPolicy does not admit broker port %d", label, wantPort)
}
for _, port := range []int{17777, 18887} {
if port != wantPort && policyAllows(policy, port) {
t.Errorf("%s: NetworkPolicy admits %d with no broker on it", label, port)
}
}
}
func TestMqBrokerModes(t *testing.T) {
for _, gateway := range brokerGateways {
on := "-" + gateway.prefix + "mq.broker=true"
off := "-" + gateway.prefix + "mq.broker=false"
port := "-" + gateway.prefix + "mq.broker.port=18887"
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"auto without security", nil, nil, 0},
{"auto with security", []string{security}, nil, 17777},
{"auto with security, custom port", []string{security, gateway.port + "=18887"}, []string{port}, 18887},
{"auto without security, custom port", []string{gateway.port + "=18887"}, nil, 0},
{"true", []string{gateway.broker + "=true"}, []string{on}, 17777},
{"true, custom port", []string{gateway.broker + "=true", gateway.port + "=18887"}, []string{on, port}, 18887},
{"false with security", []string{security, gateway.broker + "=false"}, []string{off}, 0},
{"true, port 0", []string{gateway.broker + "=true", gateway.port + "=0"}, []string{off}, 0},
}
for _, c := range cases {
checkBroker(t, gateway, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
}
func TestMqBrokerAllInOneInherits(t *testing.T) {
allInOne := brokerGateways[2]
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"null inherits s3.mqBroker=true", []string{"s3.mqBroker=true"}, []string{"-mq.broker=true"}, 17777},
{"null inherits s3.mqBroker=false", []string{security, "s3.mqBroker=false"}, []string{"-mq.broker=false"}, 0},
{"explicit auto overrides s3.mqBroker=false", []string{security, "s3.mqBroker=false", "allInOne.s3.mqBroker=auto"}, nil, 17777},
{"null inherits s3.mqBrokerPort", []string{security, "s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
{"explicit port overrides s3.mqBrokerPort=0", []string{security, "s3.mqBrokerPort=0", "allInOne.s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
}
for _, c := range cases {
checkBroker(t, allInOne, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
func TestMqBrokerTLSOnlyWithSecurity(t *testing.T) {
for _, secured := range []bool{false, true} {
// filer JWT signing writes security.toml without enableSecurity
settings := []string{"s3.enabled=true", "global.seaweedfs.securityConfig.jwtSigning.filerWrite=true"}
if secured {
settings = append(settings, security)
}
_, documents := render(t, settings...)
secret := findDocument(documents, "Secret", "vector-test-seaweedfs-security-config")
if secret == nil {
t.Fatalf("security %v: no security config Secret", secured)
}
toml := secret["stringData"].(map[string]interface{})["security.toml"].(string)
section := "[grpc.msg_broker]\ncert = \"/usr/local/share/ca-certificates/client/tls.crt\"\nkey = \"/usr/local/share/ca-certificates/client/tls.key\""
if got := strings.Contains(toml, section); got != secured {
t.Errorf("security %v: [grpc.msg_broker] with the client cert present = %v\n%s", secured, got, toml)
}
if !secured && strings.Contains(toml, "[grpc.msg_broker]") {
t.Errorf("[grpc.msg_broker] written without enableSecurity")
}
}
}
func TestMqBrokerRejectsUnknownValue(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
output, err := exec.Command("helm", "template", "test", "..", "--set", "s3.enabled=true", "--set", "s3.mqBroker=yes").CombinedOutput()
if err == nil || !strings.Contains(string(output), `s3.mqBroker must be auto, true or false, not "yes"`) {
t.Fatalf("s3.mqBroker=yes accepted: %v %s", err, output)
}
}
+13 -1
View File
@@ -1096,6 +1096,9 @@ filer:
port: 8333
# add additional https port
httpsPort: 0
# Message queue broker beside the gateway, see s3.mqBroker
mqBroker: auto
mqBrokerPort: 17777
# Suffix of the host name, {bucket}.{domainName}
domainName: ""
# Seconds the gateway keeps serving after SIGTERM while its health checks
@@ -1186,6 +1189,13 @@ s3:
# Lance Namespace port; weed serves 9101 by default, 0 disables it
# (and the worker's Lance container)
lancePort: 9101
# Message queue broker beside the gateway: auto runs it only with
# global.seaweedfs.enableSecurity, which gives it mTLS; true runs it either
# way, without TLS when security is off; false never does.
mqBroker: auto
# Its gRPC port, 0 turns it off. Clients and other brokers find the broker
# through the master and dial the pod IP, so no Service carries this port.
mqBrokerPort: 17777
loggingOverrideLevel: null
# enable user & permission to s3 (need to inject to all services)
enableAuth: false
@@ -1886,7 +1896,7 @@ worker:
# Worker job types - categories or comma-separated list of names/aliases
# Categories: all, default, heavy
# default: vacuum, volume_balance, ec_balance, admin_script
# heavy: erasure_coding, iceberg_maintenance
# heavy: erasure_coding, iceberg_maintenance, mq_topic_table
# all: every registered job type
# Examples: "all", "default", "heavy", "default,iceberg" (default+iceberg), "vacuum,volume_balance"
# Refer: https://github.com/seaweedfs/seaweedfs/wiki/Worker
@@ -2060,6 +2070,8 @@ allInOne:
enabled: false # Whether to enable S3 gateway
port: null # S3 gateway port (null inherits from s3.port)
httpsPort: null # S3 gateway HTTPS port (null inherits from s3.httpsPort)
mqBroker: null # Message queue broker: auto, true or false (null inherits from s3.mqBroker)
mqBrokerPort: null # Message queue broker gRPC port (null inherits from s3.mqBrokerPort, 0 turns the broker off)
domainName: null # Suffix of the host name (null inherits from s3.domainName)
enableAuth: false # Enable user & permission to S3
# Set to the name of an existing kubernetes Secret with the s3 json config file
+1025 -1056
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+406
View File
@@ -15239,6 +15239,412 @@
"pluginVersion": "10.3.1"
}
]
},
{
"type": "row",
"title": "S3 Notifications",
"collapsed": true,
"id": 275,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 30
},
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification records delivered",
"type": "timeseries",
"id": 276,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 31
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_delivered_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification lag",
"description": "Undelivered bucket event records the forwarder can see: current ranges, ranges held back behind an older generation, and sealed retired ranges. An old range still being sealed after a repartition cannot be read yet and is not counted.",
"type": "timeseries",
"id": 277,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 31
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (SeaweedFS_s3_notification_lag_records{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification send retries",
"type": "timeseries",
"id": 278,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 39
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_send_retries_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification records skipped or lost",
"type": "timeseries",
"id": 279,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 39
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target, reason) (increase(SeaweedFS_s3_notification_skipped_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}} skipped {{reason}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (increase(SeaweedFS_s3_notification_retention_gap_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "B",
"legendFormat": "{{target}} retention gap"
}
],
"pluginVersion": "10.3.1"
}
]
}
],
"refresh": "30s",
+169
View File
@@ -0,0 +1,169 @@
//! JWT signing keys under [`FipsMode::Strict`].
//!
//! FIPS 140 needs HMAC keys of at least 112 bits, and Go's `crypto/hmac`
//! panics on a shorter one under `GODEBUG=fips140=only`, so every Go process
//! refuses to start when a JWT key in security.toml is shorter
//! (`weed/util/fips140_keys.go`). The Rust binaries take `fips.mode = strict`
//! to mean the same and apply the same rule with the same wording, so one
//! security.toml gets the same answer from a Go and a Rust server.
use crate::fips::FipsMode;
/// The shortest HMAC key FIPS 140 allows: 112 bits.
pub const MIN_HMAC_KEY_BYTES: usize = 14;
/// The wiki section on switching JWT signing keys without downtime.
pub const JWT_SIGNING_KEYS_WIKI: &str =
"https://github.com/seaweedfs/seaweedfs/wiki/Cryptography-and-FIPS-Compliance#jwt-signing-keys";
/// Every security.toml setting that keys an HS256 JWT, in the order Go checks
/// them. Go refuses a short one at startup in any process that reads the file.
pub const JWT_KEY_SETTINGS: [&str; 11] = [
"jwt.signing.key",
"jwt.signing.previous_key",
"jwt.signing.read.key",
"jwt.signing.read.previous_key",
"jwt.filer_signing.key",
"jwt.filer_signing.previous_key",
"jwt.filer_signing.read.key",
"jwt.filer_signing.read.previous_key",
"jwt.filer_signing.grpc_key",
"jwt.filer_signing.grpc_previous_key",
"jwt.filer_signing.subscribe.key",
];
/// Whether `key` is shorter than the FIPS mode allows (14 characters when
/// strict).
pub fn is_short(mode: FipsMode, key: &[u8]) -> bool {
mode == FipsMode::Strict && !key.is_empty() && key.len() < MIN_HMAC_KEY_BYTES
}
/// Go's `CheckFips140HmacKeys`: under strict mode, one message naming each
/// setting in `keys` whose key is too short, with its length; otherwise `None`.
pub fn short_keys(mode: FipsMode, keys: &[(&str, &[u8])]) -> Option<String> {
let short: Vec<String> = keys
.iter()
.filter(|(_, key)| is_short(mode, key))
.map(|(setting, key)| format!("{} ({} characters)", setting, key.len()))
.collect();
match short.as_slice() {
[] => None,
[one] => Some(format!(
"{} is shorter than the {} characters FIPS 140 needs for HMAC keys",
one, MIN_HMAC_KEY_BYTES
)),
[rest @ .., last] => Some(format!(
"{} and {} are shorter than the {} characters FIPS 140 needs for HMAC keys",
rest.join(", "),
last,
MIN_HMAC_KEY_BYTES
)),
}
}
/// The error a server logs before it exits at startup over the short keys in
/// `file`; `short` is the message from [`short_keys`].
pub fn startup_refusal(file: &str, short: &str) -> String {
format!(
"{}: this process runs with fips.mode strict, and stops because {}; replace them on every server that uses them, with or without downtime, see {}",
file, short, JWT_SIGNING_KEYS_WIKI
)
}
/// Go's `shortJwtKeyWarning`: a warning that the key (other than a previous
/// key) of `setting` in `file` is too short for strict mode, asking for a
/// longer one while the short one still works.
pub fn short_key_warning(mode: FipsMode, file: &str, setting: &str, key: &[u8]) -> Option<String> {
if mode == FipsMode::Strict
|| key.is_empty()
|| key.len() >= MIN_HMAC_KEY_BYTES
|| setting.ends_with("previous_key")
{
return None;
}
Some(format!(
"{}: this process does not run with fips.mode strict, so {} works, but under fips.mode strict this server would not start: the key is shorter than the {} characters FIPS 140 needs for HMAC keys (it has {}); to replace it on every server that uses it without downtime, see {}",
file,
setting,
MIN_HMAC_KEY_BYTES,
key.len(),
JWT_SIGNING_KEYS_WIKI
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_keys_only_under_strict() {
let keys: [(&str, &[u8]); 1] = [("jwt.signing.key", b"0123456789")];
assert_eq!(short_keys(FipsMode::On, &keys), None);
assert_eq!(short_keys(FipsMode::Off, &keys), None);
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) is shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn short_keys_names_every_short_key_and_skips_unset_and_long_ones() {
let keys: [(&str, &[u8]); 4] = [
("jwt.signing.key", b"0123456789"),
("jwt.signing.read.key", b""),
("jwt.filer_signing.key", b"01234567890123"),
("jwt.filer_signing.subscribe.key", b"01234567"),
];
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) and jwt.filer_signing.subscribe.key (8 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
let three: [(&str, &[u8]); 3] = [("a", b"1"), ("b", b"12"), ("c", b"123")];
assert_eq!(
short_keys(FipsMode::Strict, &three).as_deref(),
Some(
"a (1 characters), b (2 characters) and c (3 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn warning_outside_strict_except_for_previous_keys() {
assert!(short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b"0123456789")
.unwrap()
.starts_with("s.toml: this process does not run with fips.mode strict, so jwt.signing.key works"));
assert!(
short_key_warning(FipsMode::On, "s.toml", "jwt.signing.key", b"0123456789").is_some()
);
assert_eq!(
short_key_warning(FipsMode::Strict, "s.toml", "jwt.signing.key", b"0123456789"),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.previous_key",
b"0123456789"
),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.key",
b"01234567890123"
),
None
);
assert_eq!(
short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b""),
None
);
}
}
+3 -1
View File
@@ -8,9 +8,11 @@
//! rustls provider, which only works if every binary installs the same one.
//! The security.toml search path joined them for the same reason: an operator
//! mounts the file once and every binary has to look where `weed` looks.
//! The FIPS mode joined them because it decides that provider.
//! The FIPS mode joined them because it decides that provider, and the JWT key
//! rule for strict mode because every binary that reads the keys applies it.
pub mod address;
pub mod fips;
pub mod jwt_keys;
pub mod security_config;
pub mod tls;
+2
View File
@@ -6332,7 +6332,9 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
"bytes",
"crc32c",
"log",
"prost",
"protoc-bin-vendored",
+6 -1
View File
@@ -190,7 +190,12 @@ async fn main() -> Result<()> {
let args = Args::parse();
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
weed_lance_worker::tls::install_for_fips_mode(&security)?;
let mode = weed_lance_worker::tls::install_for_fips_mode(&security)?;
weed_lance_worker::security::check_signing_key_flag(
mode,
"--filer-signing-key (WEED_FILER_SIGNING_KEY)",
args.filer_signing_key.as_deref(),
)?;
let signing_key = SigningKey::new(
args.filer_signing_key
.or_else(|| security.get("jwt.filer_signing.key")),
@@ -0,0 +1,76 @@
//! weed-vector-cli under `fips.mode = strict` exits at startup when a JWT
//! key is too short for FIPS 140, before it dials anything.
use std::io::Read;
use std::process::{Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
/// Runs weed-vector-cli with `args` under `WEED_FIPS_MODE=strict` and a
/// security.toml holding `security`, without the caller's other WEED_
/// variables, and returns its exit status and stderr. Fails when it is still
/// running after 30 s, which means it accepted the keys.
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("security.toml");
std::fs::write(&file, security).unwrap();
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-vector-cli"));
for (name, _) in std::env::vars_os() {
if name.to_string_lossy().starts_with("WEED_") {
command.env_remove(name);
}
}
let mut child = command
.arg("--security-toml")
.arg(&file)
.args(args)
.env("WEED_FIPS_MODE", "strict")
.current_dir(dir.path())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
if let Some(status) = child.try_wait().unwrap() {
let mut stderr = String::new();
child
.stderr
.take()
.unwrap()
.read_to_string(&mut stderr)
.unwrap();
return (status, stderr);
}
if Instant::now() > deadline {
let _ = child.kill();
panic!("weed-vector-cli still running after 30 s: it accepted the short key");
}
std::thread::sleep(Duration::from_millis(100));
}
}
#[test]
fn a_short_key_in_security_toml_stops_the_cli() {
let (status, stderr) = run_strict(
"[jwt.filer_signing]\nkey = \"0123456789\"\n",
&["describe", "bucket$table"],
);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("jwt.filer_signing.key (10 characters) is shorter than the 14 characters"),
"{stderr}"
);
}
#[test]
fn a_short_signing_key_flag_stops_the_cli() {
let (status, stderr) = run_strict(
"",
&["--filer-signing-key", "short", "describe", "bucket$table"],
);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("--filer-signing-key (WEED_FILER_SIGNING_KEY) (5 characters)"),
"{stderr}"
);
}
@@ -0,0 +1,65 @@
//! weed-vector under `fips.mode = strict` exits at startup when a JWT key is
//! too short for FIPS 140, before it dials the masters.
use std::io::Read;
use std::process::{Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
/// Runs weed-vector with `args` under `WEED_FIPS_MODE=strict` and a
/// security.toml holding `security`, without the caller's other WEED_
/// variables, and returns its exit status and stderr. Fails when it is still
/// running after 30 s, which means it accepted the keys.
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("security.toml");
std::fs::write(&file, security).unwrap();
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-vector"));
for (name, _) in std::env::vars_os() {
if name.to_string_lossy().starts_with("WEED_") {
command.env_remove(name);
}
}
let mut child = command
.arg("--security-toml")
.arg(&file)
.args(args)
.env("WEED_FIPS_MODE", "strict")
.current_dir(dir.path())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
if let Some(status) = child.try_wait().unwrap() {
let mut stderr = String::new();
child
.stderr
.take()
.unwrap()
.read_to_string(&mut stderr)
.unwrap();
return (status, stderr);
}
if Instant::now() > deadline {
let _ = child.kill();
panic!("weed-vector still running after 30 s: it accepted the short key");
}
std::thread::sleep(Duration::from_millis(100));
}
}
#[test]
fn a_short_key_in_security_toml_stops_the_engine() {
let (status, stderr) = run_strict(
"[jwt.signing.read]\nkey = \"0123456789\"\n",
&["--masters", "127.0.0.1:9333.19333"],
);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("fips.mode strict")
&& stderr
.contains("jwt.signing.read.key (10 characters) is shorter than the 14 characters"),
"{stderr}"
);
}
+4
View File
@@ -148,6 +148,7 @@ message BatchDeleteRequest {
repeated string file_ids = 1;
bool skip_cookie_check = 2;
bool fsync = 3;
bool skip_replica_check = 4; // the caller updates the other copies itself
}
message BatchDeleteResponse {
@@ -170,6 +171,7 @@ message VacuumVolumeCheckRequest {
message VacuumVolumeCheckResponse {
double garbage_ratio = 1;
bool disk_space_low = 4; // the volume is read-only solely because its disk is low on space — a cause compaction itself reclaims
bool can_delete_mark = 5; // the volume is read-only through a readonlyCanDelete mark and nothing that refuses deletes — compaction only reclaims what the mark lets go
}
message VacuumVolumeCompactRequest {
@@ -631,6 +633,8 @@ message VolumeInfo {
bool read_only = 7;
EcShardConfig ec_shard_config = 8; // EC shard configuration (optional, null = use default 10+4)
bool read_only_can_delete = 9; // with read_only: writes are rejected but deletes still land
uint64 vacuumed_max_file_key = 12; // largest needle id the volume's vacuums could have erased; 0 = not known
uint32 vacuumed_compaction_revision = 13; // compaction revision the vacuum that wrote vacuumed_max_file_key produced; the record holds only while it equals the volume's
}
// EcShardConfig specifies erasure coding shard configuration
+459 -150
View File
@@ -31,8 +31,12 @@ fn parse_common_names(value: &str) -> Vec<String> {
.collect()
}
/// The value of the WEED_ variable `key`, or `None` when it is unset or empty:
/// Go's viper ignores an empty variable, so the setting keeps its file value.
fn env_string(env: EnvLookup<'_>, key: &str) -> Option<String> {
env(key).and_then(|value| value.into_string().ok())
env(key)
.and_then(|value| value.into_string().ok())
.filter(|value| !value.is_empty())
}
/// SeaweedFS Volume Server (Rust implementation)
@@ -337,6 +341,13 @@ pub struct VolumeServerConfig {
pub tls_policy: TlsPolicy,
/// Path to security.toml — stored for SIGHUP reload.
pub security_file: String,
/// The security.toml the settings came from, for messages that name it.
pub security_file_name: String,
/// Every JWT key setting, from `SecurityConfig::jwt_keys`, for the strict
/// mode check at startup.
pub jwt_keys: Vec<(&'static str, Vec<u8>)>,
/// The FIPS mode, from the same read of security.toml as `jwt_keys`.
pub fips_setting: Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError>,
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
/// (allows loopback / link-local / metadata hosts).
pub allow_untrusted_remote_endpoints: bool,
@@ -974,6 +985,7 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
// Parse security config from TOML file
let sec = parse_security_config_with_env(&cli.security_file, env);
let fips_setting = resolve_fips_setting_with_env(&cli.security_file, &sec, env);
// Parse whitelist: merge CLI --whiteList with guard.white_list from security.toml
let mut white_list: Vec<String> = cli
@@ -1030,6 +1042,9 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
debug: cli.debug,
debug_port: cli.debug_port,
ui_enabled: sec.jwt_signing_key.is_empty() || sec.access_ui,
security_file_name: sec.file_name(),
jwt_keys: sec.jwt_keys(),
fips_setting,
jwt_signing_key: sec.jwt_signing_key,
jwt_signing_expires_seconds: sec.jwt_signing_expires,
jwt_previous_signing_key: sec.jwt_previous_signing_key,
@@ -1061,6 +1076,12 @@ fn default_volume_dir() -> String {
std::env::temp_dir().to_string_lossy().into_owned()
}
/// The WEED_ variable that overrides `setting`, as Go's viper names it:
/// `jwt.filer_signing.key` is `WEED_JWT_FILER_SIGNING_KEY`.
fn env_name(setting: &str) -> String {
format!("WEED_{}", setting.to_uppercase().replace('.', "_"))
}
/// Parsed security configuration from security.toml.
#[derive(Debug, Default)]
pub struct SecurityConfig {
@@ -1089,6 +1110,12 @@ pub struct SecurityConfig {
pub access_ui: bool,
/// The file was read; otherwise only defaults and WEED_ overrides are set.
pub file_read: bool,
/// The file the settings came from, for messages that name it.
pub file_used: Option<PathBuf>,
/// The `jwt.filer_signing*` keys, by setting. The volume server does not
/// use them; they are read so strict mode refuses a short one, as every Go
/// process that reads the same security.toml does.
pub filer_jwt_keys: Vec<(&'static str, Vec<u8>)>,
/// IPs from [guard] white_list in security.toml
pub guard_white_list: Vec<String>,
/// `[fips] mode` as the file sets it, read like every other key here;
@@ -1096,6 +1123,48 @@ pub struct SecurityConfig {
pub fips_mode: Option<String>,
}
impl SecurityConfig {
/// Sets the `jwt.filer_signing*` key `setting` to `value`, replacing an
/// earlier value as a later line or a WEED_ variable does in Go.
fn set_filer_jwt_key(&mut self, setting: &'static str, value: &str) {
self.filer_jwt_keys.retain(|(s, _)| *s != setting);
self.filer_jwt_keys
.push((setting, value.as_bytes().to_vec()));
}
/// Every JWT key setting the file and the WEED_ variables set, in the
/// order of `seaweed_common::jwt_keys::JWT_KEY_SETTINGS`; an unset key is
/// empty.
pub fn jwt_keys(&self) -> Vec<(&'static str, Vec<u8>)> {
seaweed_common::jwt_keys::JWT_KEY_SETTINGS
.iter()
.map(|&setting| {
let key = match setting {
"jwt.signing.key" => self.jwt_signing_key.clone(),
"jwt.signing.previous_key" => self.jwt_previous_signing_key.clone(),
"jwt.signing.read.key" => self.jwt_read_signing_key.clone(),
"jwt.signing.read.previous_key" => self.jwt_previous_read_signing_key.clone(),
_ => self
.filer_jwt_keys
.iter()
.find(|(s, _)| *s == setting)
.map(|(_, key)| key.clone())
.unwrap_or_default(),
};
(setting, key)
})
.collect()
}
/// The name messages give the file: its path, or "security.toml" when no
/// file was read, as Go does.
pub fn file_name(&self) -> String {
self.file_used
.as_ref()
.map_or_else(|| "security.toml".to_string(), |p| p.display().to_string())
}
}
/// Parse a security.toml file to extract JWT signing keys and TLS configuration.
/// Format:
/// ```toml
@@ -1154,129 +1223,62 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
}
};
let mut cfg = SecurityConfig::default();
let table = lowercase_keys(
content
.parse::<toml::Table>()
.unwrap_or_else(|_| lenient_toml_table(&content)),
);
let setting = |name: &str| toml_setting(&table, name);
let text = |name: &str| setting(name).unwrap_or_default();
let flag = |name: &str| text(name).parse().unwrap_or(false);
let expires =
|name: &str, default: i64| setting(name).map_or(0, |v| v.parse().unwrap_or(default));
#[derive(PartialEq)]
enum Section {
None,
JwtSigning,
JwtSigningRead,
HttpsClient,
Grpc,
HttpsVolume,
GrpcVolume,
Tls,
Guard,
Access,
Fips,
}
let mut section = Section::None;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if let Some(header) = section_header(trimmed) {
section = match header {
"[jwt.signing.read]" => Section::JwtSigningRead,
"[jwt.signing]" => Section::JwtSigning,
"[https.client]" => Section::HttpsClient,
"[grpc]" => Section::Grpc,
"[https.volume]" => Section::HttpsVolume,
"[grpc.volume]" => Section::GrpcVolume,
"[tls]" => Section::Tls,
"[guard]" => Section::Guard,
"[access]" => Section::Access,
"[fips]" => Section::Fips,
_ => Section::None,
};
continue;
}
if let Some((key, value)) = trimmed.split_once('=') {
let key = key.trim();
let value: &str = &toml_value_text(value);
match section {
Section::JwtSigningRead => match key {
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_read_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_read_signing_expires = value.parse().unwrap_or(60)
}
_ => {}
},
Section::JwtSigning => match key {
"key" => cfg.jwt_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_signing_expires = value.parse().unwrap_or(10)
}
_ => {}
},
Section::HttpsClient => match key {
"enabled" => cfg.https_client_enabled = value.parse().unwrap_or(false),
"cert" => cfg.https_client_cert_file = value.to_string(),
"key" => cfg.https_client_key_file = value.to_string(),
"ca" => cfg.https_client_ca_file = value.to_string(),
_ => {}
},
Section::Grpc => match key {
"ca" => cfg.grpc_ca_file = value.to_string(),
"allowed_wildcard_domain" => {
cfg.grpc_allowed_wildcard_domain = value.to_string()
}
"health_check_commonNames" => {
cfg.grpc_health_check_common_names = parse_common_names(value)
}
_ => {}
},
Section::HttpsVolume => match key {
"cert" => cfg.https_cert_file = value.to_string(),
"key" => cfg.https_key_file = value.to_string(),
"ca" => cfg.https_ca_file = value.to_string(),
_ => {}
},
Section::GrpcVolume => match key {
"cert" => cfg.grpc_cert_file = value.to_string(),
"key" => cfg.grpc_key_file = value.to_string(),
"client_cert" => cfg.grpc_client_cert_file = value.to_string(),
"client_key" => cfg.grpc_client_key_file = value.to_string(),
// Go only reads CA from [grpc], not [grpc.volume]
"allowed_commonNames" => {
cfg.grpc_volume_allowed_common_names =
value.split(',').map(|name| name.to_string()).collect();
}
_ => {}
},
Section::Tls => match key {
"min_version" => cfg.tls_policy.min_version = value.to_string(),
"max_version" => cfg.tls_policy.max_version = value.to_string(),
"cipher_suites" => cfg.tls_policy.cipher_suites = value.to_string(),
_ => {}
},
Section::Guard => {
if key == "white_list" {
cfg.guard_white_list = value
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
Section::Access => {
if key == "ui" {
cfg.access_ui = value.parse().unwrap_or(false)
}
}
Section::Fips => {
if key == "mode" {
cfg.fips_mode = Some(value.to_string())
}
}
Section::None => {}
}
let mut cfg = SecurityConfig {
jwt_signing_key: text("jwt.signing.key").into_bytes(),
jwt_previous_signing_key: text("jwt.signing.previous_key").into_bytes(),
jwt_signing_expires: expires("jwt.signing.expires_after_seconds", 10),
jwt_read_signing_key: text("jwt.signing.read.key").into_bytes(),
jwt_previous_read_signing_key: text("jwt.signing.read.previous_key").into_bytes(),
jwt_read_signing_expires: expires("jwt.signing.read.expires_after_seconds", 60),
https_client_enabled: flag("https.client.enabled"),
https_client_cert_file: text("https.client.cert"),
https_client_key_file: text("https.client.key"),
https_client_ca_file: text("https.client.ca"),
grpc_ca_file: text("grpc.ca"),
grpc_allowed_wildcard_domain: text("grpc.allowed_wildcard_domain"),
grpc_health_check_common_names: parse_common_names(&text("grpc.health_check_commonNames")),
https_cert_file: text("https.volume.cert"),
https_key_file: text("https.volume.key"),
https_ca_file: text("https.volume.ca"),
grpc_cert_file: text("grpc.volume.cert"),
grpc_key_file: text("grpc.volume.key"),
grpc_client_cert_file: text("grpc.volume.client_cert"),
grpc_client_key_file: text("grpc.volume.client_key"),
// Go only reads CA from [grpc], not [grpc.volume]
grpc_volume_allowed_common_names: setting("grpc.volume.allowed_commonNames")
.map(|names| names.split(',').map(String::from).collect())
.unwrap_or_default(),
tls_policy: TlsPolicy {
min_version: text("tls.min_version"),
max_version: text("tls.max_version"),
cipher_suites: text("tls.cipher_suites"),
},
guard_white_list: text("guard.white_list")
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
access_ui: flag("access.ui"),
fips_mode: toml_entry(&table, &["fips", "mode"]).map(toml_text),
..SecurityConfig::default()
};
for name in seaweed_common::jwt_keys::JWT_KEY_SETTINGS
.iter()
.filter(|name| name.starts_with("jwt.filer_signing"))
{
if let Some(key) = setting(name) {
cfg.set_filer_jwt_key(name, &key);
}
}
@@ -1294,6 +1296,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
// e.g. WEED_JWT_SIGNING_KEY overrides [jwt.signing] key
apply_env_overrides(&mut cfg, env);
cfg.file_read = true;
cfg.file_used = Some(config_path);
cfg
}
@@ -1312,6 +1315,95 @@ fn section_header(trimmed: &str) -> Option<&str> {
Some(header.trim_end())
}
/// The value of the dotted `setting` in `table`, a table from
/// `lowercase_keys`, as Go's viper GetString reads it: a value that is not a
/// string reads as its TOML text, and an array or a table as unset.
fn toml_setting(table: &toml::Table, setting: &str) -> Option<String> {
let setting = setting.to_lowercase();
let path: Vec<&str> = setting.split('.').collect();
match toml_entry(table, &path)? {
toml::Value::Array(_) | toml::Value::Table(_) => None,
value => Some(toml_text(value)),
}
}
fn toml_text(value: &toml::Value) -> String {
match value {
toml::Value::String(text) => text.clone(),
toml::Value::Float(number) => number.to_string(),
other => other.to_string(),
}
}
/// The value at `path` in `table`. As in viper, the longest run of leading
/// parts that is itself a key wins (`"jwt.signing.key" = ...` over
/// `[jwt.signing] key`), and a shorter run is tried when the rest of the path
/// is not under it.
fn toml_entry<'a>(table: &'a toml::Table, path: &[&str]) -> Option<&'a toml::Value> {
(1..=path.len()).rev().find_map(|n| {
let value = table.get(&path[..n].join("."))?;
match (&path[n..], value) {
([], value) => Some(value),
(rest, toml::Value::Table(next)) => toml_entry(next, rest),
_ => None,
}
})
}
/// `table` with every key lowercased, as viper holds a config file. When two
/// spellings of a key collide, the one that is not lowercase wins, as it does
/// in viper.
fn lowercase_keys(table: toml::Table) -> toml::Table {
let mut lowered = toml::Table::new();
for (key, value) in table {
let value = match value {
toml::Value::Table(nested) => toml::Value::Table(lowercase_keys(nested)),
other => other,
};
let lower = key.to_lowercase();
if key != lower || !lowered.contains_key(&lower) {
lowered.insert(lower, value);
}
}
lowered
}
/// The `key = value` lines of a file that is not valid TOML, each under its
/// full dotted name (`jwt.signing.key`), so no line can replace the table
/// another line's value is in. Go's viper skips such a file; this server keeps
/// reading what it can from it, one line at a time.
fn lenient_toml_table(content: &str) -> toml::Table {
let mut table = toml::Table::new();
let mut section = String::new();
let mut in_array_of_tables = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if let Some(header) = section_header(trimmed) {
in_array_of_tables = header.starts_with("[[");
section = header
.trim_start_matches('[')
.trim_end_matches(']')
.split('.')
.map(|part| format!("{}.", part.trim()))
.collect();
continue;
}
if in_array_of_tables {
continue;
}
if let Some((key, value)) = trimmed.split_once('=') {
table.insert(
format!("{section}{}", key.trim()),
toml::Value::String(toml_value_text(value)),
);
}
}
table
}
/// Reads the right-hand side of `key = value` the way TOML (and so Go) does:
/// escapes decoded, literal strings kept as written, a trailing comment
/// dropped. Text TOML rejects keeps the plain quote trimming.
@@ -1327,31 +1419,22 @@ fn toml_value_text(raw: &str) -> String {
}
/// The FIPS mode this volume server runs in: `WEED_FIPS_MODE`, else
/// `fips.mode` in the security.toml `--securityFile` names or the search
/// finds, read by the same loader as the JWT keys, else off. A file that
/// exists but cannot be read is an error, since it may set the mode.
pub fn resolve_fips_setting(
security_file: &str,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(security_file, &process_env)
}
/// `fips.mode` in `parsed`, the security.toml `--securityFile` names or the
/// search finds, else off. A file that exists but was not read is an error,
/// since it may set the mode.
fn resolve_fips_setting_with_env(
security_file: &str,
parsed: &SecurityConfig,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
let path = resolve_security_config_path(security_file, env).filter(|p| p.exists());
let path = parsed
.file_used
.clone()
.or_else(|| resolve_security_config_path(security_file, env).filter(|p| p.exists()));
let Some(path) = path else {
return seaweed_common::fips::resolve(None, None, env);
};
if let Err(e) = std::fs::read_to_string(&path) {
return Err(seaweed_common::fips::FipsModeError::File {
path,
reason: e.to_string(),
});
}
let parsed = parse_security_config_with_env(&path.to_string_lossy(), env);
fips_setting_from_parsed(path, &parsed, env)
fips_setting_from_parsed(path, parsed, env)
}
/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env`
@@ -1386,6 +1469,13 @@ fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBu
/// Apply WEED_ environment variable overrides to a SecurityConfig.
/// Matches Go's Viper convention: WEED_ prefix, uppercase, dots replaced with underscores.
fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
for setting in seaweed_common::jwt_keys::JWT_KEY_SETTINGS {
if setting.starts_with("jwt.filer_signing") {
if let Some(v) = env_string(env, &env_name(setting)) {
cfg.set_filer_jwt_key(setting, &v);
}
}
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_KEY") {
cfg.jwt_signing_key = v.into_bytes();
}
@@ -2004,6 +2094,58 @@ mod tests {
}
}
#[test]
fn test_jwt_keys_include_the_filer_keys_and_their_env_overrides() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "volume-write"
previous_key = "volume-write-old"
[jwt.signing.read]
key = "volume-read"
[jwt.filer_signing]
key = "filer-write"
grpc_key = "filer-grpc"
[jwt.filer_signing.read]
previous_key = "filer-read-old"
[jwt.filer_signing.subscribe]
key = "filer-subscribe"
"#,
)
.unwrap();
let path = tmp.path().to_str().unwrap();
let env = fake_env(&[("WEED_JWT_FILER_SIGNING_KEY", "filer-write-env")]);
let cfg = parse_security_config_with_env(path, &env);
let keys: Vec<(&str, String)> = cfg
.jwt_keys()
.into_iter()
.map(|(setting, key)| (setting, String::from_utf8(key).unwrap()))
.collect();
let want = [
("jwt.signing.key", "volume-write"),
("jwt.signing.previous_key", "volume-write-old"),
("jwt.signing.read.key", "volume-read"),
("jwt.signing.read.previous_key", ""),
("jwt.filer_signing.key", "filer-write-env"),
("jwt.filer_signing.previous_key", ""),
("jwt.filer_signing.read.key", ""),
("jwt.filer_signing.read.previous_key", "filer-read-old"),
("jwt.filer_signing.grpc_key", "filer-grpc"),
("jwt.filer_signing.grpc_previous_key", ""),
("jwt.filer_signing.subscribe.key", "filer-subscribe"),
];
let want: Vec<(&str, String)> = want.iter().map(|(s, k)| (*s, k.to_string())).collect();
assert_eq!(keys, want);
assert_eq!(cfg.file_name(), path);
assert_eq!(SecurityConfig::default().file_name(), "security.toml");
}
#[test]
fn test_parse_security_config_access_ui() {
let tmp = tempfile::NamedTempFile::new().unwrap();
@@ -2323,6 +2465,39 @@ cipher_suites = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_empty_env_override_keeps_the_file_value() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "file-write"
[jwt.filer_signing]
key = "file-filer"
[grpc]
ca = "/file/ca.pem"
"#,
)
.unwrap();
let env = fake_env(&[
("WEED_JWT_SIGNING_KEY", ""),
("WEED_JWT_FILER_SIGNING_KEY", ""),
("WEED_GRPC_CA", ""),
]);
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &env);
assert_eq!(cfg.jwt_signing_key, b"file-write");
assert_eq!(cfg.grpc_ca_file, "/file/ca.pem");
let filer_key = cfg
.jwt_keys()
.into_iter()
.find(|(setting, _)| *setting == "jwt.filer_signing.key")
.map(|(_, key)| key);
assert_eq!(filer_key.as_deref(), Some(&b"file-filer"[..]));
}
#[test]
fn test_previous_signing_keys_from_file_and_env() {
let tmp = tempfile::NamedTempFile::new().unwrap();
@@ -2374,16 +2549,16 @@ previous_key = "read-old"
std::fs::write(tmp.path(), "[fips]\nmode = \"on\"\n").unwrap();
let path = tmp.path().to_str().unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
let env = fake_env(&[("WEED_FIPS_MODE", "strict")]);
let setting = resolve_fips_setting_with_env(path, &env).unwrap();
let setting = fips_setting_of(path, &env).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
let env = fake_env(&[("WEED_FIPS_MODE", "only")]);
assert!(resolve_fips_setting_with_env(path, &env).is_err());
assert!(fips_setting_of(path, &env).is_err());
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Off);
}
@@ -2397,11 +2572,34 @@ previous_key = "read-old"
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"unquoted-secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
std::fs::write(tmp.path(), "[fips]\nmode = [\"strict\"]\n").unwrap();
assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err());
assert!(fips_setting_of(path, &fake_env(&[])).is_err());
}
#[test]
fn test_lenient_file_keeps_a_key_a_later_line_would_shadow() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[jwt]\nsigning = \"x\"\n\
[jwt.signing.key]\nx = unquoted\n";
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
}
#[test]
fn test_lenient_file_skips_array_of_tables_sections() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[[jwt.signing]]\nkey = \"\"\n\
[fips]\nmode = \"on\"\n";
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
}
#[test]
@@ -2418,23 +2616,134 @@ previous_key = "read-old"
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
assert_eq!(cfg.jwt_signing_key, b"secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
}
#[test]
fn test_security_config_reads_the_toml_forms_go_reads() {
for text in [
"[jwt.signing]\n\"key\" = \"0123456789\"\n\
[jwt.filer_signing]\n'key' = \"0123456789\"\n[fips]\n\"mode\" = \"on\"\n",
"[jwt.signing]\nkey = \"\"\"\n0123456789\"\"\"\n\
[jwt.filer_signing]\nkey = '''\n0123456789'''\n[fips]\nmode = \"on\"\n",
"jwt.signing.key = \"0123456789\"\njwt.filer_signing.key = \"0123456789\"\n\
fips.mode = \"on\"\n",
"[jwt]\nsigning = { key = \"0123456789\" }\nfiler_signing = { key = \"0123456789\" }\n\
[fips]\nmode = \"on\"\n",
"[ \"jwt\" . signing ]\nKey = \"0123456789\"\n[jwt.\"filer_signing\"]\nKEY = \"0123456789\"\n\
[FIPS]\nMode = \"on\"\n",
] {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), text).unwrap();
assert!(
text.parse::<toml::Table>().is_ok(),
"TOML, as Go reads it: {text}"
);
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
let keys = cfg.jwt_keys();
for setting in ["jwt.signing.key", "jwt.filer_signing.key"] {
let key = keys
.iter()
.find(|(s, _)| *s == setting)
.map(|(_, k)| k.as_slice());
assert_eq!(key, Some(&b"0123456789"[..]), "{setting} in {text}");
}
assert_eq!(cfg.fips_mode.as_deref(), Some("on"), "{text}");
}
}
fn fips_setting_of(
path: &str,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(path, &parse_security_config_with_env(path, env), env)
}
#[test]
fn test_fips_mode_comes_from_the_read_the_jwt_keys_come_from() {
use seaweed_common::fips::FipsMode;
let tmp = tempfile::NamedTempFile::new().unwrap();
let path = tmp.path().to_str().unwrap();
std::fs::write(tmp.path(), "[fips]\nmode = \"strict\"\n").unwrap();
let parsed = parse_security_config_with_env(path, &fake_env(&[]));
std::fs::write(tmp.path(), "[fips]\nmode = \"off\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &parsed, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
}
/// The value Go's viper GetString reads for `jwt.filer_signing.key` from
/// security.toml `text`, as this server reads it.
fn filer_jwt_key(text: &str) -> Vec<u8> {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_ok(), "TOML: {text}");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
cfg.jwt_keys()
.into_iter()
.find(|(s, _)| *s == "jwt.filer_signing.key")
.map(|(_, k)| k)
.unwrap()
}
#[test]
fn test_security_config_prefers_the_longest_literal_key_as_go_does() {
let nested = "[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n";
for literal in [
"\"jwt.filer_signing.key\" = \"short\"\n",
"[jwt]\n\"filer_signing.key\" = \"short\"\n",
] {
assert_eq!(filer_jwt_key(&format!("{literal}{nested}")), b"short");
}
assert_eq!(
filer_jwt_key(&format!("\"jwt.filer_signing\" = \"x\"\n{nested}")),
b"0123456789abcdef"
);
}
#[test]
fn test_security_config_resolves_key_case_collisions_as_go_does() {
for text in [
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\nKEY = \"short\"\n",
"[jwt.filer_signing]\nKEY = \"short\"\nkey = \"0123456789abcdef\"\n",
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n[JWT.filer_signing]\nkey = \"short\"\n",
] {
assert_eq!(filer_jwt_key(text), b"short", "{text}");
}
assert_eq!(
filer_jwt_key("[JWT.Filer_Signing]\nKey = \"0123456789abcdef\"\n"),
b"0123456789abcdef"
);
}
#[test]
fn test_security_config_reads_a_non_string_jwt_key_as_go_does() {
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = [\"x\"]\n"), b"");
assert_eq!(filer_jwt_key("[jwt.filer_signing.key]\nx = \"y\"\n"), b"");
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = 1234\n"), b"1234");
}
#[test]
fn test_security_config_reads_a_float_jwt_key_as_go_does() {
let key = filer_jwt_key("[jwt.filer_signing]\nkey = 1234567890123.0\n");
assert_eq!(key, b"1234567890123");
let key = filer_jwt_key("[jwt.filer_signing]\nkey = \"1234567890123.0\"\n");
assert_eq!(key, b"1234567890123.0");
}
#[test]
fn test_fips_mode_refuses_a_security_file_it_cannot_read() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"[fips]\nmode = \"on\"\n\xff\xfe\n").unwrap();
let path = tmp.path().to_str().unwrap();
let err = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap_err();
let err = fips_setting_of(path, &fake_env(&[])).unwrap_err();
assert!(
err.to_string()
.contains("cannot tell whether it sets fips.mode"),
"{err}"
);
let missing = format!("{path}.missing");
let setting = resolve_fips_setting_with_env(&missing, &fake_env(&[])).unwrap();
let setting = fips_setting_of(&missing, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off);
}
+32 -3
View File
@@ -57,7 +57,8 @@ fn main() {
.init();
let config = config::parse_cli();
install_crypto_provider_for_fips_mode(&config.security_file);
install_crypto_provider_for_fips_mode(&config);
check_jwt_keys_for_fips_mode(&config);
seaweed_volume::server::server_stats::init_process_start();
#[cfg(unix)]
let cpu_profile = match CpuProfileSession::start(&config) {
@@ -105,8 +106,10 @@ fn main() {
/// Resolves the FIPS mode from `fips.mode` or `WEED_FIPS_MODE`, logs it and
/// installs the matching rustls provider before anything builds TLS; exits
/// when the value is unknown.
fn install_crypto_provider_for_fips_mode(security_file: &str) {
let installed = config::resolve_fips_setting(security_file)
fn install_crypto_provider_for_fips_mode(config: &config::VolumeServerConfig) {
let installed = config
.fips_setting
.clone()
.map_err(|e| e.to_string())
.and_then(|setting| {
seaweed_common::tls::install_process_provider(setting.mode)
@@ -126,6 +129,32 @@ fn install_crypto_provider_for_fips_mode(security_file: &str) {
}
}
/// Checks the JWT HMAC signing keys from security.toml and their WEED_
/// variables for a length of at least 14 characters, as FIPS 140 requires.
/// Under `fips.mode = strict`, if any of them is shorter, it logs an error
/// naming each such setting and its length and exits the server with status 1.
/// In any other mode the server starts, and each such key except a
/// `previous_key` gets a warning that strict mode would refuse it.
fn check_jwt_keys_for_fips_mode(config: &config::VolumeServerConfig) {
use seaweed_common::jwt_keys;
let mode = seaweed_common::fips::process_mode();
let file = &config.security_file_name;
for (setting, key) in &config.jwt_keys {
if let Some(warning) = jwt_keys::short_key_warning(mode, file, setting, key) {
warn!("{}", warning);
}
}
let keys: Vec<(&str, &[u8])> = config
.jwt_keys
.iter()
.map(|(setting, key)| (*setting, key.as_slice()))
.collect();
if let Some(short) = jwt_keys::short_keys(mode, &keys) {
error!("{}", jwt_keys::startup_refusal(file, &short));
std::process::exit(1);
}
}
/// Mirrors Go's rejectHttpsDowngrade: a redirect must not downgrade a request
/// carrying data and auth headers from https to plaintext.
fn redirect_is_https_downgrade(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
+116 -2
View File
@@ -12,6 +12,8 @@ use std::net::IpAddr;
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use seaweed_common::fips::FipsMode;
use seaweed_common::jwt_keys;
use serde::{Deserialize, Serialize};
// ============================================================================
@@ -184,6 +186,21 @@ pub struct Guard {
is_write_active: bool,
}
/// Go's `usablePreviousKey`: under strict mode, a previous key shorter than 14
/// characters is dropped with an error naming it (`name`), and the reload goes
/// ahead without it.
fn usable_previous_key(mode: FipsMode, name: &str, key: SigningKey) -> SigningKey {
if jwt_keys::is_short(mode, &key.0) {
tracing::error!(
"JWT reload: ignoring the {}, which is shorter than the {} characters FIPS 140 needs for HMAC keys; the new keys are in effect",
name,
jwt_keys::MIN_HMAC_KEY_BYTES
);
return SigningKey(vec![]);
}
key
}
impl Guard {
pub fn new(
whitelist: &[String],
@@ -238,7 +255,10 @@ impl Guard {
/// Refresh the JWT signing keys and their expirations in place so operators
/// can rotate keys via SIGHUP without restarting the process. Mirrors Go's
/// `Guard::UpdateSigningKeys`: it swaps the fields and recomputes
/// `is_write_active`.
/// `is_write_active`. Under `fips.mode = strict`, a new write or read key
/// shorter than 14 characters keeps the keys as they were, logs an error and
/// returns false; a short previous key is dropped with an error and the
/// other keys take effect.
pub fn update_signing_keys(
&mut self,
signing_key: SigningKey,
@@ -247,7 +267,42 @@ impl Guard {
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) {
) -> bool {
self.update_signing_keys_in_mode(
seaweed_common::fips::process_mode(),
signing_key,
expires_after_sec,
read_signing_key,
read_expires_after_sec,
previous_signing_key,
previous_read_signing_key,
)
}
/// [`Guard::update_signing_keys`] for the FIPS mode `mode`.
#[allow(clippy::too_many_arguments)]
fn update_signing_keys_in_mode(
&mut self,
mode: FipsMode,
signing_key: SigningKey,
expires_after_sec: i64,
read_signing_key: SigningKey,
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) -> bool {
let current: [(&str, &[u8]); 2] = [
("signing key", &signing_key.0),
("read signing key", &read_signing_key.0),
];
if let Some(short) = jwt_keys::short_keys(mode, &current) {
tracing::error!("JWT reload: keeping the keys in effect, because {}", short);
return false;
}
let previous_signing_key =
usable_previous_key(mode, "previous signing key", previous_signing_key);
let previous_read_signing_key =
usable_previous_key(mode, "previous read signing key", previous_read_signing_key);
self.signing_key = signing_key;
self.expires_after_sec = expires_after_sec;
self.read_signing_key = read_signing_key;
@@ -257,6 +312,7 @@ impl Guard {
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
true
}
/// Whether any write-side control is configured: a non-empty whitelist or a
@@ -688,6 +744,64 @@ mod tests {
assert!(!accepts(&guard, "read-old", false));
}
#[test]
fn test_strict_reload_keeps_keys_when_a_current_key_is_short() {
let mut guard = Guard::new(
&[],
SigningKey::from_string("write-key-long-enough"),
10,
SigningKey::from_string("read-key-long-enough"),
60,
);
for (write, read) in [
("0123456789", "read-key-replaced-ok"),
("write-key-replaced-ok", "short"),
] {
assert!(!guard.update_signing_keys_in_mode(
FipsMode::Strict,
SigningKey::from_string(write),
11,
SigningKey::from_string(read),
61,
SigningKey(vec![]),
SigningKey(vec![]),
));
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
assert_eq!(guard.read_signing_key.0, b"read-key-long-enough");
assert_eq!(guard.expires_after_sec, 10);
}
assert!(guard.update_signing_keys_in_mode(
FipsMode::On,
SigningKey::from_string("0123456789"),
11,
SigningKey(vec![]),
61,
SigningKey(vec![]),
SigningKey(vec![]),
));
assert_eq!(guard.signing_key.0, b"0123456789");
}
#[test]
fn test_strict_reload_drops_a_short_previous_key() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(guard.update_signing_keys_in_mode(
FipsMode::Strict,
SigningKey::from_string("write-key-long-enough"),
10,
SigningKey::from_string("read-key-long-enough"),
60,
SigningKey::from_string("old-short"),
SigningKey::from_string("old-read-key-long-enough"),
));
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
assert!(guard.previous_signing_key.is_empty());
assert_eq!(
guard.previous_read_signing_key.0,
b"old-read-key-long-enough"
);
}
#[test]
fn test_update_signing_keys_toggles_write_active() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
+6
View File
@@ -457,6 +457,12 @@ mod tests {
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
security_file_name: String::new(),
jwt_keys: Vec::new(),
fips_setting: Ok(seaweed_common::fips::Setting {
mode: Default::default(),
source: None,
}),
}
}
+208 -16
View File
@@ -1141,6 +1141,8 @@ impl VolumeServer for VolumeGrpcService {
self.state.check_maintenance()?;
let req = request.into_inner();
let mut results = Vec::new();
let mut replica_errs: std::collections::HashMap<u32, Result<(), String>> =
std::collections::HashMap::new();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -1162,6 +1164,23 @@ impl VolumeServer for VolumeGrpcService {
}
};
let vid = file_id.volume_id.0;
if !req.skip_replica_check && !replica_errs.contains_key(&vid) {
let checked =
crate::server::handlers::check_delete_replicas(&self.state, vid).await;
replica_errs.insert(vid, checked);
}
if let Some(Err(e)) = replica_errs.get(&vid) {
results.push(volume_server_pb::DeleteResult {
file_id: fid_str.clone(),
status: 503,
error: e.clone(),
size: 0,
version: 0,
});
continue;
}
let mut n = Needle {
id: file_id.key,
cookie: file_id.cookie,
@@ -1453,15 +1472,21 @@ impl VolumeServer for VolumeGrpcService {
) -> Result<Response<volume_server_pb::VacuumVolumeCheckResponse>, Status> {
let vid = VolumeId(request.into_inner().volume_id);
let store = self.state.store.read().unwrap();
let (garbage_ratio, disk_space_low) = match store.find_volume(vid) {
let (garbage_ratio, disk_space_low, can_delete_mark) = match store.find_volume(vid) {
Some((_, vol)) => {
// disk_space_low only counts when it is the sole read-only
// cause — an operator mark or I/O quarantine still shields
// the volume.
let (_, no_write_or_delete, no_write_can_delete, is_low) = vol.read_only_reasons();
// A readonlyCanDelete mark keeps taking deletes, so compacting
// their space away stays within it; a mark that refuses
// deletes or an I/O quarantine still wins. A remote-tiered
// volume carries the same flag but cannot be compacted in
// place.
(
vol.garbage_level(),
is_low && !no_write_or_delete && !no_write_can_delete,
no_write_can_delete && !no_write_or_delete && !vol.has_remote_file(),
)
}
None => {
@@ -1471,6 +1496,7 @@ impl VolumeServer for VolumeGrpcService {
Ok(Response::new(volume_server_pb::VacuumVolumeCheckResponse {
garbage_ratio,
disk_space_low,
can_delete_mark,
}))
}
@@ -15032,6 +15058,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -15051,6 +15078,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: true,
fsync: false,
skip_replica_check: false,
}))
.await
.expect_err("a server in maintenance mode must refuse a batch delete");
@@ -15102,6 +15130,120 @@ mod tests {
);
}
/// Go's TestBatchDelete_WaitsForEveryReplica: a replica the master no
/// longer lists would miss the delete, so the delete waits for it.
#[tokio::test]
async fn test_batch_delete_waits_for_every_replica() {
let (service, _tmp) = make_local_service_with_volume("", None);
{
let mut store = service.state.store.write().unwrap();
store
.add_volume(
VolumeId(2),
DiskType::HardDrive,
&VolumeSpec {
replica_placement: Some(
crate::storage::super_block::ReplicaPlacement::from_string("001")
.unwrap(),
),
..Default::default()
},
)
.unwrap();
let mut n = Needle {
id: NeedleId(1),
cookie: Cookie(0x3344),
data: b"hello".to_vec(),
data_size: 5,
..Needle::default()
};
store
.write_volume_needle(VolumeId(2), &mut n, false)
.unwrap();
for id in [2, 3] {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(0x3344),
data: b"hello".to_vec(),
data_size: 5,
..Needle::default()
};
store
.write_volume_needle(VolumeId(2), &mut n, false)
.unwrap();
}
}
let urls = Arc::new(std::sync::Mutex::new(vec!["127.0.0.1:1"]));
let min_writable_copies = Arc::new(std::sync::atomic::AtomicU32::new(0));
*service.state.current_master_url.write().await =
crate::server::handlers::tests::spawn_lookup_master({
let urls = urls.clone();
let min_writable_copies = min_writable_copies.clone();
move |vid| {
let locations = urls
.lock()
.unwrap()
.iter()
.map(|url| master_pb::Location {
url: url.to_string(),
..Default::default()
})
.collect();
let mut answer =
crate::server::handlers::tests::lookup_answer(vid, locations, "");
answer.volume_id_locations[0].min_writable_copies =
min_writable_copies.load(std::sync::atomic::Ordering::SeqCst);
Ok(answer)
}
})
.await;
let service = &service;
let delete = |id: u64| async move {
let fid = needle::FileId::new(VolumeId(2), NeedleId(id), Cookie(0x3344)).to_string();
let resp = service
.batch_delete(Request::new(volume_server_pb::BatchDeleteRequest {
file_ids: vec![fid],
skip_cookie_check: true,
fsync: false,
skip_replica_check: id == 3,
}))
.await
.unwrap()
.into_inner();
assert_eq!(resp.results.len(), 1, "{:?}", resp.results);
(resp.results[0].status, resp.results[0].error.clone())
};
let (status, error) = delete(1).await;
assert_eq!(status, 503, "{error}");
assert!(error.contains("replication copy count"), "{error}");
{
let store = service.state.store.read().unwrap();
let (_, v) = store.find_volume(VolumeId(2)).unwrap();
let mut n = Needle {
id: NeedleId(1),
..Needle::default()
};
v.read_needle(&mut n)
.expect("needle deleted while a replica was offline");
}
let (status, error) = delete(3).await;
assert_eq!(status, 202, "a delete skipping the replica check: {error}");
urls.lock().unwrap().push("127.0.0.2:8080");
let (status, error) = delete(1).await;
assert_eq!(status, 202, "{error}");
// a volume grown degraded is complete with the copies the master asks for
urls.lock().unwrap().pop();
min_writable_copies.store(1, std::sync::atomic::Ordering::SeqCst);
let (status, error) = delete(2).await;
assert_eq!(status, 202, "{error}");
}
/// Go's TestBatchDeleteFsyncsOnlyWhenAsked.
#[tokio::test]
async fn test_batch_delete_fsyncs_only_when_asked() {
@@ -15133,6 +15275,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: true,
fsync,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -16320,6 +16463,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: false,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -16403,6 +16547,7 @@ mod tests {
file_ids: vec![fid.to_string()],
skip_cookie_check: false,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
@@ -16899,21 +17044,22 @@ mod tests {
// The .idx sits beside the .dat. It keeps the .ecx rows the .dat holds
// and tombstones each journaled one once, however often it was journaled.
let mut expected_idx = ecx[..2 * NEEDLE_MAP_ENTRY_SIZE].to_vec();
crate::storage::idx::write_index_entry(
&mut expected_idx,
NeedleId(1),
Offset::default(),
TOMBSTONE_FILE_SIZE,
)
.unwrap();
for id in [1, 3] {
crate::storage::idx::write_index_entry(
&mut expected_idx,
NeedleId(id),
Offset::default(),
TOMBSTONE_FILE_SIZE,
)
.unwrap();
}
assert_eq!(
std::fs::read(format!("{data}/1.idx")).unwrap(),
expected_idx
);
assert!(!std::path::Path::new(&format!("{idx}/1.idx")).exists());
// Needle 1 is still in the .dat, so it counts as garbage; needle 3 is not.
assert_decoded_volume(&service, (2, 1), &[2], &[1, 3]);
assert_decoded_volume(&service, (2, 2), &[2], &[1, 3]);
}
/// Collected journals land in the idx dir even when the .ecx is beside the
@@ -16933,13 +17079,21 @@ mod tests {
size_before_needle_3
);
assert_decoded_volume(&service, (2, 0), &[1, 2], &[3]);
// the cut tail needle is the largest id the decode erased
let store = service.state.store.read().unwrap();
let vi = store.find_volume(VolumeId(1)).unwrap().1.volume_info();
assert_eq!(
(vi.vacuumed_max_file_key, vi.vacuumed_compaction_revision),
(3, 1)
);
}
/// A tail needle tombstoned in the .ecx itself (Go's RebuildEcxFile) is cut
/// from the .dat the same way, so its row must not survive either, even
/// when compaction fails.
/// from the .dat the same way, so its row loses its offset too, even when
/// compaction fails.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_volume_ec_shards_to_volume_drops_sealed_tail_tombstone() {
async fn test_volume_ec_shards_to_volume_cuts_sealed_tail_tombstone() {
let (service, _tmp, data, idx, size_before_needle_3) =
make_split_idx_ec_decode_service(&[], false).await;
let ecx_path = format!("{idx}/1.ecx");
@@ -16959,11 +17113,19 @@ mod tests {
std::fs::metadata(format!("{data}/1.dat")).unwrap().len(),
size_before_needle_3
);
let mut expected_idx = ecx[..2 * NEEDLE_MAP_ENTRY_SIZE].to_vec();
crate::storage::idx::write_index_entry(
&mut expected_idx,
NeedleId(3),
Offset::default(),
TOMBSTONE_FILE_SIZE,
)
.unwrap();
assert_eq!(
std::fs::read(format!("{data}/1.idx")).unwrap(),
ecx[..2 * NEEDLE_MAP_ENTRY_SIZE]
expected_idx
);
assert_decoded_volume(&service, (2, 0), &[1, 2], &[3]);
assert_decoded_volume(&service, (2, 1), &[1, 2], &[3]);
}
/// Go compacts the decoded volume (CompactVolumeFiles), so needles deleted
@@ -17002,7 +17164,35 @@ mod tests {
[2, 3]
);
assert!(idx_rows.iter().all(|(_, size)| !size.is_deleted()));
assert_eq!(vifs(), vifs_before, "the EC .vif is left alone");
// the compaction is a vacuum: it records what it could erase
let vif_fields = |vifs: [Option<Vec<u8>>; 2]| {
vifs.map(|vif| {
vif.map(|vif| {
let mut v: serde_json::Value = serde_json::from_slice(&vif).unwrap();
let obj = v.as_object_mut().unwrap();
let record = (
obj.remove("vacuumedMaxFileKey"),
obj.remove("vacuumedCompactionRevision"),
);
obj.remove("bytesOffset");
(v, record)
})
})
};
let (after, before) = (vif_fields(vifs()), vif_fields(vifs_before));
for (after, before) in after.iter().zip(before.iter()) {
assert_eq!(
after.as_ref().map(|(v, _)| v),
before.as_ref().map(|(v, _)| v),
"the EC .vif is left alone"
);
if let Some((_, record)) = after {
assert_eq!(
record,
&(Some(serde_json::json!("3")), Some(serde_json::json!(1)))
);
}
}
assert_decoded_volume(&service, (2, 0), &[2, 3], &[1]);
}
@@ -17525,6 +17715,7 @@ mod tests {
file_ids: vec!["1,b00003344".to_string()],
skip_cookie_check: false,
fsync: false,
skip_replica_check: false,
})
};
@@ -17575,6 +17766,7 @@ mod tests {
file_ids: vec!["2,b00003344".to_string()],
skip_cookie_check,
fsync: false,
skip_replica_check: false,
}))
.await
.unwrap()
+134 -9
View File
@@ -722,6 +722,7 @@ async fn batch_delete_file_ids(
file_ids: batch.clone(),
skip_cookie_check: true,
fsync: false,
skip_replica_check: false,
})
.await
.map_err(|e| format!("batch delete {}: {}", grpc_addr, e))?
@@ -743,6 +744,47 @@ async fn batch_delete_file_ids(
Ok(())
}
/// Mirrors Go's checkDeleteReplicas: refuses a delete the master cannot route
/// to every replica, as the HTTP delete path does, so an offline replica does
/// not keep the needle once it returns.
pub(crate) async fn check_delete_replicas(
state: &VolumeServerState,
vid: u32,
) -> Result<(), String> {
let copy_count = {
let store = state.store.read().unwrap();
match store.find_volume(VolumeId(vid)) {
Some((_, v)) => v.super_block().replica_placement.get_copy_count() as u32,
None => return Ok(()),
}
};
if copy_count <= 1 {
return Ok(());
}
let (locations, min_writable_copies) = lookup_volume(
state.outgoing_grpc_tls.as_ref(),
&state.current_master().await,
vid,
)
.await
.map_err(|e| format!("replicating lookup failed for {}: {}", vid, e))?;
let copy_count = match min_writable_copies {
n if n > 0 && n < copy_count => n,
_ => copy_count,
};
let deletable = locations
.iter()
.filter(|loc| !loc.read_only || loc.read_only_can_delete)
.count();
if deletable < copy_count as usize {
return Err(format!(
"replication locations [{}] is less than volume {} replication copy count [{}]",
deletable, vid, copy_count
));
}
Ok(())
}
/// `query` with the fields named in `overrides` replaced by their values.
fn override_query_fields(
query: &str,
@@ -786,6 +828,41 @@ fn replica_request_timeout(body_len: usize) -> std::time::Duration {
)
}
/// How a pooled connection the peer has closed fails a request, depending on
/// when its close reached this side. Mirrors Go's inner resend in
/// `upload_content`.
fn is_stale_connection_error(err: &reqwest::Error) -> bool {
let mut source = std::error::Error::source(err);
while let Some(e) = source {
if let Some(io) = e.downcast_ref::<std::io::Error>()
&& matches!(
io.kind(),
std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
)
{
return true;
}
source = e.source();
}
false
}
/// Sends a replica forward, once more on a new connection when the first
/// attempt rode a pooled connection the peer had closed.
async fn send_replica_request(
request: reqwest::RequestBuilder,
) -> reqwest::Result<reqwest::Response> {
let resend = request.try_clone();
let sent = request.send().await;
match resend {
Some(resend) if sent.as_ref().is_err_and(is_stale_connection_error) => {
tracing::debug!("resend replica request: {:?}", sent.err());
resend.send().await
}
_ => sent,
}
}
fn replica_request(
client: &reqwest::Client,
method: axum::http::Method,
@@ -936,7 +1013,7 @@ async fn do_replicated_request(
}
futures.push(async move {
match req_builder.send().await {
match send_replica_request(req_builder).await {
Ok(r)
if r.status().is_success()
|| (allow_delete && r.status() == StatusCode::NOT_FOUND) =>
@@ -3275,12 +3352,14 @@ pub async fn post_handler(
let original_data_size = uncompressed_data.len() as u32;
// Only compute and validate Content-MD5 when the client provided one
// (Go only computes MD5 when Content-MD5 header/field is present)
// (Go only computes MD5 when Content-MD5 header/field is present).
// Under fips.mode strict no MD5 is computed: the client's value is kept
// unchecked, as Go does under GODEBUG=fips140=only.
let content_md5 = content_md5.or(parsed_content_md5);
let original_content_md5 = if content_md5.is_some() {
Some(compute_md5_base64(&uncompressed_data))
} else {
None
let original_content_md5 = match &content_md5 {
Some(expected) if strict_fips_mode() => Some(expected.clone()),
Some(_) => Some(compute_md5_base64(&uncompressed_data)),
None => None,
};
if let (Some(expected_md5), Some(actual_md5)) = (&content_md5, &original_content_md5)
&& expected_md5 != actual_md5
@@ -5335,6 +5414,12 @@ fn check_content_crc32c(expected: &str, data: &[u8]) -> Result<(), String> {
Ok(())
}
/// Whether this process runs under `fips.mode = strict`, where it computes no
/// MD5.
fn strict_fips_mode() -> bool {
seaweed_common::fips::process_mode() == seaweed_common::fips::FipsMode::Strict
}
fn compute_md5_base64(data: &[u8]) -> String {
use base64::Engine;
use md5::{Digest, Md5};
@@ -5447,7 +5532,7 @@ fn parse_content_disposition_filename(value: &str) -> Option<String> {
// ============================================================================
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
/// A replica that reads the forward and never answers. Each request's
@@ -5657,6 +5742,46 @@ mod tests {
);
}
/// A replica that resets the connection mid-body, as one closing a
/// pooled connection at its idle timeout does, gets the forward once more.
#[tokio::test]
async fn test_replicated_write_resends_after_a_connection_reset() {
use tokio::io::AsyncReadExt;
let tmp = tempfile::TempDir::new().unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let peer = listener.local_addr().unwrap();
let (received, mut receipts) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut head = vec![0u8; 1024];
let _ = socket.read(&mut head).await;
socket.set_zero_linger().unwrap();
drop(socket);
let app = axum::Router::new()
.fallback(move |body: bytes::Bytes| {
let _ = received.send(body.len());
async { StatusCode::CREATED }
})
.layer(axum::extract::DefaultBodyLimit::disable());
axum::serve(listener, app).await.unwrap();
});
let state = remote_manifest_state(&tmp, spawn_lookup(peer).await);
let body = bytes::Bytes::from(vec![7u8; 8 << 20]);
let sent = do_replicated_request(
&state,
1,
axum::http::Method::POST,
"/1,01ab",
"",
&axum::http::HeaderMap::new(),
Some(body.clone()),
None,
)
.await;
sent.expect("the resend reaches the replica on a new connection");
assert_eq!(receipts.try_recv(), Ok(body.len()));
}
/// A peer that accepts the connection but never answers (a silent
/// partition after connect) must fail the forward at the bound, not hold
/// the write until TCP gives up.
@@ -6432,7 +6557,7 @@ mod tests {
/// Serve `answer` as the master's gRPC LookupVolume. The returned address
/// carries an unused HTTP port, so a lookup over HTTP would fail.
async fn spawn_lookup_master(
pub(crate) async fn spawn_lookup_master(
answer: impl Fn(&str) -> Result<master_pb::LookupVolumeResponse, tonic::Status>
+ Send
+ Sync
@@ -6448,7 +6573,7 @@ mod tests {
format!("127.0.0.1:1.{}", port)
}
fn lookup_answer(
pub(crate) fn lookup_answer(
volume_id: &str,
locations: Vec<master_pb::Location>,
error: &str,
+40 -2
View File
@@ -1413,6 +1413,7 @@ fn build_heartbeat_with_ec_status(
}
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
let (read_only, read_only_can_delete) = vol.reported_read_only();
let volume_message = master_pb::VolumeInformationMessage {
id: vol.id.0,
size: volume_size,
@@ -1420,8 +1421,8 @@ fn build_heartbeat_with_ec_status(
file_count: vol.file_count() as u64,
delete_count: vol.deleted_count() as u64,
deleted_byte_count: vol.deleted_size(),
read_only: vol.is_read_only(),
read_only_can_delete: vol.is_no_write_can_delete(),
read_only,
read_only_can_delete,
replica_placement: vol.super_block().replica_placement.to_byte() as u32,
version: vol.super_block().version.0 as u32,
ttl: vol.super_block().ttl.to_u32(),
@@ -1868,6 +1869,43 @@ mod tests {
);
}
#[test]
fn test_build_heartbeat_low_disk_volume_reports_can_delete() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
3,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
vec![],
)
.unwrap();
store
.add_volume(VolumeId(7), DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
store.locations[0]
.is_disk_space_low
.store(true, std::sync::atomic::Ordering::Relaxed);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert!(heartbeat.volumes[0].read_only);
assert!(heartbeat.volumes[0].read_only_can_delete);
store
.find_volume(VolumeId(7))
.unwrap()
.1
.set_no_write_or_delete(true);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert!(heartbeat.volumes[0].read_only);
assert!(!heartbeat.volumes[0].read_only_can_delete);
}
#[test]
fn test_build_heartbeat_marks_empty_store_as_has_no_volumes() {
let temp_dir = tempfile::tempdir().unwrap();
+6
View File
@@ -177,6 +177,12 @@ mod tests {
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
security_file_name: String::new(),
jwt_keys: Vec::new(),
fips_setting: Ok(seaweed_common::fips::Setting {
mode: Default::default(),
source: None,
}),
}
}
@@ -430,8 +430,9 @@ pub fn write_idx_file_from_ec_index(
///
/// Copies the `.ecx` rows, then appends one tombstone per row whose needle is
/// in `deleted`. A deleted needle at or past `dat_file_size` was cut from the
/// `.dat`, so its row is dropped: a row pointing past the end of the `.dat`
/// makes the volume load read-only.
/// `.dat`, so its row becomes a tombstone without the offset: a row pointing
/// past the end of the `.dat` makes the volume load read-only, and the id must
/// stay in the index for the vacuum record.
pub fn write_idx_file_from_ec_index_with_dirs(
ecx_dir: &str,
idx_dir: &str,
@@ -454,6 +455,7 @@ pub fn write_idx_file_from_ec_index_with_dirs(
idx::walk_index_file(&mut ecx_file, 0, |key, offset, size| {
let is_deleted = size.is_deleted() || deleted.contains(&key);
if is_deleted && offset.to_actual_offset() >= dat_file_size {
tombstoned.push(key);
return Ok(());
}
idx::write_index_entry(&mut idx_file, key, offset, size)?;
@@ -99,12 +99,12 @@ pub(super) fn metrics_from_idx<R: Read + Seek>(
let entry = &buf[i * NEEDLE_MAP_ENTRY_SIZE..(i + 1) * NEEDLE_MAP_ENTRY_SIZE];
let (key, offset, size) = idx_entry_from_bytes(entry);
metric.maybe_set_max_needle_end(offset, size, version);
metric.maybe_set_max_file_key(key);
let superseded = seen.test_and_add(key.into());
if offset.is_zero() || size.is_deleted() {
// Tombstone: reserves no bytes, only marks the key as seen.
continue;
}
metric.maybe_set_max_file_key(key);
metric.file_count.fetch_add(1, Ordering::Relaxed);
metric
.file_byte_count
@@ -157,6 +157,23 @@ mod tests {
assert!(false_positives < 500, "false positives: {false_positives}");
}
#[test]
fn test_tombstone_only_key_raises_max_file_key() {
let mut idx = Vec::new();
for (key, offset, size) in [
(1u64, Offset::from_actual_offset(8), Size(100)),
(2, Offset::from_actual_offset(136), Size(100)),
(3, Offset::default(), Size(-1)),
] {
let mut entry = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_entry_to_bytes(&mut entry, NeedleId(key), offset, size);
idx.extend_from_slice(&entry);
}
let metric = metrics_from_idx(&mut std::io::Cursor::new(&idx), Version(3)).unwrap();
assert_eq!(metric.max_file_key.load(Ordering::Relaxed), 3);
assert_eq!(metric.file_count.load(Ordering::Relaxed), 2);
}
// The deleted count rebuilt from an .idx is an estimate: an index of
// unique keys, with no overwrite and no tombstone, still reports a
// deletion once the bloom filter yields a false positive. VolumeCopy
+209 -4
View File
@@ -331,6 +331,7 @@ pub struct VifEcShardConfig {
/// Serde-compatible representation of OldVersionVolumeInfo for legacy .vif JSON deserialization.
/// Matches Go's protobuf OldVersionVolumeInfo where `DestroyTime` maps to `expire_at_sec`.
#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct OldVersionVifVolumeInfo {
#[serde(default)]
pub files: Vec<VifRemoteFile>,
@@ -371,6 +372,8 @@ impl OldVersionVifVolumeInfo {
read_only: self.read_only,
ec_shard_config: None,
read_only_can_delete: false,
vacuumed_max_file_key: 0,
vacuumed_compaction_revision: 0,
}
}
}
@@ -401,6 +404,10 @@ pub struct VifVolumeInfo {
pub ec_shard_config: Option<VifEcShardConfig>,
#[serde(default, rename = "readOnlyCanDelete")]
pub read_only_can_delete: bool,
#[serde(default, rename = "vacuumedMaxFileKey", with = "string_or_u64")]
pub vacuumed_max_file_key: u64,
#[serde(default, rename = "vacuumedCompactionRevision")]
pub vacuumed_compaction_revision: u32,
}
impl VifVolumeInfo {
@@ -433,6 +440,8 @@ impl VifVolumeInfo {
block_size: c.block_size,
}),
read_only_can_delete: pb.read_only_can_delete,
vacuumed_max_file_key: pb.vacuumed_max_file_key,
vacuumed_compaction_revision: pb.vacuumed_compaction_revision,
}
}
@@ -467,6 +476,8 @@ impl VifVolumeInfo {
}
}),
read_only_can_delete: self.read_only_can_delete,
vacuumed_max_file_key: self.vacuumed_max_file_key,
vacuumed_compaction_revision: self.vacuumed_compaction_revision,
}
}
}
@@ -4229,6 +4240,13 @@ impl Volume {
self.no_write_flags().1
}
/// What the master is told: low disk space still lets deletes through,
/// only no_write_or_delete refuses them. Mirrors Go's reportedReadOnly.
pub fn reported_read_only(&self) -> (bool, bool) {
let (read_only, no_write_or_delete, _, _) = self.read_only_reasons();
(read_only, read_only && !no_write_or_delete)
}
pub fn last_compact_revision(&self) -> u16 {
self.io.read().unwrap().last_compact_revision
}
@@ -5243,8 +5261,11 @@ impl Volume {
if content.trim().is_empty() {
return Ok(false);
}
// Try protobuf-JSON (Go-compatible VolumeInfo via VifVolumeInfo)
if let Ok(vif_info) = serde_json::from_str::<VifVolumeInfo>(&content) {
// VifVolumeInfo ignores unknown fields, so an old-format file would
// parse as it too and lose its DestroyTime.
if serde_json::from_str::<OldVersionVifVolumeInfo>(&content).is_err()
&& let Ok(vif_info) = serde_json::from_str::<VifVolumeInfo>(&content)
{
let pb_info = vif_info.to_pb();
if pb_info.read_only {
if pb_info.read_only_can_delete {
@@ -6197,8 +6218,9 @@ impl Volume {
}
// Close current files
{
let vacuum_record = {
let mut io = self.io.write().unwrap();
let vacuum_record = self.vacuum_record_to_keep(io.nm.as_ref());
if let Some(ref mut nm) = io.nm {
nm.close();
}
@@ -6208,7 +6230,8 @@ impl Volume {
}
io.dat_file = None;
io.remote_dat_file = None;
}
vacuum_record
};
#[cfg(test)]
commit_swap_hook::fire(self.id);
@@ -6220,6 +6243,9 @@ impl Volume {
// compacts to empty.
self.write_compact_commit_marker()?;
self.apply_compact_swap()?;
if let Some((max_key, revision)) = vacuum_record {
self.record_vacuumed_max_file_key(max_key, revision);
}
// The write watermark already equals what recover_last_modified_ts
// would rescan, so keep the clock instead of paying for the scan
@@ -6241,6 +6267,41 @@ impl Volume {
Ok(())
}
/// The largest needle id this vacuum could erase, live or deleted, and the
/// compaction revision it produces. None once a vacuum of the volume went
/// unrecorded: its erased ids are unknown.
fn vacuum_record_to_keep(&self, nm: Option<&NeedleMap>) -> Option<(u64, u32)> {
let nm = nm?;
let revision = self.super_block.read().unwrap().compaction_revision;
let vi = self.volume_info.read().unwrap();
let mut max_key: u64 = nm.max_file_key().into();
if revision > 0 {
if vi.vacuumed_compaction_revision != revision as u32 {
return None;
}
max_key = max_key.max(vi.vacuumed_max_file_key);
}
Some((max_key, revision.wrapping_add(1) as u32))
}
/// Saved after the swap: a record that misses the swap keeps the old
/// revision, and volume.check.disk trusts it only at the live one.
fn record_vacuumed_max_file_key(&self, max_key: u64, revision: u32) {
{
let mut vi = self.volume_info.write().unwrap();
vi.vacuumed_max_file_key = max_key;
vi.vacuumed_compaction_revision = revision;
}
if let Err(e) = self.save_vif() {
warn!(
"volume {}: record the vacuumed needle ids in {}: {}",
self.id,
self.vif_path(),
e
);
}
}
/// Write and fsync the .cpc marker, then fsync the directory so the marker
/// survives a crash before apply_compact_swap.
fn write_compact_commit_marker(&self) -> Result<(), VolumeError> {
@@ -11060,6 +11121,121 @@ mod tests {
v.cleanup_compact().unwrap();
}
fn write_ids(v: &Volume, ids: &[u64]) {
for &id in ids {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(id as u32),
data: format!("data-{}", id).into_bytes(),
data_size: format!("data-{}", id).len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true, false).unwrap();
}
}
fn delete_ids(v: &Volume, ids: &[u64]) {
for &id in ids {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(id as u32),
..Needle::default()
};
v.delete_needle(&mut n, false).unwrap();
}
}
fn vacuum(v: &Volume) {
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
}
fn vacuum_record_on_disk(v: &Volume) -> (u64, u32) {
let vif: VifVolumeInfo =
serde_json::from_str(&fs::read_to_string(v.vif_path()).unwrap()).unwrap();
(vif.vacuumed_max_file_key, vif.vacuumed_compaction_revision)
}
fn assert_vacuum_record(v: &Volume, want: (u64, u32), when: &str) {
let vi = v.volume_info();
assert_eq!(
(vi.vacuumed_max_file_key, vi.vacuumed_compaction_revision),
want,
"{}: in memory",
when
);
assert_eq!(vacuum_record_on_disk(v), want, "{}: in the .vif", when);
}
#[test]
fn test_vacuum_records_largest_needle_id_it_could_have_erased() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let v = make_test_volume(dir);
assert_eq!(v.volume_info().vacuumed_max_file_key, 0);
write_ids(&v, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
delete_ids(&v, &[8, 9, 10]);
vacuum(&v);
for id in 8..=10u64 {
let mut n = Needle {
id: NeedleId(id),
..Needle::default()
};
assert!(v.read_needle(&mut n).is_err(), "id {} survived", id);
}
assert_vacuum_record(&v, (10, 1), "after the first vacuum");
write_ids(&v, &[11, 12]);
delete_ids(&v, &[12]);
vacuum(&v);
assert_vacuum_record(&v, (12, 2), "after the second vacuum");
delete_ids(&v, &[11]);
vacuum(&v);
assert_vacuum_record(&v, (12, 3), "after a vacuum of smaller ids");
v.close();
drop(v);
let v = make_test_volume(dir);
assert_vacuum_record(&v, (12, 3), "after a reload");
}
#[test]
fn test_vacuum_after_unrecorded_vacuum_records_nothing() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let v = make_test_volume(dir);
write_ids(&v, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
delete_ids(&v, &[9]);
vacuum(&v);
assert_vacuum_record(&v, (9, 1), "after the first vacuum");
// as a vacuum that kept no record leaves it: the revision moved on
v.volume_info.write().unwrap().vacuumed_compaction_revision = 0;
v.save_vif().unwrap();
delete_ids(&v, &[8]);
vacuum(&v);
assert_eq!(v.super_block().compaction_revision, 2);
assert_vacuum_record(&v, (9, 0), "after a vacuum past an unrecorded one");
}
#[test]
fn test_vif_vacuum_record_round_trips_go_json() {
let go = r#"{"files":[],"version":3,"replication":"000","bytesOffset":4,"datFileSize":"0","expireAtSec":"0","readOnly":false,"readOnlyCanDelete":false,"vacuumedMaxFileKey":"12","vacuumedCompactionRevision":3}"#;
let pb = serde_json::from_str::<VifVolumeInfo>(go).unwrap().to_pb();
assert_eq!(pb.vacuumed_max_file_key, 12);
assert_eq!(pb.vacuumed_compaction_revision, 3);
let back = serde_json::to_string(&VifVolumeInfo::from_pb(&pb)).unwrap();
assert!(back.contains(r#""vacuumedMaxFileKey":"12""#), "{}", back);
assert!(
back.contains(r#""vacuumedCompactionRevision":3"#),
"{}",
back
);
}
/// Guards the copy-phase integrity check against regressing into
/// double-subtracting skipped bytes: expected_live_bytes already excludes
/// needles dropped as unreadable (they continue before the tally), so the
@@ -13746,4 +13922,33 @@ mod tests {
v.read_needle(&mut n1).unwrap();
assert_eq!(n1.data, b"data-1");
}
#[test]
fn test_load_vif_reads_the_old_format_destroy_time() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
{
let _v = make_test_volume(dir);
std::fs::write(
format!("{}/1.vif", dir),
format!(
r#"{{"files":[],"version":3,"replication":"000","BytesOffset":{},"datFileSize":"0","DestroyTime":"4102444800","readOnly":true}}"#,
OFFSET_SIZE
),
)
.unwrap();
}
let v = Volume::new(
dir,
dir,
VolumeId(1),
NeedleMapKind::InMemory,
&VolumeSpec::default(),
)
.unwrap();
assert_eq!(v.volume_info().expire_at_sec, 4102444800);
assert!(v.volume_info().read_only);
}
}
+2
View File
@@ -6357,7 +6357,9 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
"bytes",
"crc32c",
"log",
"prost",
"protoc-bin-vendored",
+107
View File
@@ -0,0 +1,107 @@
//! The digest a cluster writes ETags and chunk digests in.
//!
//! The filer decides it (`weed filer -digest`) and reports it in its
//! configuration; every writer follows it, so a cluster holds one kind of
//! digest (Go's `util.AdoptFilerDigest`). Under sha256 a digest keeps MD5's
//! 16 bytes but is SHA-256 cut to that size.
use std::fmt;
use anyhow::{Result, bail};
use md5::{Digest as _, Md5};
use seaweed_common::fips::FipsMode;
use sha2::Sha256;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ContentDigest {
#[default]
Md5,
Sha256,
}
impl ContentDigest {
/// The digest to write into `filer`, which reports `reported`: the filer's
/// own, or, from a filer that reports none, sha256 under strict mode and
/// md5 otherwise. Under strict mode a filer using md5 is refused, as the Go
/// clients refuse it under `GODEBUG=fips140=only`.
pub fn for_filer(filer: &str, reported: &str, mode: FipsMode) -> Result<Self> {
let strict = mode == FipsMode::Strict;
match reported {
"sha256" => Ok(Self::Sha256),
"md5" if strict => {
bail!("filer {filer} uses digest md5, which needs MD5; fips.mode strict refuses it")
}
"md5" => Ok(Self::Md5),
"" => {
let own = if strict { Self::Sha256 } else { Self::Md5 };
tracing::warn!(
"filer {filer} does not report its digest; writing {own} digests as this process's fips.mode implies"
);
Ok(own)
}
other => bail!("filer {filer} reports digest {other:?}; want md5 or sha256"),
}
}
/// The digest of `data`: its MD5, or its SHA-256 cut to MD5's 16 bytes.
pub fn sum(self, data: &[u8]) -> [u8; 16] {
match self {
Self::Md5 => Md5::digest(data).into(),
Self::Sha256 => {
let full = Sha256::digest(data);
let mut cut = [0u8; 16];
cut.copy_from_slice(&full[..16]);
cut
}
}
}
}
impl fmt::Display for ContentDigest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Md5 => "md5",
Self::Sha256 => "sha256",
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn follows_the_filer_and_refuses_md5_under_strict_mode() {
let pick = |reported, mode| ContentDigest::for_filer("f:18888", reported, mode);
assert_eq!(
pick("sha256", FipsMode::Off).unwrap(),
ContentDigest::Sha256
);
assert_eq!(pick("md5", FipsMode::On).unwrap(), ContentDigest::Md5);
assert_eq!(pick("", FipsMode::Off).unwrap(), ContentDigest::Md5);
assert_eq!(pick("", FipsMode::Strict).unwrap(), ContentDigest::Sha256);
assert_eq!(
pick("sha256", FipsMode::Strict).unwrap(),
ContentDigest::Sha256
);
assert!(
pick("md5", FipsMode::Strict)
.unwrap_err()
.to_string()
.contains("fips.mode strict")
);
assert!(pick("sha512", FipsMode::Off).is_err());
}
#[test]
fn sha256_digests_keep_md5s_length() {
assert_eq!(
hex::encode(ContentDigest::Md5.sum(b"bar")),
"37b51d194a7513e45b56f6524f2d51f2"
);
assert_eq!(
hex::encode(ContentDigest::Sha256.sum(b"bar")),
"fcde2b2edba56bf408601fb721fe9b5c"
);
}
}
+94 -17
View File
@@ -13,6 +13,7 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::digest::ContentDigest;
use anyhow::{Context, bail};
use base64::prelude::{BASE64_STANDARD, Engine};
use bytes::Bytes;
@@ -21,7 +22,6 @@ use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use lance::io::WrappingObjectStore;
use md5::{Digest, Md5};
use object_store::path::Path;
use object_store::{Attribute, Attributes, PutMode, UploadPart};
use object_store::{
@@ -349,13 +349,9 @@ impl Source for Filers {
data: Bytes,
) -> anyhow::Result<FileChunk> {
let name = path.rsplit('/').next().unwrap_or(path).to_string();
let digest = BASE64_STANDARD.encode(Md5::digest(&data));
let mut chunk = self
.writer
self.writer
.upload_assigned_chunk_bytes(assignment, &name, offset as i64, data)
.await?;
chunk.e_tag = digest;
Ok(chunk)
.await
}
async fn create(&self, dir: &str, entry: Entry, exclusive: bool) -> anyhow::Result<()> {
@@ -436,6 +432,9 @@ struct Shared {
chunk_size: usize,
/// Chunks are encrypted for the volume servers, as the cluster asks.
cipher: bool,
/// The digest ETags and chunk digests are written in, as the filer reports
/// it.
digest: ContentDigest,
/// The filer group, which prefixes a bucket's collection as the gateway
/// names it.
filer_group: String,
@@ -530,6 +529,11 @@ impl DirectReads {
Box::pin(async move { c.get_configuration().await })
})
.await?;
let digest = ContentDigest::for_filer(
&conn.filers.join(","),
&config.digest,
seaweed_common::fips::process_mode(),
)?;
let kek_file = filers
.lookup(KEK_PATH.0, KEK_PATH.1)
.await
@@ -546,6 +550,7 @@ impl DirectReads {
let shared = Arc::get_mut(&mut reads.shared).expect("just created");
shared.chunk_size = chunk_size;
shared.cipher = config.cipher;
shared.digest = digest;
shared.filer_group = if conn.filer_group.is_empty() {
config.filer_group.clone()
} else {
@@ -568,6 +573,7 @@ impl DirectReads {
keys,
chunk_size: DEFAULT_CHUNK_SIZE,
cipher: false,
digest: ContentDigest::default(),
filer_group: String::new(),
objects: moka::sync::Cache::builder()
.max_capacity(OBJECT_CACHE_ENTRIES)
@@ -779,8 +785,8 @@ fn bare_directory(entry: &Entry) -> bool {
/// The object's ETag as the gateway reports it: its stored S3 ETag, else the
/// remote ETag while the entry holds the remote bytes, else the entry's md5,
/// else derived from the chunks', quoted.
fn etag(entry: &Entry) -> Option<String> {
/// else derived from the chunks' in the cluster's `digest`, quoted.
fn etag(entry: &Entry, digest: ContentDigest) -> Option<String> {
let quoted = |etag: String| {
if etag.starts_with('"') {
etag
@@ -828,7 +834,7 @@ fn etag(entry: &Entry) -> Option<String> {
[] => None,
[one] => Some(quoted(hex::encode(one))),
many => {
let joined = Md5::digest(many.concat());
let joined = digest.sum(&many.concat());
Some(quoted(format!("{}-{}", hex::encode(joined), many.len())))
}
}
@@ -968,7 +974,7 @@ impl DirectStore {
.map_err(generic)?;
Ok(Arc::new(Object {
size: file_size(&entry, &chunks),
etag: etag(&entry),
etag: etag(&entry, self.reads.digest),
entry,
chunks,
decoder,
@@ -1009,7 +1015,7 @@ impl DirectStore {
)
.unwrap_or_default(),
size: entry_size(entry),
e_tag: etag(entry),
e_tag: etag(entry, self.reads.digest),
version: None,
}
}
@@ -1107,7 +1113,7 @@ impl ObjectStore for DirectStore {
};
let upload = Upload::start(self.clone(), location.clone(), &opts.attributes)?;
let data: Bytes = payload.into();
let md5 = Md5::digest(&data);
let md5 = self.reads.digest.sum(&data);
if let Err(err) = upload.put(data).await {
if let Err(discard) = upload.discard_all().await {
tracing::warn!("{location}: discarding after a failed upload: {discard:#}");
@@ -1275,9 +1281,14 @@ impl fmt::Debug for Upload {
impl Upload {
fn start(store: DirectStore, location: Path, attributes: &Attributes) -> Result<Self> {
let path = store.filer_path(&location);
let encoder = EntryEncoder::new(store.reads.keys.clone(), store.sse_s3, store.reads.cipher)
.with_context(|| format!("encoding {path}"))
.map_err(generic)?;
let encoder = EntryEncoder::new(
store.reads.keys.clone(),
store.sse_s3,
store.reads.cipher,
store.reads.digest,
)
.with_context(|| format!("encoding {path}"))
.map_err(generic)?;
let collection = match store.reads.filer_group.as_str() {
"" => String::new(),
group => format!("{group}_{}", store.bucket),
@@ -1345,6 +1356,7 @@ impl Upload {
}
};
chunk.size = size;
chunk.e_tag = encoded.e_tag;
chunk.cipher_key = encoded.cipher_key;
chunk.sse_type = encoded.sse_type;
chunk.sse_metadata = encoded.sse_metadata;
@@ -1405,7 +1417,7 @@ impl Upload {
}
let attributes = self.encoder.attributes().map_err(generic)?;
entry.extended.extend(attributes);
let e_tag = etag(&entry);
let e_tag = etag(&entry, self.store.reads.digest);
let created = self.store.reads.source.create(dir, entry, exclusive).await;
if let Err(err) = created {
// A create the filer took and never answered may still be applied,
@@ -1672,6 +1684,7 @@ impl VolumeTransport for JwtTransport {
mod tests {
use super::*;
use futures::TryStreamExt;
use md5::{Digest, Md5};
use object_store::ObjectStoreExt;
use object_store::memory::InMemory;
use std::collections::HashMap;
@@ -2667,6 +2680,64 @@ mod tests {
assert_eq!(got, Bytes::from_static(b"again"));
}
/// A store writing through `fake` into a cluster whose digest is `digest`,
/// with 4096-byte chunks.
fn writing_store_in(fake: Arc<Fake>, digest: ContentDigest) -> Arc<dyn ObjectStore> {
let mut reads = DirectReads::new(fake, "", no_keys());
{
let shared = Arc::get_mut(&mut reads.shared).unwrap();
shared.chunk_size = 4096;
shared.digest = digest;
}
reads
.encrypting(false)
.wrap("s3$vb", Arc::new(InMemory::new()))
}
/// In a sha256 cluster the entry's digest, its chunks' ETags and a
/// multipart ETag are SHA-256 cut to 16 bytes, as Go's writers write them.
#[tokio::test]
async fn writes_follow_a_sha256_digest() {
let fake = Arc::new(Fake::default());
let store = writing_store_in(fake.clone(), ContentDigest::Sha256);
let sum = |data: &[u8]| ContentDigest::Sha256.sum(data);
let body = Bytes::from(vec![9u8; 5000]);
let path = Path::from("vector/idx/_versions/1.manifest");
let result = store
.put_opts(&path, body.clone().into(), PutMode::Create.into())
.await
.unwrap();
let whole = hex::encode(sum(&body));
assert_eq!(
result.e_tag.as_deref(),
Some(format!("\"{whole}\"").as_str())
);
let entry = entry_of(&fake, "vector/idx/_versions/1.manifest");
assert_eq!(hex::encode(&entry.attributes.as_ref().unwrap().md5), whole);
let tags: Vec<String> = entry.chunks.iter().map(|c| c.e_tag.clone()).collect();
let want: Vec<String> = [&body[..4096], &body[4096..]]
.iter()
.map(|piece| BASE64_STANDARD.encode(sum(piece)))
.collect();
assert_eq!(tags, want);
let mut upload = store
.put_multipart(&Path::from("vector/idx/data/ef.lance"))
.await
.unwrap();
let parts = [vec![1u8; 3000], vec![2u8; 1000]];
for part in &parts {
upload
.put_part(Bytes::from(part.clone()).into())
.await
.unwrap();
}
let result = upload.complete().await.unwrap();
let digests: Vec<u8> = parts.iter().flat_map(|p| sum(p)).collect();
let want = format!("\"{}-2\"", hex::encode(sum(&digests)));
assert_eq!(result.e_tag.as_deref(), Some(want.as_str()));
}
/// A multipart upload's parts become chunks in order, its ETag derives
/// from them as the gateway's does, and an abort leaves no needle behind.
#[tokio::test]
@@ -2743,6 +2814,12 @@ mod tests {
let plain =
&body[chunk.offset as usize..chunk.offset as usize + chunk.size as usize];
assert_ne!(needle, plain, "cipher {cipher} sse {sse_s3}");
// The ETag digests the bytes before the volume encryption.
if !cipher {
assert_eq!(chunk.e_tag, BASE64_STANDARD.encode(Md5::digest(needle)));
} else if !sse_s3 {
assert_eq!(chunk.e_tag, BASE64_STANDARD.encode(Md5::digest(plain)));
}
assert_eq!(!chunk.cipher_key.is_empty(), cipher);
assert_eq!(chunk.sse_type == SSE_S3_TYPE, sse_s3);
}
+1
View File
@@ -13,6 +13,7 @@ pub mod admin_cluster;
pub mod catalog;
pub mod cluster;
pub mod dataset;
pub mod digest;
pub mod direct_read;
pub mod drop_guard;
pub mod grpc_tls;
+6 -1
View File
@@ -130,7 +130,12 @@ async fn main() -> Result<()> {
// One security.toml for everything: the admin stream's and the catalog's
// signing key, and the cluster connection.
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
weed_lance_worker::tls::install_for_fips_mode(&security)?;
let mode = weed_lance_worker::tls::install_for_fips_mode(&security)?;
weed_lance_worker::security::check_signing_key_flag(
mode,
"--filer-signing-key (WEED_FILER_SIGNING_KEY)",
args.filer_signing_key.as_deref(),
)?;
let filer_signing = match args.filer_signing_key.filter(|key| !key.is_empty()) {
Some(key) => Some((key, 0)),
None => security
@@ -6,6 +6,8 @@ use std::path::{Path, PathBuf};
use crate::sse::SseConfig;
use anyhow::{Context, Result, bail};
use seaweed_common::fips::FipsMode;
use seaweed_common::jwt_keys;
use sw_client::HttpsTls;
const FILE_NAME: &str = "security.toml";
@@ -149,6 +151,32 @@ impl Security {
self.path.as_deref()
}
/// Checks the JWT HMAC signing keys from this security.toml and their
/// WEED_ variables for a length of at least 14 characters, as FIPS 140
/// requires. Under `fips.mode = strict`, if any of them is shorter, it
/// returns an error naming each such setting and its length. In any other
/// mode each such key except a `previous_key` gets a warning that strict
/// mode would refuse it.
pub fn check_jwt_keys(&self, mode: FipsMode) -> Result<()> {
let file = self
.path()
.map_or_else(|| FILE_NAME.to_string(), |p| p.display().to_string());
let keys: Vec<(&str, Vec<u8>)> = jwt_keys::JWT_KEY_SETTINGS
.iter()
.map(|&setting| (setting, self.get(setting).unwrap_or_default().into_bytes()))
.collect();
for (setting, key) in &keys {
if let Some(warning) = jwt_keys::short_key_warning(mode, &file, setting, key) {
tracing::warn!("{warning}");
}
}
let keys: Vec<(&str, &[u8])> = keys.iter().map(|(s, k)| (*s, k.as_slice())).collect();
if let Some(short) = jwt_keys::short_keys(mode, &keys) {
bail!("{}", jwt_keys::startup_refusal(&file, &short));
}
Ok(())
}
fn raw(&self, key: &str) -> Option<String> {
let env_name = format!("WEED_{}", key.to_uppercase().replace('.', "_"));
// viper treats an empty variable as unset
@@ -329,11 +357,70 @@ impl Security {
}
}
/// Checks a signing key given on the command line as `flag`, as
/// [`Security::check_jwt_keys`] checks the file's: under `fips.mode = strict`
/// a key shorter than 14 characters is an error naming the flag and the
/// key's length; in any other mode it gets a warning that strict mode would
/// refuse it.
pub fn check_signing_key_flag(mode: FipsMode, flag: &str, key: Option<&str>) -> Result<()> {
let key = key.unwrap_or_default().as_bytes();
if let Some(warning) = jwt_keys::short_key_warning(mode, "command line", flag, key) {
tracing::warn!("{warning}");
}
if let Some(short) = jwt_keys::short_keys(mode, &[(flag, key)]) {
bail!("this process runs with fips.mode strict, and stops because {short}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn strict_mode_refuses_a_short_jwt_key_from_the_file_or_the_environment() {
let file = "[jwt.signing.read]\nkey = \"0123456789\"\n[jwt.filer_signing]\nkey = \"long-enough-filer-key\"\n";
let err = security(file, &[])
.check_jwt_keys(FipsMode::Strict)
.unwrap_err();
assert!(
err.to_string()
.contains("jwt.signing.read.key (10 characters) is shorter than the 14 characters"),
"{err}"
);
assert!(security(file, &[]).check_jwt_keys(FipsMode::On).is_ok());
let env = [("WEED_JWT_FILER_SIGNING_KEY", "short")];
let err = security("", &env)
.check_jwt_keys(FipsMode::Strict)
.unwrap_err();
assert!(
err.to_string()
.contains("jwt.filer_signing.key (5 characters)"),
"{err}"
);
let long = "[jwt.signing]\nkey = \"a-key-long-enough\"\n";
assert!(security(long, &[]).check_jwt_keys(FipsMode::Strict).is_ok());
assert!(security("", &[]).check_jwt_keys(FipsMode::Strict).is_ok());
}
#[test]
fn strict_mode_refuses_a_short_signing_key_flag() {
let err = check_signing_key_flag(FipsMode::Strict, "--filer-signing-key", Some("short"))
.unwrap_err();
assert!(
err.to_string()
.contains("--filer-signing-key (5 characters)"),
"{err}"
);
assert!(
check_signing_key_flag(FipsMode::Off, "--filer-signing-key", Some("short")).is_ok()
);
assert!(check_signing_key_flag(FipsMode::Strict, "--filer-signing-key", None).is_ok());
}
fn security(toml: &str, env: &[(&str, &str)]) -> Security {
let env: HashMap<String, String> = env
.iter()
+15 -1
View File
@@ -20,6 +20,8 @@ use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use sw_client::ChunkDecoder;
use crate::digest::ContentDigest;
use sw_client::filer_pb::{Entry, FileChunk};
type Aes256Ctr = ctr::Ctr128BE<aes::Aes256>;
@@ -332,6 +334,9 @@ impl ObjectKey {
/// records about them.
pub struct EncodedChunk {
pub data: Vec<u8>,
/// The chunk's ETag: the digest of its bytes before the volume encryption,
/// as Go's uploader records it under cipher.
pub e_tag: String,
pub cipher_key: Vec<u8>,
pub sse_type: i32,
pub sse_metadata: Vec<u8>,
@@ -348,6 +353,7 @@ pub struct EntryEncoder {
keys: Arc<SseS3Keys>,
object: Option<(ObjectKey, String)>,
cipher: bool,
digest: ContentDigest,
}
fn key_id() -> String {
@@ -355,7 +361,12 @@ fn key_id() -> String {
}
impl EntryEncoder {
pub fn new(keys: Arc<SseS3Keys>, sse_s3: bool, cipher: bool) -> Result<Self> {
pub fn new(
keys: Arc<SseS3Keys>,
sse_s3: bool,
cipher: bool,
digest: ContentDigest,
) -> Result<Self> {
let object = if sse_s3 {
if !keys.configured() {
bail!(
@@ -370,6 +381,7 @@ impl EntryEncoder {
keys,
object,
cipher,
digest,
})
}
@@ -390,6 +402,7 @@ impl EntryEncoder {
}
None => (0, Vec::new()),
};
let e_tag = BASE64_STANDARD.encode(self.digest.sum(&data));
let (data, cipher_key) = if self.cipher {
encrypt_chunk(&data)
} else {
@@ -397,6 +410,7 @@ impl EntryEncoder {
};
Ok(EncodedChunk {
data,
e_tag,
cipher_key,
sse_type,
sse_metadata,
+4 -2
View File
@@ -10,8 +10,9 @@ pub use seaweed_common::tls::{crypto_provider, install_default_crypto_provider,
/// Resolves the FIPS mode of a process that reads `security`
/// (`WEED_FIPS_MODE`, else its `fips.mode`, read from the same parsed file
/// as the JWT keys), installs the matching rustls provider as the process
/// default and logs the mode. Call it once at startup, before anything
/// configures TLS.
/// default, logs the mode and checks the file's JWT keys for it
/// ([`crate::security::Security::check_jwt_keys`]). Call it once at
/// startup, before anything configures TLS or signs a token.
pub fn install_for_fips_mode(
security: &crate::security::Security,
) -> anyhow::Result<seaweed_common::fips::FipsMode> {
@@ -30,6 +31,7 @@ pub fn install_for_fips_mode(
} else {
tracing::info!("{setting}");
}
security.check_jwt_keys(setting.mode)?;
Ok(setting.mode)
}
@@ -0,0 +1,72 @@
//! weed-worker under `fips.mode = strict` exits at startup when a JWT key is
//! too short for FIPS 140, before it dials the admin server.
use std::io::Read;
use std::process::{Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
/// Runs weed-worker with `args` under `WEED_FIPS_MODE=strict` and a
/// security.toml holding `security`, without the caller's other WEED_
/// variables, and returns its exit status and stderr. Fails when it is still
/// running after 30 s, which means it accepted the keys.
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("security.toml");
std::fs::write(&file, security).unwrap();
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-worker"));
for (name, _) in std::env::vars_os() {
if name.to_string_lossy().starts_with("WEED_") {
command.env_remove(name);
}
}
let mut child = command
.arg("--security-toml")
.arg(&file)
.args(args)
.env("WEED_FIPS_MODE", "strict")
.current_dir(dir.path())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
if let Some(status) = child.try_wait().unwrap() {
let mut stderr = String::new();
child
.stderr
.take()
.unwrap()
.read_to_string(&mut stderr)
.unwrap();
return (status, stderr);
}
if Instant::now() > deadline {
let _ = child.kill();
panic!("weed-worker still running after 30 s: it accepted the short key");
}
std::thread::sleep(Duration::from_millis(100));
}
}
#[test]
fn a_short_key_in_security_toml_stops_the_worker() {
let (status, stderr) = run_strict("[jwt.signing.read]\nkey = \"0123456789\"\n", &[]);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("fips.mode strict")
&& stderr
.contains("jwt.signing.read.key (10 characters) is shorter than the 14 characters"),
"{stderr}"
);
}
#[test]
fn a_short_signing_key_flag_stops_the_worker() {
let (status, stderr) = run_strict("", &["--filer-signing-key", "short"]);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("--filer-signing-key (WEED_FILER_SIGNING_KEY) (5 characters)"),
"{stderr}"
);
}
@@ -11,7 +11,10 @@ name = "sw_client"
[dependencies]
anyhow.workspace = true
async-trait.workspace = true
base64 = "0.22"
bytes = "1"
# The checksum each upload carries for the volume server to check.
crc32c = "0.6"
log = "0.4"
prost.workspace = true
# System roots for volume servers behind public CAs, as Go's http client.
@@ -323,6 +323,9 @@ pub struct FilerConfig {
pub version: String,
pub cluster_id: String,
pub filer_group: String,
/// The digest the cluster writes ETags and chunk digests in, "md5" or
/// "sha256"; empty from a filer that predates the setting.
pub digest: String,
}
impl From<GetFilerConfigurationResponse> for FilerConfig {
@@ -337,6 +340,7 @@ impl From<GetFilerConfigurationResponse> for FilerConfig {
version: r.version,
cluster_id: r.cluster_id,
filer_group: r.filer_group,
digest: r.digest,
}
}
}
@@ -524,6 +524,17 @@ impl VolumeTransport for HttpTransport {
}
}
/// The header in which an upload carries the CRC32C of its bytes, which the
/// volume server checks before storing them (Go's needle.ContentCrc32cHeader).
pub const CONTENT_CRC32C_HEADER: &str = "X-Seaweed-Content-Crc32c";
/// The [`CONTENT_CRC32C_HEADER`] value for `data`: the base64 of its CRC32C,
/// big-endian, as Go's needle.ContentCrc32c writes it.
pub fn content_crc32c(data: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(crc32c::crc32c(data).to_be_bytes())
}
impl HttpTransport {
async fn upload(
&self,
@@ -539,6 +550,7 @@ impl HttpTransport {
url.push_str("?fsync=true");
}
let size = data.len() as u64;
let crc32c = content_crc32c(&data);
let part = reqwest::multipart::Part::stream_with_length(data, size)
.file_name(filename.to_string());
let form = reqwest::multipart::Form::new().part("file", part);
@@ -546,6 +558,7 @@ impl HttpTransport {
.http
.post(&url)
.timeout(self.write_timeout)
.header(CONTENT_CRC32C_HEADER, crc32c)
.multipart(form);
if !auth.is_empty() {
req = req.header(AUTHORIZATION, format!("BEARER {auth}"));
@@ -967,6 +980,68 @@ AAAA
);
}
/// Reads one HTTP request from `socket`, however TCP splits it: the head up
/// to its blank line, then as many body bytes as its Content-Length says.
/// Returns the head.
async fn read_request_head_and_body(socket: &mut tokio::net::TcpStream) -> String {
let mut request = Vec::new();
let mut buf = [0u8; 4096];
let head_end = loop {
if let Some(at) = request.windows(4).position(|w| w == b"\r\n\r\n") {
break at + 4;
}
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed inside the request head");
request.extend_from_slice(&buf[..n]);
};
let head = String::from_utf8_lossy(&request[..head_end]).to_string();
let body_len: usize = head
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse().ok())?
})
.unwrap_or(0);
while request.len() < head_end + body_len {
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed inside the request body");
request.extend_from_slice(&buf[..n]);
}
head
}
/// An upload carries the CRC32C of its bytes for the volume server to
/// check, in the form Go writes it.
#[tokio::test]
async fn upload_carries_the_crc32c_of_its_bytes() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let head = read_request_head_and_body(&mut socket).await;
socket
.write_all(
b"HTTP/1.1 201 Created\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await
.unwrap();
head.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case(CONTENT_CRC32C_HEADER)
.then(|| value.trim().to_string())
})
.unwrap_or_default()
});
HttpTransport::new()
.write(&address, "7,abc", "", "k", Bytes::from_static(b"hello"))
.await
.unwrap();
assert_eq!(server.await.unwrap(), content_crc32c(b"hello"));
assert_eq!(content_crc32c(b"hello"), "mnG7TA==");
}
/// A write that never reached the server (connection refused) is a plain
/// error, not an ambiguous commit.
#[tokio::test]
+2 -2
View File
@@ -379,7 +379,7 @@ func createTopicData(masterAddr, filerAddr, namespace, topicName string,
}
// Create publisher
publisher, err := pub_client.NewTopicPublisher(config)
publisher, err := pub_client.NewTopicPublisher(context.Background(), config)
if err != nil {
return fmt.Errorf("failed to create publisher: %v", err)
}
@@ -397,7 +397,7 @@ func createTopicData(masterAddr, filerAddr, namespace, topicName string,
}
// Publish structured record
err = publisher.PublishRecord([]byte(fmt.Sprintf("key-%d", i)), recordValue)
_, err = publisher.PublishRecord([]byte(fmt.Sprintf("key-%d", i)), recordValue)
if err != nil {
log.Printf("Error publishing message %d: %v", i+1, err)
continue
+259
View File
@@ -0,0 +1,259 @@
package postgres_flat
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/seaweedfs/seaweedfs/test/testutil"
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
"github.com/seaweedfs/seaweedfs/weed/filer/store_test"
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
"github.com/stretchr/testify/require"
)
const (
accessKey = "pgflat_access_key"
secretKey = "pgflat_secret_key"
)
// cluster is a "weed mini" whose filer keeps its metadata in a postgres_flat
// store, in a schema of its own.
type cluster struct {
t *testing.T
baseDir string
weedBinary string
filerAddr string
s3Endpoint string
db *sql.DB
}
func startCluster(t *testing.T) *cluster {
pg := store_test.NewPostgresTestDatabase(t)
weedBinary, err := framework.FindOrBuildWeedBinary()
require.NoError(t, err)
c := &cluster{t: t, baseDir: t.TempDir(), weedBinary: weedBinary}
configDir := filepath.Join(c.baseDir, "config")
dataDir := filepath.Join(c.baseDir, "data")
for _, d := range []string{configDir, dataDir} {
require.NoError(t, os.MkdirAll(d, 0o755))
}
require.NoError(t, os.WriteFile(filepath.Join(configDir, "filer.toml"), []byte(filerToml(pg)), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(configDir, "security.toml"), nil, 0o644))
s3Config, err := testutil.WriteIAMConfig(configDir, accessKey, secretKey)
require.NoError(t, err)
dsn, _ := pgxutil.BuildDSN(pg)
c.db, err = sql.Open("pgx", dsn)
require.NoError(t, err)
t.Cleanup(func() { c.db.Close() })
ports := testutil.MustFreeMiniPorts(t, []string{"master", "volume", "filer", "s3", "admin"})
c.filerAddr = fmt.Sprintf("127.0.0.1:%d", ports[2])
c.s3Endpoint = fmt.Sprintf("http://127.0.0.1:%d", ports[3])
args := append([]string{
"-config_dir=" + configDir,
"mini",
"-dir=" + dataDir,
"-ip=127.0.0.1",
"-ip.bind=127.0.0.1",
"-master.port=" + strconv.Itoa(ports[0]),
"-master.peers=none",
"-master.volumeSizeLimitMB=32",
"-master.telemetry=false",
"-volume.port=" + strconv.Itoa(ports[1]),
"-volume.max=8",
"-filer.port=" + strconv.Itoa(ports[2]),
"-s3.port=" + strconv.Itoa(ports[3]),
"-s3.config=" + s3Config,
"-s3.port.iceberg=0",
"-s3.port.lance=0",
"-webdav=false",
"-admin.ui=false",
}, testutil.MiniAdminArgs(ports[4])...)
mini := c.start(t, "mini", args...)
client := c.s3Client()
deadline := time.Now().Add(testutil.SeaweedMiniStartupTimeout)
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
_, err := client.ListBuckets(ctx, &s3.ListBucketsInput{})
cancel()
if err == nil {
break
}
if exited(mini) || time.Now().After(deadline) {
t.Fatalf("s3 not ready: %v\n%s", err, c.logTail("mini"))
}
time.Sleep(200 * time.Millisecond)
}
return c
}
func filerToml(pg pgxutil.DSNOptions) string {
return fmt.Sprintf(`[postgres_flat]
enabled = true
hostname = %q
port = %d
username = %q
password = %q
database = %q
schema = %q
sslmode = "disable"
`, pg.Hostname, pg.Port, pg.User, pg.Password, pg.Database, pg.Schema)
}
// start runs a weed command until the test ends, logging to <baseDir>/<name>.log.
// The returned channel is closed once the command exits.
func (c *cluster) start(t *testing.T, name string, args ...string) <-chan struct{} {
log, err := os.Create(filepath.Join(c.baseDir, name+".log"))
require.NoError(t, err)
cmd := exec.Command(c.weedBinary, args...)
cmd.Dir = c.baseDir
cmd.Stdout = log
cmd.Stderr = log
require.NoError(t, cmd.Start())
done := make(chan struct{})
go func() {
_ = cmd.Wait()
close(done)
}()
t.Cleanup(func() {
stop(cmd, done)
log.Close()
if t.Failed() {
t.Logf("%s log tail:\n%s", name, c.logTail(name))
}
})
return done
}
func stop(cmd *exec.Cmd, done <-chan struct{}) {
if exited(done) {
return
}
_ = cmd.Process.Signal(os.Interrupt)
select {
case <-done:
case <-time.After(10 * time.Second):
_ = cmd.Process.Kill()
<-done
}
}
func exited(done <-chan struct{}) bool {
select {
case <-done:
return true
default:
return false
}
}
func (c *cluster) logTail(name string) string {
data, _ := os.ReadFile(filepath.Join(c.baseDir, name+".log"))
if len(data) > 8192 {
data = data[len(data)-8192:]
}
return string(data)
}
func (c *cluster) s3Client() *s3.Client {
cfg, err := config.LoadDefaultConfig(context.Background(),
config.WithRegion("us-east-1"),
config.WithRetryMaxAttempts(1),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
)
require.NoError(c.t, err)
return s3.NewFromConfig(cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(c.s3Endpoint)
o.UsePathStyle = true
})
}
// paths returns the path column of a table, in order, under a prefix.
func (c *cluster) paths(t *testing.T, table, prefix string) []string {
t.Helper()
rows, err := c.db.Query(fmt.Sprintf(`SELECT path FROM "%s" WHERE starts_with(path, $1) ORDER BY path`, table), prefix)
require.NoError(t, err)
defer rows.Close()
var paths []string
for rows.Next() {
var p string
require.NoError(t, rows.Scan(&p))
paths = append(paths, p)
}
require.NoError(t, rows.Err())
return paths
}
func (c *cluster) tableExists(t *testing.T, table string) bool {
t.Helper()
var exists bool
require.NoError(t, c.db.QueryRow(`SELECT to_regclass(quote_ident($1)) IS NOT NULL`, table).Scan(&exists))
return exists
}
func (c *cluster) count(t *testing.T, query string, args ...interface{}) int {
t.Helper()
var n int
require.NoError(t, c.db.QueryRow(query, args...).Scan(&n))
return n
}
// eventually retries check until it passes or the timeout ends; the filer
// creates and drops bucket tables from its metadata events.
func eventually(t *testing.T, what string, check func() bool) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for !check() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting until %s", what)
}
time.Sleep(100 * time.Millisecond)
}
}
// filerList pages through a directory listing of the filer's HTTP API.
func (c *cluster) filerList(t *testing.T, dir string, pageSize int) []string {
t.Helper()
var names []string
last := ""
for {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s%s/?limit=%d&lastFileName=%s", c.filerAddr, dir, pageSize, url.QueryEscape(last)), nil)
require.NoError(t, err)
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
var page struct {
Entries []struct{ FullPath string }
LastFileName string
ShouldDisplayLoadMore bool
}
err = json.NewDecoder(resp.Body).Decode(&page)
resp.Body.Close()
require.NoError(t, err)
for _, e := range page.Entries {
names = append(names, e.FullPath[strings.LastIndex(e.FullPath, "/")+1:])
}
if !page.ShouldDisplayLoadMore {
return names
}
last = page.LastFileName
}
}
+237
View File
@@ -0,0 +1,237 @@
//go:build linux
package postgres_flat
import (
"context"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"syscall"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/stretchr/testify/require"
)
// mount mounts the filer root with a metadata cache of its own, so a new
// mount reads everything back from the store.
func (c *cluster) mount(t *testing.T, name string) string {
t.Helper()
if _, err := os.Stat("/dev/fuse"); err != nil {
t.Skip("no /dev/fuse")
}
dir := filepath.Join(c.baseDir, name)
cacheDir := filepath.Join(c.baseDir, name+"-cache")
require.NoError(t, os.MkdirAll(dir, 0o755))
require.NoError(t, os.MkdirAll(cacheDir, 0o755))
done := c.start(t, name, "mount", "-filer="+c.filerAddr, "-dir="+dir, "-filer.path=/", "-cacheDir="+cacheDir, "-allowOthers=false")
t.Cleanup(func() {
_ = exec.Command("fusermount3", "-u", dir).Run()
_ = exec.Command("fusermount", "-u", dir).Run()
})
var parent syscall.Stat_t
require.NoError(t, syscall.Stat(c.baseDir, &parent))
probe := filepath.Join(dir, ".probe-"+name)
deadline := time.Now().Add(90 * time.Second)
for {
var st syscall.Stat_t
if syscall.Stat(dir, &st) == nil && st.Dev != parent.Dev {
if err := os.WriteFile(probe, []byte("probe"), 0o644); err == nil {
require.NoError(t, os.Remove(probe))
return dir
}
}
if exited(done) || time.Now().After(deadline) {
t.Fatalf("mount %s not ready:\n%s", name, c.logTail(name))
}
time.Sleep(200 * time.Millisecond)
}
}
func unmount(t *testing.T, dir string) {
t.Helper()
out, err := exec.Command("fusermount3", "-u", dir).CombinedOutput()
if err != nil {
out, err = exec.Command("fusermount", "-u", dir).CombinedOutput()
}
require.NoError(t, err, "unmount %s: %s", dir, out)
}
// tree lists every file under root with its content, and every directory
// with a trailing slash.
func tree(t *testing.T, root string) map[string]string {
t.Helper()
got := map[string]string{}
require.NoError(t, filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil || p == root {
return err
}
rel, _ := filepath.Rel(root, p)
switch {
case d.IsDir():
got[rel+"/"] = ""
case d.Type()&fs.ModeSymlink != 0:
target, err := os.Readlink(p)
got[rel+" -> "+target] = ""
return err
default:
data, err := os.ReadFile(p)
got[rel] = string(data)
return err
}
return nil
}))
return got
}
func TestPosix(t *testing.T) {
c := startCluster(t)
mnt := c.mount(t, "mount")
client := c.s3Client()
root := filepath.Join(mnt, "posix")
require.NoError(t, os.MkdirAll(root, 0o755))
write := func(t *testing.T, rel, body string) {
t.Helper()
p := filepath.Join(root, rel)
require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755))
require.NoError(t, os.WriteFile(p, []byte(body), 0o644))
}
read := func(t *testing.T, rel string) string {
t.Helper()
data, err := os.ReadFile(filepath.Join(root, rel))
require.NoError(t, err)
return string(data)
}
kvRows := func(t *testing.T) int { return c.count(t, `SELECT count(*) FROM filemeta_kv`) }
t.Run("files and directories are rows keyed by their path", func(t *testing.T) {
write(t, "a/b/f.txt", "f")
write(t, "a/g.txt", "g")
require.Equal(t, []string{"/posix", "/posix/a", "/posix/a/b", "/posix/a/b/f.txt", "/posix/a/g.txt"}, c.paths(t, "filemeta", "/posix"))
require.NoError(t, os.WriteFile(filepath.Join(root, "a/g.txt"), []byte("g2"), 0o644))
require.Equal(t, "g2", read(t, "a/g.txt"))
require.NoError(t, os.Chmod(filepath.Join(root, "a/g.txt"), 0o600))
st, err := os.Stat(filepath.Join(root, "a/g.txt"))
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), st.Mode().Perm())
})
t.Run("a directory longer than a listing page", func(t *testing.T) {
require.NoError(t, os.Mkdir(filepath.Join(root, "many"), 0o755))
var want []string
for i := 0; i < filer.PaginationSize+100; i++ {
name := fmt.Sprintf("f%05d", i)
want = append(want, name)
f, err := os.Create(filepath.Join(root, "many", name))
require.NoError(t, err)
require.NoError(t, f.Close())
}
entries, err := os.ReadDir(filepath.Join(root, "many"))
require.NoError(t, err)
var got []string
for _, e := range entries {
got = append(got, e.Name())
}
require.Equal(t, want, got)
require.Equal(t, want, c.filerList(t, "/posix/many", 100))
require.Equal(t, len(want), c.count(t, `SELECT count(*) FROM filemeta WHERE directory = '/posix/many'`))
})
t.Run("rename moves rows", func(t *testing.T) {
write(t, "mv/src/one.txt", "one")
write(t, "mv/src/sub/two.txt", "two")
require.NoError(t, os.Rename(filepath.Join(root, "mv/src/one.txt"), filepath.Join(root, "mv/uno.txt")))
require.Equal(t, "one", read(t, "mv/uno.txt"))
require.NoError(t, os.Rename(filepath.Join(root, "mv/src"), filepath.Join(root, "mv/dst")))
require.Equal(t, "two", read(t, "mv/dst/sub/two.txt"))
require.Equal(t, []string{"/posix/mv", "/posix/mv/dst", "/posix/mv/dst/sub", "/posix/mv/dst/sub/two.txt", "/posix/mv/uno.txt"}, c.paths(t, "filemeta", "/posix/mv"))
})
t.Run("hard links keep their record in the key-value table", func(t *testing.T) {
before := kvRows(t)
write(t, "links/orig.txt", "linked")
require.NoError(t, os.Link(filepath.Join(root, "links/orig.txt"), filepath.Join(root, "links/hard.txt")))
require.Greater(t, kvRows(t), before)
require.Equal(t, "linked", read(t, "links/hard.txt"))
st, err := os.Stat(filepath.Join(root, "links/hard.txt"))
require.NoError(t, err)
require.Equal(t, uint64(2), uint64(st.Sys().(*syscall.Stat_t).Nlink))
require.NoError(t, os.Remove(filepath.Join(root, "links/orig.txt")))
require.Equal(t, "linked", read(t, "links/hard.txt"))
require.NoError(t, os.Symlink("hard.txt", filepath.Join(root, "links/soft")))
target, err := os.Readlink(filepath.Join(root, "links/soft"))
require.NoError(t, err)
require.Equal(t, "hard.txt", target)
require.Equal(t, "linked", read(t, "links/soft"))
})
t.Run("remove a tree", func(t *testing.T) {
write(t, "gone/x/y/z.txt", "z")
write(t, "gone/w.txt", "w")
write(t, "gone2/kept.txt", "kept")
require.NoError(t, os.RemoveAll(filepath.Join(root, "gone")))
require.Empty(t, c.paths(t, "filemeta", "/posix/gone/"))
require.Equal(t, []string{"/posix/gone2", "/posix/gone2/kept.txt"}, c.paths(t, "filemeta", "/posix/gone"))
})
t.Run("bucket made through the mount", func(t *testing.T) {
bucket := "pgflat-posix"
bucketDir := filepath.Join(mnt, "buckets", bucket)
require.NoError(t, os.Mkdir(bucketDir, 0o755))
eventually(t, "the bucket has a table", func() bool { return c.tableExists(t, bucket) })
require.NoError(t, os.MkdirAll(filepath.Join(bucketDir, "k"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(bucketDir, "k/v.txt"), []byte("from mount"), 0o644))
require.Equal(t, []string{"/k", "/k/v.txt"}, c.paths(t, bucket, "/"))
ctx := context.Background()
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String("k/v.txt")})
require.NoError(t, err)
data, err := io.ReadAll(out.Body)
out.Body.Close()
require.NoError(t, err)
require.Equal(t, "from mount", string(data))
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("k/s3.txt"), Body: strings.NewReader("from s3")})
require.NoError(t, err)
eventually(t, "the mount sees the S3 object", func() bool {
data, err := os.ReadFile(filepath.Join(bucketDir, "k/s3.txt"))
return err == nil && string(data) == "from s3"
})
require.NoError(t, os.RemoveAll(bucketDir))
eventually(t, "the bucket table is dropped", func() bool { return !c.tableExists(t, bucket) })
})
t.Run("a new mount reads the same tree from the store", func(t *testing.T) {
write(t, "remount/sub/deep.txt", "deep")
require.NoError(t, os.Symlink("sub/deep.txt", filepath.Join(root, "remount/link")))
want := tree(t, root)
require.Contains(t, want, "remount/sub/deep.txt")
require.Contains(t, want, "remount/link -> sub/deep.txt")
unmount(t, mnt)
fresh := c.mount(t, "remount")
got := tree(t, filepath.Join(fresh, "posix"))
require.Equal(t, keys(want), keys(got))
require.Equal(t, want, got)
})
}
func keys(m map[string]string) []string {
var ks []string
for k := range m {
ks = append(ks, k)
}
sort.Strings(ks)
return ks
}
@@ -0,0 +1,115 @@
package postgres_flat
import (
"context"
"fmt"
"sort"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestS3RecursiveListing lists through a gateway that reads one path range of
// the bucket's table per page, and expects the pages S3 returns: the keys under
// the prefix and past the marker, in byte order.
func TestS3RecursiveListing(t *testing.T) {
c := startCluster(t)
fast := c.s3Client()
ctx := context.Background()
bucket := "pgflat-recursive"
b := aws.String(bucket)
_, err := fast.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: b})
require.NoError(t, err)
keys := []string{"a+b", "a-b/x", "a/x", "a/y/z", "a0", "日本/x", "sp ace/%_!", "z", "m/", "m/c", "m+/c", "mk/", "p", "p/q"}
for i := 0; i < 60; i++ {
keys = append(keys, fmt.Sprintf("deep/acct-%03d/Contract/rec-%03d/2026/10/doc.pdf", i, i))
}
for _, k := range keys {
_, err := fast.PutObject(ctx, &s3.PutObjectInput{Bucket: b, Key: aws.String(k), Body: strings.NewReader("body of " + k)})
require.NoError(t, err, "put %s", k)
}
_, err = fast.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{Bucket: b, Key: aws.String("up/unfinished")})
require.NoError(t, err)
sorted := append([]string(nil), keys...)
sort.Strings(sorted)
want := func(prefix, startAfter string, maxKeys int) (pages [][]string) {
var page []string
for _, k := range sorted {
if !strings.HasPrefix(k, prefix) || k <= startAfter {
continue
}
if len(page) == maxKeys {
pages, page = append(pages, page), nil
}
page = append(page, k)
}
return append(pages, page)
}
listV2 := func(t *testing.T, client *s3.Client, prefix, startAfter string, maxKeys int32) (pages [][]string) {
t.Helper()
in := &s3.ListObjectsV2Input{Bucket: b, Prefix: aws.String(prefix), StartAfter: aws.String(startAfter), MaxKeys: aws.Int32(maxKeys)}
for {
require.Less(t, len(pages), 500, "listing did not terminate")
out, err := client.ListObjectsV2(ctx, in)
require.NoError(t, err)
var page []string
for _, o := range out.Contents {
page = append(page, aws.ToString(o.Key))
}
pages = append(pages, page)
if !aws.ToBool(out.IsTruncated) {
return pages
}
in.ContinuationToken = out.NextContinuationToken
}
}
listV1 := func(t *testing.T, client *s3.Client, prefix, marker string, maxKeys int32) (keys []string, truncated bool) {
t.Helper()
out, err := client.ListObjects(ctx, &s3.ListObjectsInput{Bucket: b, Prefix: aws.String(prefix), Marker: aws.String(marker), MaxKeys: aws.Int32(maxKeys)})
require.NoError(t, err)
for _, o := range out.Contents {
keys = append(keys, aws.ToString(o.Key))
}
return keys, aws.ToBool(out.IsTruncated)
}
all := listV2(t, fast, "", "", 1000)
require.Len(t, all, 1)
require.Len(t, all[0], len(keys), "every key once, no upload parts: %v", all[0])
for _, prefix := range []string{"", "a", "a/", "deep/", "deep/acct-01", "m", "m/", "p", "p/", "日", "sp ace/%_", "up/", "zz"} {
for _, maxKeys := range []int32{1, 7, 1000} {
require.Equal(t, want(prefix, "", int(maxKeys)), listV2(t, fast, prefix, "", maxKeys), "prefix %q max %d", prefix, maxKeys)
}
}
for _, marker := range []string{"a", "a+", "a+b", "a/", "a/y", "m", "m+", "m/", "mk", "p", "p/", "deep/acct-010", "日本"} {
for _, prefix := range []string{"", "m", "deep/"} {
wantPages := want(prefix, marker, 3)
require.Equal(t, wantPages, listV2(t, fast, prefix, marker, 3), "prefix %q start-after %q", prefix, marker)
gotKeys, gotTruncated := listV1(t, fast, prefix, marker, 3)
require.Equal(t, wantPages[0], gotKeys, "prefix %q marker %q", prefix, marker)
require.Equal(t, len(wantPages) > 1, gotTruncated, "prefix %q marker %q", prefix, marker)
}
}
t.Run("a page reads the bucket table a few times, not once per directory", func(t *testing.T) {
// A backend reports its table statistics when idle, at least every 10s.
scans := func() int {
time.Sleep(11 * time.Second)
_, err := c.db.Exec(`SELECT pg_stat_clear_snapshot()`)
require.NoError(t, err)
return c.count(t, `SELECT coalesce(idx_scan, 0) + coalesce(seq_scan, 0) FROM pg_stat_user_tables WHERE schemaname = current_schema() AND relname = $1`, bucket)
}
before := scans()
require.Len(t, listV2(t, fast, "deep/", "", 1000)[0], 60)
after := scans()
t.Logf("60 keys in 300 directories under deep/: %d scans", after-before)
require.LessOrEqual(t, after-before, 5)
})
}
+198
View File
@@ -0,0 +1,198 @@
package postgres_flat
import (
"bytes"
"context"
"io"
"sort"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
func TestS3(t *testing.T) {
c := startCluster(t)
client := c.s3Client()
ctx := context.Background()
bucket := "pgflat-s3"
put := func(t *testing.T, bkt, key, body string) {
t.Helper()
_, err := client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bkt), Key: aws.String(key), Body: strings.NewReader(body)})
require.NoError(t, err, "put %s", key)
}
get := func(t *testing.T, bkt, key string) string {
t.Helper()
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bkt), Key: aws.String(key)})
require.NoError(t, err, "get %s", key)
defer out.Body.Close()
data, err := io.ReadAll(out.Body)
require.NoError(t, err)
return string(data)
}
listAll := func(t *testing.T, in s3.ListObjectsV2Input) (keys, prefixes []string) {
t.Helper()
in.Bucket = aws.String(bucket)
p := s3.NewListObjectsV2Paginator(client, &in)
for p.HasMorePages() {
page, err := p.NextPage(ctx)
require.NoError(t, err)
for _, o := range page.Contents {
keys = append(keys, aws.ToString(o.Key))
}
for _, cp := range page.CommonPrefixes {
prefixes = append(prefixes, aws.ToString(cp.Prefix))
}
}
return
}
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)})
require.NoError(t, err)
eventually(t, "the bucket has a table", func() bool { return c.tableExists(t, bucket) })
deep := strings.Repeat(strings.Repeat("k", 200)+"/", 5) + "deep.txt"
keys := []string{
"top.txt",
"a/x.txt",
"a/b/c.txt",
"a/b/d.txt",
"a+b=c.txt",
"dir with space/f %_!.txt",
"日本/語.txt",
deep,
}
sorted := append([]string(nil), keys...)
sort.Strings(sorted)
for _, k := range keys {
put(t, bucket, k, "body of "+k)
}
vb := "pgflat-versioned"
_, err = client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(vb)})
require.NoError(t, err)
_, err = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: aws.String(vb),
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}})
require.NoError(t, err)
t.Run("objects are rows keyed by their key", func(t *testing.T) {
for _, k := range keys {
require.Equal(t, "body of "+k, get(t, bucket, k))
}
rows := c.paths(t, bucket, "/")
for _, k := range keys {
require.Contains(t, rows, "/"+k)
}
require.Contains(t, rows, "/a/b", "parent directories are rows too")
require.Empty(t, c.paths(t, "filemeta", "/buckets/"+bucket+"/"), "bucket entries stay out of the default table")
})
t.Run("list", func(t *testing.T) {
got, _ := listAll(t, s3.ListObjectsV2Input{})
require.Equal(t, sorted, got, "recursive listing in key order")
got, _ = listAll(t, s3.ListObjectsV2Input{MaxKeys: aws.Int32(2)})
require.Equal(t, sorted, got, "recursive listing in pages of two")
require.Equal(t, []string{"a", "a+b=c.txt", "dir with space", deep[:200], "top.txt", "日本"}, c.filerList(t, "/buckets/"+bucket, 2))
got, prefixes := listAll(t, s3.ListObjectsV2Input{Delimiter: aws.String("/")})
require.Equal(t, []string{"a+b=c.txt", "top.txt"}, got)
require.Equal(t, []string{"a/", "dir with space/", deep[:201], "日本/"}, prefixes)
got, prefixes = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/"), Delimiter: aws.String("/"), MaxKeys: aws.Int32(1)})
require.Equal(t, []string{"a/x.txt"}, got)
require.Equal(t, []string{"a/b/"}, prefixes)
got, _ = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/b/")})
require.Equal(t, []string{"a/b/c.txt", "a/b/d.txt"}, got)
got, _ = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/b/d")})
require.Equal(t, []string{"a/b/d.txt"}, got)
got, _ = listAll(t, s3.ListObjectsV2Input{StartAfter: aws.String("a/b/c.txt")})
require.Equal(t, sorted[sort.SearchStrings(sorted, "a/b/c.txt")+1:], got)
got, _ = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("dir with space/f %_")})
require.Equal(t, []string{"dir with space/f %_!.txt"}, got)
})
t.Run("overwrite, copy and delete", func(t *testing.T) {
put(t, bucket, "a/x.txt", "replaced")
require.Equal(t, "replaced", get(t, bucket, "a/x.txt"))
require.Equal(t, 1, c.count(t, `SELECT count(*) FROM "`+bucket+`" WHERE path = '/a/x.txt'`))
_, err := client.CopyObject(ctx, &s3.CopyObjectInput{Bucket: aws.String(bucket), Key: aws.String("copied/x.txt"), CopySource: aws.String(bucket + "/a/x.txt")})
require.NoError(t, err)
require.Equal(t, "replaced", get(t, bucket, "copied/x.txt"))
require.Contains(t, c.paths(t, bucket, "/copied/"), "/copied/x.txt")
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String("copied/x.txt")})
require.NoError(t, err)
require.NotContains(t, c.paths(t, bucket, "/copied/"), "/copied/x.txt")
_, err = client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String("copied/x.txt")})
require.Error(t, err)
_, err = client.DeleteObjects(ctx, &s3.DeleteObjectsInput{Bucket: aws.String(bucket), Delete: &types.Delete{Objects: []types.ObjectIdentifier{
{Key: aws.String("a/b/c.txt")}, {Key: aws.String("a/b/d.txt")},
}}})
require.NoError(t, err)
require.Empty(t, c.paths(t, bucket, "/a/b/"))
got, _ := listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/")})
require.Equal(t, []string{"a/x.txt"}, got)
})
t.Run("multipart upload", func(t *testing.T) {
key := "multi/part.bin"
created, err := client.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
require.NoError(t, err)
require.NotEmpty(t, c.paths(t, bucket, "/.uploads/"), "the upload lives in the bucket table")
parts := [][]byte{bytes.Repeat([]byte{'1'}, 5<<20), []byte("tail")}
var completed []types.CompletedPart
for i, p := range parts {
out, err := client.UploadPart(ctx, &s3.UploadPartInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
PartNumber: aws.Int32(int32(i + 1)), Body: bytes.NewReader(p)})
require.NoError(t, err)
completed = append(completed, types.CompletedPart{ETag: out.ETag, PartNumber: aws.Int32(int32(i + 1))})
}
_, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
MultipartUpload: &types.CompletedMultipartUpload{Parts: completed}})
require.NoError(t, err)
require.Equal(t, string(parts[0])+string(parts[1]), get(t, bucket, key))
require.Contains(t, c.paths(t, bucket, "/multi/"), "/multi/part.bin")
eventually(t, "the upload folder is gone", func() bool {
return len(c.paths(t, bucket, "/.uploads/"+aws.ToString(created.UploadId))) == 0
})
})
t.Run("versioning", func(t *testing.T) {
first, err := client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(vb), Key: aws.String("doc/v.txt"), Body: strings.NewReader("one")})
require.NoError(t, err)
put(t, vb, "doc/v.txt", "two")
require.Equal(t, "two", get(t, vb, "doc/v.txt"))
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(vb), Key: aws.String("doc/v.txt"), VersionId: first.VersionId})
require.NoError(t, err)
data, err := io.ReadAll(out.Body)
out.Body.Close()
require.NoError(t, err)
require.Equal(t, "one", string(data))
versions, err := client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(vb)})
require.NoError(t, err)
require.Len(t, versions.Versions, 2)
require.True(t, c.tableExists(t, vb))
})
t.Run("delete bucket drops its table", func(t *testing.T) {
keys, _ := listAll(t, s3.ListObjectsV2Input{})
for _, k := range keys {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(k)})
require.NoError(t, err)
}
_, err := client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)})
require.NoError(t, err)
eventually(t, "the bucket table is dropped", func() bool { return !c.tableExists(t, bucket) })
require.True(t, c.tableExists(t, vb), "other buckets keep their tables")
})
}
+200
View File
@@ -0,0 +1,200 @@
package postgres_flat
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
func TestS3Versioning(t *testing.T) {
c := startCluster(t)
client := c.s3Client()
ctx := context.Background()
bucket := "pgflat-versioned"
b := aws.String(bucket)
put := func(t *testing.T, key, body string) string {
t.Helper()
out, err := client.PutObject(ctx, &s3.PutObjectInput{Bucket: b, Key: aws.String(key), Body: strings.NewReader(body)})
require.NoError(t, err, "put %s", key)
return aws.ToString(out.VersionId)
}
get := func(t *testing.T, key, versionId string) (string, error) {
t.Helper()
in := &s3.GetObjectInput{Bucket: b, Key: aws.String(key)}
if versionId != "" {
in.VersionId = aws.String(versionId)
}
out, err := client.GetObject(ctx, in)
if err != nil {
return "", err
}
defer out.Body.Close()
data, err := io.ReadAll(out.Body)
require.NoError(t, err)
return string(data), nil
}
mustGet := func(t *testing.T, key, versionId string) string {
t.Helper()
body, err := get(t, key, versionId)
require.NoError(t, err, "get %s %s", key, versionId)
return body
}
type version struct {
key, id string
latest bool
marker bool
}
listVersions := func(t *testing.T, prefix string, maxKeys int32) []version {
t.Helper()
in := &s3.ListObjectVersionsInput{Bucket: b, Prefix: aws.String(prefix)}
if maxKeys > 0 {
in.MaxKeys = aws.Int32(maxKeys)
}
var all []version
for {
out, err := client.ListObjectVersions(ctx, in)
require.NoError(t, err)
for _, v := range out.Versions {
all = append(all, version{aws.ToString(v.Key), aws.ToString(v.VersionId), aws.ToBool(v.IsLatest), false})
}
for _, m := range out.DeleteMarkers {
all = append(all, version{aws.ToString(m.Key), aws.ToString(m.VersionId), aws.ToBool(m.IsLatest), true})
}
if !aws.ToBool(out.IsTruncated) {
return all
}
in.KeyMarker, in.VersionIdMarker = out.NextKeyMarker, out.NextVersionIdMarker
}
}
listKeys := func(t *testing.T, delimiter string) (keys, prefixes []string) {
t.Helper()
in := &s3.ListObjectsV2Input{Bucket: b}
if delimiter != "" {
in.Delimiter = aws.String(delimiter)
}
out, err := client.ListObjectsV2(ctx, in)
require.NoError(t, err)
for _, o := range out.Contents {
keys = append(keys, aws.ToString(o.Key))
}
for _, p := range out.CommonPrefixes {
prefixes = append(prefixes, aws.ToString(p.Prefix))
}
return
}
notFound := func(t *testing.T, key, versionId string) {
t.Helper()
_, err := get(t, key, versionId)
var re *awshttp.ResponseError
require.ErrorAs(t, err, &re, "get %s %s", key, versionId)
require.Equal(t, http.StatusNotFound, re.HTTPStatusCode(), "get %s %s", key, versionId)
}
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: b})
require.NoError(t, err)
eventually(t, "the bucket has a table", func() bool { return c.tableExists(t, bucket) })
_, err = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: b,
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}})
require.NoError(t, err)
var docIds, topIds []string
for i := 1; i <= 3; i++ {
docIds = append(docIds, put(t, "doc/v.txt", "doc "+string(rune('0'+i))))
}
for i := 1; i <= 2; i++ {
topIds = append(topIds, put(t, "top.txt", "top "+string(rune('0'+i))))
}
t.Run("each version is a row under the key's .versions folder", func(t *testing.T) {
rows := c.paths(t, bucket, "/")
for _, id := range docIds {
require.NotEmpty(t, id)
require.Contains(t, rows, "/doc/v.txt.versions/v_"+id)
}
for _, id := range topIds {
require.Contains(t, rows, "/top.txt.versions/v_"+id)
}
require.Equal(t, "doc 3", mustGet(t, "doc/v.txt", ""))
for i, id := range docIds {
require.Equal(t, "doc "+string(rune('1'+i)), mustGet(t, "doc/v.txt", id))
}
require.Empty(t, c.paths(t, "filemeta", "/buckets/"+bucket+"/"), "versions stay out of the default table")
})
t.Run("listings", func(t *testing.T) {
all := listVersions(t, "", 0)
require.Equal(t, []version{
{"doc/v.txt", docIds[2], true, false}, {"doc/v.txt", docIds[1], false, false}, {"doc/v.txt", docIds[0], false, false},
{"top.txt", topIds[1], true, false}, {"top.txt", topIds[0], false, false},
}, all)
require.Equal(t, all, listVersions(t, "", 1), "one version a page")
require.Equal(t, all[:3], listVersions(t, "doc/", 0))
keys, _ := listKeys(t, "")
require.Equal(t, []string{"doc/v.txt", "top.txt"}, keys, ".versions folders are not keys")
keys, prefixes := listKeys(t, "/")
require.Equal(t, []string{"top.txt"}, keys)
require.Equal(t, []string{"doc/"}, prefixes)
})
t.Run("a delete marker hides the key until it is deleted", func(t *testing.T) {
out, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String("doc/v.txt")})
require.NoError(t, err)
require.True(t, aws.ToBool(out.DeleteMarker))
markerId := aws.ToString(out.VersionId)
require.Contains(t, c.paths(t, bucket, "/doc/v.txt.versions/"), "/doc/v.txt.versions/v_"+markerId)
notFound(t, "doc/v.txt", "")
require.Equal(t, "doc 2", mustGet(t, "doc/v.txt", docIds[1]))
keys, _ := listKeys(t, "")
require.Equal(t, []string{"top.txt"}, keys)
require.Equal(t, version{"doc/v.txt", markerId, true, true}, listVersions(t, "doc/", 0)[3])
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String("doc/v.txt"), VersionId: aws.String(markerId)})
require.NoError(t, err)
require.NotContains(t, c.paths(t, bucket, "/doc/v.txt.versions/"), "/doc/v.txt.versions/v_"+markerId)
require.Equal(t, "doc 3", mustGet(t, "doc/v.txt", ""))
})
t.Run("deleting the latest version promotes the one before", func(t *testing.T) {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String("doc/v.txt"), VersionId: aws.String(docIds[2])})
require.NoError(t, err)
require.NotContains(t, c.paths(t, bucket, "/doc/v.txt.versions/"), "/doc/v.txt.versions/v_"+docIds[2])
notFound(t, "doc/v.txt", docIds[2])
require.Equal(t, "doc 2", mustGet(t, "doc/v.txt", ""))
require.Equal(t, []version{{"doc/v.txt", docIds[1], true, false}, {"doc/v.txt", docIds[0], false, false}}, listVersions(t, "doc/", 0))
})
t.Run("suspended versioning writes the null version", func(t *testing.T) {
_, err := client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: b,
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusSuspended}})
require.NoError(t, err)
put(t, "top.txt", "top null")
put(t, "top.txt", "top null again")
require.Equal(t, "top null again", mustGet(t, "top.txt", ""))
require.Equal(t, "top null again", mustGet(t, "top.txt", "null"))
require.Equal(t, "top 1", mustGet(t, "top.txt", topIds[0]))
require.ElementsMatch(t, []version{{"top.txt", "null", true, false}, {"top.txt", topIds[1], false, false}, {"top.txt", topIds[0], false, false}},
listVersions(t, "top", 0))
})
t.Run("deleting every version and the bucket drops its table", func(t *testing.T) {
for _, v := range listVersions(t, "", 0) {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String(v.key), VersionId: aws.String(v.id)})
require.NoError(t, err, "delete %s %s", v.key, v.id)
}
require.Empty(t, listVersions(t, "", 0))
_, err := client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: b})
require.NoError(t, err)
eventually(t, "the bucket table is dropped", func() bool { return !c.tableExists(t, bucket) })
})
}
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Checks what strict FIPS mode refuses, in the Go components
# (GODEBUG=fips140=only) and the Rust volume server (WEED_FIPS_MODE=strict).
# Go's crypto/hmac refuses keys shorter than 112 bits (14 bytes) in that mode,
# so a component must refuse such a key at startup instead of failing (or
# panicking) on the first request that needs it.
#
# master, filer, volume (Go), volume (Rust): started alone with a 10-byte
# jwt.signing.key; each must exit non-zero within 20 s naming the mode.
# s3: a fips140=only cluster with valid JWT keys and an identity whose
# 8-character secret makes a SigV4 signing key under 14 bytes; a request
# signed with it must get an S3 error answer, not a dropped connection.
#
# Prints one line per component and exits non-zero if any check fails.
# WEED, WEED_VOLUME, WORK_DIR binaries and scratch dir
set -uo pipefail
WEED=${WEED:-weed}
WEED_VOLUME=${WEED_VOLUME:-weed-volume}
WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-negative-config}
export GODEBUG=fips140=only WEED_FIPS_MODE=strict
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR/short" "$WORK_DIR/valid"
printf '[jwt.signing]\nkey = "0123456789"\n' > "$WORK_DIR/short/security.toml"
printf '[jwt.signing]\nkey = "%s"\n' "$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')" \
> "$WORK_DIR/valid/security.toml"
failures=0
# expect_refusal starts a component with the short key and reports whether it
# exited non-zero within 20 s naming the mode in its log: fips140=only for Go,
# fips.mode strict for Rust.
expect_refusal() {
local name=$1; shift
local log="$WORK_DIR/$name.log"
(cd "$WORK_DIR/short" && exec "$@") > "$log" 2>&1 &
local pid=$! status=
for _ in $(seq 1 20); do
if ! kill -0 "$pid" 2>/dev/null; then wait "$pid"; status=$?; break; fi
sleep 1
done
if [ -z "$status" ]; then
kill -KILL "$pid" 2>/dev/null; wait "$pid" 2>/dev/null
echo "FAIL $name: still running after 20 s with a 10-byte jwt.signing.key"
failures=$((failures + 1))
elif [ "$status" -ne 0 ] && grep -q -E 'fips140=only|fips\.mode strict' "$log"; then
echo "ok $name: refused at startup (exit $status)"
else
echo "FAIL $name: exited $status without naming the FIPS mode; log tail:"
tail -5 "$log" | sed 's/^/ /'
failures=$((failures + 1))
fi
}
mkdir -p "$WORK_DIR/m" "$WORK_DIR/f" "$WORK_DIR/vg" "$WORK_DIR/vr"
expect_refusal master "$WEED" master -port=19333 -mdir="$WORK_DIR/m" -peers=none
expect_refusal filer "$WEED" filer -master=127.0.0.1:19333 -port=18888 -defaultStoreDir="$WORK_DIR/f"
expect_refusal volume-go "$WEED" volume -master=127.0.0.1:19333 -port=18080 -dir="$WORK_DIR/vg"
expect_refusal volume-rust "$WEED_VOLUME" --master 127.0.0.1:19333 --port 18081 --port.grpc 28081 \
--dir "$WORK_DIR/vr" --securityFile "$WORK_DIR/short/security.toml"
cat > "$WORK_DIR/valid/s3.json" <<'EOF'
{"identities":[{"name":"short","credentials":[{"accessKey":"shortsecretkey01","secretKey":"abcd1234"}],"actions":["Admin"]}]}
EOF
mkdir -p "$WORK_DIR/s"
(cd "$WORK_DIR/valid" && exec "$WEED" server -filer -s3 -ip=127.0.0.1 -dir="$WORK_DIR/s" \
-master.port=29333 -volume.port=28080 -filer.port=28888 -s3.port=28000 -master.peers=none \
-s3.config="$WORK_DIR/valid/s3.json") > "$WORK_DIR/s3.log" 2>&1 &
server_pid=$!
for _ in $(seq 1 60); do curl -s -o /dev/null http://127.0.0.1:28000/ && break; sleep 1; done
code=$(curl -s -o "$WORK_DIR/s3.body" -w '%{http_code}' --aws-sigv4 "aws:amz:us-east-1:s3" \
--user shortsecretkey01:abcd1234 http://127.0.0.1:28000/)
curl_status=$?
if [ "$curl_status" -eq 0 ] && [ "${code:0:1}" = 4 ]; then
echo "ok s3: an 8-character secret gets HTTP $code ($(grep -o '<Code>[^<]*' "$WORK_DIR/s3.body" | cut -c7-))"
else
echo "FAIL s3: an 8-character secret got curl exit $curl_status, HTTP $code (a dropped connection is a panic in the request)"
failures=$((failures + 1))
fi
kill -TERM "$server_pid" 2>/dev/null; wait "$server_pid" 2>/dev/null
exit $((failures > 0))
+4 -2
View File
@@ -4,7 +4,9 @@
# $WORK_DIR/pids, so `xargs kill < "$WORK_DIR/pids"` stops the cell.
#
# DIGEST_MODE md5 (GODEBUG=fips140=off), sha256 (fips140=on with the
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only)
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only
# and WEED_FIPS_MODE=strict, which the Rust volume server
# takes its mode from and the Go processes check)
# VOLUME_SERVER go (weed server's own volume server) or rust (weed-volume)
# WEED, WEED_VOLUME, WORK_DIR, S3_CONFIG binaries, scratch dir, identities
#
@@ -22,7 +24,7 @@ WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-digest-matrix}
case "$DIGEST_MODE" in
md5) export GODEBUG=fips140=off; digest_flag=() ;;
sha256) export GODEBUG=fips140=on; digest_flag=(-filer.digest=sha256) ;;
fips140only) export GODEBUG=fips140=only; digest_flag=() ;;
fips140only) export GODEBUG=fips140=only WEED_FIPS_MODE=strict; digest_flag=() ;;
*) echo "unknown DIGEST_MODE $DIGEST_MODE" >&2; exit 2 ;;
esac
case "$VOLUME_SERVER" in
@@ -0,0 +1,192 @@
package example
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"testing"
"time"
v2aws "github.com/aws/aws-sdk-go-v2/aws"
v2credentials "github.com/aws/aws-sdk-go-v2/credentials"
v2s3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/smithy-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func s3ErrorCode(err error) string {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
return apiErr.ErrorCode()
}
return ""
}
func TestS3BucketDefaultStorageClass(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()
ctx := context.Background()
client := newS3V2Client(cluster)
bucket := createTestBucket(t, cluster, "test-default-class-")
otherBucket := createTestBucket(t, cluster, "test-default-class-src-")
getDefault := func(t *testing.T) types.BucketDefaultStorageClass {
t.Helper()
out, err := client.GetBucketDefaultStorageClass(ctx, &v2s3.GetBucketDefaultStorageClassInput{Bucket: v2aws.String(bucket)})
require.NoError(t, err)
require.NotNil(t, out.DefaultStorageClassConfiguration)
return out.DefaultStorageClassConfiguration.DefaultStorageClass
}
putDefault := func(sc types.BucketDefaultStorageClass) error {
_, err := client.PutBucketDefaultStorageClass(ctx, &v2s3.PutBucketDefaultStorageClassInput{
Bucket: v2aws.String(bucket),
DefaultStorageClassConfiguration: &types.DefaultStorageClassConfiguration{DefaultStorageClass: sc},
})
return err
}
put := func(t *testing.T, b, key string, sc types.StorageClass) {
t.Helper()
_, err := client.PutObject(ctx, &v2s3.PutObjectInput{Bucket: v2aws.String(b), Key: v2aws.String(key), Body: strings.NewReader("data"), StorageClass: sc})
require.NoError(t, err)
}
classOf := func(t *testing.T, key string) types.StorageClass {
t.Helper()
out, err := client.HeadObject(ctx, &v2s3.HeadObjectInput{Bucket: v2aws.String(bucket), Key: v2aws.String(key)})
require.NoError(t, err)
return out.StorageClass
}
t.Run("unset default reads STANDARD", func(t *testing.T) {
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
})
put(t, bucket, "before.txt", "")
t.Run("unsupported class is rejected", func(t *testing.T) {
err := putDefault("GLACIER")
require.Error(t, err)
assert.Equal(t, "InvalidStorageClass", s3ErrorCode(err))
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
})
require.NoError(t, putDefault(types.BucketDefaultStorageClassIntelligentTiering))
t.Run("default is stored in the bucket entry", func(t *testing.T) {
assert.Equal(t, types.BucketDefaultStorageClassIntelligentTiering, getDefault(t))
resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/buckets/%s?metadata=true", cluster.filerPort, bucket))
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
var entry struct{ Extended map[string][]byte }
require.NoError(t, json.NewDecoder(resp.Body).Decode(&entry))
assert.Equal(t, "INTELLIGENT_TIERING", string(entry.Extended["Seaweed-X-Amz-Default-Storage-Class"]))
})
t.Run("put without a class takes the default", func(t *testing.T) {
put(t, bucket, "plain.txt", "")
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "plain.txt"))
})
t.Run("explicit class wins", func(t *testing.T) {
put(t, bucket, "ia.txt", types.StorageClassStandardIa)
assert.Equal(t, types.StorageClassStandardIa, classOf(t, "ia.txt"))
put(t, bucket, "standard.txt", types.StorageClassStandard)
assert.Equal(t, types.StorageClassStandard, classOf(t, "standard.txt"))
})
t.Run("multipart upload keeps the class from initiation", func(t *testing.T) {
created, err := client.CreateMultipartUpload(ctx, &v2s3.CreateMultipartUploadInput{Bucket: v2aws.String(bucket), Key: v2aws.String("mpu.bin")})
require.NoError(t, err)
require.NoError(t, putDefault(types.BucketDefaultStorageClassStandard))
part, err := client.UploadPart(ctx, &v2s3.UploadPartInput{
Bucket: v2aws.String(bucket), Key: v2aws.String("mpu.bin"), UploadId: created.UploadId,
PartNumber: v2aws.Int32(1), Body: strings.NewReader("only part"),
})
require.NoError(t, err)
_, err = client.CompleteMultipartUpload(ctx, &v2s3.CompleteMultipartUploadInput{
Bucket: v2aws.String(bucket), Key: v2aws.String("mpu.bin"), UploadId: created.UploadId,
MultipartUpload: &types.CompletedMultipartUpload{Parts: []types.CompletedPart{{PartNumber: v2aws.Int32(1), ETag: part.ETag}}},
})
require.NoError(t, err)
require.NoError(t, putDefault(types.BucketDefaultStorageClassIntelligentTiering))
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "mpu.bin"))
})
t.Run("copy takes the destination default unless it names a class", func(t *testing.T) {
put(t, otherBucket, "src.txt", types.StorageClassStandardIa)
source := v2aws.String(otherBucket + "/src.txt")
_, err := client.CopyObject(ctx, &v2s3.CopyObjectInput{Bucket: v2aws.String(bucket), Key: v2aws.String("copied.txt"), CopySource: source})
require.NoError(t, err)
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "copied.txt"))
_, err = client.CopyObject(ctx, &v2s3.CopyObjectInput{Bucket: v2aws.String(bucket), Key: v2aws.String("copied-ia.txt"), CopySource: source, StorageClass: types.StorageClassStandardIa})
require.NoError(t, err)
assert.Equal(t, types.StorageClassStandardIa, classOf(t, "copied-ia.txt"))
})
t.Run("changing the default leaves existing objects alone", func(t *testing.T) {
require.NoError(t, putDefault(types.BucketDefaultStorageClassIntelligentTiering))
put(t, bucket, "tiered.txt", "")
assert.Empty(t, classOf(t, "before.txt"))
require.NoError(t, putDefault(types.BucketDefaultStorageClassStandard))
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "tiered.txt"))
put(t, bucket, "after.txt", "")
assert.Empty(t, classOf(t, "after.txt"))
})
t.Run("each API needs its own grant", func(t *testing.T) {
require.NoError(t, putDefault(types.BucketDefaultStorageClassStandard))
sess, err := session.NewSession(cluster.s3Client.Config.Copy())
require.NoError(t, err)
iamClient := iam.New(sess)
userName := "default-class-user"
_, 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)
userClient := v2s3.New(client.Options(), func(o *v2s3.Options) {
o.Credentials = v2credentials.NewStaticCredentialsProvider(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "")
})
attach := func(name, action string) {
doc := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s","Resource":"arn:aws:s3:::%s"}]}`, action, bucket)
created, err := iamClient.CreatePolicy(&iam.CreatePolicyInput{PolicyName: aws.String(name), PolicyDocument: aws.String(doc)})
require.NoError(t, err)
_, err = iamClient.AttachUserPolicy(&iam.AttachUserPolicyInput{UserName: aws.String(userName), PolicyArn: created.Policy.Arn})
require.NoError(t, err)
}
userPut := func() error {
_, err := userClient.PutBucketDefaultStorageClass(ctx, &v2s3.PutBucketDefaultStorageClassInput{
Bucket: v2aws.String(bucket),
DefaultStorageClassConfiguration: &types.DefaultStorageClassConfiguration{DefaultStorageClass: types.BucketDefaultStorageClassIntelligentTiering},
})
return err
}
attach("default-class-get", "s3:GetBucketDefaultStorageClass")
require.Eventually(t, func() bool {
_, err := userClient.GetBucketDefaultStorageClass(ctx, &v2s3.GetBucketDefaultStorageClassInput{Bucket: v2aws.String(bucket)})
return err == nil
}, 10*time.Second, 200*time.Millisecond)
err = userPut()
require.Error(t, err)
assert.Equal(t, "AccessDenied", s3ErrorCode(err))
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
attach("default-class-put", "s3:PutBucketDefaultStorageClass")
require.Eventually(t, func() bool { return userPut() == nil }, 10*time.Second, 200*time.Millisecond)
assert.Equal(t, types.BucketDefaultStorageClassIntelligentTiering, getDefault(t))
})
}
@@ -26,8 +26,3 @@ TestIntegration/FsMkdir/FsEncoding/trailing_VT # name with a vertical tab liste
# BucketAlreadyOwnedByYou, which rclone expects only with use_already_exists set;
# the SeaweedFS provider defaults it to false and rclone.conf keeps that (see there).
TestIntegration/FsMkdir/FsPutFiles/Internal/Versions/Mkdir # rclone provider quirk use_already_exists=false
# The test itself, not its subtests: FsMkdir ends by removing the test bucket,
# and DeleteBucket answers 409 BucketNotEmpty although no keys are left -
# leftover empty directories or FsEncoding objects that were not deleted.
TestIntegration/FsMkdir # DeleteBucket returns BucketNotEmpty at the end of the run
+49
View File
@@ -40,6 +40,55 @@ func TestVacuumVolumeCheckSuccessAndMissingVolume(t *testing.T) {
}
}
// can_delete_mark reports a readonlyCanDelete mark, the read-only cause a
// sweep compacts through; a plain read-only mark refuses deletes and is not one.
func TestVacuumVolumeCheckReportsCanDeleteMark(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(32)
framework.AllocateVolume(t, grpcClient, volumeID, "")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
check := func(stage string, want bool) {
t.Helper()
resp, err := grpcClient.VacuumVolumeCheck(ctx, &volume_server_pb.VacuumVolumeCheckRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("%s: VacuumVolumeCheck failed: %v", stage, err)
}
if resp.GetCanDeleteMark() != want {
t.Fatalf("%s: can_delete_mark = %v, want %v", stage, resp.GetCanDeleteMark(), want)
}
}
check("writable", false)
_, err := grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: volumeID, CanDelete: true})
if err != nil {
t.Fatalf("VolumeMarkReadonly canDelete failed: %v", err)
}
check("readonlyCanDelete", true)
_, err = grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeMarkReadonly failed: %v", err)
}
check("readonly", false)
_, err = grpcClient.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{VolumeId: volumeID})
if err != nil {
t.Fatalf("VolumeMarkWritable failed: %v", err)
}
check("writable again", false)
}
func TestVacuumMaintenanceModeRejections(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
@@ -79,6 +79,53 @@ func TestWriteMalformedMultipartAndMD5Mismatch(t *testing.T) {
}
}
// TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS checks that in strict FIPS
// mode (GODEBUG=fips140=only for Go, fips.mode strict for Rust), where no MD5
// may be computed, an upload whose Content-MD5 does not match its body is
// stored with the client's value instead of refused. The master and volume
// server inherit the environment set here; this test process keeps the mode it
// started with.
func TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
t.Setenv("GODEBUG", "fips140=only")
t.Setenv("WEED_FIPS_MODE", "strict")
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(97)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
url := clusterHarness.VolumeAdminURL() + "/" + framework.NewFileID(volumeID, 772101, 0x1A2B3C4D)
payload := []byte("content-md5-unchecked-body")
const wrongMD5 = "AAAAAAAAAAAAAAAAAAAAAA=="
uploadReq := newUploadRequest(t, url, payload)
uploadReq.Header.Set("Content-MD5", wrongMD5)
uploadResp := framework.DoRequest(t, client, uploadReq)
uploadBody := framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("content-md5 mismatch write under strict FIPS mode expected 201, got %d: %s", uploadResp.StatusCode, uploadBody)
}
if !strings.Contains(string(uploadBody), `"contentMd5":"`+wrongMD5+`"`) {
t.Fatalf("upload result should carry the client's Content-MD5 %s, got %s", wrongMD5, uploadBody)
}
readReq, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
t.Fatalf("create read request: %v", err)
}
readResp := framework.DoRequest(t, client, readReq)
readBody := framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK || !bytes.Equal(readBody, payload) {
t.Fatalf("read back expected 200 with the payload, got %d: %q", readResp.StatusCode, readBody)
}
}
func TestWriteReadOnlyReportsConflictAndSafeRefusal(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
+2 -1
View File
@@ -86,8 +86,9 @@ var jobTypeLaneMap = map[string]SchedulerLane{
"erasure_coding": LaneDefault,
"admin_script": LaneDefault,
// Iceberg table maintenance
// Iceberg table maintenance and MQ topic table appends
"iceberg_maintenance": LaneIceberg,
"mq_topic_table": LaneIceberg,
// S3 lifecycle management
"s3_lifecycle": LaneLifecycle,
+1
View File
@@ -63,6 +63,7 @@ func TestKnownJobTypesInMap(t *testing.T) {
"erasure_coding": LaneDefault,
"admin_script": LaneDefault,
"iceberg_maintenance": LaneIceberg,
"mq_topic_table": LaneIceberg,
"s3_lifecycle": LaneLifecycle,
}
for jobType, wantLane := range expected {
+58 -9
View File
@@ -36,17 +36,47 @@ import (
)
var (
f FilerOptions
filerStartS3 *bool
filerS3Options S3Options
filerStartWebDav *bool
filerWebDavOptions WebDavOption
filerStartIam *bool
filerIamOptions IamOptions
filerStartSftp *bool
filerSftpOptions SftpOptions
f FilerOptions
filerStartS3 *bool
filerS3Options S3Options
filerStartS3MqBroker *bool
filerS3MqBrokerOptions MessageQueueBrokerOptions
filerStartWebDav *bool
filerWebDavOptions WebDavOption
filerStartIam *bool
filerIamOptions IamOptions
filerStartSftp *bool
filerSftpOptions SftpOptions
)
// filerRunsMqBrokerBesideS3 reports whether weed filer starts a broker with
// its S3 gateway; the filer has no other broker to collide with.
func filerRunsMqBrokerBesideS3(brokerFlagPassed bool) bool {
return *filerStartS3 && wantsMqBrokerBesideS3("s3.mq.broker", *filerStartS3MqBroker, brokerFlagPassed)
}
// filerPortsBesideS3 lists the ports of the filer and the other servers weed
// filer starts with its gateway, derived gRPC ports included.
func filerPortsBesideS3() []int {
ports := append([]int{*f.metricsHttpPort}, withGrpc(f.port, f.portGrpc)...)
if *f.debug {
ports = append(ports, *f.debugPort)
}
if *f.publicPort != 0 {
ports = append(ports, *f.publicPort)
}
if *filerStartWebDav {
ports = append(ports, *filerWebDavOptions.port)
}
if *filerStartIam {
ports = append(ports, *filerIamOptions.port)
}
if *filerStartSftp {
ports = append(ports, *filerSftpOptions.port)
}
return ports
}
// allowUntrustedRemoteEndpointsUsage documents the flag shared by the filer and
// S3 gateway, whose remote-mount read paths dial the mounted endpoint directly.
const allowUntrustedRemoteEndpointsUsage = "if true, a read of a remote-only entry accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints."
@@ -225,6 +255,8 @@ func init() {
filerS3Options.unreachableOwnerTTL = cmdFiler.Flag.Duration("s3.unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage)
filerS3Options.volumeLookupTimeout = cmdFiler.Flag.Duration("s3.volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage)
filerS3Options.preStopSeconds = cmdFiler.Flag.Int("s3.preStopSeconds", 0, s3PreStopSecondsUsage)
filerStartS3MqBroker = cmdFiler.Flag.Bool("s3.mq.broker", false, mqBrokerBesideS3Usage)
filerS3MqBrokerOptions.port = cmdFiler.Flag.Int("s3.mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
// start webdav on filer
filerStartWebDav = cmdFiler.Flag.Bool("webdav", false, "whether to start webdav gateway")
@@ -282,6 +314,10 @@ func filerLongDesc() string {
The example filer.toml configuration file can be generated by "weed scaffold -config=filer"
With -s3, and grpc.msg_broker cert and key in security.toml, a message queue broker
runs beside the S3 gateway on -s3.mq.broker.port; use -s3.mq.broker=false to leave it
out, or -s3.mq.broker=true to run it without TLS.
Supported Filer Stores:
`
@@ -346,8 +382,21 @@ func runFiler(cmd *Command, args []string) bool {
if *filerS3Options.metricsHttpIp == "" {
*filerS3Options.metricsHttpIp = *filerS3Options.bindIp
}
filerS3Options.mqBroker = nil
if filerRunsMqBrokerBesideS3(isFlagExplicitlySet(cmdFiler, "s3.mq.broker")) {
filerS3Options.mqBroker = &filerS3MqBrokerOptions
if err := filerS3Options.checkMqBrokerPort("s3.mq.broker.port", isFlagExplicitlySet(cmdFiler, "s3.mq.broker.port"), filerPortsBesideS3()...); err != nil {
glog.Fatalf("%v", err)
}
}
go func(delay time.Duration) {
time.Sleep(delay * time.Second)
// By now startFiler has filled an empty -ip.bind, which the gateway
// and its broker both bind.
if b := filerS3Options.mqBroker; b != nil {
filerS3Options.brokerBeside(b)
b.dataCenter, b.rack = f.dataCenter, f.rack
}
filerS3Options.startS3Server()
}(startDelay)
startDelay++
+74
View File
@@ -0,0 +1,74 @@
package command
import "testing"
func TestFilerS3MqBrokerFlagDefaults(t *testing.T) {
for name, want := range map[string]string{
"s3": "false",
"s3.mq.broker": "false",
"s3.mq.broker.port": "17777",
} {
flag := cmdFiler.Flag.Lookup(name)
if flag == nil {
t.Fatalf("weed filer does not expose -%s", name)
}
if flag.DefValue != want {
t.Errorf("-%s default = %q, want %q", name, flag.DefValue, want)
}
}
}
func TestFilerRunsMqBrokerOnlyBesideS3(t *testing.T) {
oldS3, oldBroker := *filerStartS3, *filerStartS3MqBroker
defer func() { *filerStartS3, *filerStartS3MqBroker = oldS3, oldBroker }()
for _, tc := range mqBrokerDefaultCases {
t.Run("-s3 "+tc.name, func(t *testing.T) {
withMqBrokerTLS(t, tc.tls)
*filerStartS3, *filerStartS3MqBroker = true, tc.value
if got := filerRunsMqBrokerBesideS3(tc.passed); got != tc.want {
t.Errorf("runs broker %v, want %v", got, tc.want)
}
})
}
t.Run("no -s3", func(t *testing.T) {
withMqBrokerTLS(t, true)
*filerStartS3, *filerStartS3MqBroker = false, true
if filerRunsMqBrokerBesideS3(true) {
t.Error("broker started without the S3 gateway")
}
})
}
// weed filer -s3 -webdav -webdav.port=17777, weed filer -port=7777 -s3
// whose filer gRPC port is 17777, and weed filer -s3 -debug -debug.port=17777.
func TestFilerDefaultBrokerYieldsToFilerProcessPorts(t *testing.T) {
port, portGrpc, webdav, webdavPort := *f.port, *f.portGrpc, *filerStartWebDav, *filerWebDavOptions.port
debug, debugPort := *f.debug, *f.debugPort
t.Cleanup(func() {
*f.port, *f.portGrpc, *filerStartWebDav, *filerWebDavOptions.port = port, portGrpc, webdav, webdavPort
*f.debug, *f.debugPort = debug, debugPort
})
for _, tc := range []struct {
name string
filerPort, webdavPort int
webdav bool
debugPort int
}{
{"-webdav.port on the broker port", 8888, 17777, true, 0},
{"-port whose derived gRPC port is the broker's", 7777, 7333, false, 0},
{"-debug.port on the broker port", 8888, 7333, false, 17777},
} {
t.Run(tc.name, func(t *testing.T) {
*f.port, *f.portGrpc, *filerStartWebDav, *filerWebDavOptions.port = tc.filerPort, 0, tc.webdav, tc.webdavPort
*f.debug, *f.debugPort = tc.debugPort != 0, tc.debugPort
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("s3.mq.broker.port", false, filerPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on a filer process port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("s3.mq.broker.port", true, filerPortsBesideS3()...); err == nil {
t.Fatal("explicit -s3.mq.broker.port on a filer process port was accepted")
}
})
}
}
+67 -5
View File
@@ -300,6 +300,10 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -437,6 +441,10 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -474,6 +482,11 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
return nil
}
}
// deleteOldFile removes the renamed-from object. When the entry
// is written to a new key too, that runs first: the old key can
// hold the only remote copy, and a rename whose local data turns
// out to be gone (errSourceGone) leaves it where it is.
var deleteOldFile func() error
if oldOk {
client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
if err != nil {
@@ -486,9 +499,15 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
glog.V(0).Infof("keep %s: the renamed entry's only content", remote_storage.FormatLocation(oldDest))
return nil
}
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
if err := deleteRemoteFileIfUnchanged(client, oldDest, message.OldEntry.GetRemoteEntry()); err != nil {
return err
deleteOldFile = func() error {
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
return deleteRemoteFileIfUnchanged(client, oldDest, message.OldEntry.GetRemoteEntry())
}
if !newOk || message.NewEntry.IsDirectory {
if err := deleteOldFile(); err != nil {
return err
}
deleteOldFile = nil
}
}
if newOk {
@@ -501,12 +520,30 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
return client.WriteDirectory(newDest, message.NewEntry)
}
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, newDest)
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can
// upload it, and the old object stays
if deleteOldFile != nil {
glog.Errorf("source data gone: keeping %s (renamed to %s)", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(newDest))
}
return nil
}
if writeErr != nil && !errors.Is(writeErr, errSuperseded) {
return writeErr
}
if errors.Is(writeErr, errSuperseded) {
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
if deleteOldFile != nil {
if err := gatewaySupersededRename(filerSource, option, option, resp, deleteOldFile); err != nil {
return err
}
}
return releaseGatewayRenamedSource(filerSource, option, message)
}
if writeErr != nil {
return writeErr
if deleteOldFile != nil {
if err := deleteOldFile(); err != nil {
return err
}
}
if err := updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry); err != nil {
return err
@@ -520,6 +557,31 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
return eachEntryFunc, nil
}
// gatewaySupersededRename settles the renamed-from object of a rename the
// filer has moved past, as uploadCurrentEntry does for filer.remote.sync: a
// remote-only entry is copied from it; otherwise it no longer holds the
// entry's content (the entry is gone, the superseding event writes its new
// content to the new key, or a later rename's source holds it), so it goes.
func gatewaySupersededRename(filerSource, filerClient filer_pb.FilerClient, option *RemoteGatewayOptions, resp *filer_pb.SubscribeMetadataResponse, deleteOldFile func() error) error {
message := resp.EventNotification
current, err := currentEntry(filerSource, message.NewParentPath, message.NewEntry.Name)
if err != nil {
return err
}
if isRemoteOnly(current) {
if err := gatewayRemoteOnlyRename(filerClient, option, resp, current); err != nil {
return err
}
src := util.FullPath(current.Extended[filer.ExtRemoteRenameSourceKey])
if src == "" || src == util.NewFullPath(resp.Directory, message.OldEntry.Name) {
return nil
}
// copied from an earlier rename's source: the entry no longer reads
// the old object
}
return deleteOldFile()
}
// gatewayRemoteOnlyRename completes a rename whose content exists only as
// the object the renamed-from path maps to: the chunkless entry has nothing
// to upload. When the destination already holds what the entry's stamp
@@ -575,3 +575,66 @@ func TestGatewayLockReleaseLooksUpTheKeptMarker(t *testing.T) {
})
}
}
// TestGatewaySupersededRenameSettlesTheOldObject: a rename the filer has moved
// past removes the renamed-from object once it no longer holds the entry's
// content (the entry was deleted or rewritten since), so a rename followed by
// a delete or rewrite leaves nothing behind; an entry that has become
// remote-only is copied from it instead.
func TestGatewaySupersededRenameSettlesTheOldObject(t *testing.T) {
option, remote := gatewayTestOption("gatewaytest-superseded")
t.Cleanup(func() {
delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-superseded")
remote_storage.ResetRemoteStorageClients()
})
const newPath = "/buckets/gold/dir/new.txt"
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-superseded", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/gold/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: &filer_pb.Entry{Name: "old.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5}, RemoteEntry: stamp},
NewParentPath: "/buckets/gold/dir",
NewEntry: entryWith("new.txt", stamp, chunk("3,01", "e1")),
},
}
remoteOnly := &filer_pb.Entry{Name: "new.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5}, RemoteEntry: stamp}
fromLaterRename := &filer_pb.Entry{
Name: "new.txt",
Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5},
RemoteEntry: stamp,
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/buckets/gold/dir/other.txt")},
}
for _, tc := range []struct {
name string
current *filer_pb.Entry
wantDelete bool
}{
{"deleted since", nil, true},
{"rewritten since", entryWith("new.txt", nil, chunk("4,02", "e2")), true},
{"remote-only since", remoteOnly, false},
// renamed over by another remote-only entry: copied from that one's
// source, and the old object is no longer read
{"remote-only from a later rename", fromLaterRename, true},
} {
t.Run(tc.name, func(t *testing.T) {
*remote = recordingRemote{objects: map[string][]byte{"/dir/old.txt": []byte("hello"), "/dir/other.txt": []byte("hello")}, statETag: `"abc"`, statMtime: 100}
entries := map[string]*filer_pb.Entry{}
if tc.current != nil {
entries[newPath] = tc.current
}
filerClient := &stubFilerClient{entries: entries}
deleted := 0
if err := gatewaySupersededRename(filerClient, filerClient, option, resp, func() error { deleted++; return nil }); err != nil {
t.Fatal(err)
}
if got := deleted == 1; got != tc.wantDelete {
t.Errorf("deleted the old object %d times, want delete=%v", deleted, tc.wantDelete)
}
if isRemoteOnly(tc.current) && (len(remote.writes) != 1 || remote.writes[0].Path != "/dir/new.txt") {
t.Errorf("writes = %+v, want the source object copied to /dir/new.txt", remote.writes)
}
})
}
}
+139 -32
View File
@@ -711,6 +711,10 @@ func processCreateEvent(
}
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -935,7 +939,32 @@ func processUpdateEvent(
return nil
}
glog.V(2).Infof("update: %s/%s ts_ns=%d", filer_pb.MetadataEventTargetDirectory(resp), message.GetNewEntry().GetName(), resp.TsNs)
if !proto.Equal(oldDest, dest) {
// deleteOld removes the renamed-from key, once the new key holds the
// content. A multipart part or a system path whose old key cannot be
// deleted is left behind, as it always was; the new key is written, so
// the event still goes on to stamp the entry.
deleteOld := func() error {
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
if err := client.DeleteFile(oldDest); err != nil {
if isMultipartUploadFile(resp.Directory, message.OldEntry.Name) || isSystemPath(resp.Directory, message.OldEntry.Name) {
glog.V(0).Infof("leaving %s: %v", remote_storage.FormatLocation(oldDest), err)
return nil
}
if !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
return err
}
}
return nil
}
// The old key can hold the entry's only remote copy, whether or not the
// event's old entry carries a stamp (an upload whose stamp was refused by
// a rename in between leaves an unstamped copy there). So it is deleted
// only once the new key holds the content: a rename whose local data turns
// out to be gone (errSourceGone) leaves it where it is, and a remote-only
// entry can still be copied from it. Deleting a key that was never written
// is harmless (ErrRemoteObjectNotFound).
renamed := !proto.Equal(oldDest, dest)
if renamed {
// A renamed entry that holds no local data now (the snapshot was
// remote-only, or remote.uncache ran since) has its content only as a
// remote object. Remote-only reads resolve by the entry's own path, so
@@ -966,34 +995,51 @@ func processUpdateEvent(
glog.V(0).Infof("keep %s: the pending rename moved on", remote_storage.FormatLocation(oldDest))
return nil
}
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
if err := client.DeleteFile(oldDest); err != nil {
if isMultipartUploadFile(resp.Directory, message.OldEntry.Name) || isSystemPath(resp.Directory, message.OldEntry.Name) {
return nil
}
if !errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
return err
}
}
}
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, remoteWriteEntry(message.NewEntry, storageClass), dest)
if errors.Is(writeErr, errSuperseded) {
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
if !proto.Equal(oldDest, dest) {
if err := uploadCurrentEntry(filerClient, filerSource, client, message.NewParentPath, message.NewEntry.Name, eventSource, dest, storageClass, sourceOf); err != nil {
if renamed {
// what the filer holds now goes up first: when it has become
// remote-only, the old key is what it is copied from
old, err := uploadCurrentEntry(filerClient, filerSource, client, message.NewParentPath, message.NewEntry.Name, eventSource, dest, storageClass, sourceOf)
if err != nil {
return err
}
switch old {
case oldKeyKeep:
glog.Errorf("source data gone: keeping %s (renamed to %s)", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(dest))
return nil
case oldKeyDelete:
if err := deleteOld(); err != nil {
return err
}
}
// oldKeyHandled: the remote-only copy cleaned up its own source,
// only while it was still the object the stamp describes
return releaseRenamedSource(filerSource, client, mountedDir, remoteStorageMountLocation, message)
}
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
if renamed {
glog.Errorf("source data gone: keeping %s (renamed to %s)", remote_storage.FormatLocation(oldDest), remote_storage.FormatLocation(dest))
}
return nil
}
if writeErr != nil {
return writeErr
}
if renamed {
if err := deleteOld(); err != nil {
return err
}
}
if err := updateLocalEntry(filerClient, message.NewParentPath, message.NewEntry, remoteEntry); err != nil {
return err
}
if !proto.Equal(oldDest, dest) {
if renamed {
return releaseRenamedSource(filerSource, client, mountedDir, remoteStorageMountLocation, message)
}
return nil
@@ -1160,38 +1206,67 @@ func openRemoteObject(client remote_storage.RemoteStorageClient, loc *remote_pb.
// up once. A remote-only entry is finished the way completeRemoteOnlyRename
// finishes a rename: its stamp can already describe the destination (a sync
// plus remote.uncache in the meantime), and only then is it complete.
func uploadCurrentEntry(filerClient filer_pb.FilerClient, filerSource filer_pb.FilerClient, client remote_storage.RemoteStorageClient, dir, name string, oldSource renameSource, dest *remote_pb.RemoteStorageLocation, storageClass string, sourceOf func(*filer_pb.Entry, renameSource) renameSource) error {
//
// The result says what the caller does with the old key once this returns
// without an error: oldKeyKeep when the current entry's data is gone
// (errSourceGone) and the old key may hold the only copy; oldKeyHandled when
// the remote-only copy came from the old key and already removed it, and only
// if it was still the object its stamp describes; oldKeyDelete otherwise.
func uploadCurrentEntry(filerClient filer_pb.FilerClient, filerSource filer_pb.FilerClient, client remote_storage.RemoteStorageClient, dir, name string, oldSource renameSource, dest *remote_pb.RemoteStorageLocation, storageClass string, sourceOf func(*filer_pb.Entry, renameSource) renameSource) (oldKey, error) {
ctx, cancel := lookupContext()
defer cancel()
current, _, _, err := filer_pb.GetEntry(ctx, filerSource, util.NewFullPath(dir, name))
if errors.Is(err, filer_pb.ErrNotFound) {
return nil
return oldKeyDelete, nil
}
if err != nil {
return err
return oldKeyDelete, err
}
if current.IsDirectory {
return nil
return oldKeyDelete, nil
}
if isRemoteOnly(current) {
return completeRemoteOnlyRename(filerClient, client, dir, current, sourceOf(current, oldSource), dest, storageClass)
source := sourceOf(current, oldSource)
if err := completeRemoteOnlyRename(filerClient, client, dir, current, source, dest, storageClass); err != nil {
return oldKeyHandled, err
}
if !proto.Equal(source.loc, oldSource.loc) {
// copied from an earlier rename's source: the entry no longer
// reads the old key
return oldKeyDelete, nil
}
return oldKeyHandled, nil
}
if shouldSendToRemote(current) {
glog.V(0).Infof("leaving %s to the rewrite that superseded the rename", remote_storage.FormatLocation(dest))
return nil
return oldKeyDelete, nil
}
glog.V(0).Infof("uploading the current %s in place of the superseded rename", remote_storage.FormatLocation(dest))
remoteEntry, writeErr := retriedWriteFile(client, filerSource, dir, remoteWriteEntry(current, storageClass), dest)
if errors.Is(writeErr, errSuperseded) {
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
return nil
return oldKeyDelete, nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return oldKeyKeep, nil
}
if writeErr != nil {
return writeErr
return oldKeyDelete, writeErr
}
return updateLocalEntry(filerClient, dir, current, remoteEntry)
return oldKeyDelete, updateLocalEntry(filerClient, dir, current, remoteEntry)
}
// oldKey is what a superseded rename does with its renamed-from key
// (uploadCurrentEntry).
type oldKey int
const (
oldKeyDelete oldKey = iota
oldKeyKeep
oldKeyHandled
)
// recoverSupersededCreate finishes a create reshaped from a rename into the
// mount when the filer has moved past the entry the event described. A plain
// superseded create skips because the superseding event follows in the log; a
@@ -1233,6 +1308,10 @@ func recoverSupersededCreate(
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(dest), writeErr)
return nil
}
if errors.Is(writeErr, errSourceGone) {
// logged and counted by retriedWriteFile; nothing can upload it
return nil
}
if writeErr != nil {
return writeErr
}
@@ -1449,43 +1528,71 @@ var errLookupUnanswered = errors.New("supersession lookup unanswered")
// trip the remote's per-object mutation rate limit; only the version the filer
// still holds is worth sending. After: a dead chunk reads as a transient
// "RequestError" from the SDK, and waiting out the backoff on it buys nothing.
// An entry the filer still holds whose chunk the volume servers answer 404 for
// ends in errSourceGone once that has held for sourceGoneGrace: the caller
// treats the event as handled, and the path is logged with the chunk's fid.
func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource filer_pb.FilerClient, dir string, newEntry *filer_pb.Entry, dest *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
path := string(util.NewFullPath(dir, newEntry.Name))
if superseded, lookupErr := isSuperseded(filerSource, dir, newEntry); lookupErr != nil {
return nil, fmt.Errorf("%s: supersession lookup: %w", util.NewFullPath(dir, newEntry.Name), lookupErr)
sourceGone.forget(path)
return nil, fmt.Errorf("%s: supersession lookup: %w", path, lookupErr)
} else if superseded {
return nil, fmt.Errorf("%s %w", util.NewFullPath(dir, newEntry.Name), errSuperseded)
sourceGone.forget(path)
return nil, fmt.Errorf("%s %w", path, errSuperseded)
}
// A failed attempt is retried only once the filer has answered that the
// entry is still the one the event described; an unanswered lookup
// ends the loop so no further attempt uploads an unverified snapshot.
afterFailure := func(attemptErr error) error {
// sourceErr is what the entry's own chunks answered, never the remote.
afterFailure := func(attemptErr, sourceErr error) error {
superseded, lookupErr := isSuperseded(filerSource, dir, newEntry)
if lookupErr != nil {
return fmt.Errorf("%s %w: %w (after: %v)", util.NewFullPath(dir, newEntry.Name), errLookupUnanswered, lookupErr, attemptErr)
sourceGone.forget(path)
return fmt.Errorf("%s %w: %w (after: %v)", path, errLookupUnanswered, lookupErr, attemptErr)
}
if superseded {
return fmt.Errorf("%s %w: %w", util.NewFullPath(dir, newEntry.Name), errSuperseded, attemptErr)
return fmt.Errorf("%s %w: %w", path, errSuperseded, attemptErr)
}
return attemptErr
if !isSourceGone(sourceErr) {
sourceGone.forget(path)
return attemptErr
}
fid := goneFid(sourceErr, newEntry)
gone, isNew := sourceGone.observe(path, chunkSetKey(newEntry), time.Now())
if !gone {
return attemptErr
}
if isNew {
n := sourceGoneCount.Add(1)
glog.Errorf("source data gone: %s (fid %s): not written back to %s (%d in this process; %v)", path, fid, remote_storage.FormatLocation(dest), n, sourceErr)
}
return fmt.Errorf("%s (fid %s): %w", path, fid, errSourceGone)
}
err = util.RetryOnError("writeFile", func(err error) bool {
return !errors.Is(err, errSuperseded) && !errors.Is(err, errLookupUnanswered) && util.IsTransientError(err)
return !errors.Is(err, errSuperseded) && !errors.Is(err, errLookupUnanswered) && !errors.Is(err, errSourceGone) && util.IsTransientError(err)
}, func() error {
reader, closeFn, readerErr := remoteUploadReader(filerSource, newEntry)
if readerErr != nil {
return afterFailure(readerErr)
return afterFailure(readerErr, readerErr)
}
if closeFn != nil {
defer closeFn()
}
body, recorder := newSourceReadRecorder(reader)
glog.V(0).Infof("create %s", remote_storage.FormatLocation(dest))
var writeErr error
remoteEntry, writeErr = client.WriteFile(dest, newEntry, reader)
remoteEntry, writeErr = client.WriteFile(dest, newEntry, body)
if writeErr != nil {
return afterFailure(writeErr)
return afterFailure(writeErr, recorder.readErr())
}
return nil
})
if errors.Is(err, errSourceGone) {
return nil, err
}
if err == nil || errors.Is(err, errSuperseded) {
sourceGone.forget(path)
}
if err != nil && !errors.Is(err, errSuperseded) {
glog.Errorf("write to %s: %v", dest, err)
}
+134 -2
View File
@@ -550,6 +550,39 @@ func entryWith(name string, remote *filer_pb.RemoteEntry, chunks ...*filer_pb.Fi
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: remote, Chunks: chunks}
}
// changingFilerClient answers its i-th lookup with seq[i], and the last one
// after that: the filer's entry changing while an event is processed.
type changingFilerClient struct {
stubFilerClient
seq []*filer_pb.Entry
}
func (c *changingFilerClient) LookupDirectoryEntry(_ context.Context, _ *filer_pb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
i := min(c.lookups, len(c.seq)-1)
c.lookups++
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.seq[i]}, nil
}
func (c *changingFilerClient) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return fn(c)
}
// replacingRemote puts another object at path once a write completes: a
// replacement landing on a key while something else is being copied.
type replacingRemote struct {
*recordingRemote
path string
with []byte
}
func (r replacingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
e, err := r.recordingRemote.WriteFile(loc, entry, reader)
if err == nil {
r.objects[r.path] = r.with
}
return e, err
}
// blockingFilerClient answers a lookup only when its context ends.
type blockingFilerClient struct {
stubFilerClient
@@ -1183,6 +1216,10 @@ func (r *recordingRemote) ReadFile(loc *remote_pb.RemoteStorageLocation, offset
func (r *recordingRemote) DeleteFile(loc *remote_pb.RemoteStorageLocation) error {
r.deletes = append(r.deletes, loc)
if r.deleteErr == nil && r.objects != nil {
// the object is gone for a later copy or read, as on a real remote
delete(r.objects, loc.Path)
}
return r.deleteErr
}
@@ -1840,6 +1877,84 @@ func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
}
})
t.Run("uncached between the check and the upload: copied from the old key before it goes", func(t *testing.T) {
// remote.uncache drops the written-back entry's chunks after the
// remote-only check and before the upload's supersession lookup: the
// old key is where the content is copied from, so it must still be
// there when uploadCurrentEntry runs.
stamp := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
synced := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/b/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: entryWith("a.txt", stamp, chunk("3,01", "e1")),
NewParentPath: "/buckets/b/dir",
NewEntry: entryWith("b.txt", stamp, chunk("3,01", "e1")),
},
}
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
filerClient := &changingFilerClient{seq: []*filer_pb.Entry{
entryWith("b.txt", stamp, chunk("3,01", "e1")), // the remote-only check
entryWith("b.txt", stamp), // uncached since
}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, synced); err != nil {
t.Fatalf("err = %v, want nil: the content is copied from the old key", err)
}
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], wantWrite) || string(remote.written[0]) != "payload" {
t.Fatalf("writes = %+v (%q), want the old object's bytes at the new key", remote.writes, remote.written)
}
if _, ok := remote.objects["/b/dir/a.txt"]; ok {
t.Errorf("the old key is still there after the rename completed")
}
})
t.Run("uncached, and the old key replaced during the copy: the replacement stays", func(t *testing.T) {
// the copy cleans up its source only while it is the object the
// stamp describes; nothing after it may delete the old key blindly
stamp := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
synced := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/b/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: entryWith("a.txt", stamp, chunk("3,01", "e1")),
NewParentPath: "/buckets/b/dir",
NewEntry: entryWith("b.txt", stamp, chunk("3,01", "e1")),
},
}
inner := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}
remote := replacingRemote{recordingRemote: inner, path: "/b/dir/a.txt", with: []byte("a newer object")}
filerClient := &changingFilerClient{seq: []*filer_pb.Entry{
entryWith("b.txt", stamp, chunk("3,01", "e1")),
entryWith("b.txt", stamp),
}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, synced); err != nil {
t.Fatalf("err = %v", err)
}
if len(inner.writes) != 1 || string(inner.written[0]) != "payload" {
t.Fatalf("writes = %+v (%q), want the old object copied", inner.writes, inner.written)
}
if got := string(inner.objects["/b/dir/a.txt"]); got != "a newer object" {
t.Errorf("old key holds %q, want the replacement kept", got)
}
})
t.Run("current entry's chunks gone: the old key stays", func(t *testing.T) {
// the old entry carries no stamp (its upload's stamp was refused by
// a rename in between), yet the old key holds the only copy
withSourceGone(t, 0, 1)
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 1024, LastLocalSyncTsNs: 1786096669*1e9 + 1}, chunk("3,02", "e2"))
filerClient, done := servingFilerClient(current, map[string][]byte{})
defer done()
remote := bodyReadingRemote{&recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload")}}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err)
}
if len(remote.deletes) != 0 {
t.Errorf("deletes = %+v, want none: the old key holds the only copy", remote.deletes)
}
if got := sourceGoneCount.Load(); got != 1 {
t.Errorf("counted %d gone entries, want 1", got)
}
})
t.Run("snapshot already remote-only: completed the same way", func(t *testing.T) {
remoteOnly := &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7}
snapshot := &filer_pb.SubscribeMetadataResponse{
@@ -1867,7 +1982,7 @@ func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 1024})
remote := &recordingRemote{}
filerClient := &stubFilerClient{entry: current}
err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource)
_, err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource)
if err == nil || !strings.Contains(err.Error(), "neither") {
t.Errorf("err = %v, want the lost-content failure", err)
}
@@ -1876,11 +1991,28 @@ func TestSupersededRenameUploadsCurrentEntry(t *testing.T) {
}
})
t.Run("uncached with a later rename's source: copied from it, the old key deleted", func(t *testing.T) {
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/c.txt": []byte("payload")}}
filerClient := &stubFilerClient{entry: current}
laterSource := renameSource{loc: &remote_pb.RemoteStorageLocation{Name: "gcs", Bucket: "bucket", Path: "/b/dir/c.txt"}}
old, err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", func(*filer_pb.Entry, renameSource) renameSource { return laterSource })
if err != nil {
t.Fatalf("err = %v", err)
}
if len(remote.writes) != 1 || string(remote.written[0]) != "payload" {
t.Errorf("writes = %+v (%q), want the later source copied to the destination", remote.writes, remote.written)
}
if old != oldKeyDelete {
t.Errorf("old key = %v, want oldKeyDelete: the entry no longer reads it", old)
}
})
t.Run("uncached with the destination already synced: complete without a write", func(t *testing.T) {
current := entryWith("b.txt", &filer_pb.RemoteEntry{StorageName: "gcs", RemoteMtime: 1786096669, RemoteSize: 7})
remote := &recordingRemote{objects: map[string][]byte{"/b/dir/a.txt": []byte("payload"), "/b/dir/b.txt": []byte("payload")}}
filerClient := &stubFilerClient{entry: current}
if err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource); err != nil {
if _, err := uploadCurrentEntry(filerClient, filerClient, remote, "/buckets/b/dir", "b.txt", renameSource{loc: wantDelete}, wantWrite, "", eventSource); err != nil {
t.Fatalf("err = %v, want nil: the destination object matches the entry's stamp", err)
}
if len(remote.writes) != 0 {
+238
View File
@@ -0,0 +1,238 @@
package command
import (
"errors"
"fmt"
"hash/fnv"
"io"
"regexp"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// errSourceGone marks an upload whose source data no longer exists in this
// cluster: a volume server answered 404 for one of the entry's chunks (read
// with readDeleted=true, so not even a deleted needle is left), the filer
// still holds the entry as the event described it, and that held for
// sourceGoneGrace over sourceGoneMinAnswers attempts in a row. Retrying
// cannot produce the bytes: the write-back reports the path once and moves
// past the event instead of holding the directory's offset on it forever.
// A volume lost with its disk (a server restored from a metadata-only
// backup) leaves entries like this behind.
var errSourceGone = errors.New("source data gone")
// A 404 can also come from a volume server that has not loaded the volume
// yet, or from a stale location right after a move; neither lasts. Only a
// 404 that persists this long, over this many attempts with nothing else in
// between, counts as gone. A volume the master cannot locate at all is also
// what a volume server that is down looks like, so it never counts.
var (
sourceGoneGrace = 5 * time.Minute
sourceGoneMinAnswers = 3
)
// sourceGoneRemembered bounds how many paths a process keeps, both those with
// sightings in a row and those found gone.
const sourceGoneRemembered = 10000
// sourceGoneCount is how many entries this process left unwritten because
// their source data was gone.
var sourceGoneCount atomic.Int64
// sourceReadRecorder keeps the first error the upload body's reader returned.
// Remote clients wrap a body read failure in their own errors (the AWS SDK's
// RequestError has no Unwrap), so the write error cannot say whether the
// source or the remote failed; the recorder can, and a 404 from the remote
// itself never reaches it.
type sourceReadRecorder struct {
r io.Reader
mu sync.Mutex
err error
}
func (s *sourceReadRecorder) Read(p []byte) (int, error) {
n, err := s.r.Read(p)
s.record(err)
return n, err
}
// sourceReadAtRecorder keeps an io.ReaderAt + io.Seeker body one: an S3
// uploader reads the parts of such a body in place and in parallel, where a
// plain io.Reader is copied into a buffer per part.
type sourceReadAtRecorder struct {
*sourceReadRecorder
ra io.ReaderAt
sk io.Seeker
}
func (s *sourceReadAtRecorder) ReadAt(p []byte, off int64) (int, error) {
n, err := s.ra.ReadAt(p, off)
s.record(err)
return n, err
}
func (s *sourceReadAtRecorder) Seek(offset int64, whence int) (int64, error) {
return s.sk.Seek(offset, whence)
}
// newSourceReadRecorder wraps an upload body, keeping the shape the remote
// client sees.
func newSourceReadRecorder(r io.Reader) (io.Reader, *sourceReadRecorder) {
rec := &sourceReadRecorder{r: r}
ra, okAt := r.(io.ReaderAt)
sk, okSeek := r.(io.Seeker)
if okAt && okSeek {
return &sourceReadAtRecorder{sourceReadRecorder: rec, ra: ra, sk: sk}, rec
}
return rec, rec
}
func (s *sourceReadRecorder) record(err error) {
if err == nil || err == io.EOF {
return
}
s.mu.Lock()
if s.err == nil {
s.err = err
}
s.mu.Unlock()
}
func (s *sourceReadRecorder) readErr() error {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
return s.err
}
// isSourceGone reports whether a read of the entry's own chunks says the data
// may be gone: every location of a chunk answered 404
// (util_http.NotFoundEverywhere). Only errors from the source side are passed
// here: the upload body's reader or the chunk view resolution.
func isSourceGone(sourceErr error) bool {
return errors.Is(sourceErr, util_http.ErrNotFound)
}
var fidInURL = regexp.MustCompile(`/(\d+,[0-9a-fA-F]+)(?:[?:/\s"]|$)`)
// goneFid names the chunk the sighting was for, for the log: the file id in
// the URL the error carries, else the entry's first chunk and how many more
// it has.
func goneFid(sourceErr error, entry *filer_pb.Entry) string {
if m := fidInURL.FindStringSubmatch(sourceErr.Error()); m != nil {
return m[1]
}
chunks := entry.GetChunks()
switch len(chunks) {
case 0:
return "unknown"
case 1:
return chunks[0].GetFileIdString()
}
return fmt.Sprintf("%s and %d more", chunks[0].GetFileIdString(), len(chunks)-1)
}
// chunkSetKey identifies the content a sighting is about: the entry's chunk
// file ids, in any order. The chunk that fails first can differ from one
// attempt to the next (an uploader reads parts in parallel), so sightings in
// a row are counted per content, not per failing chunk.
func chunkSetKey(entry *filer_pb.Entry) string {
fids := make([]string, 0, len(entry.GetChunks()))
for _, c := range entry.GetChunks() {
fids = append(fids, c.GetFileIdString())
}
sort.Strings(fids)
h := fnv.New64a()
for _, f := range fids {
h.Write([]byte(f))
h.Write([]byte{0})
}
return fmt.Sprintf("%d:%016x", len(fids), h.Sum64())
}
type goneSighting struct {
key string
first time.Time
last time.Time
answers int
}
// sourceGoneTracker holds, per path, the sightings seen in a row. Any other
// outcome for the path forgets them, so the grace starts again. A path found
// gone is remembered with its content key: a later event of the same entry (a
// metadata update, a replay) is skipped at once instead of holding the
// directory's offset for another grace.
type sourceGoneTracker struct {
mu sync.Mutex
seen map[string]*goneSighting
gone map[string]string
}
func newSourceGoneTracker() *sourceGoneTracker {
return &sourceGoneTracker{seen: map[string]*goneSighting{}, gone: map[string]string{}}
}
var sourceGone = newSourceGoneTracker()
// observe records a sighting for path under key (chunkSetKey) and reports
// whether it has now held for sourceGoneGrace over sourceGoneMinAnswers
// attempts, and whether this call is the one that found it gone (a path
// already known gone reports gone, not new).
func (t *sourceGoneTracker) observe(path, key string, now time.Time) (gone, isNew bool) {
t.mu.Lock()
defer t.mu.Unlock()
if g, ok := t.gone[path]; ok && g == key {
return true, false
}
s := t.seen[path]
if s == nil || s.key != key {
if s == nil && len(t.seen) >= sourceGoneRemembered {
t.pruneSeen(now)
}
s = &goneSighting{key: key, first: now}
t.seen[path] = s
}
s.answers++
s.last = now
if s.answers >= sourceGoneMinAnswers && now.Sub(s.first) >= sourceGoneGrace {
delete(t.seen, path)
if len(t.gone) >= sourceGoneRemembered {
t.gone = map[string]string{}
}
t.gone[path] = key
return true, true
}
return false, false
}
// pruneSeen drops sightings of paths no attempt has reached for longer than
// the grace (the entry was deleted, or the subscription moved past it), and
// every sighting if the map is still full. Dropping one only restarts that
// path's grace.
func (t *sourceGoneTracker) pruneSeen(now time.Time) {
stale := 2 * sourceGoneGrace
for p, s := range t.seen {
if now.Sub(s.last) > stale {
delete(t.seen, p)
}
}
if len(t.seen) >= sourceGoneRemembered {
t.seen = map[string]*goneSighting{}
}
}
// forget drops path's sightings, and its gone mark: the entry was written
// back, superseded, or failed some other way.
func (t *sourceGoneTracker) forget(path string) {
t.mu.Lock()
delete(t.seen, path)
delete(t.gone, path)
t.mu.Unlock()
}
+357
View File
@@ -0,0 +1,357 @@
package command
import (
"bytes"
"errors"
"fmt"
"io"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"google.golang.org/protobuf/proto"
)
func withSourceGone(t *testing.T, grace time.Duration, minAnswers int) {
t.Helper()
prevGrace, prevMin, prevWait := sourceGoneGrace, sourceGoneMinAnswers, util.RetryWaitTime
sourceGoneGrace, sourceGoneMinAnswers = grace, minAnswers
// one pass of the chunk fetch's and the upload's backoff loops
util.RetryWaitTime = 1100 * time.Millisecond
sourceGone = newSourceGoneTracker()
sourceGoneCount.Store(0)
t.Cleanup(func() {
sourceGoneGrace, sourceGoneMinAnswers, util.RetryWaitTime = prevGrace, prevMin, prevWait
sourceGone = newSourceGoneTracker()
sourceGoneCount.Store(0)
})
}
// TestRetriedWriteFileSourceGone: an entry the filer still holds whose chunk
// the volume server answers 404 for (a volume lost with its disk) ends in
// errSourceGone once the 404 has held, instead of failing its event forever
// and holding the directory's offset behind it. The encrypted read path
// (GetAuthenticated) must report the 404 as ErrNotFound too: production
// cells encrypt volume data.
func TestRetriedWriteFileSourceGone(t *testing.T) {
const dir = "/buckets/garden--blobs/camera"
for _, tc := range []struct {
name string
chunk *filer_pb.FileChunk
}{
{"plain chunk", &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 100}},
{"encrypted chunk", &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 100, CipherKey: make([]byte, 32)}},
} {
t.Run(tc.name, func(t *testing.T) {
withSourceGone(t, 0, 3)
entry := entryWith("snapshot.jpg", nil, tc.chunk)
entry.Attributes.FileSize = 100
filerClient, done := servingFilerClient(entry, map[string][]byte{}) // the chunk is gone
defer done()
dest := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/camera/snapshot.jpg"}
for call := 1; call <= 2; call++ {
_, err := retriedWriteFile(&captureRemote{}, filerClient, dir, entry, dest)
if err == nil || errors.Is(err, errSourceGone) || errors.Is(err, errSuperseded) {
t.Fatalf("call %d: err = %v, want the read failure itself while the 404 is young", call, err)
}
}
_, err := retriedWriteFile(&captureRemote{}, filerClient, dir, entry, dest)
if !errors.Is(err, errSourceGone) {
t.Fatalf("third call: err = %v, want errSourceGone", err)
}
if got := sourceGoneCount.Load(); got != 1 {
t.Errorf("counted %d gone entries, want 1", got)
}
want := fmt.Sprintf("%s/snapshot.jpg (fid 79,2cb9d2dd0ea2)", dir)
if msg := err.Error(); len(msg) < len(want) || msg[:len(want)] != want {
t.Errorf("err = %q, want it to start with %q", msg, want)
}
})
}
}
// TestRetriedWriteFileRemoteNotFoundIsNeverGone: only the source's own chunk
// reads decide. A remote that answers 404 (or anything else) to the upload,
// while the chunks read fine, is retried as before: skipping it would drop
// data that exists.
// TestRetriedWriteFileSourceGoneAcrossChunks: an uploader reads the parts of
// a ReaderAt body in parallel, so which lost chunk fails first changes from
// one attempt to the next. The sightings are of the same content and must
// add up, or a large file missing several chunks holds the offset forever.
func TestRetriedWriteFileSourceGoneAcrossChunks(t *testing.T) {
withSourceGone(t, 0, 3)
entry := entryWith("big.bin", nil,
&filer_pb.FileChunk{FileId: "7,01", ETag: "e1", Offset: 0, Size: 4},
&filer_pb.FileChunk{FileId: "8,02", ETag: "e2", Offset: 4, Size: 4})
entry.Attributes.FileSize = 8
filerClient, done := servingFilerClient(entry, map[string][]byte{}) // both chunks lost
defer done()
dest := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/big.bin"}
remote := &partReadingRemote{}
for call := 1; call <= 3; call++ {
_, err := retriedWriteFile(remote, filerClient, "/buckets/b", entry, dest)
if call < 3 && errors.Is(err, errSourceGone) {
t.Fatalf("call %d: gone before three sightings", call)
}
if call == 3 && !errors.Is(err, errSourceGone) {
t.Fatalf("call 3: err = %v, want errSourceGone after three sightings of the same entry", err)
}
}
if len(remote.offsets) < 2 || remote.offsets[0] == remote.offsets[1] {
t.Fatalf("precondition: the attempts read different parts, got offsets %v", remote.offsets)
}
}
// partReadingRemote reads one 4-byte part of the body per write, the next
// part on each call, as parallel part readers do in no fixed order.
type partReadingRemote struct {
recordingRemote
offsets []int64
}
func (r *partReadingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
ra, ok := reader.(io.ReaderAt)
if !ok {
return nil, errors.New("body is not a ReaderAt")
}
off := int64(len(r.offsets)%2) * 4
r.offsets = append(r.offsets, off)
if _, err := ra.ReadAt(make([]byte, 4), off); err != nil {
return nil, fmt.Errorf("RequestError: send request failed\ncaused by: %v", err)
}
return r.recordingRemote.WriteFile(loc, entry, reader)
}
func TestRetriedWriteFileRemoteNotFoundIsNeverGone(t *testing.T) {
withSourceGone(t, 0, 1)
const dir = "/buckets/ingest"
entry := entryWith("lease.json", nil, chunk("3,01", "e1"))
filerClient := &stubFilerClient{entry: entryWith(entry.Name, nil, chunk("3,01", "e1"))}
dest := &remote_pb.RemoteStorageLocation{Name: "b2", Bucket: "tier", Path: "/lease.json"}
remoteErr := fmt.Errorf("https://s3.example.com/tier/lease.json: 404 Not Found: %w", util_http.ErrNotFound)
for call := 1; call <= 3; call++ {
_, err := retriedWriteFile(&failingRemote{err: remoteErr}, filerClient, dir, entry, dest)
if err == nil || errors.Is(err, errSourceGone) {
t.Fatalf("call %d: err = %v, want the remote's failure, never errSourceGone", call, err)
}
}
if got := sourceGoneCount.Load(); got != 0 {
t.Errorf("counted %d gone entries, want 0", got)
}
}
// TestSourceGoneTrackerGrace: a sighting counts as gone only after both the
// grace and the answer count, for the same chunk, with nothing else in
// between; a gone path is then skipped at once until something else happens.
func TestSourceGoneTrackerGrace(t *testing.T) {
withSourceGone(t, 5*time.Minute, 3)
t0 := time.Unix(1_800_000_000, 0)
tr := newSourceGoneTracker()
observe := func(path, key string, at time.Time) bool {
gone, _ := tr.observe(path, key, at)
return gone
}
if observe("/a", "1,01", t0) || observe("/a", "1,01", t0.Add(time.Minute)) || observe("/a", "1,01", t0.Add(2*time.Minute)) {
t.Fatal("gone before the grace ended")
}
if !observe("/a", "1,01", t0.Add(5*time.Minute)) {
t.Fatal("not gone after the grace and three answers")
}
// a later event of the same gone entry is skipped at once
if !observe("/a", "1,01", t0.Add(6*time.Minute)) {
t.Fatal("a known-gone entry waits for another grace")
}
// written back or failed otherwise since: the grace starts again
tr.forget("/a")
if observe("/a", "1,01", t0.Add(7*time.Minute)) {
t.Fatal("gone on the first answer after forget")
}
// an unknown path never matches the empty fid of a chunkless entry
if observe("/c", "", t0) {
t.Fatal("a first sighting with an empty fid counted as gone")
}
// many answers inside the grace are not enough
for i := 0; i < 10; i++ {
if observe("/b", "1,02", t0.Add(time.Duration(i)*time.Second)) {
t.Fatalf("answer %d: gone inside the grace", i)
}
}
tr.forget("/b")
if observe("/b", "1,02", t0.Add(6*time.Minute)) || observe("/b", "1,02", t0.Add(7*time.Minute)) || observe("/b", "1,02", t0.Add(8*time.Minute)) {
t.Fatal("gone without a full grace after forget")
}
// another chunk of the same path starts again too
if observe("/b", "1,03", t0.Add(20*time.Minute)) {
t.Fatal("gone on a new chunk's first answer")
}
}
// TestSourceGoneTrackerCountsOnce: a path is new-gone once; replayed events
// of it are skipped without another log line or count.
func TestSourceGoneTrackerCountsOnce(t *testing.T) {
withSourceGone(t, 5*time.Minute, 3)
t0 := time.Unix(1_800_000_000, 0)
entry := entryWith("x.jpg", nil, chunk("79,01", "e1"))
tr := newSourceGoneTracker()
key := chunkSetKey(entry)
for i, at := range []time.Duration{0, time.Minute, 5 * time.Minute} {
gone, isNew := tr.observe("/x", key, t0.Add(at))
if want := i == 2; gone != want || isNew != want {
t.Fatalf("answer %d: gone=%v new=%v, want %v %v", i, gone, isNew, want, want)
}
}
if gone, isNew := tr.observe("/x", key, t0.Add(6*time.Minute)); !gone || isNew {
t.Errorf("a replay of a gone path: gone=%v new=%v, want gone and not new", gone, isNew)
}
}
// TestIsSourceGone: only a 404 from every location of a chunk is a sighting.
func TestIsSourceGone(t *testing.T) {
for _, tc := range []struct {
err error
want bool
}{
{fmt.Errorf("http://v:8080/79,2cb9: 404 Not Found: %w", util_http.ErrNotFound), true},
// a volume the master cannot locate: a volume server that is down
// looks the same
{errors.New("failed to locate 79,2cb9d2dd0ea2"), false},
// a 404 on one replica while another failed otherwise
{util_http.NotFoundEverywhere(fmt.Errorf("a: %w", util_http.ErrNotFound), errors.New("b: 503 Service Unavailable")), false},
{errors.New("http://v:8080/79,2cb9: 500 Internal Server Error"), false},
{errors.New("read tcp: connection reset by peer"), false},
{nil, false},
} {
if got := isSourceGone(tc.err); got != tc.want {
t.Errorf("isSourceGone(%v) = %v, want %v", tc.err, got, tc.want)
}
}
}
// TestSourceReadRecorderKeepsReaderAt: the recorder must not hide a
// ReaderAt + Seeker body, or an S3 uploader buffers every part in memory.
func TestSourceReadRecorderKeepsReaderAt(t *testing.T) {
body, rec := newSourceReadRecorder(io.NewSectionReader(goneChunkReaderAt{}, 0, 10))
ra, okAt := body.(io.ReaderAt)
_, okSeek := body.(io.Seeker)
if !okAt || !okSeek {
t.Fatalf("body %T: ReaderAt %v, Seeker %v; want both", body, okAt, okSeek)
}
if _, err := ra.ReadAt(make([]byte, 4), 0); err == nil {
t.Fatal("ReadAt succeeded")
}
if !errors.Is(rec.readErr(), util_http.ErrNotFound) {
t.Errorf("recorded %v, want the ReadAt failure", rec.readErr())
}
if _, ok := mustReader(newSourceReadRecorder(bytes.NewBufferString("x"))).(io.ReaderAt); ok {
t.Error("a plain reader gained ReadAt")
}
}
type goneChunkReaderAt struct{}
func (goneChunkReaderAt) ReadAt([]byte, int64) (int, error) {
return 0, fmt.Errorf("http://v:8080/79,2cb9: 404 Not Found: %w", util_http.ErrNotFound)
}
func mustReader(r io.Reader, _ *sourceReadRecorder) io.Reader { return r }
// bodyReadingRemote reads the upload body before recording the write, as a
// real remote does; a body read failure fails the write.
type bodyReadingRemote struct{ *recordingRemote }
func (r bodyReadingRemote) WriteFile(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry, reader io.Reader) (*filer_pb.RemoteEntry, error) {
if _, err := io.ReadAll(reader); err != nil {
return nil, fmt.Errorf("RequestError: send request failed\ncaused by: %v", err)
}
return r.recordingRemote.WriteFile(loc, entry, reader)
}
// TestRenameOfGoneEntryKeepsTheOldKey: a written-back entry renamed after its
// local chunks were lost still has its content under the old key. The event
// is acknowledged as gone, and the old key is not deleted: it is the only
// copy left. With the chunks present, the old key goes once the new one is
// written.
func TestRenameOfGoneEntryKeepsTheOldKey(t *testing.T) {
const mountedDir = "/buckets"
mountLoc := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/"}
oldKey := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/b/src/photo.jpg"}
newKey := &remote_pb.RemoteStorageLocation{Name: "bunny", Bucket: "cells", Path: "/b/dst/photo.jpg"}
event := func(stamped bool) (*filer_pb.Entry, *filer_pb.SubscribeMetadataResponse) {
newEntry := entryWith("photo.jpg", nil, &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 4})
newEntry.Attributes.FileSize = 4
var stamp *filer_pb.RemoteEntry
if stamped {
stamp = &filer_pb.RemoteEntry{StorageName: "bunny", RemoteETag: "etag", RemoteSize: 4, RemoteMtime: 1786096669}
}
oldEntry := entryWith("photo.jpg", stamp, &filer_pb.FileChunk{FileId: "79,2cb9d2dd0ea2", ETag: "e1", Size: 4})
return newEntry, &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/b/src",
EventNotification: &filer_pb.EventNotification{
OldEntry: oldEntry,
NewParentPath: "/buckets/b/dst",
NewEntry: newEntry,
},
}
}
t.Run("chunks gone", func(t *testing.T) {
withSourceGone(t, 0, 1)
newEntry, resp := event(true)
filerClient, done := servingFilerClient(newEntry, map[string][]byte{})
defer done()
remote := bodyReadingRemote{&recordingRemote{}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err)
}
if len(remote.deletes) != 0 {
t.Errorf("deleted %+v; the old key holds the only copy", remote.deletes)
}
if len(remote.writes) != 0 {
t.Errorf("wrote %+v, want nothing", remote.writes)
}
if got := sourceGoneCount.Load(); got != 1 {
t.Errorf("counted %d gone entries, want 1", got)
}
})
t.Run("chunks gone, old entry unstamped", func(t *testing.T) {
// the upload's stamp was refused by the rename in between: the old
// key still holds the only copy
withSourceGone(t, 0, 1)
newEntry, resp := event(false)
filerClient, done := servingFilerClient(newEntry, map[string][]byte{})
defer done()
remote := bodyReadingRemote{&recordingRemote{}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v, want nil: the gone entry is acknowledged", err)
}
if len(remote.deletes) != 0 {
t.Errorf("deletes = %+v; the old key holds the only copy", remote.deletes)
}
})
t.Run("chunks present", func(t *testing.T) {
withSourceGone(t, 0, 1)
newEntry, resp := event(true)
filerClient, done := servingFilerClient(newEntry, map[string][]byte{"79,2cb9d2dd0ea2": []byte("jpeg")})
defer done()
remote := bodyReadingRemote{&recordingRemote{}}
if err := processUpdateEvent(filerClient, filerClient, "", remote, mountedDir, mountLoc, resp); err != nil {
t.Fatalf("err = %v", err)
}
if len(remote.writes) != 1 || !proto.Equal(remote.writes[0], newKey) {
t.Errorf("writes = %+v, want the new key", remote.writes)
}
if len(remote.deletes) != 1 || !proto.Equal(remote.deletes[0], oldKey) {
t.Errorf("deletes = %+v, want the old key once the new one is written", remote.deletes)
}
})
}
+1
View File
@@ -28,6 +28,7 @@ import (
_ "github.com/seaweedfs/seaweedfs/weed/filer/mysql2"
_ "github.com/seaweedfs/seaweedfs/weed/filer/postgres"
_ "github.com/seaweedfs/seaweedfs/weed/filer/postgres2"
_ "github.com/seaweedfs/seaweedfs/weed/filer/postgres_flat"
_ "github.com/seaweedfs/seaweedfs/weed/filer/redis"
_ "github.com/seaweedfs/seaweedfs/weed/filer/redis2"
_ "github.com/seaweedfs/seaweedfs/weed/filer/redis3"
+84 -16
View File
@@ -64,18 +64,20 @@ const (
)
var (
miniOptions MiniOptions
miniMasterOptions MasterOptions
miniFilerOptions FilerOptions
miniS3Options S3Options
miniWebDavOptions WebDavOption
miniAdminOptions AdminOptions
miniOptions MiniOptions
miniMasterOptions MasterOptions
miniFilerOptions FilerOptions
miniS3Options S3Options
miniMqBrokerOptions MessageQueueBrokerOptions
miniWebDavOptions WebDavOption
miniAdminOptions AdminOptions
// Flags explicitly provided on the command line or via WEED_* env vars,
// captured before the saved options file is applied
explicitFlags map[string]bool
miniEnableWebDAV *bool
miniWebDavAllowInsecureBind *bool
miniEnableS3 *bool
miniEnableMqBroker *bool
miniEnableAdminUI *bool
miniAdminWorkerBindIP *string
miniS3IamReadOnly *bool
@@ -224,6 +226,9 @@ func miniStartupServices() []string {
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
services = append(services, "Lance")
}
if miniEnableMqBroker != nil && *miniEnableMqBroker {
services = append(services, "MQ Broker")
}
}
services = append(services, "Admin")
return services
@@ -348,7 +353,7 @@ var cmdMini = &Command{
Long: `start a complete SeaweedFS setup with all components optimized for small/dev use cases
This command starts all components in one process (master, volume, filer,
S3 gateway, WebDAV gateway, and Admin UI).
S3 gateway with its message queue broker, WebDAV gateway, and Admin UI).
All settings are optimized for small/dev use cases:
- Volume size limit: auto configured based on disk space (64MB-1024MB)
@@ -378,6 +383,7 @@ After starting, you can access:
- Iceberg Catalog: http://localhost:8181
- WebDAV: http://localhost:7333
- Admin UI: http://localhost:12535
- MQ Broker: localhost:17777 (gRPC; -mq.broker=false to turn off)
S3 Access:
The S3 endpoint is available at http://localhost:8333. For client
@@ -582,6 +588,22 @@ func initMiniS3Flags() {
// In mini mode, S3 uses the shared debug server started at line 681, not its own separate debug server
miniS3Options.debug = new(bool) // explicitly false
miniS3Options.debugPort = cmdMini.Flag.Int("s3.debug.port", 6060, "http port for debugging (unused in mini mode)")
miniEnableMqBroker = cmdMini.Flag.Bool("mq.broker", true, "start a message queue broker beside the S3 gateway, on its own gRPC port, with or without grpc.msg_broker TLS")
miniMqBrokerOptions.port = cmdMini.Flag.Int("mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
}
// miniRunsMqBroker reports whether mini starts the broker beside its S3 gateway.
func miniRunsMqBroker() bool {
return *miniEnableS3 && *miniEnableMqBroker
}
// miniMqBrokerAddress is the broker address for the welcome banner, or empty
// when the broker is off or did not bind.
func miniMqBrokerAddress() string {
if !miniRunsMqBroker() || !miniMqBrokerOptions.bound.Load() {
return ""
}
return util.JoinHostPort(*miniIp, *miniMqBrokerOptions.port)
}
// initMiniWebDAVFlags initializes WebDAV server flag options
@@ -967,6 +989,16 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
}{miniS3Options.portLance, "Lance", "s3.port.lance", nil, listenOnLocalhost})
}
}
if miniRunsMqBroker() {
// The broker port is itself gRPC; there is no derived port to reserve.
portConfigs = append(portConfigs, struct {
port *int
name string
flagName string
grpcPtr *int
localhost bool
}{miniMqBrokerOptions.port, "MQ Broker", "mq.broker.port", nil, listenOnLocalhost})
}
if *miniVector {
portConfigs = append(portConfigs, struct {
port *int
@@ -1005,14 +1037,21 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
// First, reserve all gRPC ports that will be calculated to prevent HTTP port allocation from using them
// This prevents collisions like: HTTP port moves to X, then gRPC port is calculated as Y where Y == X
reservedPorts := make(map[int]bool)
for _, config := range portConfigs {
if config.grpcPtr != nil && *config.grpcPtr == 0 {
// This gRPC port will be calculated as httpPort + GrpcPortOffset
calculatedGrpcPort := *config.port + GrpcPortOffset
reservedPorts[calculatedGrpcPort] = true
reserveGrpcPorts := func() map[int]bool {
reserved := make(map[int]bool)
for _, config := range portConfigs {
if config.grpcPtr != nil && *config.grpcPtr == 0 {
// This gRPC port will be calculated as httpPort + GrpcPortOffset
reserved[*config.port+GrpcPortOffset] = true
} else if config.grpcPtr != nil {
// A gRPC port given outright is reserved too, or a port without a
// gRPC companion (the broker's) could take it first.
reserved[*config.grpcPtr] = true
}
}
return reserved
}
reservedPorts := reserveGrpcPorts()
chosenPorts := make(map[int]string)
for _, config := range portConfigs {
@@ -1053,10 +1092,10 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
if *config.port > 0 {
chosenPorts[*config.port] = config.flagName
}
// If port was changed, update the reserved gRPC ports mapping
// If port was changed, rebuild the reserved gRPC ports: the old derived
// port may also be another service's explicit gRPC port.
if *config.port != original && config.grpcPtr != nil && *config.grpcPtr == 0 {
delete(reservedPorts, original+GrpcPortOffset)
reservedPorts[*config.port+GrpcPortOffset] = true
reservedPorts = reserveGrpcPorts()
}
}
@@ -1163,6 +1202,9 @@ func initializeGrpcPortsOnIP(bindIp string, listenOnLocalhost bool) map[int]bool
allocatedPorts[*miniS3Options.portLance] = true
}
}
if miniRunsMqBroker() {
allocatedPorts[*miniMqBrokerOptions.port] = true
}
if *miniVector {
allocatedPorts[*miniVectorPort] = true
@@ -1549,6 +1591,13 @@ func runMini(cmd *Command, args []string) bool {
miniS3Options.ip = miniIp
miniS3Options.bindIp = miniBindIp
miniS3Options.listenOnLocalhost = &listenOnLocalhost
miniS3Options.mqBroker = nil
miniMqBrokerOptions.bound.Store(false)
if miniRunsMqBroker() {
miniS3Options.mqBroker = miniS3Options.brokerBeside(&miniMqBrokerOptions)
miniMqBrokerOptions.dataCenter = miniDataCenter
miniMqBrokerOptions.rack = miniRack
}
webDavBindIP := miniWebDavBindIP(*miniBindIp)
if *miniEnableWebDAV && webDavBindIP != *miniBindIp {
glog.Warningf("WebDAV has no authentication; binding it to %s instead of %s. Set [webdav.basic_auth] in security.toml, or use -webdav.allowInsecureBind to keep the network bind.", webDavBindIP, *miniBindIp)
@@ -1822,6 +1871,9 @@ func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) {
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
defer reportMiniStopped("Lance")
}
if miniRunsMqBroker() {
defer reportMiniStopped("MQ Broker")
}
startMiniService("S3", startS3Service, *miniS3Options.port)
}()
}
@@ -1872,6 +1924,19 @@ func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) {
glog.Warningf("Lance namespace server on port %d did not start; see S3 startup log", *miniS3Options.portLance)
}
}
if miniRunsMqBroker() {
// The S3 gateway binds the broker before it serves, so this is final.
if miniMqBrokerOptions.bound.Load() {
if miniProgressBoard != nil {
miniProgressBoard.ready("MQ Broker")
}
} else {
if miniProgressBoard != nil {
miniProgressBoard.failed("MQ Broker")
}
glog.Warningf("message queue broker on port %d did not start; see S3 startup log", *miniMqBrokerOptions.port)
}
}
}
if *miniEnableWebDAV {
waitForServiceReady("WebDAV", *miniWebDavOptions.port, *miniWebDavOptions.ipBind)
@@ -2392,6 +2457,9 @@ func printWelcomeMessage() {
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
fmt.Fprintf(&sb, " Lance Namespace: http://%s:%d\n", *miniIp, *miniS3Options.portLance)
}
if addr := miniMqBrokerAddress(); addr != "" {
fmt.Fprintf(&sb, " MQ Broker: %s (gRPC)\n", addr)
}
}
if *miniEnableAdminUI {
fmt.Fprintf(&sb, " Admin UI: http://%s\n", adminHTTPAddress)
+179
View File
@@ -0,0 +1,179 @@
package command
import (
"net"
"strconv"
"strings"
"testing"
)
func TestMqBrokerDefaultPortBelowEphemeralFloor(t *testing.T) {
if defaultMqBrokerPort >= linuxEphemeralPortFloor {
t.Fatalf("default broker port %d must stay below the ephemeral floor %d", defaultMqBrokerPort, linuxEphemeralPortFloor)
}
for _, c := range []struct {
name string
cmd *Command
flag string
}{
{"mini", cmdMini, "mq.broker.port"},
{"s3", cmdS3, "mq.broker.port"},
{"server", cmdServer, "mq.broker.port"},
{"mq.broker", cmdMqBroker, "port"},
} {
flag := c.cmd.Flag.Lookup(c.flag)
if flag == nil {
t.Fatalf("%s: flag -%s not registered", c.name, c.flag)
}
if flag.DefValue != strconv.Itoa(defaultMqBrokerPort) {
t.Errorf("%s -%s default = %s, want %d", c.name, c.flag, flag.DefValue, defaultMqBrokerPort)
}
}
if flag := cmdMini.Flag.Lookup("mq.broker"); flag == nil || flag.DefValue != "true" {
t.Fatalf("mini -mq.broker should default to true, got %v", flag)
}
}
func TestMiniRunsMqBrokerOnlyBesideS3(t *testing.T) {
// Mini keeps its broker on by default without grpc.msg_broker TLS.
withMqBrokerTLS(t, false)
oldS3, oldBroker := *miniEnableS3, *miniEnableMqBroker
defer func() { *miniEnableS3, *miniEnableMqBroker = oldS3, oldBroker }()
for _, tc := range []struct {
s3, broker, want bool
}{
{true, true, true},
{true, false, false},
{false, true, false},
{false, false, false},
} {
*miniEnableS3, *miniEnableMqBroker = tc.s3, tc.broker
if got := miniRunsMqBroker(); got != tc.want {
t.Errorf("-s3=%v -mq.broker=%v: runs broker %v, want %v", tc.s3, tc.broker, got, tc.want)
}
}
}
// The broker port takes part in mini's port layout, so it cannot silently
// share a port with another mini service.
func TestMiniMqBrokerPortJoinsPortLayout(t *testing.T) {
oldS3, oldBroker, oldS3Port, oldBrokerPort, oldVector, oldFlags := *miniEnableS3, *miniEnableMqBroker, *miniS3Options.port, *miniMqBrokerOptions.port, *miniVector, explicitFlags
defer func() {
*miniEnableS3, *miniEnableMqBroker, *miniS3Options.port, *miniMqBrokerOptions.port, *miniVector, explicitFlags = oldS3, oldBroker, oldS3Port, oldBrokerPort, oldVector, oldFlags
}()
*miniEnableS3, *miniEnableMqBroker, *miniVector = true, true, false
*miniS3Options.port = 8333
*miniMqBrokerOptions.port = 8333
explicitFlags = map[string]bool{"s3.port": true, "mq.broker.port": true}
err := ensureAllPortsAvailableOnIP("127.0.0.1", false)
if err == nil || !strings.Contains(err.Error(), "shared by explicit flags s3.port and mq.broker.port") {
t.Fatalf("broker port conflict not rejected: %v", err)
}
}
func TestMiniExplicitS3GrpcPortIsReservedFromBroker(t *testing.T) {
saved := []*int{miniMasterOptions.port, miniFilerOptions.port, miniOptions.v.port, miniS3Options.port,
miniS3Options.portGrpc, miniS3Options.portIceberg, miniS3Options.portLance, miniMqBrokerOptions.port}
values := make([]int, len(saved))
for i, p := range saved {
values[i] = *p
}
oldS3, oldBroker, oldVector, oldWebDav, oldFlags := *miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags
defer func() {
for i, p := range saved {
*p = values[i]
}
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags = oldS3, oldBroker, oldVector, oldWebDav, oldFlags
}()
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV = true, true, false, false
*miniS3Options.portIceberg, *miniS3Options.portLance = 0, 0
port := freePort(t)
*miniS3Options.portGrpc, *miniMqBrokerOptions.port = port, port
explicitFlags = map[string]bool{"s3.port.grpc": true, "mq.broker.port": true}
err := ensureAllPortsAvailableOnIP("127.0.0.1", false)
if err == nil || !strings.Contains(err.Error(), "mq.broker.port") {
t.Fatalf("explicit broker port on the explicit S3 gRPC port not rejected: %v", err)
}
}
// The filer's HTTP port is taken, so it moves; its old derived gRPC port is
// also the explicit S3 gRPC port, which must stay reserved from the broker.
func TestMiniMovedFilerKeepsExplicitS3GrpcPortReserved(t *testing.T) {
saved := []*int{miniMasterOptions.port, miniFilerOptions.port, miniFilerOptions.portGrpc, miniOptions.v.port, miniS3Options.port,
miniS3Options.portGrpc, miniS3Options.portIceberg, miniS3Options.portLance, miniMqBrokerOptions.port}
values := make([]int, len(saved))
for i, p := range saved {
values[i] = *p
}
oldS3, oldBroker, oldVector, oldWebDav, oldFlags := *miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags
defer func() {
for i, p := range saved {
*p = values[i]
}
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV, explicitFlags = oldS3, oldBroker, oldVector, oldWebDav, oldFlags
}()
var held net.Listener
filerPort := 0
for p := 20000; p < 30000 && held == nil; p += 7 {
l, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(p))
if err != nil {
continue
}
if probe, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(p+GrpcPortOffset)); err == nil {
probe.Close()
held, filerPort = l, p
} else {
l.Close()
}
}
if held == nil {
t.Skip("no free port pair")
}
defer held.Close()
*miniEnableS3, *miniEnableMqBroker, *miniVector, *miniEnableWebDAV = true, true, false, false
*miniS3Options.portIceberg, *miniS3Options.portLance = 0, 0
*miniFilerOptions.port, *miniFilerOptions.portGrpc = filerPort, 0
*miniS3Options.portGrpc, *miniMqBrokerOptions.port = filerPort+GrpcPortOffset, filerPort+GrpcPortOffset
explicitFlags = map[string]bool{"s3.port.grpc": true, "mq.broker.port": true}
err := ensureAllPortsAvailableOnIP("127.0.0.1", false)
if err == nil || !strings.Contains(err.Error(), "mq.broker.port") {
t.Fatalf("explicit broker port on the explicit S3 gRPC port not rejected after the filer moved: %v", err)
}
}
func TestMiniListsMqBrokerOnlyWhenRunning(t *testing.T) {
oldS3, oldBroker, oldIp, oldPort := *miniEnableS3, *miniEnableMqBroker, *miniIp, *miniMqBrokerOptions.port
defer func() {
*miniEnableS3, *miniEnableMqBroker, *miniIp, *miniMqBrokerOptions.port = oldS3, oldBroker, oldIp, oldPort
miniMqBrokerOptions.bound.Store(false)
}()
*miniIp, *miniMqBrokerOptions.port = "127.0.0.1", 17777
hasRow := func() bool {
for _, s := range miniStartupServices() {
if s == "MQ Broker" {
return true
}
}
return false
}
for _, tc := range []struct {
name string
s3, broker, bound bool
wantRow bool
wantAddr string
}{
{"running", true, true, true, true, "127.0.0.1:17777"},
{"failed to bind", true, true, false, true, ""},
{"turned off", true, false, false, false, ""},
{"no S3", false, true, false, false, ""},
} {
*miniEnableS3, *miniEnableMqBroker = tc.s3, tc.broker
miniMqBrokerOptions.bound.Store(tc.bound)
if got := hasRow(); got != tc.wantRow {
t.Errorf("%s: progress row %v, want %v", tc.name, got, tc.wantRow)
}
if got := miniMqBrokerAddress(); got != tc.wantAddr {
t.Errorf("%s: banner address %q, want %q", tc.name, got, tc.wantAddr)
}
}
}
+2 -2
View File
@@ -15,7 +15,7 @@ func TestMiniDefaultPluginJobTypes(t *testing.T) {
if err != nil {
t.Fatalf("buildPluginWorkerHandlers(mini default) err = %v", err)
}
if len(handlers) != 9 {
t.Fatalf("expected mini default job types to include 9 handlers, got %d", len(handlers))
if len(handlers) != 10 {
t.Fatalf("expected mini default job types to include 10 handlers, got %d", len(handlers))
}
}
+99 -30
View File
@@ -1,6 +1,11 @@
package command
import (
"context"
"fmt"
"net"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
@@ -17,6 +22,11 @@ var (
mqBrokerStandaloneOptions MessageQueueBrokerOptions
)
const (
defaultMqBrokerPort = 17777
defaultMqBrokerLogFlushInterval = 5
)
type MessageQueueBrokerOptions struct {
masters map[string]pb.ServerAddress
mastersString *string
@@ -32,6 +42,15 @@ type MessageQueueBrokerOptions struct {
logFlushInterval *int
debug *bool
debugPort *int
// shutdownCtx, when non-nil, stops the broker once cancelled, in addition
// to on interrupt. Set by commands that embed the broker; not a flag.
shutdownCtx context.Context
// bound records whether the gRPC port is bound, so weed mini lists the
// broker only when it runs; not a flag.
bound atomic.Bool
// TLS options listenQueueServer loads for serveQueueServer.
grpcDialOption grpc.DialOption
grpcServerOptions []grpc.ServerOption
}
func init() {
@@ -40,12 +59,12 @@ func init() {
mqBrokerStandaloneOptions.filerGroup = cmdMqBroker.Flag.String("filerGroup", "", "share metadata with other filers in the same filerGroup")
mqBrokerStandaloneOptions.ip = cmdMqBroker.Flag.String("ip", util.DetectedHostAddress(), "broker host address")
mqBrokerStandaloneOptions.ipBind = cmdMqBroker.Flag.String("ip.bind", "", "ip address to bind to. If empty, listen on all interfaces.")
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", 17777, "broker gRPC listen port")
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", defaultMqBrokerPort, "broker gRPC listen port")
mqBrokerStandaloneOptions.dataCenter = cmdMqBroker.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
mqBrokerStandaloneOptions.rack = cmdMqBroker.Flag.String("rack", "", "prefer to write to volumes in this rack")
mqBrokerStandaloneOptions.cpuprofile = cmdMqBroker.Flag.String("cpuprofile", "", "cpu profile output file")
mqBrokerStandaloneOptions.memprofile = cmdMqBroker.Flag.String("memprofile", "", "memory profile output file")
mqBrokerStandaloneOptions.logFlushInterval = cmdMqBroker.Flag.Int("logFlushInterval", 5, "log buffer flush interval in seconds")
mqBrokerStandaloneOptions.logFlushInterval = cmdMqBroker.Flag.Int("logFlushInterval", defaultMqBrokerLogFlushInterval, "log buffer flush interval in seconds")
mqBrokerStandaloneOptions.debug = cmdMqBroker.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
mqBrokerStandaloneOptions.debugPort = cmdMqBroker.Flag.Int("debug.port", 6060, "http port for debugging")
}
@@ -68,20 +87,68 @@ func runMqBroker(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
mqBrokerStandaloneOptions.masters = pb.ServerAddresses(*mqBrokerStandaloneOptions.mastersString).ToAddressMap()
return mqBrokerStandaloneOptions.startQueueServer()
}
func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
*mqBrokerStandaloneOptions.cpuprofile = util.ResolvePath(*mqBrokerStandaloneOptions.cpuprofile)
*mqBrokerStandaloneOptions.memprofile = util.ResolvePath(*mqBrokerStandaloneOptions.memprofile)
grace.SetupProfiling(*mqBrokerStandaloneOptions.cpuprofile, *mqBrokerStandaloneOptions.memprofile)
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.msg_broker")
mqBrokerStandaloneOptions.masters = pb.ServerAddresses(*mqBrokerStandaloneOptions.mastersString).ToAddressMap()
if err := mqBrokerStandaloneOptions.startQueueServer(); err != nil {
glog.Fatalf("%v", err)
}
return true
}
// startQueueServer serves the broker until it is interrupted or shutdownCtx is
// cancelled. It returns an error only when the broker could not start.
func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() error {
grpcL, localL, err := mqBrokerOpt.listenQueueServer()
if err != nil {
return err
}
return mqBrokerOpt.serveQueueServer(grpcL, localL)
}
// listenQueueServer loads the broker's TLS config and binds its gRPC port.
// Bind before creating the broker: it registers with the master as soon as
// it exists, and a broker that cannot serve must not.
func (mqBrokerOpt *MessageQueueBrokerOptions) listenQueueServer() (grpcL, localL net.Listener, err error) {
mqBrokerOpt.bound.Store(false)
// Returned, not fatal: a gateway's broker must not take the gateway down.
if mqBrokerOpt.grpcDialOption, err = security.TryLoadClientTLS(util.GetViper(), "grpc.msg_broker", "grpc.msg_broker"); err != nil {
return nil, nil, fmt.Errorf("message queue broker gRPC client TLS: %v", err)
}
tlsCreds, tlsVerify, err := security.TryLoadServerTLS(util.GetViper(), "grpc.msg_broker")
if err != nil {
return nil, nil, fmt.Errorf("message queue broker gRPC server TLS: %v", err)
}
mqBrokerOpt.grpcServerOptions = append([]grpc.ServerOption{tlsCreds, tlsVerify}, broker.GrpcServerOptions()...)
// The loopback companion listener is only kept while -ip.bind is unset.
// An explicit -ip.bind pins the port to exactly that address.
listenOnLocalhost := *mqBrokerOpt.ipBind == ""
if mqBrokerOpt.listenOnLocalhost != nil {
listenOnLocalhost = *mqBrokerOpt.listenOnLocalhost
}
grpcL, localL, err = util.NewIpAndLocalListeners(*mqBrokerOpt.ipBind, *mqBrokerOpt.port, 0, listenOnLocalhost)
if err != nil {
return nil, nil, fmt.Errorf("message queue broker failed to listen on grpc port %d: %v", *mqBrokerOpt.port, err)
}
mqBrokerOpt.bound.Store(true)
return grpcL, localL, nil
}
// boundAddress is the address the broker registers with the master, or empty
// when it is not running.
func (mqBrokerOpt *MessageQueueBrokerOptions) boundAddress() pb.ServerAddress {
if mqBrokerOpt == nil || !mqBrokerOpt.bound.Load() {
return ""
}
return pb.ServerAddress(util.JoinHostPort(*mqBrokerOpt.ip, *mqBrokerOpt.port))
}
func (mqBrokerOpt *MessageQueueBrokerOptions) serveQueueServer(grpcL, localL net.Listener) error {
qs, err := broker.NewMessageBroker(&broker.MessageQueueBrokerOption{
Masters: mqBrokerOpt.masters,
FilerGroup: *mqBrokerOpt.filerGroup,
@@ -92,35 +159,27 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
Ip: *mqBrokerOpt.ip,
Port: *mqBrokerOpt.port,
LogFlushInterval: *mqBrokerOpt.logFlushInterval,
}, grpcDialOption)
}, mqBrokerOpt.grpcDialOption)
if err != nil {
glog.Fatalf("failed to create new message broker for queue server: %v", err)
}
// The loopback companion listener is only kept while -ip.bind is unset.
// An explicit -ip.bind pins the port to exactly that address.
listenOnLocalhost := *mqBrokerOpt.ipBind == ""
if mqBrokerOpt.listenOnLocalhost != nil {
listenOnLocalhost = *mqBrokerOpt.listenOnLocalhost
}
// start grpc listener
grpcL, localL, err := util.NewIpAndLocalListeners(*mqBrokerOpt.ipBind, *mqBrokerOpt.port, 0, listenOnLocalhost)
if err != nil {
glog.Fatalf("failed to listen on grpc port %d: %v", *mqBrokerOpt.port, err)
mqBrokerOpt.bound.Store(false)
grpcL.Close()
if localL != nil {
localL.Close()
}
return fmt.Errorf("failed to create new message broker for queue server: %v", err)
}
// Create main gRPC server
tlsCreds, tlsVerify := security.LoadServerTLS(util.GetViper(), "grpc.msg_broker")
serverOptions := append([]grpc.ServerOption{tlsCreds, tlsVerify}, broker.GrpcServerOptions()...)
serverOptions := mqBrokerOpt.grpcServerOptions
grpcS := pb.NewGrpcServer(serverOptions...)
mq_pb.RegisterSeaweedMessagingServer(grpcS, qs)
reflection.Register(grpcS)
grace.OnInterrupt(grpcS.Stop)
// Start localhost listener if available
var localGrpcS *grpc.Server
if localL != nil {
localGrpcS := pb.NewGrpcServer(serverOptions...)
localGrpcS = pb.NewGrpcServer(serverOptions...)
mq_pb.RegisterSeaweedMessagingServer(localGrpcS, qs)
reflection.Register(localGrpcS)
grace.OnInterrupt(localGrpcS.Stop)
@@ -133,12 +192,22 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
}
// Hooks run last-registered first: flush the partitions, then drop the connections.
grace.OnInterrupt(qs.Stop)
if mqBrokerOpt.shutdownCtx != nil {
go func() {
<-mqBrokerOpt.shutdownCtx.Done()
qs.Stop()
if localGrpcS != nil {
localGrpcS.Stop()
}
grpcS.Stop()
}()
}
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ipBind, *mqBrokerOpt.port)
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
glog.Errorf("Failed to serve MQ Broker: %v", err)
}
return true
return nil
}
+87
View File
@@ -0,0 +1,87 @@
package command
import (
"context"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
func testBrokerOptions(port int) *MessageQueueBrokerOptions {
bind := "127.0.0.1"
empty := ""
noLocalhost := false
flushInterval := 5
return &MessageQueueBrokerOptions{
// Nothing listens here; the broker keeps retrying until stopped.
masters: map[string]pb.ServerAddress{"127.0.0.1:1": "127.0.0.1:1"},
filerGroup: &empty,
ip: &bind,
ipBind: &bind,
listenOnLocalhost: &noLocalhost,
port: &port,
dataCenter: &empty,
rack: &empty,
logFlushInterval: &flushInterval,
}
}
func freePort(t *testing.T) int {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
return port
}
func TestQueueServerReturnsErrorOnOccupiedPort(t *testing.T) {
opt := testBrokerOptions(holdPort(t))
errCh := make(chan error, 1)
go func() { errCh <- opt.startQueueServer() }()
select {
case err := <-errCh:
if err == nil {
t.Fatal("startQueueServer on an occupied port returned nil")
}
case <-time.After(5 * time.Second):
t.Fatal("startQueueServer did not return for an occupied port")
}
}
func TestQueueServerStopsOnShutdownCtx(t *testing.T) {
port := freePort(t)
opt := testBrokerOptions(port)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
opt.shutdownCtx = ctx
errCh := make(chan error, 1)
go func() { errCh <- opt.startQueueServer() }()
deadline := time.Now().Add(5 * time.Second)
for {
conn, err := net.Dial("tcp", pb.NewServerAddress("127.0.0.1", port, 0).String())
if err == nil {
conn.Close()
break
}
if time.Now().After(deadline) {
t.Fatalf("broker never listened on %d: %v", port, err)
}
time.Sleep(20 * time.Millisecond)
}
cancel()
select {
case err := <-errCh:
if err != nil {
t.Fatalf("startQueueServer = %v after a clean stop", err)
}
case <-time.After(10 * time.Second):
t.Fatal("broker did not stop when shutdownCtx was cancelled")
}
}
+145 -1
View File
@@ -40,7 +40,9 @@ import (
)
var (
s3StandaloneOptions S3Options
s3StandaloneOptions S3Options
s3StandaloneMqBrokerOptions MessageQueueBrokerOptions
s3StandaloneStartMqBroker *bool
)
// S3Options holds CLI flags for the S3 gateway.
@@ -117,6 +119,9 @@ type S3Options struct {
// lanceWorkerKey is set by mini for the weed-worker it starts when the
// cluster has no jwt.filer_signing.key; not a flag.
lanceWorkerKey security.SigningKey
// mqBroker, when set by the command, is the message queue broker started
// beside this gateway once the filer is reached; not a flag.
mqBroker *MessageQueueBrokerOptions
}
func init() {
@@ -169,6 +174,30 @@ func init() {
s3StandaloneOptions.routedLookupTimeout = cmdS3.Flag.Duration("routedLookupTimeout", defaultS3RoutedLookupTimeout, s3RoutedLookupTimeoutUsage)
s3StandaloneOptions.unreachableOwnerTTL = cmdS3.Flag.Duration("unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage)
s3StandaloneOptions.volumeLookupTimeout = cmdS3.Flag.Duration("volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage)
s3StandaloneStartMqBroker = cmdS3.Flag.Bool("mq.broker", false, mqBrokerBesideS3Usage)
s3StandaloneMqBrokerOptions.port = cmdS3.Flag.Int("mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
}
const mqBrokerBesideS3Usage = "start a message queue broker beside the S3 gateway, on its own gRPC port; it joins the cluster like any other broker. When not set, it starts only if grpc.msg_broker has a cert and key in security.toml"
// mqBrokerTLSConfigured reports whether security.toml gives the broker a
// server cert and key. Without them the broker serves any peer.
func mqBrokerTLSConfigured() bool {
v := util.GetViper()
return v.GetString("grpc.msg_broker.cert") != "" && v.GetString("grpc.msg_broker.key") != ""
}
// wantsMqBrokerBesideS3 decides the broker beside a gateway: a flag given on
// the command line wins, and an unset one starts it only with TLS.
func wantsMqBrokerBesideS3(flagName string, value, passed bool) bool {
if passed {
return value
}
if mqBrokerTLSConfigured() {
return true
}
glog.V(0).Infof("message queue broker beside the S3 gateway is off: grpc.msg_broker TLS is not configured; -%s=true runs it without TLS", flagName)
return false
}
var cmdS3 = &Command{
@@ -259,6 +288,13 @@ var cmdS3 = &Command{
and no configuration is available from the filer. This provides a simple way
to get started without requiring configuration files.
When grpc.msg_broker has a cert and key in security.toml, the gateway
also runs a message queue broker on -mq.broker.port (17777), a separate
gRPC server that finds the masters through the filer and joins the
cluster like any other broker. -mq.broker=true runs it without TLS too,
and -mq.broker=false never runs it. If the broker cannot start, for
example because the port is taken, the gateway logs it and keeps serving.
`,
}
@@ -278,6 +314,13 @@ func runS3(cmd *Command, args []string) bool {
}
go stats_collect.StartMetricsServer(*s3StandaloneOptions.metricsHttpIp, *s3StandaloneOptions.metricsHttpPort)
if wantsMqBrokerBesideS3("mq.broker", *s3StandaloneStartMqBroker, isFlagExplicitlySet(cmdS3, "mq.broker")) {
s3StandaloneOptions.mqBroker = s3StandaloneOptions.brokerBeside(&s3StandaloneMqBrokerOptions)
if err := s3StandaloneOptions.checkMqBrokerPort("mq.broker.port", isFlagExplicitlySet(cmdS3, "mq.broker.port")); err != nil {
glog.Fatalf("%v", err)
}
}
return s3StandaloneOptions.startS3Server()
}
@@ -367,6 +410,7 @@ func (s3opt *S3Options) startS3Server() bool {
}
}
adoptFilerDigest(*s3opt.filer, filerDigest)
s3opt.startMqBroker(masterAddresses, filerGroup)
go stats_collect.LoopPushingMetric("s3", stats_collect.SourceName(uint32(*s3opt.port)), metricsAddress, metricsIntervalSec)
@@ -448,6 +492,7 @@ func (s3opt *S3Options) startS3Server() bool {
AllowBackslashInKey: *s3opt.allowBackslashInKey,
LancePort: s3opt.lancePort(),
S3Endpoint: s3opt.s3Endpoint(),
MqBroker: s3opt.mqBroker.boundAddress(),
IamSelfServiceRequiresGrant: *s3opt.iamSelfServiceRequiresGrant,
RoutedLookupTimeout: *s3opt.routedLookupTimeout,
UnreachableOwnerTTL: *s3opt.unreachableOwnerTTL,
@@ -630,6 +675,105 @@ func (s3opt *S3Options) startS3Server() bool {
}
// gatewayPorts lists the ports the gateway binds itself, the derived gRPC
// port included.
func (s3opt *S3Options) gatewayPorts() []int {
ports := []int{*s3opt.port}
grpcPort := 10000 + *s3opt.port
if s3opt.portGrpc != nil && *s3opt.portGrpc != 0 {
grpcPort = *s3opt.portGrpc
}
ports = append(ports, grpcPort)
if s3opt.tlsPrivateKey != nil && *s3opt.tlsPrivateKey != "" && s3opt.portHttps != nil && *s3opt.portHttps > 0 {
ports = append(ports, *s3opt.portHttps)
}
for _, p := range []*int{s3opt.portIceberg, s3opt.portLance, s3opt.metricsHttpPort} {
if p != nil && *p > 0 {
ports = append(ports, *p)
}
}
return ports
}
// checkMqBrokerPort keeps the broker off the gateway's own ports and off
// processPorts, those of the servers started with it: the broker can bind
// first, and a server exits when its port is taken. A default port that
// clashes drops the broker; a port given as flagName is an error.
func (s3opt *S3Options) checkMqBrokerPort(flagName string, explicit bool, processPorts ...int) error {
b := s3opt.mqBroker
if b == nil {
return nil
}
for _, port := range append(s3opt.gatewayPorts(), processPorts...) {
if port != *b.port {
continue
}
if explicit {
return fmt.Errorf("-%s=%d is also a port of the S3 gateway or a server started with it", flagName, port)
}
glog.Warningf("not starting the message queue broker: its default port %d is a port of the S3 gateway or a server started with it; set -%s to run it", port, flagName)
s3opt.mqBroker = nil
return nil
}
return nil
}
// brokerBeside points b at the address this gateway binds and advertises.
// Call it before startS3Server, which rewrites an empty -ip.bind.
func (s3opt *S3Options) brokerBeside(b *MessageQueueBrokerOptions) *MessageQueueBrokerOptions {
advertised := (&s3api.S3ApiServerOption{Ip: *s3opt.ip, BindIp: *s3opt.bindIp}).AdvertisedHost()
bindIp := *s3opt.bindIp
listenOnLocalhost := bindIp == ""
if s3opt.listenOnLocalhost != nil {
listenOnLocalhost = *s3opt.listenOnLocalhost
}
b.ip = &advertised
b.ipBind = &bindIp
b.listenOnLocalhost = &listenOnLocalhost
b.dataCenter = s3opt.dataCenter
if b.rack == nil {
b.rack = new(string)
}
if b.logFlushInterval == nil {
flushInterval := defaultMqBrokerLogFlushInterval
b.logFlushInterval = &flushInterval
}
return b
}
// startMqBroker starts the gateway's broker on its own port and lifecycle. A
// broker that cannot start is logged and the gateway keeps serving.
func (s3opt *S3Options) startMqBroker(masters []pb.ServerAddress, filerGroup string) {
b := s3opt.mqBroker
if b == nil {
return
}
if len(masters) == 0 {
glog.Warningf("S3 gateway not starting its message queue broker: filers %s reported no masters", *s3opt.filer)
return
}
b.masters = make(map[string]pb.ServerAddress, len(masters))
for _, master := range masters {
b.masters[string(master)] = master
}
b.filerGroup = &filerGroup
b.shutdownCtx = s3opt.shutdownCtx
// Bind here, before the gateway serves, so once the S3 port answers
// b.bound is final, as for the auxiliary catalogs.
grpcL, localL, err := b.listenQueueServer()
if err != nil {
glog.Errorf("S3 gateway continues without its message queue broker: %v", err)
return
}
done := trackMiniClient()
go func() {
defer done()
if err := b.serveQueueServer(grpcL, localL); err != nil {
glog.Errorf("S3 gateway continues without its message queue broker: %v", err)
}
}()
}
func (s3opt *S3Options) newShutdown(stopGrpc func(), s3ApiServer *s3api.S3ApiServer, httpServers []*http.Server) func() {
shutdown := newGracefulShutdown(stopGrpc, s3ApiServer.Shutdown, httpServers...)
var cancelled <-chan struct{}
+258
View File
@@ -0,0 +1,258 @@
package command
import (
"context"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestS3MqBrokerFlagDefaults(t *testing.T) {
for name, want := range map[string]string{
"mq.broker": "false",
"mq.broker.port": "17777",
} {
flag := cmdS3.Flag.Lookup(name)
if flag == nil {
t.Fatalf("weed s3 does not expose -%s", name)
}
if flag.DefValue != want {
t.Errorf("-%s default = %q, want %q", name, flag.DefValue, want)
}
}
}
// withMqBrokerTLS sets or clears grpc.msg_broker cert and key for the test.
func withMqBrokerTLS(t *testing.T, on bool) {
t.Helper()
v := util.GetViper()
cert, key := "", ""
if on {
cert, key = "/etc/seaweedfs/broker.crt", "/etc/seaweedfs/broker.key"
}
v.Set("grpc.msg_broker.cert", cert)
v.Set("grpc.msg_broker.key", key)
t.Cleanup(func() {
v.Set("grpc.msg_broker.cert", "")
v.Set("grpc.msg_broker.key", "")
})
}
// The cases the flag of weed s3, weed server and weed filer share.
var mqBrokerDefaultCases = []struct {
name string
tls, value, passed bool
want bool
}{
{"unset with TLS", true, false, false, true},
{"unset without TLS", false, false, false, false},
{"explicit true without TLS", false, true, true, true},
{"explicit false with TLS", true, false, true, false},
}
func TestS3MqBrokerStartsByDefaultOnlyWithTLS(t *testing.T) {
for _, tc := range mqBrokerDefaultCases {
t.Run(tc.name, func(t *testing.T) {
withMqBrokerTLS(t, tc.tls)
if got := wantsMqBrokerBesideS3("mq.broker", tc.value, tc.passed); got != tc.want {
t.Errorf("weed s3 runs broker %v, want %v", got, tc.want)
}
})
}
}
func TestS3BrokerBesideAdvertisesGatewayAddress(t *testing.T) {
detected := util.DetectedHostAddress()
for _, tc := range []struct {
name, ip, bindIp string
wantIp string
wantLocalhostPeer bool
}{
{"defaults bind everywhere and advertise the detected address", "", "", detected, true},
{"explicit bind is advertised and pinned", "", "10.0.0.5", "10.0.0.5", false},
{"advertised ip wins over a wildcard bind", "s3.example.com", "0.0.0.0", "s3.example.com", false},
} {
t.Run(tc.name, func(t *testing.T) {
ip, bindIp, dc := tc.ip, tc.bindIp, "dc1"
s3opt := &S3Options{ip: &ip, bindIp: &bindIp, dataCenter: &dc}
b := s3opt.brokerBeside(&MessageQueueBrokerOptions{})
if *b.ip != tc.wantIp {
t.Errorf("broker ip = %q, want %q", *b.ip, tc.wantIp)
}
if *b.ipBind != tc.bindIp {
t.Errorf("broker ip.bind = %q, want %q", *b.ipBind, tc.bindIp)
}
if *b.listenOnLocalhost != tc.wantLocalhostPeer {
t.Errorf("broker listenOnLocalhost = %v, want %v", *b.listenOnLocalhost, tc.wantLocalhostPeer)
}
if *b.dataCenter != "dc1" || *b.rack != "" || *b.logFlushInterval != defaultMqBrokerLogFlushInterval {
t.Errorf("broker dc/rack/flush = %q/%q/%d", *b.dataCenter, *b.rack, *b.logFlushInterval)
}
// startS3Server rewrites an empty -ip.bind; the broker keeps its copy.
bindIp = "0.0.0.0"
if *b.ipBind != tc.bindIp {
t.Errorf("broker ip.bind followed the gateway's rewrite to %q", *b.ipBind)
}
})
}
}
// startMqBroker hands the broker the masters and filer group the gateway read
// from its filer, and ties it to the gateway's shutdown.
func startTestGatewayBroker(t *testing.T, port int) *MessageQueueBrokerOptions {
t.Helper()
savedClients, savedClusterCtx := miniClients, MiniClusterCtx
t.Cleanup(func() { miniClients, MiniClusterCtx = savedClients, savedClusterCtx })
clusterCtx, stopCluster := context.WithCancel(context.Background())
t.Cleanup(stopCluster)
MiniClusterCtx = clusterCtx
resetMiniClients()
filer := "127.0.0.1:2"
b := testBrokerOptions(port)
s3opt := &S3Options{filer: &filer, shutdownCtx: miniClientsCtx(), mqBroker: b}
s3opt.startMqBroker([]pb.ServerAddress{"127.0.0.1:1"}, "group1")
if _, ok := b.masters["127.0.0.1:1"]; !ok || len(b.masters) != 1 || *b.filerGroup != "group1" {
t.Fatalf("broker masters %v filerGroup %q, want the filer's", b.masters, *b.filerGroup)
}
return b
}
func waitMiniClientsDrained(t *testing.T, within time.Duration) bool {
t.Helper()
clients := miniClients
drained := make(chan struct{})
go func() {
clients.wg.Wait()
close(drained)
}()
select {
case <-drained:
return true
case <-time.After(within):
return false
}
}
func TestS3GatewaySurvivesBrokerThatFailsToStart(t *testing.T) {
b := startTestGatewayBroker(t, holdPort(t))
// startMqBroker returned and the process, gateway included, is still here.
if b.bound.Load() {
t.Error("broker on an occupied port reported bound")
}
if address := b.boundAddress(); address != "" {
t.Errorf("broker on an occupied port has address %q", address)
}
if !waitMiniClientsDrained(t, 5*time.Second) {
t.Fatal("broker on an occupied port did not return")
}
}
// A bad grpc.msg_broker TLS config used to exit the process from inside the
// broker; the gateway must log it and keep serving.
func TestS3GatewaySurvivesBrokerTLSConfigError(t *testing.T) {
v := util.GetViper()
v.Set("grpc.msg_broker.cert", "/nonexistent/broker.crt")
t.Cleanup(func() { v.Set("grpc.msg_broker.cert", "") })
port := freePort(t)
b := startTestGatewayBroker(t, port)
if b.bound.Load() {
t.Error("broker with a bad TLS config reported bound")
}
if !waitMiniClientsDrained(t, 5*time.Second) {
t.Fatal("broker with a bad TLS config did not return")
}
l, err := net.Listen("tcp", pb.NewServerAddress("127.0.0.1", port, 0).String())
if err != nil {
t.Fatalf("broker port %d left bound after the TLS error: %v", port, err)
}
l.Close()
}
func TestS3GatewayBrokerStopsWithGateway(t *testing.T) {
b := startTestGatewayBroker(t, freePort(t))
if !b.bound.Load() {
t.Fatal("broker not bound once startMqBroker returned")
}
if want := pb.ServerAddress(util.JoinHostPort(*b.ip, *b.port)); b.boundAddress() != want {
t.Fatalf("bound address %q, want %q", b.boundAddress(), want)
}
if waitMiniClientsDrained(t, 300*time.Millisecond) {
t.Fatal("broker returned before the gateway shut down")
}
triggerMiniClientsShutdown(10 * time.Second)
if !waitMiniClientsDrained(t, time.Second) {
t.Fatal("broker still running after the gateway shut down")
}
}
func TestS3GatewayWithoutMastersSkipsBroker(t *testing.T) {
filer := "127.0.0.1:2"
b := testBrokerOptions(holdPort(t))
b.masters = nil
s3opt := &S3Options{filer: &filer, mqBroker: b}
s3opt.startMqBroker(nil, "")
if b.masters != nil {
t.Fatal("broker was started without masters")
}
}
func gatewayWithBroker(httpPort, grpcPort, brokerPort int) *S3Options {
filer, empty, zero := "127.0.0.1:2", "", 0
return &S3Options{
filer: &filer, port: &httpPort, portGrpc: &grpcPort, portHttps: &zero,
portIceberg: &zero, portLance: &zero, tlsPrivateKey: &empty,
mqBroker: testBrokerOptions(brokerPort),
}
}
func TestS3DefaultBrokerYieldsToGatewayPorts(t *testing.T) {
brokerPort := freePort(t)
for _, tc := range []struct {
name string
httpPort, grpcPort int
}{
{"-port whose derived gRPC port is the broker's", brokerPort - 10000, 0},
{"-port.grpc on the broker port", 8333, brokerPort},
{"-port on the broker port", brokerPort, 0},
} {
t.Run(tc.name, func(t *testing.T) {
s3opt := gatewayWithBroker(tc.httpPort, tc.grpcPort, brokerPort)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false); err != nil {
t.Fatalf("default broker port clash returned %v, want the broker skipped", err)
}
if s3opt.mqBroker != nil {
t.Fatal("broker kept a port the gateway binds")
}
// Nothing binds for the skipped broker, so the gateway still gets its port.
s3opt.startMqBroker([]pb.ServerAddress{"127.0.0.1:1"}, "")
l, err := net.Listen("tcp", pb.NewServerAddress("127.0.0.1", brokerPort, 0).String())
if err != nil {
t.Fatalf("gateway port %d taken: %v", brokerPort, err)
}
l.Close()
})
}
}
func TestS3ExplicitBrokerPortClashIsRejected(t *testing.T) {
for _, s3opt := range []*S3Options{
gatewayWithBroker(7777, 0, 17777),
gatewayWithBroker(8333, 17777, 17777),
} {
if err := s3opt.checkMqBrokerPort("mq.broker.port", true); err == nil {
t.Errorf("explicit -mq.broker.port on gateway port of %d/%d was accepted", *s3opt.port, *s3opt.portGrpc)
}
}
}
func TestS3BrokerPortOffTheGatewayIsKept(t *testing.T) {
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", true); err != nil || s3opt.mqBroker == nil {
t.Fatalf("broker on a free port dropped: %v", err)
}
}
+34
View File
@@ -200,6 +200,40 @@ upsertQuery = """
meta=EXCLUDED.meta
"""
[postgres_flat]
# Rows are keyed by their full path, which inside a bucket's table is the
# object key. Give it a database or schema apart from the postgres and
# postgres2 stores. The path index caps a path at about 2700 bytes.
enabled = false
createTable = """
CREATE TABLE IF NOT EXISTS "%s" (
path TEXT COLLATE "C" PRIMARY KEY,
directory TEXT NOT NULL,
name TEXT NOT NULL,
meta bytea
);
"""
hostname = "localhost"
port = 5432
username = "postgres"
password = ""
database = "postgres" # create or use an existing database
schema = ""
sslmode = "disable"
# sslcert = "/path/to/client.crt"
# sslkey = "/path/to/client.key"
# sslrootcert = "/path/to/ca.crt"
# sslcrl = "/path/to/client.crl"
connection_max_idle = 50
connection_max_lifetime_seconds = 300
pgbouncer_compatible = false
enableUpsert = true
upsertQuery = """
INSERT INTO "%[1]s" (path, directory, name, meta)
VALUES($1, $2, $3, $4)
ON CONFLICT (path) DO UPDATE SET meta=EXCLUDED.meta
"""
[cassandra2]
# CREATE TABLE filemeta (
# dirhash bigint,
+71 -4
View File
@@ -55,6 +55,9 @@ var cmdServer = &Command{
Optionally, a filer server can be started.
Also optionally, a S3 gateway can be started.
When grpc.msg_broker has a cert and key in security.toml, a S3 gateway
brings a message queue broker on -mq.broker.port; use -mq.broker=false
to leave it out, or -mq.broker=true to run a broker without TLS.
`,
}
@@ -84,7 +87,7 @@ var (
isStartingSftp = cmdServer.Flag.Bool("sftp", false, "whether to start Sftp server")
isStartingIam = cmdServer.Flag.Bool("iam", false, "whether to start IAM service")
isStartingWebDav = cmdServer.Flag.Bool("webdav", false, "whether to start WebDAV gateway")
isStartingMqBroker = cmdServer.Flag.Bool("mq.broker", false, "whether to start message queue broker")
isStartingMqBroker = cmdServer.Flag.Bool("mq.broker", false, "whether to start message queue broker; when not set, -s3 starts one beside the gateway if grpc.msg_broker has a cert and key in security.toml")
isStartingMqAgent = cmdServer.Flag.Bool("mq.agent", false, "whether to start message queue agent")
False = false
@@ -249,14 +252,65 @@ func init() {
webdavOptions.filerRootPath = cmdServer.Flag.String("webdav.filer.path", "/", "use this remote path from filer server")
webdavOptions.idleTimeout = cmdServer.Flag.Int("webdav.idleTimeout", 10, "connection idle seconds")
mqBrokerOptions.port = cmdServer.Flag.Int("mq.broker.port", 17777, "message queue broker gRPC listen port")
mqBrokerOptions.logFlushInterval = cmdServer.Flag.Int("mq.broker.logFlushInterval", 5, "log buffer flush interval in seconds")
mqBrokerOptions.port = cmdServer.Flag.Int("mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
mqBrokerOptions.logFlushInterval = cmdServer.Flag.Int("mq.broker.logFlushInterval", defaultMqBrokerLogFlushInterval, "log buffer flush interval in seconds")
mqAgentServerOptions.brokersString = cmdServer.Flag.String("mq.agent.brokers", "localhost:17777", "comma-separated message queue brokers")
mqAgentServerOptions.port = cmdServer.Flag.Int("mq.agent.port", 16777, "message queue agent gRPC listen port")
}
// serverRunsMqBrokerBesideS3 reports whether the S3 gateway starts the broker.
// -mq.broker (or -mq.agent) starts it on its own and a failure to start is
// fatal; -s3 with -mq.broker unset brings it along when grpc.msg_broker TLS
// is configured, and a failure is only logged, so a host that already runs a
// broker on the port keeps its gateway.
func serverRunsMqBrokerBesideS3(s3, broker, brokerFlagPassed bool) bool {
return s3 && !broker && wantsMqBrokerBesideS3("mq.broker", broker, brokerFlagPassed)
}
// withGrpc is a server's port and its gRPC port, derived when unset.
func withGrpc(port, portGrpc *int) []int {
if *portGrpc != 0 {
return []int{*port, *portGrpc}
}
return []int{*port, 10000 + *port}
}
// serverPortsBesideS3 lists the ports of the other servers weed server
// starts, derived gRPC ports included.
func serverPortsBesideS3() []int {
ports := []int{*serverMetricsHttpPort}
if *serverOptions.debug {
ports = append(ports, *serverOptions.debugPort)
}
if *isStartingMasterServer {
ports = append(ports, withGrpc(masterOptions.port, masterOptions.portGrpc)...)
}
if *isStartingVolumeServer {
ports = append(ports, withGrpc(serverOptions.v.port, serverOptions.v.portGrpc)...)
if *serverOptions.v.publicPort != 0 {
ports = append(ports, *serverOptions.v.publicPort)
}
}
if *isStartingFiler {
ports = append(ports, withGrpc(filerOptions.port, filerOptions.portGrpc)...)
if *filerOptions.publicPort != 0 {
ports = append(ports, *filerOptions.publicPort)
}
}
if *isStartingWebDav {
ports = append(ports, *webdavOptions.port)
}
if *isStartingSftp {
ports = append(ports, *sftpOptions.port)
}
if *isStartingIam {
ports = append(ports, *iamOptions.port)
}
return ports
}
// isServerFlagPassed checks if a specific flag was passed on the command line
func isServerFlagPassed(name string) bool {
found := false
@@ -307,6 +361,12 @@ func runServer(cmd *Command, args []string) bool {
*isStartingMqBroker = true
*isStartingFiler = true
}
if serverRunsMqBrokerBesideS3(*isStartingS3, *isStartingMqBroker, isServerFlagPassed("mq.broker")) {
s3Options.mqBroker = &mqBrokerOptions
if err := s3Options.checkMqBrokerPort("mq.broker.port", isServerFlagPassed("mq.broker.port"), serverPortsBesideS3()...); err != nil {
glog.Fatalf("%v", err)
}
}
var actualPeersForComponents string
var embeddedMaster atomic.Pointer[weed_server.MasterServer]
@@ -420,6 +480,11 @@ func runServer(cmd *Command, args []string) bool {
iamOptions.filer = &filerAddress
webdavOptions.filer = &filerAddress
mqBrokerOptions.filerGroup = filerOptions.filerGroup
if s3Options.mqBroker != nil {
// The broker beside the gateway binds where -s3.ip.bind puts it.
s3Options.brokerBeside(s3Options.mqBroker)
mqBrokerOptions.dataCenter = serverDataCenter
}
go stats_collect.StartMetricsServer(*serverMetricsHttpIp, *serverMetricsHttpPort)
@@ -532,7 +597,9 @@ func runServer(cmd *Command, args []string) bool {
if *isStartingMqBroker {
go func() {
time.Sleep(2 * time.Second)
mqBrokerOptions.startQueueServer()
if err := mqBrokerOptions.startQueueServer(); err != nil {
glog.Fatalf("%v", err)
}
}()
}
+87
View File
@@ -29,6 +29,93 @@ func TestServerGatewayDataCenterFlags(t *testing.T) {
}
}
func TestServerStartsAtMostOneMqBroker(t *testing.T) {
for _, tc := range []struct {
name string
s3, broker, passed, agent, tls bool
wantStandalone, wantBesideS3 bool
}{
{name: "nothing", tls: true},
{name: "-s3 with TLS", s3: true, tls: true, wantBesideS3: true},
{name: "-s3 without TLS", s3: true},
{name: "-s3 -mq.broker=false with TLS", s3: true, passed: true, tls: true},
{name: "-s3 -mq.broker without TLS", s3: true, broker: true, passed: true, wantStandalone: true},
{name: "-mq.broker", broker: true, passed: true, wantStandalone: true},
{name: "-mq.broker=false", passed: true, tls: true},
{name: "-s3 -mq.agent", s3: true, agent: true, tls: true, wantStandalone: true},
{name: "-s3 -mq.agent -mq.broker=false", s3: true, passed: true, agent: true, tls: true, wantStandalone: true},
} {
t.Run(tc.name, func(t *testing.T) {
withMqBrokerTLS(t, tc.tls)
// runServer turns -mq.agent into -mq.broker before deciding.
broker := tc.broker || tc.agent
besideS3 := serverRunsMqBrokerBesideS3(tc.s3, broker, tc.passed)
if broker != tc.wantStandalone || besideS3 != tc.wantBesideS3 {
t.Fatalf("standalone %v beside S3 %v, want %v %v", broker, besideS3, tc.wantStandalone, tc.wantBesideS3)
}
if broker && besideS3 {
t.Fatal("two brokers would start")
}
})
}
}
// weed server -s3 -filer.port.public=17777, which -s3 turns the filer on for.
func TestServerDefaultBrokerYieldsToFilerPublicPort(t *testing.T) {
startFiler, publicPort := *isStartingFiler, *filerOptions.publicPort
t.Cleanup(func() { *isStartingFiler, *filerOptions.publicPort = startFiler, publicPort })
*isStartingFiler, *filerOptions.publicPort = true, 17777
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false, serverPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on the filer public port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", true, serverPortsBesideS3()...); err == nil {
t.Fatal("explicit -mq.broker.port on the filer public port was accepted")
}
}
func TestServerDefaultBrokerYieldsToVolumeGrpcPort(t *testing.T) {
volumePort, volumeGrpcPort, startVolume := *serverOptions.v.port, *serverOptions.v.portGrpc, *isStartingVolumeServer
t.Cleanup(func() {
*serverOptions.v.port, *serverOptions.v.portGrpc, *isStartingVolumeServer = volumePort, volumeGrpcPort, startVolume
})
*serverOptions.v.port, *serverOptions.v.portGrpc, *isStartingVolumeServer = 7777, 0, true
s3opt := gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false, serverPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on the volume gRPC port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", true, serverPortsBesideS3()...); err == nil {
t.Fatal("explicit -mq.broker.port on the volume gRPC port was accepted")
}
publicPort := *serverOptions.v.publicPort
t.Cleanup(func() { *serverOptions.v.publicPort = publicPort })
*serverOptions.v.port, *serverOptions.v.publicPort = 8080, 17777
s3opt = gatewayWithBroker(8333, 0, 17777)
if err := s3opt.checkMqBrokerPort("mq.broker.port", false, serverPortsBesideS3()...); err != nil || s3opt.mqBroker != nil {
t.Fatalf("default broker on the volume public port: err %v, broker kept %v", err, s3opt.mqBroker != nil)
}
}
func TestServerMqBrokerFlagDefaults(t *testing.T) {
for name, want := range map[string]string{
"mq.broker": "false",
"mq.broker.port": "17777",
} {
flag := cmdServer.Flag.Lookup(name)
if flag == nil {
t.Fatalf("weed server does not expose -%s", name)
}
if flag.DefValue != want {
t.Errorf("-%s default = %q, want %q", name, flag.DefValue, want)
}
}
}
func TestIdleTimeoutSeconds(t *testing.T) {
if got := idleTimeoutSeconds(nil); got != 10*time.Second {
t.Fatalf("idleTimeoutSeconds(nil) = %v, want 10s", got)
+78 -2
View File
@@ -3,6 +3,8 @@ package command
import (
"context"
"fmt"
"os"
"os/user"
"runtime"
"time"
@@ -42,6 +44,7 @@ type SftpOptions struct {
metricsHttpPort *int
metricsHttpIp *string
localSocket *string
stdio bool
}
// cmdSftp defines the SFTP command similar to the S3 command.
@@ -53,6 +56,16 @@ var cmdSftp = &Command{
Instead of reading from or writing to a local filesystem, all file operations
are routed through the filer (filer_pb) gRPC API. This allows you to centralize
your file management in SeaweedFS.
When OpenSSH sshd runs it as the sftp Subsystem, it serves that one session on
stdin/stdout instead of listening, and the SSH options are ignored:
Subsystem sftp /usr/local/bin/weed sftp -filer=filer:8888
sshd authenticates, and the session belongs to the logged-in OS user. With
-userStoreFile that user must be in the store, which the user must be able to
read (keep passwords and keys out of it), and its home and permissions apply;
without a store the session can reach the whole filer.
`,
}
@@ -80,6 +93,9 @@ func init() {
sftpOptionsStandalone.localSocket = cmdSftp.Flag.String("localSocket", "", "default to /tmp/seaweedfs-sftp-<port>.sock")
}
// stdioFilerWait bounds how long an sshd subsystem session waits for the filer.
const stdioFilerWait = 30 * time.Second
// runSftp is the command entry point.
func runSftp(cmd *Command, args []string) bool {
sftpOptionsStandalone.resolvePaths()
@@ -93,7 +109,10 @@ func runSftp(cmd *Command, args []string) bool {
case *sftpOptionsStandalone.bindIp != "":
*sftpOptionsStandalone.metricsHttpIp = *sftpOptionsStandalone.bindIp
}
go stats_collect.StartMetricsServer(*sftpOptionsStandalone.metricsHttpIp, *sftpOptionsStandalone.metricsHttpPort)
sftpOptionsStandalone.stdio = launchedAsSshSubsystem()
if !sftpOptionsStandalone.stdio {
go stats_collect.StartMetricsServer(*sftpOptionsStandalone.metricsHttpIp, *sftpOptionsStandalone.metricsHttpPort)
}
return sftpOptionsStandalone.startSftpServer()
}
@@ -136,9 +155,18 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
var digest string
// Connect to the filer service and try to retrieve basic configuration.
// The listener waits for the filer; a subsystem session is one login, so it
// gives up instead of holding the process for the whole outage.
stdio := sftpOpt.stdio
discoveryCtx := context.Background()
if stdio {
var cancel context.CancelFunc
discoveryCtx, cancel = context.WithTimeout(discoveryCtx, stdioFilerWait)
defer cancel()
}
for {
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
resp, err := client.GetFilerConfiguration(discoveryCtx, &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
}
@@ -150,6 +178,11 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
return nil
})
if err != nil {
if discoveryCtx.Err() != nil {
glog.Errorf("sftp subsystem: filer %s unreachable: %v", filerAddress.ToGrpcAddress(), err)
SetCommandExitStatus(1)
return true
}
glog.V(0).Infof("Waiting to connect to filer %s grpc address %s...", *sftpOpt.filer, filerAddress.ToGrpcAddress())
time.Sleep(time.Second)
} else {
@@ -159,6 +192,22 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
}
adoptFilerDigest(*sftpOpt.filer, digest)
if stdio {
if err := sftpOpt.serveStdio(&sftpd.SFTPServiceOptions{
GrpcDialOption: grpcDialOption,
DataCenter: *sftpOpt.dataCenter,
FilerGroup: filerGroup,
Filer: filerAddress,
FilerSigningKey: []byte(filerSigningKey),
FilerSigningExpiresAfter: filerSigningExpiresAfter,
BucketsDir: bucketsDir,
}); err != nil {
glog.Errorf("sftp subsystem: %v", err)
SetCommandExitStatus(1)
}
return true
}
go stats_collect.LoopPushingMetric("sftp", stats_collect.SourceName(uint32(*sftpOpt.port)), metricsAddress, metricsIntervalSec)
// Parse auth methods
@@ -232,3 +281,30 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
return true
}
// serveStdio serves one SFTP session on stdin/stdout for the OS user running
// the command, which sshd has already authenticated
func (sftpOpt *SftpOptions) serveStdio(options *sftpd.SFTPServiceOptions) error {
osUser, err := user.Current()
if err != nil {
return fmt.Errorf("current user: %w", err)
}
u, err := sftpd.StdioUser(*sftpOpt.userStoreFile, osUser.Username, uint32(os.Getuid()), uint32(os.Getgid()))
if err != nil {
return err
}
glog.V(0).Infof("SFTP session on stdio for %s", u.Username)
return sftpd.ServeStdio(options, u, sftpd.Stdio{})
}
// launchedAsSshSubsystem reports whether sshd started this process as its sftp
// Subsystem: sshd sets SSH_CONNECTION and wires stdin and stdout to the channel,
// while a listener has a terminal, /dev/null or a file there.
func launchedAsSshSubsystem() bool {
return os.Getenv("SSH_CONNECTION") != "" && isPipeOrSocket(os.Stdin) && isPipeOrSocket(os.Stdout)
}
func isPipeOrSocket(f *os.File) bool {
fi, err := f.Stat()
return err == nil && fi.Mode()&(os.ModeNamedPipe|os.ModeSocket) != 0
}
+47
View File
@@ -0,0 +1,47 @@
package command
import (
"os"
"path/filepath"
"testing"
)
func TestLaunchedAsSshSubsystem(t *testing.T) {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer r.Close()
defer w.Close()
regular, err := os.Create(filepath.Join(t.TempDir(), "out"))
if err != nil {
t.Fatal(err)
}
defer regular.Close()
stdin, stdout := os.Stdin, os.Stdout
defer func() { os.Stdin, os.Stdout = stdin, stdout }()
cases := []struct {
name string
sshConnection string
in, out *os.File
want bool
}{
{"sshd subsystem", "10.0.0.1 50000 10.0.0.2 22", r, w, true},
{"no ssh connection", "", r, w, false},
{"stdout to a file", "10.0.0.1 50000 10.0.0.2 22", r, regular, false},
{"stdin from a file", "10.0.0.1 50000 10.0.0.2 22", regular, w, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
t.Setenv("SSH_CONNECTION", c.sshConnection)
os.Stdin, os.Stdout = c.in, c.out
got := launchedAsSshSubsystem()
os.Stdin, os.Stdout = stdin, stdout
if got != c.want {
t.Fatalf("launchedAsSshSubsystem() = %v, want %v", got, c.want)
}
})
}
}
+1
View File
@@ -22,6 +22,7 @@ func TestWorkerDefaultJobTypes(t *testing.T) {
"filer_ttl",
"iceberg_maintenance",
"meta_log_purge",
"mq_topic_table",
"s3_lifecycle",
"vacuum",
"volume_balance",
+61 -27
View File
@@ -15,20 +15,39 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// RowKey is the primary key of a row: an entry's directory and name, or the
// split of a key-value key that GenDirAndName makes.
type RowKey struct {
DirHash int64
Name string
Directory string
}
func EntryRowKey(dir, name string) RowKey {
return RowKey{DirHash: util.HashStringToLong(dir), Name: name, Directory: dir}
}
// Args returns the key's values in (dirhash, name, directory) order, then extra.
func (k RowKey) Args(extra ...interface{}) []interface{} {
return append([]interface{}{k.DirHash, k.Name, k.Directory}, extra...)
}
// SqlGenerator returns each statement together with its arguments.
type SqlGenerator interface {
GetSqlInsert(tableName string) string
GetSqlUpdate(tableName string) string
GetSqlFind(tableName string) string
// GetSqlFindBatch selects dirhash, name, directory and meta of the rows
// matching count (dirhash, name, directory) triples, as GetSqlFind does one.
GetSqlFindBatch(tableName string, count int) string
GetSqlDelete(tableName string) string
GetSqlDeleteFolderChildren(tableName string) string
GetSqlListExclusive(tableName string) string
GetSqlListInclusive(tableName string) string
GetSqlInsert(tableName string, key RowKey, meta []byte) (string, []interface{})
GetSqlUpdate(tableName string, key RowKey, meta []byte) (string, []interface{})
GetSqlFind(tableName string, key RowKey) (string, []interface{})
// GetSqlFindBatch selects name, directory and meta of the rows of keys.
GetSqlFindBatch(tableName string, keys []RowKey) (string, []interface{})
GetSqlDelete(tableName string, key RowKey) (string, []interface{})
GetSqlDeleteFolderChildren(tableName string, dir string) (string, []interface{})
// GetSqlListExclusive selects name and meta of the entries in dir after
// startFileName whose name is LIKE namePattern, in name order.
GetSqlListExclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{})
GetSqlListInclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{})
// GetSqlScanPage returns the query and arguments selecting dirhash, name,
// directory and meta of up to limit rows after the (dirhash, name) cursor.
GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{})
// directory and meta of up to limit rows after the cursor row.
GetSqlScanPage(tableName string, after RowKey, limit int) (string, []interface{})
GetSqlCreateTable(tableName string) string
GetSqlDropTable(tableName string) string
}
@@ -39,9 +58,13 @@ type AbstractSqlStore struct {
KvDB *sql.DB
// ScanDB, when set, is the pool snapshot scans run on (SQLite's main pool
// is a single connection that a long scan must not hold).
ScanDB *sql.DB
SupportBucketTable bool
SkipDDL bool
ScanDB *sql.DB
SupportBucketTable bool
SkipDDL bool
// KvSqlGenerator, when set, keeps the key-value records in KvTable, out
// of the entry tables.
KvSqlGenerator SqlGenerator
KvTable string
dbs map[string]bool
dbsLock sync.Mutex
RetryableErrorCallback func(err error) bool
@@ -247,13 +270,16 @@ func (store *AbstractSqlStore) InsertEntry(ctx context.Context, entry *filer.Ent
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
meta = util.MaybeGzipData(meta)
}
key := EntryRowKey(dir, name)
sqlInsert := "insert"
res, err := db.ExecContext(ctx, store.GetSqlInsert(bucket), util.HashStringToLong(dir), name, dir, meta)
sqlText, args := store.GetSqlInsert(bucket, key, meta)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil && strings.Contains(strings.ToLower(err.Error()), "duplicate entry") {
// now the insert failed possibly due to duplication constraints
sqlInsert = "falls back to update"
glog.V(1).InfofCtx(ctx, "insert %s %s: %v", entry.FullPath, sqlInsert, err)
res, err = db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
sqlText, args = store.GetSqlUpdate(bucket, key, meta)
res, err = db.ExecContext(ctx, sqlText, args...)
}
if err != nil {
return fmt.Errorf("%s %s: %w", sqlInsert, entry.FullPath, err)
@@ -291,7 +317,8 @@ func (store *AbstractSqlStore) UpdateEntry(ctx context.Context, entry *filer.Ent
return fmt.Errorf("encode %s: %w", entry.FullPath, err)
}
res, err := db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlUpdate(bucket, EntryRowKey(dir, name), meta)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("update %s: %w", entry.FullPath, err)
}
@@ -320,7 +347,8 @@ func (store *AbstractSqlStore) FindEntry(ctx context.Context, fullpath util.Full
}
dir, name := shortPath.DirAndName()
row := db.QueryRowContext(ctx, store.GetSqlFind(bucket), util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlFind(bucket, EntryRowKey(dir, name))
row := db.QueryRowContext(ctx, sqlText, args...)
var data []byte
if err := row.Scan(&data); err != nil {
@@ -351,7 +379,8 @@ func (store *AbstractSqlStore) DeleteEntry(ctx context.Context, fullpath util.Fu
dir, name := shortPath.DirAndName()
res, err := db.ExecContext(ctx, store.GetSqlDelete(bucket), util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlDelete(bucket, EntryRowKey(dir, name))
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("delete %s: %w", fullpath, err)
}
@@ -392,8 +421,9 @@ func (store *AbstractSqlStore) DeleteFolderChildren(ctx context.Context, fullpat
}
}
glog.V(4).InfofCtx(ctx, "delete %s SQL %s %d", string(shortPath), store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)))
res, err := db.ExecContext(ctx, store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)), string(shortPath))
sqlText, args := store.GetSqlDeleteFolderChildren(bucket, string(shortPath))
glog.V(4).InfofCtx(ctx, "delete %s SQL %s %v", string(shortPath), sqlText, args)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("deleteFolderChildren %s: %w", fullpath, err)
}
@@ -428,13 +458,17 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
if err != nil {
return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err)
}
sqlText := store.GetSqlListExclusive(bucket)
if includeStartFile {
sqlText = store.GetSqlListInclusive(bucket)
if gen, ok := store.SqlGenerator.(PathListSqlGenerator); ok {
return store.listDirectoryByPath(ctx, gen, db, bucket, dirPath, shortPath, startFileName, includeStartFile, limit, prefix, eachEntryFunc)
}
rows, err := db.QueryContext(ctx, sqlText, util.HashStringToLong(string(shortPath)), startFileName, string(shortPath), LikePattern(prefix), limit+1)
getSqlList := store.GetSqlListExclusive
if includeStartFile {
getSqlList = store.GetSqlListInclusive
}
sqlText, args := getSqlList(bucket, string(shortPath), startFileName, LikePattern(prefix), limit+1)
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
}
@@ -24,13 +24,22 @@ func (store *AbstractSqlStore) kvDB(ctx context.Context) TxOrDB {
return store.DB
}
func (store *AbstractSqlStore) kvSql() (SqlGenerator, string) {
if store.KvSqlGenerator != nil {
return store.KvSqlGenerator, store.KvTable
}
return store.SqlGenerator, DEFAULT_TABLE
}
func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
rowKey := kvRowKey(key)
_, err = db.ExecContext(ctx, store.GetSqlInsert(DEFAULT_TABLE), dirHash, name, dirStr, value)
gen, table := store.kvSql()
sqlText, args := gen.GetSqlInsert(table, rowKey, value)
_, err = db.ExecContext(ctx, sqlText, args...)
if err == nil {
return
}
@@ -43,7 +52,8 @@ func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []by
// now the insert failed possibly due to duplication constraints
glog.V(1).InfofCtx(ctx, "kv insert falls back to update: %s", err)
res, err := db.ExecContext(ctx, store.GetSqlUpdate(DEFAULT_TABLE), value, dirHash, name, dirStr)
sqlText, args = gen.GetSqlUpdate(table, rowKey, value)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("kv upsert: %s", err)
}
@@ -60,8 +70,9 @@ func (store *AbstractSqlStore) KvGet(ctx context.Context, key []byte) (value []b
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
row := db.QueryRowContext(ctx, store.GetSqlFind(DEFAULT_TABLE), dirHash, name, dirStr)
gen, table := store.kvSql()
sqlText, args := gen.GetSqlFind(table, kvRowKey(key))
row := db.QueryRowContext(ctx, sqlText, args...)
err = row.Scan(&value)
@@ -82,23 +93,22 @@ const kvBatchGetSize = 256
func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
db := store.kvDB(ctx)
gen, table := store.kvSql()
values := make(map[string][]byte, len(keys))
for start := 0; start < len(keys); start += kvBatchGetSize {
batch := keys[start:min(start+kvBatchGetSize, len(keys))]
type row struct {
dirHash int64
name, directory string
}
type row struct{ name, directory string }
asked := make(map[row][]string, len(batch))
args := make([]interface{}, 0, 3*len(batch))
rowKeys := make([]RowKey, 0, len(batch))
for _, key := range batch {
dirStr, dirHash, name := GenDirAndName(key)
r := row{dirHash, name, dirStr}
rowKey := kvRowKey(key)
r := row{rowKey.Name, rowKey.Directory}
asked[r] = append(asked[r], string(key))
args = append(args, dirHash, name, dirStr)
rowKeys = append(rowKeys, rowKey)
}
if err := func() error {
rows, err := db.QueryContext(ctx, store.GetSqlFindBatch(DEFAULT_TABLE, len(batch)), args...)
sqlText, args := gen.GetSqlFindBatch(table, rowKeys)
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return err
}
@@ -106,7 +116,7 @@ func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (m
for rows.Next() {
var r row
var value []byte
if err := rows.Scan(&r.dirHash, &r.name, &r.directory, &value); err != nil {
if err := rows.Scan(&r.name, &r.directory, &value); err != nil {
return err
}
for _, key := range asked[r] {
@@ -125,9 +135,9 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
res, err := db.ExecContext(ctx, store.GetSqlDelete(DEFAULT_TABLE), dirHash, name, dirStr)
gen, table := store.kvSql()
sqlText, args := gen.GetSqlDelete(table, kvRowKey(key))
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("kv delete: %s", err)
}
@@ -141,6 +151,11 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er
}
func kvRowKey(key []byte) RowKey {
dirStr, dirHash, name := GenDirAndName(key)
return RowKey{DirHash: dirHash, Name: name, Directory: dirStr}
}
func GenDirAndName(key []byte) (dirStr string, dirHash int64, name string) {
for len(key) < 8 {
key = append(key, 0)
@@ -0,0 +1,164 @@
package abstract_sql
import (
"context"
"fmt"
"strings"
"unicode/utf8"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// PathListSqlGenerator is implemented by a generator whose rows are keyed by
// their path. GetSqlListPath selects directory, name and, for the rows of dir
// only, meta of the rows with after < path and from <= path < to, in path order.
type PathListSqlGenerator interface {
GetSqlListPath(tableName, dir, after, from, to string, limit int64) (string, []interface{})
}
// In path order a directory's children interleave with their own subtrees,
// such as the versions of an object. A listing reads growing batches of the
// directory's range and skips subtree rows in Go; past pathListMaxSkip rows of
// one subtree it queries again from the end of that subtree, starting over
// with a small batch, as the rows a cut-short batch still holds are read anyway.
var (
pathListMinBatch int64 = 8
pathListMaxBatch int64 = 4096
pathListMaxSkip = 64
)
// SetPathListBatchesForTest lets tests drive a listing across batches and
// subtree skips. It returns the previous values.
func SetPathListBatchesForTest(minBatch, maxBatch int64, maxSkip int) (int64, int64, int) {
prevMin, prevMax, prevSkip := pathListMinBatch, pathListMaxBatch, pathListMaxSkip
pathListMinBatch, pathListMaxBatch, pathListMaxSkip = minBatch, maxBatch, maxSkip
return prevMin, prevMax, prevSkip
}
// listDirectoryByPath lists the children of dirPath, stored under shortPath in
// table, from a generator that keys rows by path.
func (store *AbstractSqlStore) listDirectoryByPath(ctx context.Context, gen PathListSqlGenerator, db TxOrDB, table string, dirPath, shortPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
dir := string(shortPath)
childPrefix := strings.TrimSuffix(dir, "/") + "/"
from := childPrefix + prefix
to, _ := prefixEnd(from)
after := ""
if start := childPrefix + startFileName; !includeStartFile {
after = start
} else if start > from {
from = start
}
// As in the directory-keyed listing, limit+1 entries are read.
want := limit + 1
batch := min(max(want, pathListMinBatch), pathListMaxBatch)
for want > 0 {
sqlText, args := gen.GetSqlListPath(table, dir, after, from, to, batch)
entries, read, resume, err := readPathListBatch(ctx, db, sqlText, args, dirPath, dir, childPrefix, want)
if err != nil {
return lastFileName, err
}
for _, entry := range entries {
lastFileName = entry.Name()
more, eachErr := eachEntryFunc(entry)
if eachErr != nil {
return lastFileName, fmt.Errorf("failed to process eachEntryFunc: %w", eachErr)
}
if !more {
return lastFileName, nil
}
}
want -= int64(len(entries))
switch {
case resume.cut:
after, from, batch = "", resume.skipTo, pathListMinBatch
continue
case read < batch:
return lastFileName, nil
case resume.skipTo != "":
after, from = "", resume.skipTo
default:
after = resume.after
}
next := batch * 2
if n := int64(len(entries)); n > 0 {
// Closing the rows reads the rest of a batch, so ask for about
// as many rows as the remaining entries took so far.
next = min(next, min(want, pathListMaxBatch)*read/n*5/4+pathListMinBatch)
}
batch = min(next, pathListMaxBatch)
}
return lastFileName, nil
}
type pathListResume struct {
after string // the last row read was a child with this path
skipTo string // the last row read lies in a subtree ending before this path
cut bool // the batch was left unread past pathListMaxSkip rows of that subtree
}
// readPathListBatch returns up to want children of dir from one batch, and
// where the next batch starts. read counts the rows taken from the batch.
func readPathListBatch(ctx context.Context, db TxOrDB, sqlText string, args []interface{}, dirPath util.FullPath, dir, childPrefix string, want int64) (entries []*filer.Entry, read int64, resume pathListResume, err error) {
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return nil, 0, resume, fmt.Errorf("list %s : %v", dirPath, err)
}
// A transaction has one connection, and the callback may query on it (a
// hard link's KvGet), so entries are handed over after the rows close.
defer rows.Close()
skipping, skipped := "", 0
for rows.Next() {
var rowDir, name string
var data []byte
if err = rows.Scan(&rowDir, &name, &data); err != nil {
return nil, read, resume, fmt.Errorf("scan %s: %v", dirPath, err)
}
read++
if rowDir != dir {
child, _, _ := strings.Cut(strings.TrimPrefix(rowDir, childPrefix), "/")
if child != skipping {
skipping, skipped = child, 0
}
skipped++
resume = pathListResume{skipTo: childPrefix + child + "0", cut: skipped >= pathListMaxSkip}
if resume.cut {
break
}
continue
}
resume = pathListResume{after: childPrefix + name}
entry := &filer.Entry{FullPath: util.NewFullPath(string(dirPath), name)}
if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
return nil, read, resume, fmt.Errorf("scan decode %s : %v", entry.FullPath, err)
}
entries = append(entries, entry)
if int64(len(entries)) == want {
break
}
}
if err = rows.Err(); err != nil {
return nil, read, resume, fmt.Errorf("list %s: %w", dirPath, err)
}
return entries, read, resume, nil
}
// prefixEnd returns the least string greater than every string starting with
// p, in byte order. ok is false when there is none.
func prefixEnd(p string) (end string, ok bool) {
for len(p) > 0 {
r, size := utf8.DecodeLastRuneInString(p)
p = p[:len(p)-size]
if r == utf8.MaxRune || r == utf8.RuneError && size == 1 {
continue
}
r++
if r >= 0xD800 && r <= 0xDFFF {
r = 0xE000
}
return p + string(r), true
}
return "", false
}
@@ -0,0 +1,25 @@
package abstract_sql
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPrefixEnd(t *testing.T) {
for p, want := range map[string]string{
"/a/": "/a0",
"/a": "/b",
"/日本": "/日\u672D",
"/a\U0010FFFF": "/b",
"/a퟿": "/a",
} {
end, ok := prefixEnd(p)
require.True(t, ok, p)
require.Equal(t, want, end, p)
require.Less(t, p, end)
require.Less(t, p+"\U0010FFFF\U0010FFFF", end)
}
_, ok := prefixEnd("\U0010FFFF")
require.False(t, ok)
}
@@ -0,0 +1,95 @@
package abstract_sql
import (
"context"
"fmt"
"strings"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
var _ filer.RecursiveLister = (*AbstractSqlStore)(nil)
// RecursiveListSqlGenerator is implemented by a generator whose rows are keyed
// by their path. GetSqlListRecursive selects directory, name and meta of the
// rows with after < path, from <= path and, unless to is empty, path < to, in
// path order.
type RecursiveListSqlGenerator interface {
GetSqlListRecursive(tableName string, after, from, to string, limit int64) (string, []interface{})
}
// ListRecursivePrefixedEntries implements filer.RecursiveLister for a
// generator keyed by path, and for a directory whose subtree is in one table.
func (store *AbstractSqlStore) ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastPath util.FullPath, err error) {
gen, ok := store.SqlGenerator.(RecursiveListSqlGenerator)
if !ok {
return "", filer.ErrUnsupportedRecursiveListing
}
if store.SupportBucketTable && (dirPath == "/" || string(dirPath) == bucketsRoot) {
return "", fmt.Errorf("%w: %s spans the bucket tables", filer.ErrUnsupportedRecursiveListing, dirPath)
}
db, table, shortPath, err := store.getTxOrDB(ctx, dirPath, true)
if err != nil {
return "", fmt.Errorf("findDB %s : %v", dirPath, err)
}
base := ""
if table != DEFAULT_TABLE {
base = bucketBase(table)
}
from := strings.TrimSuffix(string(shortPath), "/") + "/" + prefix
to, _ := prefixEnd(from)
after := string(startPath)
if base != "" {
switch {
case strings.HasPrefix(after, base+"/"):
after = after[len(base):]
case after < base+"/":
after = ""
default:
return "", nil
}
}
sqlText, args := gen.GetSqlListRecursive(table, after, from, to, limit)
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return "", fmt.Errorf("list %s recursively: %v", dirPath, err)
}
defer rows.Close()
// The callback may query the store (a hard link's record), so the entries
// are handed over after the rows close.
var entries []*filer.Entry
for rows.Next() {
var dir, name string
var data []byte
if err = rows.Scan(&dir, &name, &data); err != nil {
return lastPath, fmt.Errorf("scan %s: %v", dirPath, err)
}
if base != "" {
dir = base + strings.TrimSuffix(dir, "/")
}
entry := &filer.Entry{FullPath: util.NewFullPath(dir, name)}
if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
return lastPath, fmt.Errorf("decode %s : %v", entry.FullPath, err)
}
entries = append(entries, entry)
}
if err = rows.Err(); err != nil {
return lastPath, fmt.Errorf("list %s recursively: %w", dirPath, err)
}
rows.Close()
for _, entry := range entries {
lastPath = entry.FullPath
more, eachErr := eachEntryFunc(entry)
if eachErr != nil {
return lastPath, fmt.Errorf("failed to process eachEntryFunc: %w", eachErr)
}
if !more {
break
}
}
return lastPath, nil
}
@@ -100,7 +100,8 @@ func (store *AbstractSqlStore) readRowInSnapshot(ctx context.Context, tx *sql.Tx
}
}
var data []byte
err := tx.QueryRowContext(ctx, store.GetSqlFind(table), util.HashStringToLong(shortDir), name, shortDir).Scan(&data)
sqlText, args := store.GetSqlFind(table, EntryRowKey(shortDir, name))
err := tx.QueryRowContext(ctx, sqlText, args...).Scan(&data)
if err == sql.ErrNoRows {
return nil, nil
}
@@ -227,7 +228,8 @@ func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx,
}
var rows []row
if err := func() error {
res, err := tx.QueryContext(ctx, store.GetSqlListExclusive(DEFAULT_TABLE), util.HashStringToLong(bucketsRoot), startFrom, bucketsRoot, "%", page)
sqlText, args := store.GetSqlListExclusive(DEFAULT_TABLE, bucketsRoot, startFrom, "%", page)
res, err := tx.QueryContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("list %s: %v", bucketsRoot, err)
}
@@ -266,17 +268,17 @@ func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx,
}
// scanOneTable reads one table in primary-key pages and hands the entries
// strictly below dirPath to fn (the root itself is read separately). Key-value
// records share the default table; GenDirAndName stores the raw key bytes as
// their dirhash while entry rows hash the directory, so the mismatch
// identifies them exactly.
// strictly below dirPath to fn (the root itself is read separately). Unless
// they have a table of their own, key-value records share the default table;
// GenDirAndName stores the raw key bytes as their dirhash while entry rows
// hash the directory, so the mismatch identifies them exactly.
func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t scanTable, dirPath util.FullPath, fn func(ctx context.Context, entry *filer.Entry) error) error {
type row struct {
dirHash int64
name, dir string
data []byte
}
cursorHash, cursorName := int64(math.MinInt64), ""
cursor := RowKey{DirHash: math.MinInt64}
firstPage := true
for {
var page []row
@@ -289,7 +291,7 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s
return fmt.Errorf("scan table %s: %v", t.table, err)
}
}
sqlText, args := store.GetSqlScanPage(t.table, cursorHash, cursorName, scanPageSize)
sqlText, args := store.GetSqlScanPage(t.table, cursor, scanPageSize)
rows, err := tx.QueryContext(ctx, sqlText, args...)
if err != nil {
if t.cachedOnly && isMissingTableError(err) {
@@ -314,8 +316,8 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s
}
for _, r := range page {
cursorHash, cursorName = r.dirHash, r.name
if r.dirHash != util.HashStringToLong(r.dir) {
cursor = RowKey{DirHash: r.dirHash, Name: r.name, Directory: r.dir}
if store.KvSqlGenerator == nil && r.dirHash != util.HashStringToLong(r.dir) {
continue // a key-value record, see GenDirAndName
}
fullPath := util.NewFullPath(t.base+r.dir, r.name)
@@ -149,8 +149,12 @@ func TestBucketHooksSkipInvalidBucketNames(t *testing.T) {
type listGen struct{ SqlGenerator }
func (listGen) GetSqlListExclusive(string) string { return "SELECT name, meta" }
func (listGen) GetSqlListInclusive(string) string { return "SELECT name, meta" }
func (listGen) GetSqlListExclusive(string, string, string, string, int64) (string, []interface{}) {
return "SELECT name, meta", nil
}
func (listGen) GetSqlListInclusive(string, string, string, string, int64) (string, []interface{}) {
return "SELECT name, meta", nil
}
// A listing that loses its connection partway through must report the error,
// not return the rows read so far as if the directory ended there.
@@ -220,8 +224,10 @@ func TestListDirectoryEntriesStoppedByCallbackWithCanceledContext(t *testing.T)
type writeGen struct{ SqlGenerator }
func (writeGen) GetSqlInsert(string) string { return "INSERT entry" }
func (writeGen) GetSqlDelete(string) string { return "DELETE entry" }
func (writeGen) GetSqlInsert(string, RowKey, []byte) (string, []interface{}) {
return "INSERT entry", nil
}
func (writeGen) GetSqlDelete(string, RowKey) (string, []interface{}) { return "DELETE entry", nil }
// What IsolatesTransactions declares: an entry write, an entry delete and a KV
// write under a transaction's context all go through that transaction, the KV
@@ -331,7 +337,7 @@ func (r *busyRows) Next(dest []driver.Value) error {
type findGen struct{ listGen }
func (findGen) GetSqlFind(string) string { return "SELECT meta" }
func (findGen) GetSqlFind(string, RowKey) (string, []interface{}) { return "SELECT meta", nil }
// A transaction has one connection, so a listing in one (a directory rename)
// must close its rows before the callback reads a hard link on it.
@@ -366,3 +372,33 @@ func TestListDirectoryEntriesInTransactionClosesRowsBeforeCallback(t *testing.T)
t.Errorf("listed %v, want %v", listed, want)
}
}
type kvTableGen struct{ SqlGenerator }
func (kvTableGen) GetSqlInsert(table string, key RowKey, meta []byte) (string, []interface{}) {
return "INSERT kv " + table, key.Args(meta)
}
func (kvTableGen) GetSqlFind(table string, key RowKey) (string, []interface{}) {
return "SELECT kv " + table, key.Args()
}
func TestKvRecordsGoToTheirOwnTable(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer db.Close()
mock.ExpectExec("INSERT kv filemeta_kv").WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery("SELECT kv filemeta_kv").WillReturnRows(sqlmock.NewRows([]string{"meta"}).AddRow([]byte("v")))
store := &AbstractSqlStore{SqlGenerator: writeGen{}, KvSqlGenerator: kvTableGen{}, KvTable: "filemeta_kv", DB: db}
if err := store.KvPut(context.Background(), []byte("key"), []byte("v")); err != nil {
t.Fatal(err)
}
if v, err := store.KvGet(context.Background(), []byte("key")); err != nil || string(v) != "v" {
t.Fatalf("KvGet = %q, %v", v, err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Error(err)
}
}
+1 -2
View File
@@ -232,8 +232,7 @@ func (store *ArangodbStore) FindEntry(ctx context.Context, fullpath util.FullPat
if driver.IsNotFound(err) {
return nil, filer_pb.ErrNotFound
}
glog.ErrorfCtx(ctx, "find %s: %v", fullpath, err)
return nil, filer_pb.ErrNotFound
return nil, fmt.Errorf("find %s: %w", fullpath, err)
}
if len(data.Meta) == 0 {
return nil, filer_pb.ErrNotFound
@@ -0,0 +1,32 @@
package arangodb
import (
"context"
"errors"
"testing"
"github.com/arangodb/go-driver"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
type unreachableCollection struct {
driver.Collection
}
func (unreachableCollection) ReadDocument(ctx context.Context, key string, result interface{}) (driver.DocumentMeta, error) {
return driver.DocumentMeta{}, errors.New("connect: connection refused")
}
func TestFindEntryReportsAFailedReadAsAnError(t *testing.T) {
store := &ArangodbStore{buckets: map[string]driver.Collection{"b": unreachableCollection{}}}
_, err := store.FindEntry(context.Background(), util.FullPath("/buckets/b/kept.bin"))
if err == nil {
t.Fatal("find succeeded although the server cannot be reached")
}
if errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("a failed read was reported as a missing entry: %v", err)
}
}
+5
View File
@@ -472,6 +472,7 @@ func retriedStreamFetchChunkData(ctx context.Context, writer io.Writer, urlStrin
retriedCnt := 0
var failed bool
var otherErr error
for _, urlString := range util_http.ReachableFirst(urlStrings) {
// Check for context cancellation before each volume server request
select {
@@ -510,6 +511,9 @@ func retriedStreamFetchChunkData(ctx context.Context, writer io.Writer, urlStrin
err = writeErr
break
}
if err != nil && !errors.Is(err, util_http.ErrNotFound) {
otherErr = err
}
if !shouldRetry {
break
}
@@ -520,6 +524,7 @@ func retriedStreamFetchChunkData(ctx context.Context, writer io.Writer, urlStrin
break
}
}
err = util_http.NotFoundEverywhere(err, otherErr)
if err == nil && failed && refreshUrls != nil {
refreshUrls()
}
+43 -17
View File
@@ -874,12 +874,15 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
// create the directory
now := time.Now()
// The directory takes the entry's permission bits, not its type: with
// a symlink's type bit as well, a mount shows the directory as a
// regular file.
dirEntry = &Entry{
FullPath: util.FullPath(dirPath),
Attr: Attr{
Mtime: now,
Crtime: now,
Mode: os.ModeDir | entry.Mode | 0111,
Mode: os.ModeDir | entry.Mode&restorableModeBits | 0111,
Uid: entry.Uid,
Gid: entry.Gid,
UserName: entry.UserName,
@@ -924,7 +927,10 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
// existing file to a directory, preserving its content/chunks so
// the original object data remains accessible.
glog.V(2).InfofCtx(ctx, "promoting %s from file to directory for %s", dirPath, entry.FullPath)
dirEntry.Attr.Mode |= os.ModeDir | 0111
// A promoted symlink keeps no type bit but the directory's: with both,
// a mount shows the directory as a regular file.
dirEntry.Attr.Mode = os.ModeDir | dirEntry.Attr.Mode&restorableModeBits | 0111
dirEntry.Attr.SymlinkTarget = ""
// Expiring the entry now deletes the directory row and strands the keys under
// it, so the prefix object gives up its lazy TTL. The lifecycle worker still
// expires it, through the delete that leaves the directory behind.
@@ -1106,6 +1112,19 @@ var (
}
)
type lookupWritesContextKey struct{}
// ErrLookupNeedsWrite is what a lookup made with WithoutLookupWrites returns
// in place of a write it would make: deleting an expired S3 object, or
// importing an object from a remote mount.
var ErrLookupNeedsWrite = errors.New("lookup needs a write")
// WithoutLookupWrites makes FindEntry report a write it would make instead of
// making it, so a caller can redo the lookup under a lock that covers writes.
func WithoutLookupWrites(ctx context.Context) context.Context {
return context.WithValue(ctx, lookupWritesContextKey{}, true)
}
// FindEntry looks up the entry at p, serving a path the store does not hold
// from a remote mount when one covers it.
func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
@@ -1134,6 +1153,9 @@ func (f *Filer) findEntry(ctx context.Context, p util.FullPath) (entry *Entry, f
// lookup outside a transaction removes it.
gone := false
if ctx.Value(storeTransactionKey{}) == nil {
if ctx.Value(lookupWritesContextKey{}) != nil {
return nil, false, ErrLookupNeedsWrite
}
if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil {
glog.ErrorfCtx(ctx, "FindEntry doDeleteEntryMetaAndData %s failed: %v", entry.FullPath, delErr)
} else {
@@ -1154,7 +1176,9 @@ func (f *Filer) findEntry(ctx context.Context, p util.FullPath) (entry *Entry, f
}
if entry == nil && (err == nil || errors.Is(err, filer_pb.ErrNotFound)) {
if lazy, lazyErr := f.maybeLazyFetchFromRemote(ctx, p); lazyErr != nil {
if lazy, lazyErr := f.maybeLazyFetchFromRemote(ctx, p); errors.Is(lazyErr, ErrLookupNeedsWrite) {
return nil, false, lazyErr
} else if lazyErr != nil {
glog.V(1).InfofCtx(ctx, "FindEntry lazy fetch %s: %v", p, lazyErr)
} else if lazy != nil {
return lazy, false, nil
@@ -1196,20 +1220,11 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
glog.V(1).InfofCtx(ctx, "listing %q canceled: %v", p, ctx.Err())
return false, fmt.Errorf("context canceled: %w", ctx.Err())
default:
if entry.TtlSec > 0 && !entry.IsDirectory() {
if entry.IsExpireS3Enabled() {
if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() {
// Collect for deletion after iteration completes to avoid DB deadlock
expiredEntries = append(expiredEntries, entry)
expiredCount++
return true, nil
}
} else if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
// Collect for deletion after iteration completes to avoid DB deadlock
expiredEntries = append(expiredEntries, entry)
expiredCount++
return true, nil
}
if listingExpired(entry) {
// Collect for deletion after iteration completes to avoid DB deadlock
expiredEntries = append(expiredEntries, entry)
expiredCount++
return true, nil
}
// Track that we found at least one valid (non-expired) entry
hasValidEntries = true
@@ -1239,6 +1254,17 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
return
}
// listingExpired reports whether a listing leaves the entry out and deletes it.
func listingExpired(entry *Entry) bool {
if entry.TtlSec <= 0 || entry.IsDirectory() {
return false
}
if entry.IsExpireS3Enabled() {
return entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning()
}
return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now())
}
// DeleteEmptyParentDirectories recursively checks and deletes parent directories if they become empty.
// It stops at root "/" or at stopAtPath (if provided).
// This is useful for cleaning up directories after deleting files or expired entries.
+1 -1
View File
@@ -238,7 +238,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
}
}
if err != nil && !ignoreRecursiveError {
break
return err
}
f.NotifyUpdateEvent(ctx, deleteEventEntry(ctx, sub), nil, shouldDeleteChunks, isFromOtherCluster, nil)
subChunksToDelete := &chunksToDelete
+51 -8
View File
@@ -23,12 +23,17 @@ import (
)
const (
// Maximum number of retry attempts for failed deletions
// Backed-off retry attempts before a failed deletion moves to the dead letter queues
MaxRetryAttempts = 10
// Initial retry delay (will be doubled with each attempt)
InitialRetryDelay = 5 * time.Minute
// Maximum retry delay
MaxRetryDelay = 6 * time.Hour
// Deletions still failing after MaxRetryAttempts move to a dead letter
// queue retried after DeadLetterRetryDelay, then to a second one retried
// after DeadLetterFinalRetryDelay, and are dropped if that fails too.
DeadLetterRetryDelay = 24 * time.Hour
DeadLetterFinalRetryDelay = 48 * time.Hour
// Interval for checking retry queue for ready items
DeletionRetryPollInterval = 1 * time.Minute
// Maximum number of items to process per retry iteration
@@ -60,6 +65,8 @@ var retryablePatterns = []string{
"lookup failed", // Volume server discovery issues
"too many requests", // Rate limiting / backpressure
"try again", // Explicit retry suggestion
"replication copy count", // A replica is offline; deletes wait for it to return
"no space left on device", // A low-disk replica could not append the tombstone yet
// A volume server in maintenance mode refuses BatchDelete until it is switched off.
// The other replicas already dropped the needle, so a delete that is not retried
// leaves this replica live for good.
@@ -174,6 +181,31 @@ func calculateBackoff(retryCount int) time.Duration {
return delay
}
const deadLetterQueues = 2
// deadLetterQueue reports which dead letter queue an item with this retry
// count is in: 0 while it is still in the regular retry schedule.
func deadLetterQueue(retryCount int) int {
if retryCount <= MaxRetryAttempts {
return 0
}
return retryCount - MaxRetryAttempts
}
// retryDelay is the wait before the attempt numbered retryCount. Items past
// the last dead letter queue are due at once so the next poll drops them.
func retryDelay(retryCount int) time.Duration {
switch deadLetterQueue(retryCount) {
case 0:
return calculateBackoff(retryCount)
case 1:
return DeadLetterRetryDelay
case 2:
return DeadLetterFinalRetryDelay
}
return 0
}
// AddOrUpdate adds a new failed deletion or updates an existing one
// Time complexity: O(log N) for insertion/update
func (q *DeletionRetryQueue) AddOrUpdate(fileId string, errorMsg string, ledgerEpoch uint64) {
@@ -234,8 +266,7 @@ func (q *DeletionRetryQueue) RequeueForRetry(item *DeletionRetryItem, errorMsg s
item.RetryCount++
item.LastError = errorMsg
// Calculate next retry time with exponential backoff
delay := calculateBackoff(item.RetryCount)
delay := retryDelay(item.RetryCount)
item.NextRetryAt = time.Now().Add(delay)
item.inFlight = false // Clear in-flight flag
glog.V(2).Infof("requeued retry for %s: attempt %d, next retry in %v", item.FileId, item.RetryCount, delay)
@@ -267,14 +298,13 @@ func (q *DeletionRetryQueue) GetReadyItems(maxItems int) (ready []*DeletionRetry
// Remove from heap but keep in itemIndex with inFlight flag
heap.Pop(&q.heap)
if item.RetryCount <= MaxRetryAttempts {
if deadLetterQueue(item.RetryCount) <= deadLetterQueues {
item.inFlight = true // Mark as being processed
ready = append(ready, item)
} else {
// Max attempts reached, log and discard completely
delete(q.itemIndex, item.FileId)
expired = append(expired, item)
glog.Warningf("max retry attempts (%d) reached for %s, last error: %s", MaxRetryAttempts, item.FileId, item.LastError)
glog.Warningf("giving up deleting %s after %d retries, last error: %s", item.FileId, item.RetryCount-1, item.LastError)
}
}
@@ -753,6 +783,7 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
// Process outcomes - iterate over readyItems to ensure all items are accounted for
var successCount, notFoundCount, retryCount, permanentErrorCount, volumeGoneCount int
var deadLettered, finalDeadLettered int
for _, item := range readyItems {
outcome := outcomes[item.FileId]
_, fsynced := fsyncIds[item.FileId]
@@ -782,6 +813,12 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
glog.Warningf("no deletion result for retried file %s, re-queuing to avoid loss", item.FileId)
}
// Keep in the durable ledger: still not confirmed.
switch deadLetterQueue(item.RetryCount + 1) {
case 1:
deadLettered++
case 2:
finalDeadLettered++
}
f.DeletionRetryQueue.RequeueForRetry(item, outcome.errorMsg)
case deletionOutcomePermanent:
permanentErrorCount++
@@ -801,6 +838,12 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
if retryCount > 0 {
glog.V(1).Infof("retry: %d files still failing, will retry again later", retryCount)
}
if deadLettered > 0 {
glog.Warningf("retry: %d files moved to the dead letter queue, next retry in %v", deadLettered, DeadLetterRetryDelay)
}
if finalDeadLettered > 0 {
glog.Warningf("retry: %d files moved to the second dead letter queue, next retry in %v", finalDeadLettered, DeadLetterFinalRetryDelay)
}
if volumeGoneCount > 0 {
glog.V(0).Infof("retry: %d files were on volumes the master has not known for %v, dropped as deleted with their volume", volumeGoneCount, VolumeGoneGrace)
}
@@ -869,8 +912,8 @@ func (f *Filer) manifestRetries() *DeletionRetryQueue {
}
// processManifestRetries resolves manifests that failed to resolve on delete.
// One that never resolves within MaxRetryAttempts is deleted alone, leaving
// its sub-chunks to volume.fsck. A pass stops after manifestRetryTimeout and
// One that never resolves through the retries and both dead letter queues is
// deleted alone, leaving its sub-chunks to volume.fsck. A pass stops after manifestRetryTimeout and
// leaves the rest queued, so the shared retry loop gets its turn.
func (f *Filer) processManifestRetries(ctx context.Context) {
q := f.manifestRetries()
+1 -1
View File
@@ -154,7 +154,7 @@ func TestDeleteChunksDropsManifestAfterMaxRetries(t *testing.T) {
manifest := &filer_pb.FileChunk{FileId: "3,01637037d6", Size: 8, IsChunkManifest: true}
f.DeleteUncommittedChunks(context.Background(), []*filer_pb.FileChunk{manifest})
makeManifestRetryDue(f, MaxRetryAttempts+1)
makeManifestRetryDue(f, MaxRetryAttempts+deadLetterQueues+1)
f.processManifestRetries(context.Background())
if got := queuedDeletions(f); !slices.Equal(got, []string{"3,01637037d6"}) {
t.Fatalf("queued %v after giving up, want the manifest needle alone", got)
+74 -25
View File
@@ -30,10 +30,17 @@ import (
// - subtractive: only terminal outcomes (success / not-found / permanent)
// remove it; retryable failures keep it,
// - snapshotted when it changes, on a timer, and on Shutdown, so a crash
// loses only ids queued in the last in-flight write — recovery re-enqueues
// loses only ids queued since the last write — recovery re-enqueues
// the whole pending set and the idempotent volume delete absorbs anything
// that actually completed before the crash.
//
// A snapshot rewrites the whole pending set, so its writes are paced to a byte
// budget: the first change after a quiet spell is written at once, and the
// changes that follow wait for one snapshot that carries them all. Without the
// pacing every queued and every finished delete rewrites the set, and a filer
// holding a backlog of deletes it cannot finish yet pays for all of it each
// time.
//
// Stores that cap value size (FoundationDB at 100KB) get the set split into
// part keys when one value would exceed deletionLedgerPartSize. Multipart
// snapshots write each generation under generation-scoped part keys and
@@ -63,6 +70,11 @@ const (
// Defaults; all three overridable via viper (filer.deleteQueue.*).
defaultDeletionPersistInterval = 10 * time.Second
defaultDeletionRecoveryGrace = 30 * time.Second
// deletionLedgerSnapshotOverhead is charged to the budget for every
// snapshot on top of its bytes, for the store requests a snapshot makes
// whatever its size. It bounds the snapshots of a small ledger.
deletionLedgerSnapshotOverhead = 4 * 1024
)
// deletionPersistEnabled reports whether ledger persistence is on.
@@ -84,6 +96,27 @@ func deletionPersistInterval() time.Duration {
return d
}
// deletionLedgerBytesPerSecond is what the ledger may write to the store over
// time. A snapshot of a thousand pending ids is about 30KB: at this budget two
// of them a second, where every queued and every finished delete used to cause
// one.
var deletionLedgerBytesPerSecond = 64 * 1024
// deletionLedgerPause is how long the snapshotter waits after a snapshot of
// wrote bytes so the ledger stays within budget bytes a second. It never
// exceeds the periodic snapshot interval: a ledger too large for the budget is
// still written that often.
func deletionLedgerPause(wrote, budget int, interval time.Duration) time.Duration {
if wrote <= 0 || budget <= 0 {
return 0
}
pause := time.Duration(wrote+deletionLedgerSnapshotOverhead) * time.Second / time.Duration(budget)
if pause > interval {
pause = interval
}
return pause
}
func deletionRecoveryGrace() time.Duration {
v := util.GetViper()
v.SetDefault("filer.deleteQueue.recoveryGrace", defaultDeletionRecoveryGrace)
@@ -120,11 +153,13 @@ func deletionLedgerGenPartKey(key string, gen, part int) []byte {
// startDeletionLedgerSnapshotter periodically flushes the pending deletion set
// to durable storage. It also wakes on deletionLedgerFlush so a queued id is
// persisted within milliseconds instead of a full interval. Started from
// SetStore only after the ledger read succeeded.
// persisted within milliseconds instead of a full interval, and then pauses
// for what that snapshot cost: the changes made meanwhile go into the next
// one. Started from SetStore only after the ledger read succeeded.
func (f *Filer) startDeletionLedgerSnapshotter() {
interval, budget := deletionPersistInterval(), deletionLedgerBytesPerSecond
go func() {
ticker := time.NewTicker(deletionPersistInterval())
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
@@ -140,7 +175,15 @@ func (f *Filer) startDeletionLedgerSnapshotter() {
return
default:
}
f.snapshotDeletionLedger()
if pause := deletionLedgerPause(f.snapshotDeletionLedger(), budget, interval); pause > 0 {
timer := time.NewTimer(pause)
select {
case <-f.deletionQuit:
timer.Stop()
return
case <-timer.C:
}
}
}
}()
}
@@ -285,8 +328,9 @@ func (f *Filer) forgetDeletionEpoch(fileId string, epoch uint64) bool {
// snapshotDeletionLedger serialises the current pending set to the store.
// Only writes when something changed since the last snapshot to keep KV churn low.
// Writes serialize on deletionSnapshotLock so a snapshot in flight when Shutdown
// starts cannot overwrite the final one with an older copy.
func (f *Filer) snapshotDeletionLedger() {
// starts cannot overwrite the final one with an older copy. It returns the
// bytes of the set it wrote, zero when it wrote none.
func (f *Filer) snapshotDeletionLedger() (wrote int) {
if !deletionPersistEnabled() || f.Store == nil {
return
}
@@ -322,14 +366,16 @@ func (f *Filer) snapshotDeletionLedger() {
f.deletionLedgerDirty = false
f.deletionLedgerLock.Unlock()
if err := f.writeDeletionLedger(ids, fsyncIds); err != nil {
wrote, err := f.writeDeletionLedger(ids, fsyncIds)
if err != nil {
glog.Warningf("failed to persist deletion ledger (%d ids): %v", len(ids), err)
f.deletionLedgerLock.Lock()
f.deletionLedgerDirty = true
f.deletionLedgerLock.Unlock()
return
return wrote
}
glog.V(3).Infof("persisted deletion ledger: %d pending deletions", len(ids))
return wrote
}
// tryUnblockDeletionLedger retries the ledger reload that originally failed.
@@ -346,8 +392,8 @@ func (f *Filer) tryUnblockDeletionLedger() bool {
// only then the manifest, so a crash or failed write leaves the previously
// published generation readable. Orphaned parts are retried on the next write.
// fsyncIds go into the trailing fsyncParts parts of a manifest, which older
// filers read as plain ids.
func (f *Filer) writeDeletionLedger(ids, fsyncIds []string) error {
// filers read as plain ids. It returns the bytes of the values it wrote.
func (f *Filer) writeDeletionLedger(ids, fsyncIds []string) (wrote int, err error) {
ctx := context.Background()
key := f.deletionLedgerKey()
@@ -392,50 +438,53 @@ func (f *Filer) writeDeletionLedger(ids, fsyncIds []string) error {
continue
}
if err := add(id); err != nil {
return err
return 0, err
}
}
if len(batch) > 0 || (len(parts) == 0 && len(fsyncSet) == 0) {
if err := flush(); err != nil {
return err
return 0, err
}
}
plainParts := len(parts)
for id := range fsyncSet {
if err := add(id); err != nil {
return err
return 0, err
}
}
if len(batch) > 0 {
if err := flush(); err != nil {
return err
return 0, err
}
}
fsyncParts := len(parts) - plainParts
if len(parts) == 1 && fsyncParts == 0 {
if err := f.Store.KvPut(ctx, []byte(key), parts[0]); err != nil {
return err
return 0, err
}
wrote = len(parts[0])
f.deleteLedgerParts(ctx, key, prevGen, prevParts)
f.deletionLedgerLock.Lock()
f.deletionLedgerGen, f.deletionLedgerParts = 0, 0
f.deletionLedgerLock.Unlock()
} else {
gen := prevGen + 1
wrote := 0
wroteParts := 0
for i, payload := range parts {
if err := f.Store.KvPut(ctx, deletionLedgerGenPartKey(key, gen, i), payload); err != nil {
f.markStaleLedgerParts(key, gen, wrote)
return err
f.markStaleLedgerParts(key, gen, wroteParts)
return wrote, err
}
wrote++
wroteParts++
wrote += len(payload)
}
manifest, _ := json.Marshal(deletionLedgerManifest{Parts: len(parts), Gen: gen, FsyncParts: fsyncParts})
if err := f.Store.KvPut(ctx, []byte(key), manifest); err != nil {
f.markStaleLedgerParts(key, gen, wrote)
return err
f.markStaleLedgerParts(key, gen, wroteParts)
return wrote, err
}
wrote += len(manifest)
f.deleteLedgerParts(ctx, key, prevGen, prevParts)
f.deletionLedgerLock.Lock()
f.deletionLedgerGen, f.deletionLedgerParts = gen, len(parts)
@@ -443,7 +492,7 @@ func (f *Filer) writeDeletionLedger(ids, fsyncIds []string) error {
}
f.persistStaleLedgerParts(ctx, key)
f.touchLedgerIndex(ctx, key)
return nil
return wrote, nil
}
// deleteLedgerParts removes a published generation's part keys; failures are
@@ -681,7 +730,7 @@ func (f *Filer) recoverForeignDeletionLedgers(key string) (ids, fsyncIds []strin
if len(claimed) == 0 {
return nil, nil, ErrKvNotFound
}
if err := f.writeDeletionLedger(ids, fsyncIds); err != nil {
if _, err := f.writeDeletionLedger(ids, fsyncIds); err != nil {
return nil, nil, err
}
mergedMore := false
@@ -715,7 +764,7 @@ func (f *Filer) recoverForeignDeletionLedgers(key string) (ids, fsyncIds []strin
if mergedMore {
// Ids from a changed source are durable only under that source's key;
// rewrite our ledger so they survive under ours too.
if err := f.writeDeletionLedger(ids, fsyncIds); err != nil {
if _, err := f.writeDeletionLedger(ids, fsyncIds); err != nil {
return nil, nil, err
}
}
+115
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
@@ -650,3 +651,117 @@ func TestDeletionLedgerVolumeGoneConfirmed(t *testing.T) {
t.Fatalf("volume unknown to the master for %v: the deletion is still pending", VolumeGoneGrace)
}
}
// ledgerWriteCountingStore counts the snapshots of one filer's ledger: every
// snapshot writes that filer's ledger key once.
type ledgerWriteCountingStore struct {
*stubFilerStore
ledgerKey string
snapshots atomic.Int64
}
func (s *ledgerWriteCountingStore) KvPut(ctx context.Context, key []byte, value []byte) error {
if string(key) == s.ledgerKey {
s.snapshots.Add(1)
}
return s.stubFilerStore.KvPut(ctx, key, value)
}
// withLedgerBudget pins the ledger's write budget for the snapshotters the test
// starts after it.
func withLedgerBudget(t *testing.T, bytesPerSecond int) {
t.Helper()
prev := deletionLedgerBytesPerSecond
deletionLedgerBytesPerSecond = bytesPerSecond
t.Cleanup(func() { deletionLedgerBytesPerSecond = prev })
}
// newSnapshottingLedgerTestFiler is a ledger test filer with its snapshotter
// running, as SetStore leaves a real one.
func newSnapshottingLedgerTestFiler(t *testing.T) (*Filer, *ledgerWriteCountingStore) {
t.Helper()
store := &ledgerWriteCountingStore{stubFilerStore: newStubFilerStore()}
f := newLedgerTestFiler(store)
store.ledgerKey = f.deletionLedgerKey()
f.deletionLedgerFlush = make(chan struct{}, 1)
f.startDeletionLedgerSnapshotter()
t.Cleanup(func() { close(f.deletionQuit) })
return f, store
}
func TestDeletionLedgerPause(t *testing.T) {
const budget, interval = 64 * 1024, 10 * time.Second
if got := deletionLedgerPause(0, budget, interval); got != 0 {
t.Errorf("a snapshot that wrote nothing: pause %v, want none", got)
}
// 60KB and the per-snapshot overhead against 64KiB a second
if got, want := deletionLedgerPause(60*1024, budget, interval), time.Second; got != want {
t.Errorf("a 60KiB snapshot: pause %v, want %v", got, want)
}
if got, want := deletionLedgerPause(1<<30, budget, interval), interval; got != want {
t.Errorf("a snapshot far over the budget: pause %v, want the periodic interval %v", got, want)
}
if got := deletionLedgerPause(60*1024, 0, interval); got != 0 {
t.Errorf("with the budget off: pause %v, want none", got)
}
}
// A steady stream of queued and finished deletes changes the ledger hundreds
// of times a second. Each change must not cost a rewrite of the whole set.
func TestDeletionLedgerSnapshotsArePaced(t *testing.T) {
withPersistedConfig(t, true)
// the per-snapshot overhead alone makes every snapshot cost 100ms
withLedgerBudget(t, 10*deletionLedgerSnapshotOverhead)
f, store := newSnapshottingLedgerTestFiler(t)
const changes = 400
start := time.Now()
for i := 0; i < changes; i++ {
f.queueDeletions(false, fmt.Sprintf("7,%08x", i))
if i > 0 {
f.forgetDeletion(fmt.Sprintf("7,%08x", i-1), false)
}
time.Sleep(time.Millisecond)
}
elapsed := time.Since(start)
// one at the first change, then one per pause
if got, limit := store.snapshots.Load(), int64(elapsed/(100*time.Millisecond))+2; got > limit {
t.Fatalf("%d ledger changes in %v took %d snapshots, want at most %d", 2*changes-1, elapsed, got, limit)
}
// what the stream left pending is still persisted, one pause later at most
want := fmt.Sprintf("7,%08x", changes-1)
deadline := time.Now().Add(5 * time.Second)
for {
persisted, _ := readPersistedLedger(t, f)
if len(persisted) == 1 && persisted[0] == want {
break
}
if time.Now().After(deadline) {
t.Fatalf("persisted ledger is %v after the stream ended, want [%s]", persisted, want)
}
time.Sleep(10 * time.Millisecond)
}
}
// The pause follows a snapshot, it does not precede one: the first id queued
// after a quiet spell is persisted at once, not a pause or a tick later.
func TestDeletionLedgerFirstChangeIsPersistedAtOnce(t *testing.T) {
withPersistedConfig(t, true)
// a budget that makes every pause as long as the periodic interval
withLedgerBudget(t, 1)
f, _ := newSnapshottingLedgerTestFiler(t)
f.queueDeletions(false, "9,01")
deadline := time.Now().Add(deletionPersistInterval() / 2)
for {
if persisted, ok := readPersistedLedger(t, f); ok && len(persisted) == 1 && persisted[0] == "9,01" {
return
}
if time.Now().After(deadline) {
t.Fatalf("the first queued id was not persisted within %v", deletionPersistInterval()/2)
}
time.Sleep(5 * time.Millisecond)
}
}
+30 -35
View File
@@ -105,49 +105,41 @@ func TestDeletionRetryQueue_OverflowProtection(t *testing.T) {
func TestDeletionRetryQueue_MaxAttemptsReached(t *testing.T) {
queue := NewDeletionRetryQueue()
// Add item
queue.AddOrUpdate("file1", "error", 0)
// Manually set retry count to max
makeReady := func() {
queue.lock.Lock()
defer queue.lock.Unlock()
item, exists := queue.itemIndex["file1"]
if !exists {
t.Fatal("Item not found in queue")
}
item.NextRetryAt = time.Now().Add(-1 * time.Second)
heap.Fix(&queue.heap, item.heapIndex)
}
queue.lock.Lock()
item, exists := queue.itemIndex["file1"]
if !exists {
queue.lock.Unlock()
t.Fatal("Item not found in queue")
}
item.RetryCount = MaxRetryAttempts
item.NextRetryAt = time.Now().Add(-1 * time.Second) // Ready now
heap.Fix(&queue.heap, item.heapIndex)
queue.itemIndex["file1"].RetryCount = MaxRetryAttempts
queue.lock.Unlock()
makeReady()
// Try to get ready items - should be returned for the last retry (attempt #10)
readyItems, _ := queue.GetReadyItems(10)
if len(readyItems) != 1 {
t.Fatalf("Expected 1 item for last retry, got %d", len(readyItems))
// The last backed-off retry, then one attempt from each dead letter queue.
for _, wantDelay := range []time.Duration{DeadLetterRetryDelay, DeadLetterFinalRetryDelay, 0} {
readyItems, expired := queue.GetReadyItems(10)
if len(readyItems) != 1 || len(expired) != 0 {
t.Fatalf("Expected 1 ready item, got %d ready and %d expired", len(readyItems), len(expired))
}
queue.RequeueForRetry(readyItems[0], "still offline")
if delay := time.Until(readyItems[0].NextRetryAt); delay > wantDelay || delay < wantDelay-time.Minute {
t.Fatalf("attempt %d: expected next retry in ~%v, got %v", readyItems[0].RetryCount, wantDelay, delay)
}
makeReady()
}
// Requeue it, which will increment its retry count beyond the max
queue.RequeueForRetry(readyItems[0], "final error")
// Manually make it ready again
queue.lock.Lock()
item, exists = queue.itemIndex["file1"]
if !exists {
queue.lock.Unlock()
t.Fatal("Item not found in queue after requeue")
readyItems, expired := queue.GetReadyItems(10)
if len(readyItems) != 0 || len(expired) != 1 {
t.Errorf("Expected the item to be dropped after the dead letter queues, got %d ready and %d expired", len(readyItems), len(expired))
}
item.NextRetryAt = time.Now().Add(-1 * time.Second)
heap.Fix(&queue.heap, item.heapIndex)
queue.lock.Unlock()
// Now it should be discarded (retry count is 11, exceeds max of 10)
readyItems, _ = queue.GetReadyItems(10)
if len(readyItems) != 0 {
t.Errorf("Expected 0 items (max attempts exceeded), got %d", len(readyItems))
}
// Should be removed from queue
if queue.Size() != 0 {
t.Errorf("Expected queue size 0 after max attempts exceeded, got %d", queue.Size())
}
@@ -195,6 +187,9 @@ func TestIsRetryableError(t *testing.T) {
{"service unavailable", true, "service unavailable"},
{"i/o timeout", true, "I/O timeout"},
{"broken pipe", true, "broken pipe"},
{"replication locations [1] is less than volume 9 replication copy count [2]", true, "replica offline"},
{"write /data/9.dat: no space left on device", true, "disk full"},
{"No space left on device (os error 28)", true, "disk full (rust)"},
{"rpc error: code = Unknown desc = volume server 10.0.0.2:8080 is in maintenance mode", true, "maintenance mode"},
{"not found", false, "not found (not retryable)"},
{"invalid file id", false, "invalid input (not retryable)"},
Loaded 100 of 491 files, more files were not shown because too many files have changed in this diff. Show more