Compare commits

...
Author SHA1 Message Date
github-actions[bot] 530be3e373 4.48 2026-09-28 15:53:40 +00:00
Chris LuandDevin 9b3b12c607 filer: pin-aware reader cache eviction and stream release (#11503)
* filer: synchronize stream pins and release them on transitions

Guard chunkStream.cacher with the ReaderCache lock everywhere: mount
sections share one ChunkReadAt across concurrent reads, and unsynchronized
release could double-unpin. Reads served from the chunk cache now detach
the stream's pin instead of retaining the previous chunk. Eviction prefers
unpinned downloaders so a pinned buffer is not dropped mid-stream. A new
ReleaseStream lets callers drop their pin without destroying the shared
cache; S3 and WebDAV readers use it. lastChunkFid becomes atomic since
concurrent mount reads can update it.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: keep eviction bounded when every downloader is pinned

Both eviction paths still fall back to a pinned victim when no unpinned
one exists, so abandoned stream pins cannot bypass the downloader limit
or stall the memory budget. Budget eviction also rechecks the pin under
the ReaderCache lock at removal time: a stream that pinned the selected
victim in between keeps it mapped and the selection retries.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: restore budget bookkeeping when a victim gets pinned mid-eviction

removeUnpinned losing the pin race left the victim out of the idle list
while still holding its reservation, making it unevictable even as the
pinned fallback. Push it back when the reservation is still live.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-28 22:37:04 +08:00
Tobias Gurtzick 3abdef3202 filer: keep shared chunk buffers pinned while another stream reads them (#11502)
The ReaderCache is shared by all streams of a process (every S3 GET, for
instance), but a ChunkReadAt released chunks as if it owned them:

- moving on to the next chunk called UnCache on the previous one,
  destroying the buffer even when other streams were still inside it;
- since #11384 a buffer is dropped once any reader has consumed it to the
  end and no read call is in flight. Streams copy out in slices (256 KiB
  in the S3 gateway), so between two calls a slower stream is not
  attached and loses the buffer to a faster one.

Either way the slower stream refetches the whole chunk from the volume
servers. With many clients downloading the same popular object at once,
each chunk is fetched over and over; in production we saw the S3 gateway
pull ~10 Gbit/s from volume servers while serving ~1 Gbit/s to clients.

A ChunkReadAt now pins the chunk it is positioned in. The pin is taken
and released only under the ReaderCache lock, since concurrent ReadAt
calls on one ChunkReadAt (as in mount) share it. It is released when the
stream reads the chunk to its end, moves to another chunk (including one
served from the chunk cache), or falls back to random reads. A buffer is
dropped once no stream pins it and no read is in progress, if it was
consumed or its last stream left it; a read still in flight when the
stream leaves drops it on detach, as UnCache did via destroy. Eviction by
slot limit and memory budget is unchanged.

lastChunkFid is now guarded as well: concurrent ReadAt calls raced on it.

Tests: two ChunkReadAt instances streaming one object in interleaved
slices fetch each chunk exactly once (2-3 times before); leaving a chunk
for a chunk-cache hit or while another read is in flight releases it;
concurrent ReadAt calls on one ChunkReadAt leave no pins behind under
-race.
2026-09-28 21:56:04 +08:00
Chris LuandDevin 43fd5b8d82 volume: reclaim staged EC shard generations left by the 2PC switch (#11501)
* volume: remove staged EC generation files on teardown and shard delete

The 2PC generation switch stages each run as <base>.ecNN.v<N> plus
versioned .ecx/.ecj/.vif files. Nothing on the volume server removes
them: isEcDataShardFile only recognises the exact .ecNN name, so the
staged files are invisible to every bookkeeping pass, and even
full_teardown's wipe-all path left them behind. Each re-encode therefore
leaks a full shard set per shard-holding disk.

RemoveEcGenerationFiles sweeps <base>.ec*.v<N> and <base>.vif.v<N>,
optionally keeping generations at or above a threshold; teardown and the
reconcile wipe remove every generation, and a per-shard delete removes
that shard's staged generations too.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: delete staged EC generations older than N via VolumeEcShardsDelete

After a 2PC generation switch commits, the superseded generation's
<base>.*.v<N> files sit on disk with no cleanup path: teardown removes
everything, and a per-shard delete only touches the named shards, so the
executor had no RPC that reclaims just the staged leftovers.

delete_generations_older_than removes staged generation files strictly
below the threshold on every disk. Versioned files are never mounted, so
nothing is unloaded first; the committed generation and the canonical
files are preserved.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: mirror staged EC generation cleanup

Parity with the Go volume server: remove_ec_generation_files sweeps
<base>.ec*.v<N> and <base>.vif.v<N> staged by the 2PC switch, called by
remove_ec_volume_files (which covers both teardown paths) and the new
delete_generations_older_than request field; delete_ec_shards removes a
shard's staged generations along with the canonical file.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: match staged generation filenames literally

filepath.Glob interprets metacharacters in the collection part of the
base name, so a collection like a[bc] could match another volume's
staged files (or miss its own). Scan the directory and compare names
literally instead, mirroring the Rust read_dir implementation.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: report generation-sweep errors and drop the store lock first

- snapshot the location base names under the read lock and run the
  filesystem sweep after dropping it, so a slow disk cannot stall the
  store;
- record per-entry read_dir errors in remove_ec_generation_files and
  propagate them from remove_ec_shard_generations instead of flatten()
  skipping them;
- warn when a staged-shard generation fails to delete rather than
  reporting success with files left behind.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: fail shard delete when the staged-generation listing fails

A transient ReadDir failure fell back to removing canonical shard names
only: staged .v<N> files survived while the RPC still reported success,
leaving the leak invisible to retrying callers. ENOENT still means the
disk simply has no such directory; other listing errors now propagate.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: propagate staged-generation removal failures

delete_ec_shards logged remove_ec_shard_generations errors and the RPC
returned success while staged .v<N> files remained, diverging from the
Go handler which surfaces the failure. The sweep keeps processing the
remaining shards, retains the first error, and volume_ec_shards_delete
maps it to Status::internal so callers can retry.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rust volume: notify state change even when the shard sweep errors

delete_ec_shards already deletes and unmounts the shards before
returning a staged-generation failure, so returning early skipped
volume_state_notify and the master kept routing to them until the next
heartbeat. Notify before propagating the error.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-28 21:55:25 +08:00
yi111andChris Lu 150a69fe11 master: make volume capacity reservation timeout configurable (#11426) (#11497)
* master: make volume capacity reservation timeout configurable (#11426)

* master: expire reservations on reads, fix int timeout units

- AvailableSpaceForReservation now expires reservations too: a node that
  is full of reservations is filtered out before TryReserveCapacity can
  clean them, which stranded expired capacity indefinitely.
- Drop TryReserveCapacityWithTimeout: a per-call timeout lets one caller
  expire another's live reservations, and the Node interface stays
  stable for implementations outside this tree.
- parseReservationTimeout no longer routes integer values through
  GetDuration, which read them as nanoseconds; bare numbers are
  seconds. The 5m fallback is now the shared DefaultReservationTimeout.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-09-28 18:40:11 +08:00
yi111andChris Lu 4fec65d949 filer: demote client-cancelled directory listing log from error (#11495) (#11496)
* filer: demote client-cancelled directory listing log from error (#11495)

* filer: quote path in canceled listing log

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-09-28 14:35:41 +08:00
github-actions[bot] f564918685 docs: regenerate star history chart 2026-09-28 00:52:53 +00:00
Chris LuandDevin f9289f0570 s3: do not promote ?prefix into the object for non-List actions (#11494)
* s3: do not promote ?prefix into the object for non-List actions

authRequestWithAuthType mapped an empty object to the prefix parameter for
every action, so PUT /bucket?versioning&prefix=x authorized as Write:bucket/x.
An object-scoped grant (Write:bucket/*) could then change bucket versioning,
lifecycle, cors, and object-lock configuration, and the promoted object also
made ResolveS3Action report s3:PutObject to attached IAM policies.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: treat GET ?uploads as a bucket listing for authorization

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: resolve the listing action through the bucket-level object

resolveS3AuthTarget fed the promoted prefix to ResolveS3Action, so a
bucket-level ?uploads request resolved as s3:GetObject on the prefix ARN
in the admin explicit-deny check. Resolve both action and resource
against the object the bucket listing actually scopes.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: resolve the listing action through the bucket-level object in AuthorizeAction

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: drop the unreachable object-level uploads case from the resolver test

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-28 07:17:58 +08:00
4303b3aa4c s3: keep a listing's start position inside the requested prefix (#11493)
* s3: a list marker that sorts past the prefix leaves nothing to list

AWS scopes a listing to keys under Prefix; StartAfter, Marker and
continuation tokens only reposition inside that range. A marker that
diverges from the prefix at a larger byte is after every key the prefix
can match, so the page is empty. normalizePrefixMarker used to keep such
a marker as the walk cutoff at the bucket root, where the walk descends
into the marker's own directory and returns keys the prefix never names.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: keep the listing variant's action when a prefix is promoted to object

authRequestWithAuthType promotes ?prefix= into the object argument for
the legacy CanDo path. ResolveS3Action treats a non-empty object as
object-level, so a bucket-level ?versions or ?uploads request carrying a
prefix missed its specific action and fell back to the base List action:
an s3:ListBucket grant then covered s3:ListBucketVersions, and an
explicit Deny on the specific action was skipped on the same path.

Resolve the action against the same bucket-level object the resource
ARN already uses.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: treat GET ?uploads as a bucket listing for authorization

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Update weed/s3api/auth_credentials.go

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-09-28 06:58:44 +08:00
yi111andChris Lu a0ee7ba314 s3: ignore empty intermediate directories in bucketHasUserObjects (#11490) (#11491)
* s3: ignore empty intermediate directories in bucketHasUserObjects (#11490)

* s3: keep nested reserved-named dirs from hiding user objects

Reserved folders (.uploads, *.versions) are internal only at the bucket
root; deeper entries with those names are user key prefixes and must be
walked. Also treat a missing subdirectory as empty via isFilerNotFound
(list errors cross gRPC as status errors, not the sentinel), let names
containing backslashes count as objects, and walk iteratively so empty
chains deeper than the old scan depth no longer report non-empty.

* s3: treat reserved-named directories as internal at every level

Object listing interprets .uploads and *.versions directories as
internal storage wherever they appear, so walking them during the
emptiness check would report invisible version remnants as user objects
and block deletion. A reserved name on a file still counts, matching
listing which only special-cases directories.

* s3: count explicit directory objects under reserved names

A directory object created by PutObject (MIME or prefix-object marker
set) is user data even when named .uploads or *.versions; only a plain
directory with a reserved name is internal storage.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-09-28 06:56:46 +08:00
Chris LuandDevin a976b21010 s3: require dedicated object-lock permissions for x-amz-object-lock-* headers (#11492)
* s3: require dedicated object-lock permissions for x-amz-object-lock-* headers

PutObject, CreateMultipartUpload, and PostPolicy honor the retention and
legal-hold headers after only the route's s3:PutObject check, so a
write-only principal could pin a version under COMPLIANCE retention that
nobody can remove before its retain-until date. On AWS these headers
require s3:PutObjectRetention / s3:PutObjectLegalHold. validateObjectLockHeaders
is the shared funnel for all four call sites; it now authorizes the
corresponding dedicated action when each header is present.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: record the verified POST-policy signer as the request identity

The handler authenticated the form policy signature but stored only the
signer's name, so downstream authorization (the object-lock header check)
re-authenticated the form-signed request as anonymous and evaluated the
wrong principal.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-27 20:17:12 +08:00
e57f8c4d87 volume server: read GET/HEAD needles off the store lock, and only once (#11487)
The GET/HEAD handler read the needle synchronously on the tokio worker
while holding store.read(): first a stream-info read that loaded the
whole record just to parse its meta, then, for every needle that was not
streamed (small, compressed, chunk manifest, image ops), a second full
read. For a tiered volume each read is an S3 GET under the store lock,
and a writer queued behind it parks every other store reader.

The regular-volume read now runs in spawn_blocking. Under the store guard
it only resolves a NeedleReadPlan (index lookup, a freshly opened .dat
handle or the remote backend, offset, size); the guard is dropped before
any needle data I/O. No data-file lease is held across the read either,
since a writer waits for one while holding the store write lock. The
index size decides the read, as in Go's readNeedle: a HEAD, a ranged read
or a needle above the stream threshold reads only its header and meta
tail (ReadNeedleMeta) and hands off to StreamingBody or the range path;
everything else is read in full once, with its checksum verified. A
compressed or manifest needle found by the meta read is then read in
full once. The range-from-source read also moves to spawn_blocking.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-09-27 20:13:15 +08:00
67691a1eea volume server: split volume_copy into phases and type the delete-after-status gate (#11485)
volume_copy was one ~400-line handler, and the rule that an existing
local replica is deleted only after the source's ReadVolumeFileStatus
succeeded was held by statement order alone. The keep_remote_data=true
that the pre-copy delete and the failed-copy rollback must share was
kept in sync by a comment pointing from one to the other.

The handler is now a ~60-line orchestrator over connect_to_copy_source,
SourceVolumeStatus::fetch, delete_existing_replica,
plan_copy_destination and a VolumeCopyJob whose run() drives
preallocate_dat, transfer_files, finish_copied_files and
mount_and_reply, with cleanup_failed_copy on error.
delete_existing_replica takes a &SourceVolumeStatus, which only fetch
can construct (private field in a child module), so the delete cannot
be called before the status RPC. Both deletes go through
delete_replica_keep_remote.

Pure refactor: call order, status codes and messages, cancellation
checks, throttling, progress reports and cleanup are unchanged.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-09-27 20:12:55 +08:00
hsdfat 02353444ac fix(volume-rust): reserve a disk before replacing a replica in VolumeCopy, and check record counts (#11483)
* fix(volume-rust): reserve a disk before replacing a replica in VolumeCopy, and check record counts

Port of the Go VolumeCopy hardening in #11238 and #11252.

- Pick the destination disk before deleting the existing replica, counting
  the slot that replica holds as free. If no disk qualifies, the healthy
  replica is kept instead of being deleted.
- Read the source's VolumeStatus before and after the copy. When both
  succeed and the counts did not change, the mounted replica's file and
  deleted counts must match; on mismatch it is unmounted and its files
  removed. A failed "before" read skips the check; a failed "after" read
  fails the copy.

* fix(volume-rust): let a departing caller cancel VolumeCopy's post-copy status read

Go reads the source's status after the copy with stream.Context(), so the
call ends when the caller leaves. The Rust call had no such link: a
source that stalled there held the copied, unmounted files after the
caller was gone. Race it against the response channel, like the other
blocking steps, so the usual error cleanup removes the partial copy.
2026-09-27 19:40:07 +08:00
Eliah RusinandClaude Opus 5.5 68944e83a3 volume: typed tier errors so a missing remote object answers NotFound (#11484)
remote_storage/s3_tier.rs returned Result<_, String> from every
transfer (upload_file, download_file, read_range[_blocking],
delete_file[_blocking]) and from the tier runtime helpers. The tier
move handlers could only wrap that in Status::internal, so a .dat whose
remote object is gone was indistinguishable from an I/O failure to
weed shell.

Add TierError { NotFound, Io, RuntimeUnavailable, Aborted }. Each
variant carries the existing message verbatim. NotFound follows the
rules remote_storage/s3.rs already uses: raw 404 status on HEAD,
NoSuchKey code on GET; a bare 404 on GET stays Io. A progress-callback
Err becomes Aborted. VolumeError gains a transparent Tier variant and
From<VolumeError> for Status maps Tier(NotFound) to NotFound; the tier
move handlers go through status_with_context, so their message text is
unchanged. Every other tier failure is still Internal.

The remote needle read path keeps io::Error::other, so its error kind
and vacuum's handling of it do not change.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 19:39:25 +08:00
Eliah RusinandClaude Opus 5.5 00310f6588 volume server: run the vacuum compaction copy without the store lock (#11482)
* volume server: run the vacuum compaction copy without the store lock

VacuumVolumeCompact held the store write lock for the whole live-needle
copy, including every progress blocking_send on the 16-deep stream. On a
large volume that is minutes with every read, write and heartbeat on the
node parked behind it, long enough for the master to unregister the node.

Split compaction the way Go's CompactByIndex runs it. A short locked step
claims the volume's compacting flag, records the makeup_diff watermark
(index size and compaction revision) and opens fresh .dat/.idx handles.
The copy then replays .idx up to the watermark and copies from those
handles with the store lock released; writes that land meanwhile are
replayed by makeup_diff at commit, as before. The flag is an Arc<AtomicBool>
released when the job is dropped, so every exit path clears it.

Because the flag is now visible to other callers, the operations that would
pull the files out from under the copy refuse while it is set: unmount
(and VolumeConfigure, which unmounts and remounts), delete (checked before
the volume is removed from the map, which a refused destroy used to leave
unmounted), cleanup, and index relocation. A second compact and a commit
stay no-ops, as in Go. The pre-copy fsync is dropped: the copy reads its
own handles through the page cache and .cpd/.cpx are fsynced before commit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* volume: keep a read-only in-memory index's size for the compaction copy

The unlocked copy replays .idx up to index_file_size(). A read-only
volume whose .sdx could not be built loads its index into memory without
a writer, so that size stayed 0: the copy came out empty and the commit
replaced the volume with it. CompactNeedleMap::load_from_idx now records
the rows it loaded, which is also what Go's IndexFileSize reports for a
read-only index.

The copy's index replay now stops reading at the recorded size instead
of walking rows appended since, which makeup_diff replays anyway.

Adds tests for compacting a read-only volume on both the sorted index
and the in-memory fallback, and for VolumeConfigure stopping when the
unmount is refused during a copy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* volume server: stop a vacuum copy as soon as its client is gone

The progress callback only noticed a closed response stream when a report
was due, every 128 MiB. With the copy now running outside the store lock,
a copy nobody waits for keeps the volume marked compacting and so keeps
refusing unmount, delete and cleanup until that next report. Check the
stream on every callback.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 19:38:59 +08:00
Eliah RusinandClaude Opus 5.5 5c9c424a84 volume server: stream ReadAllNeedles without holding the store lock (#11481)
* volume server: stream ReadAllNeedles without holding the store lock

read_all_needles held store.read() while Volume::read_all_needles read
every live needle of the volume into a Vec, and kept holding it through
the whole blocking_send loop. Memory grew with the volume, and a slow
client parked the scan in a send with the guard held; needle writes and
the heartbeat take store.write() on a writer-preferring lock, so the node
stopped serving until the client caught up.

Take a DatScanPlan (fresh .dat open, end bound) under a short guard and
walk it with the guard released, sending one needle at a time. Each
record is checked against the live needle map under a brief read guard,
as the scan reaches it, and only a live record is parsed, so a damaged
stale copy does not fail the stream. Records appended while a pass ran
are walked by a follow-up plan, so a needle overwritten during the scan
is streamed once, as its new copy. A vacuum commit or re-create of the
volume during the scan fails the stream, since the map's offsets no
longer describe the pinned file; the plan carries the volume instance
and compaction revision for that check.

DatScanPlan::scan_records yields records unparsed; scan keeps its
behaviour on top of it. Volume::read_all_needles has no caller left and
is removed; its tests move to the RPC.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* volume server: check ReadAllNeedles liveness only once the send can proceed

The per-record liveness check ran before blocking_send, so a scan parked
on a full channel held a record it had already judged live. An overwrite
landing during that park left the old copy in the stream, and the
continuation over appended records then streamed the new copy as well.

Reserve channel space first, then take the store read guard, check the
record against the needle map and enqueue it through the permit before
releasing the guard. The wait for space still happens without the lock;
the record is parsed before the guard is taken, and its parse error only
counts if the record turns out to be live.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 19:38:43 +08:00
Eliah RusinandClaude Opus 5.5 5218e68554 volume server: collect heartbeats under the store read lock, off the runtime (#11480)
* volume server: collect heartbeats under the store read lock, off the runtime

Every pulse tick, options change and volume-state notification took
store.write() for a whole heartbeat pass, directly on the async heartbeat
task. The pass fstats every volume's .dat twice and hashes its report, so
on a server with many volumes it held the store exclusively for the whole
scan: reads and writes stalled, and with the writer-preferring RwLock a
pending pass parked every new reader too.

The pass only needs to mutate the store for a few rare actions: removing
expired EC volumes, deleting expired volumes past their removal delay, and
setting no-write on IO-quarantined volumes. It now runs under store.read(),
records those as (disk, volume id) actions, and applies them afterwards
under a short store.write() that is only taken when there is something to
do. Each action re-checks its target under the write lock, so a volume
written to, replaced or removed in between is left alone. Expired EC
volumes are still removed before the volume pass, as before, because the
EC shard count feeds the disk-space-low max volume count. Every pass runs
on the blocking pool via spawn_blocking.

The heartbeat message is unchanged for the same store state.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* volume server: take has_no_ec_shards with the heartbeat's volume list

The heartbeat pass took has_no_ec_shards from the EC phase's read lock,
then built the volume list under a second one. An EC shard mounted in
between went out as "no EC shards" beside a volume list taken after the
mount, and the master clears a server's EC registrations on that flag.

has_no_ec_shards is now computed under the same read lock as the volume
list, with the EC phase's filter: not expired, not quarantined, at least
one shard.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 19:38:23 +08:00
github-actions[bot] 00cffa028c docs: regenerate star history chart 2026-09-27 00:53:30 +00:00
Chris LuandDevin a261f90e18 vacuum: let the sweep release volumes that stay empty and quiet (#11477)
* vacuum: let the sweep release volumes that stay empty and quiet

Vacuuming reclaims bytes but not slots: a fully emptied volume stays
registered to its collection forever, and since growth is gated only on
slot count a store at 99% free disk can still refuse writes to other
collections (#11429). volume.deleteEmpty exists but is manual-only.

With -vacuumDeleteEmptyAfterSeconds (or master.vacuumDeleteEmptyAfterSeconds
under weed server/mini; default 0, off) the automatic sweep now deletes
replica copies that have stayed empty and quiet for that long, the same
rule volume.deleteEmpty applies on demand: remote-backed copies are
skipped, and every delete carries the volume server's onlyEmpty /
onlyGarbage guards so a copy written since the last report is refused
rather than removed. Copies that still hold data or were written
recently stay; only a volume whose every copy is deleted leaves the
sweep's work map, sparing a compaction of bytes that are all deleted.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vacuum: harden empty-volume sweep against partial and racing deletes

Review follow-up on #11477:

- delete a volume only when every replica copy is a verifiable
  empty-and-quiet candidate; deleting the empty copy of a volume whose
  sibling holds live files would silently cut its replica count
  (greptile P1).
- drain the volume out of the writable list before deleting, the same
  drain the compact pass uses, so PickForWrite stops assigning it and
  pending writes settle (devin).
- bound the VolumeDelete RPC so one stalled server cannot hold the
  vacuum lock indefinitely (greptile P1, reusing allocateVolumeTimeout).

The vid2location panic scenario raised in review does not exist:
VolumeLocationList methods are nil-receiver safe and a missing vid just
fails enoughCopies, so a partially deleted volume skips compaction
instead of crashing the sweep.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vacuum: unregister deleted empty replicas and prune the sweep list

A successful VolumeDelete only updates the volume server; the master
still tracked the replica and kept it in the sweep's location list for
the compaction pass (coderabbit on #11477). Unregister the replica right
after its delete succeeds and drop it from the sweep copy, so a partially
deleted volume only compacts copies that still exist.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vacuum: pin deleting volumes out of the writable list across heartbeats

Review follow-up on #11477 (greptile): DrainAndRemoveFromWritable only
removed the volume once; a heartbeat landing between the drain and the
replica deletes re-evaluated writability and re-added it, so a client
write could reach a replica whose siblings were already gone and leave
the volume under-replicated when the last copy refused its onlyEmpty
delete.

MarkDeleting records the vid in deletingVolumes — checked inside
setVolumeWritable so heartbeat, capacity-recovery, and admin re-add
paths all hold it out — and UnmarkDeleting releases it once the sweep
finishes the copy pass. A partially deleted volume's surviving replicas
then return to writable through the normal heartbeat path.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vacuum: restore writability when a sweep delete survives

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-27 07:05:22 +08:00
Chris LuandDevin be29f44d87 s3: record requester identity before the authz verdict (#11479)
* s3: record requester identity before the authz verdict for audit

Identity was only stored in request context on the success branch, so
denied requests reached WriteErrorResponse without requester attribution
and audit entries had empty requester/requester_arn/requester_identity.
Authentication failures still resolve no identity, so unauthenticated
denials stay unattributed.

Fixes #11474

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: keep the resolved identity through authz denial in Auth

Review follow-up on #11479 (devin): authRequest discarded the identity
on every error, so a request that authenticated fine but failed the
action check still reached handleAuthResult with no identity and the
deny path could not audit a requester. Auth now calls
authRequestWithAuthType directly, the same entry AuthPostPolicy uses,
so the resolved identity reaches the error writer; a failed authN
still resolves no identity and stays unattributed. The regression test
now signs a denied request end to end through iam.Auth.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-27 07:03:01 +08:00
Chris LuandDevin 2864bc0fe8 s3: honor configured session bounds on AssumeRole and LDAP identity (#11478)
* sts: export CalculateSessionDuration

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: honor configured session bounds on AssumeRole and LDAP identity

prepareSTSCredentials hardcoded a one-hour session when the caller
omitted DurationSeconds, so sts.tokenDuration was ignored and
sts.maxSessionLength only clamped explicit requests: asking for 3600s
against a 20m ceiling was rejected while omitting the parameter was
granted a full hour (#11473). The two affected handlers now use the
same default-then-cap calculation as AssumeRoleWithWebIdentity.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iam: keep MaxSessionDuration through role store copies

copyRoleDefinition rebuilt RoleDefinition field by field and dropped
MaxSessionDuration, so memory-backed role stores silently discarded the
per-role session bound on every write and read (devin on #11478).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* sts: apply per-role MaxSessionDuration to resolved session durations

Review follow-up on #11478 (devin): the role bound only ever applied to
explicit DurationSeconds values — an omitted duration resolved to the
configured default and sailed past a shorter role max on every assume
path.

- capDurationByRole now resolves min(requested||tokenDuration, roleMax),
  so AssumeRoleWithWebIdentity and AssumeRoleWithCredentials cap
  defaults the same way they cap explicit values.
- prepareSTSCredentials caps the calculated duration at the named
  role's MaxSessionDuration, covering the AssumeRole and LDAP handlers;
  self-assumption has no role definition to consult.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* iam: keep MaxSessionDuration through the cached role store

genericCopyRoleDefinition drops MaxSessionDuration the same way
copyRoleDefinition did, so the cached filer role store reads back a zero
maximum and every downstream duration cap is skipped (greptile on
#11478).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* sts: only materialize defaults that pass session duration validation

Review follow-up on #11478 (greptile): materializing an omitted
DurationSeconds into an explicit value could exceed the service's own
input bound (a configured tokenDuration above maxSessionLength) and turn
a previously working request into a validation error.

capDurationByRole now leaves nil anything the service can resolve
better itself, clamps a tightened default at maxSessionLengthSeconds,
and floors a role bound below 900s to the tightest issuable value.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-27 07:01:51 +08:00
Chris LuandDevin ab95d58b7c s3: keep dedicated object-lock actions pinned during action resolution (#11475)
* s3: keep dedicated object-lock actions pinned during action resolution

A coarse action that already names a dedicated operation (governance
bypass, retention, legal hold, bucket object-lock config) now resolves to
itself before request shape is consulted. Previously a synthetic
DELETE ?versionId authorization request re-resolved to
s3:DeleteObjectVersion, so the bypass check was satisfied by the
delete-version grant alone; with the pin it evaluates
s3:BypassGovernanceRetention as intended.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: cover pinned object-lock actions against competing query params

Locks in the resolution for every dedicated action in the pin set, incl.
the retention and legal-hold shapes carrying versionId.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-26 21:42:34 +08:00
73 changed files with 7738 additions and 2456 deletions

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.47"
appVersion: "4.48"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.47.1
version: 4.48.0
+1021 -1009
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+1
View File
@@ -475,6 +475,7 @@ message VolumeEcShardsDeleteRequest {
repeated uint32 shard_ids = 3;
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
uint32 delete_generations_older_than = 6; // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
}
message VolumeEcShardsDeleteResponse {
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
+5 -5
View File
@@ -209,7 +209,7 @@ impl RemoteStorageClient for S3RemoteStorageClient {
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
use aws_sdk_s3::config::http::{HttpRequest, HttpResponse};
use aws_sdk_s3::config::retry::RetryConfig;
@@ -224,9 +224,9 @@ mod tests {
/// so the error-mapping paths can be exercised without a network or a
/// running S3 server.
#[derive(Debug, Clone)]
struct CannedResponse {
status: u16,
body: &'static str,
pub(crate) struct CannedResponse {
pub(crate) status: u16,
pub(crate) body: &'static str,
}
impl HttpConnector for CannedResponse {
@@ -272,7 +272,7 @@ mod tests {
}
}
const NO_SUCH_KEY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
pub(crate) const NO_SUCH_KEY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message><Key>dir/missing</Key></Error>"#;
const NOT_FOUND_BODY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
+216 -88
View File
@@ -8,8 +8,11 @@ use std::future::Future;
use std::sync::{Arc, OnceLock, RwLock};
use aws_sdk_s3::Client;
use aws_sdk_s3::config::http::HttpResponse;
use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region};
use aws_sdk_s3::error::DisplayErrorContext;
use aws_sdk_s3::error::{DisplayErrorContext, SdkError};
use aws_sdk_s3::operation::get_object::GetObjectError;
use aws_sdk_s3::operation::head_object::HeadObjectError;
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::sync::Semaphore;
@@ -17,6 +20,53 @@ use tokio::sync::Semaphore;
/// Concurrency limit for multipart upload/download (matches Go's s3manager).
const CONCURRENCY: usize = 5;
/// A tier transfer failure. The variant is what callers match on; the
/// message is the operator-facing text.
#[derive(Debug, thiserror::Error)]
pub enum TierError {
/// The remote object does not exist.
#[error("{0}")]
NotFound(String),
/// An S3 request or a local file operation failed.
#[error("{0}")]
Io(String),
/// The tier I/O runtime could not be built or dropped the task.
#[error("{0}")]
RuntimeUnavailable(String),
/// The progress callback asked to stop.
#[error("{0}")]
Aborted(String),
}
// Not-found rules as in remote_storage/s3.rs: HEAD by the raw 404 status,
// GET by the NoSuchKey code only.
fn head_object_error(key: &str, e: SdkError<HeadObjectError, HttpResponse>) -> TierError {
let message = format!("failed to head object {}: {}", key, DisplayErrorContext(&e));
match e {
SdkError::ServiceError(ref se) if se.raw().status().as_u16() == 404 => {
TierError::NotFound(message)
}
_ => TierError::Io(message),
}
}
fn get_object_error(
key: &str,
range: &str,
e: SdkError<GetObjectError, HttpResponse>,
) -> TierError {
let message = format!(
"failed to get object {} range {}: {}",
key,
range,
DisplayErrorContext(&e)
);
match e {
SdkError::ServiceError(ref se) if se.err().is_no_such_key() => TierError::NotFound(message),
_ => TierError::Io(message),
}
}
/// Configuration for an S3 tier backend.
#[derive(Debug, Clone)]
pub struct S3TierConfig {
@@ -90,7 +140,7 @@ impl S3TierBackend {
&self,
file_path: &str,
progress_fn: F,
) -> Result<(String, u64), String>
) -> Result<(String, u64), TierError>
where
F: FnMut(i64, f32) -> Result<(), String> + Send + Sync + 'static,
{
@@ -98,7 +148,7 @@ impl S3TierBackend {
let metadata = tokio::fs::metadata(file_path)
.await
.map_err(|e| format!("failed to stat file {}: {}", file_path, e))?;
.map_err(|e| TierError::Io(format!("failed to stat file {}: {}", file_path, e)))?;
let file_size = metadata.len();
// Calculate part size: start at 64MB, scale up for very large files (matches Go)
@@ -121,15 +171,15 @@ impl S3TierBackend {
.send()
.await
.map_err(|e| {
format!(
TierError::Io(format!(
"failed to create multipart upload: {}",
DisplayErrorContext(&e)
)
))
})?;
let upload_id = create_resp
.upload_id()
.ok_or_else(|| "no upload_id in multipart upload response".to_string())?
.ok_or_else(|| TierError::Io("no upload_id in multipart upload response".to_string()))?
.to_string();
// Build list of (part_number, offset, size) for all parts
@@ -165,19 +215,21 @@ impl S3TierBackend {
let _permit = sem
.acquire()
.await
.map_err(|e| format!("semaphore error: {}", e))?;
.map_err(|e| TierError::Io(format!("semaphore error: {}", e)))?;
// Read this part's data from the file at the correct offset
let mut file = tokio::fs::File::open(&fp)
.await
.map_err(|e| format!("failed to open file {}: {}", fp, e))?;
.map_err(|e| TierError::Io(format!("failed to open file {}: {}", fp, e)))?;
file.seek(std::io::SeekFrom::Start(off))
.await
.map_err(|e| format!("failed to seek to offset {}: {}", off, e))?;
.map_err(|e| {
TierError::Io(format!("failed to seek to offset {}: {}", off, e))
})?;
let mut buf = vec![0u8; size];
file.read_exact(&mut buf)
.await
.map_err(|e| format!("failed to read file at offset {}: {}", off, e))?;
file.read_exact(&mut buf).await.map_err(|e| {
TierError::Io(format!("failed to read file at offset {}: {}", off, e))
})?;
let upload_part_resp = client
.upload_part()
@@ -189,12 +241,12 @@ impl S3TierBackend {
.send()
.await
.map_err(|e| {
format!(
TierError::Io(format!(
"failed to upload part {} at offset {}: {}",
pn,
off,
DisplayErrorContext(&e)
)
))
})?;
let e_tag = upload_part_resp.e_tag().unwrap_or_default().to_string();
@@ -213,9 +265,9 @@ impl S3TierBackend {
};
(guard.1)(uploaded as i64, pct)
};
progress_result?;
progress_result.map_err(TierError::Aborted)?;
Ok::<_, String>(
Ok::<_, TierError>(
CompletedPart::builder()
.e_tag(e_tag)
.part_number(pn)
@@ -230,7 +282,7 @@ impl S3TierBackend {
for handle in handles {
let part = handle
.await
.map_err(|e| format!("upload task panicked: {}", e))??;
.map_err(|e| TierError::Io(format!("upload task panicked: {}", e)))??;
completed_parts.push(part);
}
@@ -248,13 +300,13 @@ impl S3TierBackend {
.send()
.await
.map_err(|e| {
format!(
TierError::Io(format!(
"failed to complete multipart upload: {}",
DisplayErrorContext(&e)
)
))
})?;
Ok::<(), String>(())
Ok::<(), TierError>(())
}
.await;
@@ -297,7 +349,7 @@ impl S3TierBackend {
dest_path: &str,
key: &str,
progress_fn: F,
) -> Result<u64, String>
) -> Result<u64, TierError>
where
F: FnMut(i64, f32) -> Result<(), String> + Send + Sync + 'static,
{
@@ -309,7 +361,7 @@ impl S3TierBackend {
.key(key)
.send()
.await
.map_err(|e| format!("failed to head object {}: {}", key, DisplayErrorContext(&e)))?;
.map_err(|e| head_object_error(key, e))?;
let file_size = head_resp.content_length().unwrap_or(0) as u64;
@@ -321,10 +373,12 @@ impl S3TierBackend {
.truncate(true)
.open(dest_path)
.await
.map_err(|e| format!("failed to open dest file {}: {}", dest_path, e))?;
.map_err(|e| {
TierError::Io(format!("failed to open dest file {}: {}", dest_path, e))
})?;
file.set_len(file_size)
.await
.map_err(|e| format!("failed to set file length: {}", e))?;
.map_err(|e| TierError::Io(format!("failed to set file length: {}", e)))?;
}
let part_size: u64 = 64 * 1024 * 1024;
@@ -360,7 +414,7 @@ impl S3TierBackend {
let _permit = sem
.acquire()
.await
.map_err(|e| format!("semaphore error: {}", e))?;
.map_err(|e| TierError::Io(format!("semaphore error: {}", e)))?;
let end = off + size - 1;
let range = format!("bytes={}-{}", off, end);
@@ -372,20 +426,13 @@ impl S3TierBackend {
.range(&range)
.send()
.await
.map_err(|e| {
format!(
"failed to get object {} range {}: {}",
key,
range,
DisplayErrorContext(&e)
)
})?;
.map_err(|e| get_object_error(&key, &range, e))?;
let body = get_resp
.body
.collect()
.await
.map_err(|e| format!("failed to read body: {}", e))?;
.map_err(|e| TierError::Io(format!("failed to read body: {}", e)))?;
let bytes = body.into_bytes();
// Write at the correct offset (like Go's WriteAt)
@@ -393,13 +440,17 @@ impl S3TierBackend {
.write(true)
.open(&dp)
.await
.map_err(|e| format!("failed to open dest file {}: {}", dp, e))?;
.map_err(|e| {
TierError::Io(format!("failed to open dest file {}: {}", dp, e))
})?;
file.seek(std::io::SeekFrom::Start(off))
.await
.map_err(|e| format!("failed to seek to offset {}: {}", off, e))?;
.map_err(|e| {
TierError::Io(format!("failed to seek to offset {}: {}", off, e))
})?;
file.write_all(&bytes)
.await
.map_err(|e| format!("failed to write to {}: {}", dp, e))?;
.map_err(|e| TierError::Io(format!("failed to write to {}: {}", dp, e)))?;
// Report progress. The lock is released before the result is
// propagated so an aborting callback cannot poison the mutex
@@ -415,9 +466,9 @@ impl S3TierBackend {
};
(guard.1)(downloaded as i64, pct)
};
progress_result?;
progress_result.map_err(TierError::Aborted)?;
Ok::<_, String>(())
Ok::<_, TierError>(())
}));
}
@@ -425,7 +476,7 @@ impl S3TierBackend {
for handle in handles {
handle
.await
.map_err(|e| format!("download task panicked: {}", e))??;
.map_err(|e| TierError::Io(format!("download task panicked: {}", e)))??;
}
// fsync the file so its content is durable before the caller trims the .vif
@@ -434,16 +485,21 @@ impl S3TierBackend {
.write(true)
.open(dest_path)
.await
.map_err(|e| format!("failed to open {} for fsync: {}", dest_path, e))?;
.map_err(|e| TierError::Io(format!("failed to open {} for fsync: {}", dest_path, e)))?;
synced
.sync_all()
.await
.map_err(|e| format!("failed to fsync {}: {}", dest_path, e))?;
.map_err(|e| TierError::Io(format!("failed to fsync {}: {}", dest_path, e)))?;
Ok(file_size)
}
pub async fn read_range(&self, key: &str, offset: u64, size: usize) -> Result<Vec<u8>, String> {
pub async fn read_range(
&self,
key: &str,
offset: u64,
size: usize,
) -> Result<Vec<u8>, TierError> {
let end = offset + (size as u64).saturating_sub(1);
let range = format!("bytes={}-{}", offset, end);
let resp = self
@@ -454,25 +510,18 @@ impl S3TierBackend {
.range(&range)
.send()
.await
.map_err(|e| {
format!(
"failed to get object {} range {}: {}",
key,
range,
DisplayErrorContext(&e)
)
})?;
.map_err(|e| get_object_error(key, &range, e))?;
let body = resp
.body
.collect()
.await
.map_err(|e| format!("failed to read object {} body: {}", key, e))?;
.map_err(|e| TierError::Io(format!("failed to read object {} body: {}", key, e)))?;
Ok(body.into_bytes().to_vec())
}
/// Delete a file from S3.
pub async fn delete_file(&self, key: &str) -> Result<(), String> {
pub async fn delete_file(&self, key: &str) -> Result<(), TierError> {
self.client
.delete_object()
.bucket(&self.bucket)
@@ -480,16 +529,16 @@ impl S3TierBackend {
.send()
.await
.map_err(|e| {
format!(
TierError::Io(format!(
"failed to delete object {}: {}",
key,
DisplayErrorContext(&e)
)
))
})?;
Ok(())
}
pub fn delete_file_blocking(&self, key: &str) -> Result<(), String> {
pub fn delete_file_blocking(&self, key: &str) -> Result<(), TierError> {
let client = self.client.clone();
let bucket = self.bucket.clone();
let key = key.to_string();
@@ -501,11 +550,11 @@ impl S3TierBackend {
.send()
.await
.map_err(|e| {
format!(
TierError::Io(format!(
"failed to delete object {}: {}",
key,
DisplayErrorContext(&e)
)
))
})?;
Ok(())
})
@@ -516,7 +565,7 @@ impl S3TierBackend {
key: &str,
offset: u64,
size: usize,
) -> Result<Vec<u8>, String> {
) -> Result<Vec<u8>, TierError> {
let client = self.client.clone();
let bucket = self.bucket.clone();
let key = key.to_string();
@@ -530,20 +579,12 @@ impl S3TierBackend {
.range(&range)
.send()
.await
.map_err(|e| {
format!(
"failed to get object {} range {}: {}",
key,
range,
DisplayErrorContext(&e)
)
})?;
.map_err(|e| get_object_error(&key, &range, e))?;
let body = resp
.body
.collect()
.await
.map_err(|e| format!("failed to read object {} body: {}", key, e))?;
let body =
resp.body.collect().await.map_err(|e| {
TierError::Io(format!("failed to read object {} body: {}", key, e))
})?;
Ok(body.into_bytes().to_vec())
})
}
@@ -615,7 +656,7 @@ pub fn global_s3_tier_registry() -> &'static RwLock<S3TierRegistry> {
static TIER_RUNTIME: std::sync::Mutex<Option<tokio::runtime::Runtime>> =
std::sync::Mutex::new(None);
fn tier_handle() -> Result<tokio::runtime::Handle, String> {
fn tier_handle() -> Result<tokio::runtime::Handle, TierError> {
let mut slot = TIER_RUNTIME
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
@@ -625,7 +666,12 @@ fn tier_handle() -> Result<tokio::runtime::Handle, String> {
.thread_name("tier-io")
.enable_all()
.build()
.map_err(|e| format!("failed to build the tier I/O tokio runtime: {}", e))?;
.map_err(|e| {
TierError::RuntimeUnavailable(format!(
"failed to build the tier I/O tokio runtime: {}",
e
))
})?;
*slot = Some(runtime);
}
Ok(slot.as_ref().expect("just initialised").handle().clone())
@@ -635,9 +681,9 @@ fn tier_handle() -> Result<tokio::runtime::Handle, String> {
/// finishes. The caller may be a worker of *another* tokio runtime, so this
/// waits on a channel rather than `Handle::block_on`, which panics when
/// called from inside any runtime context.
fn block_on_tier_future<F, T>(future: F) -> Result<T, String>
fn block_on_tier_future<F, T>(future: F) -> Result<T, TierError>
where
F: Future<Output = Result<T, String>> + Send + 'static,
F: Future<Output = Result<T, TierError>> + Send + 'static,
T: Send + 'static,
{
let handle = tier_handle()?;
@@ -651,13 +697,15 @@ where
match rx.recv() {
Ok(Ok(result)) => result,
Ok(Err(join_error)) => Err(describe_join_error(join_error)),
Err(_) => Err("tier I/O runtime dropped the task before it finished".to_string()),
Err(_) => Err(TierError::RuntimeUnavailable(
"tier I/O runtime dropped the task before it finished".to_string(),
)),
}
}
/// Turn a `JoinError` into a message that keeps the panic payload, so an
/// SDK panic surfaces as "boom" rather than a fixed "thread panicked".
fn describe_join_error(join_error: tokio::task::JoinError) -> String {
fn describe_join_error(join_error: tokio::task::JoinError) -> TierError {
if join_error.is_panic() {
let payload = join_error.into_panic();
let message = if let Some(s) = payload.downcast_ref::<&str>() {
@@ -667,19 +715,20 @@ fn describe_join_error(join_error: tokio::task::JoinError) -> String {
} else {
"non-string panic payload".to_string()
};
format!("tier I/O task panicked: {}", message)
TierError::Io(format!("tier I/O task panicked: {}", message))
} else {
format!("tier I/O task failed: {}", join_error)
TierError::RuntimeUnavailable(format!("tier I/O task failed: {}", join_error))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::remote_storage::s3::tests::{CannedResponse, NO_SUCH_KEY};
use std::collections::HashSet;
use tokio::runtime::Handle;
fn probe() -> Result<(tokio::runtime::Id, Option<String>), String> {
fn probe() -> Result<(tokio::runtime::Id, Option<String>), TierError> {
block_on_tier_future(async {
Ok((
Handle::current().id(),
@@ -709,10 +758,12 @@ mod tests {
#[test]
fn block_on_tier_future_returns_the_value_and_the_error() {
assert_eq!(block_on_tier_future(async { Ok(7u32) }), Ok(7));
assert_eq!(
block_on_tier_future::<_, u32>(async { Err("nope".to_string()) }),
Err("nope".to_string())
assert_eq!(block_on_tier_future(async { Ok(7u32) }).unwrap(), 7);
let err = block_on_tier_future::<_, u32>(async { Err(TierError::NotFound("nope".into())) })
.unwrap_err();
assert!(
matches!(&err, TierError::NotFound(m) if m == "nope"),
"{err:?}"
);
}
@@ -761,8 +812,9 @@ mod tests {
Ok(())
})
.expect_err("a panicking future must be an error");
assert!(err.contains("boom 42"), "got: {err}");
assert!(err.contains("panicked"), "got: {err}");
assert!(matches!(err, TierError::Io(_)), "got: {err:?}");
assert!(err.to_string().contains("boom 42"), "got: {err}");
assert!(err.to_string().contains("panicked"), "got: {err}");
}
#[test]
@@ -774,7 +826,83 @@ mod tests {
Ok(())
})
.expect_err("a panicking future must be an error");
assert!(err.contains("static boom"), "got: {err}");
assert!(err.to_string().contains("static boom"), "got: {err}");
}
fn backend_answering(status: u16, body: &'static str) -> S3TierBackend {
let config = aws_sdk_s3::Config::builder()
.behavior_version(BehaviorVersion::latest())
.region(Region::new("us-east-1"))
.credentials_provider(Credentials::new("AKIATEST", "secret", None, None, "test"))
.endpoint_url("http://127.0.0.1:1")
.force_path_style(true)
.http_client(CannedResponse { status, body })
.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
.build();
S3TierBackend {
client: Client::from_conf(config),
bucket: "bucket".to_string(),
storage_class: "STANDARD".to_string(),
}
}
#[tokio::test]
async fn download_head_404_is_not_found() {
let tmp = tempfile::tempdir().unwrap();
let dest = tmp.path().join("1.dat");
let err = backend_answering(404, "")
.download_file(dest.to_str().unwrap(), "missing", |_, _| Ok(()))
.await
.unwrap_err();
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
assert!(
err.to_string()
.starts_with("failed to head object missing: "),
"{err}"
);
}
#[tokio::test]
async fn download_head_403_is_io() {
let tmp = tempfile::tempdir().unwrap();
let dest = tmp.path().join("1.dat");
let err = backend_answering(403, "")
.download_file(dest.to_str().unwrap(), "denied", |_, _| Ok(()))
.await
.unwrap_err();
assert!(matches!(err, TierError::Io(_)), "{err:?}");
}
#[tokio::test]
async fn read_range_no_such_key_is_not_found() {
let err = backend_answering(404, NO_SUCH_KEY)
.read_range("missing", 0, 8)
.await
.unwrap_err();
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
assert!(
err.to_string()
.starts_with("failed to get object missing range bytes=0-7: "),
"{err}"
);
}
#[tokio::test]
async fn read_range_bare_404_is_io() {
// As in Go, GET is not-found by the NoSuchKey code, not the status.
let err = backend_answering(404, "")
.read_range("missing", 0, 8)
.await
.unwrap_err();
assert!(matches!(err, TierError::Io(_)), "{err:?}");
}
#[test]
fn read_range_blocking_no_such_key_is_not_found() {
let err = backend_answering(404, NO_SUCH_KEY)
.read_range_blocking("missing", 0, 8)
.unwrap_err();
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
}
#[test]
File diff suppressed because it is too large. Load diff
+404 -71
View File
@@ -143,6 +143,78 @@ const STREAMING_THRESHOLD: u32 = 1024 * 1024; // 1 MB
/// Default chunk size for streaming reads from the dat file.
const DEFAULT_STREAMING_CHUNK_SIZE: usize = 64 * 1024; // 64 KB
/// Whether a GET/HEAD can be answered from the needle meta and the data file.
#[derive(Clone, Copy)]
struct SourceReadRequest {
is_head: bool,
has_range: bool,
has_image_ops: bool,
bypass_cm: bool,
}
impl SourceReadRequest {
/// The payload can be served as stored.
fn direct(&self, n: &Needle) -> bool {
!n.is_compressed() && !(n.is_chunk_manifest() && !self.bypass_cm) && !self.has_image_ops
}
/// HEAD, a range, or a stream.
fn served_from_source(&self, n: &Needle) -> bool {
self.is_head || (self.direct(n) && (self.has_range || n.data_size > STREAMING_THRESHOLD))
}
/// Meta first only if the needle could be served from source; its data
/// size is below its index size.
fn try_meta_first(&self, size: Size) -> bool {
self.is_head
|| (!self.has_image_ops && (self.has_range || size.0 > STREAMING_THRESHOLD as i32))
}
}
/// Blocking part of a GET/HEAD: the store guard is dropped before any needle
/// I/O, so a slow or tiered read cannot park store writers. `Ok(None)` is a
/// cookie mismatch.
fn read_needle_for_get(
state: &VolumeServerState,
vid: VolumeId,
needle_id: NeedleId,
cookie: Cookie,
read_deleted: bool,
request: SourceReadRequest,
) -> Result<
Option<(Needle, Option<crate::storage::volume::NeedleStreamInfo>)>,
crate::storage::volume::VolumeError,
> {
let mut plan = state
.store
.read()
.unwrap()
.needle_read_plan(vid, needle_id, read_deleted)?;
let blank = || Needle {
id: needle_id,
cookie,
..Needle::default()
};
let mut n = blank();
if request.try_meta_first(plan.size()) {
plan.read_meta(&mut n)?;
if n.cookie != cookie {
return Ok(None);
}
if request.served_from_source(&n) {
let info = plan.into_stream_info(&n);
return Ok(Some((n, Some(info))));
}
// Compressed or a chunk manifest: the payload is needed after all.
n = blank();
}
plan.read_full(&mut n)?;
if n.cookie != cookie {
return Ok(None);
}
Ok(Some((n, None)))
}
/// A body that streams needle data from the dat file in chunks using pread,
/// avoiding loading the entire payload into memory at once.
struct StreamingBody {
@@ -1112,11 +1184,7 @@ async fn get_or_head_handler_inner(
// Read needle — branching between regular volume and EC volume paths.
// EC volumes always do a full read (no streaming/meta-only).
let mut n = Needle {
id: needle_id,
cookie,
..Needle::default()
};
let n: Needle;
let read_deleted = query.read_deleted.as_deref() == Some("true");
let has_range = headers.contains_key(header::RANGE);
@@ -1193,24 +1261,49 @@ async fn get_or_head_handler_inner(
can_handle_range_from_source = false;
} else {
// ---- Regular volume read path (with streaming support) ----
bypass_cm = query.cm.as_deref() == Some("false");
track_download = download_guard.is_some();
let request_kind = SourceReadRequest {
is_head: method == Method::HEAD,
has_range,
has_image_ops,
bypass_cm,
};
// Try meta-only read first for potential streaming
let store = state.store.read().unwrap();
let si_result = store.read_volume_needle_stream_info(vid, &mut n, read_deleted);
stream_info = match si_result {
Ok(info) => Some(info),
Err(crate::storage::volume::VolumeError::StreamingUnsupported) => None,
Err(crate::storage::volume::VolumeError::NotFound) => {
let read_state = state.clone();
let read = tokio::task::spawn_blocking(move || {
read_needle_for_get(
&read_state,
vid,
needle_id,
cookie,
read_deleted,
request_kind,
)
})
.await;
(n, stream_info) = match read {
Ok(Ok(Some(found))) => found,
// Cookie mismatch
Ok(Ok(None)) => return StatusCode::NOT_FOUND.into_response(),
Ok(Err(
crate::storage::volume::VolumeError::NotFound
| crate::storage::volume::VolumeError::Deleted,
)) => {
metrics::HANDLER_COUNTER
.with_label_values(&[metrics::ERROR_GET_NOT_FOUND])
.inc();
return StatusCode::NOT_FOUND.into_response();
}
Err(crate::storage::volume::VolumeError::Deleted) => {
Ok(Err(e)) => {
metrics::HANDLER_COUNTER
.with_label_values(&[metrics::ERROR_GET_NOT_FOUND])
.with_label_values(&[metrics::ERROR_GET_INTERNAL])
.inc();
return StatusCode::NOT_FOUND.into_response();
return (
StatusCode::INTERNAL_SERVER_ERROR,
format!("read error: {}", e),
)
.into_response();
}
Err(e) => {
metrics::HANDLER_COUNTER
@@ -1223,19 +1316,9 @@ async fn get_or_head_handler_inner(
.into_response();
}
};
drop(store);
// Validate cookie
if n.cookie != cookie {
return StatusCode::NOT_FOUND.into_response();
}
bypass_cm = query.cm.as_deref() == Some("false");
track_download = download_guard.is_some();
let can_direct_source_read = stream_info.is_some()
&& !n.is_compressed()
&& !(n.is_chunk_manifest() && !bypass_cm)
&& !has_image_ops;
// Stream info is only returned for a reply served from the data file.
let can_direct_source_read = stream_info.is_some() && request_kind.direct(&n);
// Determine if we can stream (large, direct-source eligible, no range)
can_stream = can_direct_source_read
@@ -1246,41 +1329,6 @@ async fn get_or_head_handler_inner(
// Go uses meta-only reads for all HEAD requests, regardless of compression/chunked files.
can_handle_head_from_meta = stream_info.is_some() && method == Method::HEAD;
can_handle_range_from_source = can_direct_source_read && has_range;
// For chunk manifest or any non-streaming path, we need the full data.
// If we can't stream, do a full read now.
if !can_stream && !can_handle_head_from_meta && !can_handle_range_from_source {
// Re-read with full data
let mut n_full = Needle {
id: needle_id,
cookie,
..Needle::default()
};
let store = state.store.read().unwrap();
match store.read_volume_needle_opt(vid, &mut n_full, read_deleted) {
Ok(count) => {
if count < 0 {
return StatusCode::NOT_FOUND.into_response();
}
}
Err(crate::storage::volume::VolumeError::NotFound) => {
return StatusCode::NOT_FOUND.into_response();
}
Err(crate::storage::volume::VolumeError::Deleted) => {
return StatusCode::NOT_FOUND.into_response();
}
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
format!("read error: {}", e),
)
.into_response();
}
}
drop(store);
// Use the full needle from here (it has the same metadata + data)
n = n_full;
}
}
// Build ETag and Last-Modified BEFORE conditional checks and chunk manifest expansion
@@ -1565,12 +1613,19 @@ async fn get_or_head_handler_inner(
&& let (Some(range_header), Some(info)) = (headers.get(header::RANGE), stream_info)
&& let Ok(range_str) = range_header.to_str()
{
return handle_range_request_from_source(
range_str,
info,
response_headers,
track_download.then(|| state.clone()),
);
let range_str = range_str.to_string();
let tracking = track_download.then(|| state.clone());
return tokio::task::spawn_blocking(move || {
handle_range_request_from_source(&range_str, info, response_headers, tracking)
})
.await
.unwrap_or_else(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("range read error: {}", e),
)
.into_response()
});
}
// ---- Buffered path: small files, compressed, images, range requests ----
@@ -4617,15 +4672,19 @@ mod tests {
}
fn streaming_test_state() -> Arc<VolumeServerState> {
use crate::security::{Guard, SigningKey};
use crate::server::volume_server::RuntimeMetricsConfig;
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::store::Store;
test_state_with_store(Store::new(NeedleMapKind::InMemory))
}
fn test_state_with_store(store: crate::storage::store::Store) -> Arc<VolumeServerState> {
use crate::security::{Guard, SigningKey};
use crate::server::volume_server::RuntimeMetricsConfig;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32};
Arc::new(VolumeServerState {
store: RwLock::new(Store::new(NeedleMapKind::InMemory)),
store: RwLock::new(store),
guard: RwLock::new(Guard::new(
&[],
SigningKey(vec![]),
@@ -4738,4 +4797,278 @@ mod tests {
assert!(saw_err, "corrupted stream must fail");
assert!(got < data.len(), "delivered {got} of {} bytes", data.len());
}
const TEST_COOKIE: u32 = 0x1234_5678;
/// State whose store holds volume 1 in `tmp`.
fn volume_test_state(tmp: &tempfile::TempDir) -> Arc<VolumeServerState> {
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::store::Store;
use crate::storage::volume::VolumeSpec;
let dir = tmp.path().to_str().unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
10,
DiskType::HardDrive,
crate::config::MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
store
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
test_state_with_store(store)
}
/// Write a needle to volume 1 and return its URL path.
fn put_test_needle(state: &VolumeServerState, id: u64, data: &[u8]) -> String {
put_test_needle_with(state, id, data, |_| {})
}
fn put_test_needle_with(
state: &VolumeServerState,
id: u64,
data: &[u8],
prepare: impl FnOnce(&mut Needle),
) -> String {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(TEST_COOKIE),
data: data.to_vec(),
data_size: data.len() as u32,
..Needle::default()
};
prepare(&mut n);
state
.store
.write()
.unwrap()
.write_volume_needle(VolumeId(1), &mut n, false)
.unwrap();
format!("/1,{:x}{:08x}", id, TEST_COOKIE)
}
async fn send_read(
state: &Arc<VolumeServerState>,
method: Method,
path: &str,
range: Option<&str>,
) -> (StatusCode, HeaderMap, Vec<u8>) {
use tower::ServiceExt;
let mut req = Request::builder().method(method).uri(path);
if let Some(range) = range {
req = req.header(header::RANGE, range);
}
let resp = super::super::volume_server::build_public_router(state.clone())
.oneshot(req.body(Body::empty()).unwrap())
.await
.unwrap();
let status = resp.status();
let headers = resp.headers().clone();
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap()
.to_vec();
(status, headers, body)
}
/// A GET whose needle read is parked must not hold the store lock: a
/// writer, here a real append to the same volume, must get through.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_needle_read_runs_off_the_store_lock() {
use crate::storage::volume::needle_read_hook;
use std::sync::Mutex;
use std::sync::mpsc;
use std::time::Duration;
const ID: u64 = 0x6e7a_0001;
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
let data = b"parked needle".to_vec();
let path = put_test_needle(&state, ID, &data);
let (entered_tx, entered_rx) = mpsc::channel::<()>();
let (release_tx, release_rx) = mpsc::channel::<()>();
let release_rx = Mutex::new(release_rx);
let _hook = needle_read_hook::register(NeedleId(ID), move |_| {
let _ = entered_tx.send(());
// Returns once released, or at once when the sender is gone.
let _ = release_rx.lock().unwrap().recv();
});
let get = tokio::spawn({
let state = state.clone();
async move { send_read(&state, Method::GET, &path, None).await }
});
tokio::task::spawn_blocking(move || entered_rx.recv_timeout(Duration::from_secs(10)))
.await
.unwrap()
.expect("the GET never reached its needle read");
let try_write_ok = state.store.try_write().is_ok();
let (wrote_tx, wrote_rx) = mpsc::channel();
std::thread::spawn({
let state = state.clone();
move || {
put_test_needle(&state, ID + 1, b"written meanwhile");
let _ = wrote_tx.send(());
}
});
let write_done = tokio::task::spawn_blocking(move || {
wrote_rx.recv_timeout(Duration::from_secs(5)).is_ok()
})
.await
.unwrap();
drop(release_tx);
assert!(
try_write_ok,
"a parked GET read must not hold the store lock"
);
assert!(write_done, "an append must not wait for a parked GET read");
let (status, _, body) = get.await.unwrap();
assert_eq!(status, StatusCode::OK);
assert_eq!(body, data);
}
/// A small needle is read from disk once, not once for its meta and
/// again in full; a large one never reads its payload before streaming.
#[tokio::test]
async fn test_get_reads_small_needle_once_and_large_needle_meta_only() {
use crate::storage::volume::needle_read_hook;
use std::sync::Mutex;
const SMALL: u64 = 0x6e7a_0101;
const LARGE: u64 = 0x6e7a_0102;
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
let small = b"small needle".to_vec();
let large: Vec<u8> = (0..(STREAMING_THRESHOLD as usize + 4096))
.map(|i| (i % 251) as u8)
.collect();
let small_path = put_test_needle(&state, SMALL, &small);
let large_path = put_test_needle(&state, LARGE, &large);
let small_reads = Arc::new(Mutex::new(Vec::new()));
let large_reads = Arc::new(Mutex::new(Vec::new()));
let _small_hook = needle_read_hook::register(NeedleId(SMALL), {
let reads = small_reads.clone();
move |len| reads.lock().unwrap().push(len)
});
let _large_hook = needle_read_hook::register(NeedleId(LARGE), {
let reads = large_reads.clone();
move |len| reads.lock().unwrap().push(len)
});
let (status, _, body) = send_read(&state, Method::GET, &small_path, None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, small);
let reads = small_reads.lock().unwrap().clone();
assert_eq!(reads.len(), 1, "reads of the small needle: {reads:?}");
let (status, _, body) = send_read(&state, Method::GET, &large_path, None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, large);
let reads = large_reads.lock().unwrap().clone();
assert!(
!reads.is_empty() && reads.iter().all(|&len| len < 64 * 1024),
"the large needle's payload must not be read before streaming: {reads:?}"
);
}
/// HEAD and ranged reads keep answering from the needle meta and the
/// data file, and a missing or wrong-cookie needle is still a 404.
#[tokio::test]
async fn test_get_head_range_and_not_found_after_single_read() {
const ID: u64 = 0x6e7a_0201;
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
let data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
let path = put_test_needle(&state, ID, &data);
let (status, headers, body) = send_read(&state, Method::HEAD, &path, None).await;
assert_eq!(status, StatusCode::OK);
assert!(body.is_empty());
assert_eq!(headers[header::CONTENT_LENGTH], data.len().to_string());
assert!(headers.contains_key(header::ETAG));
let (status, headers, body) =
send_read(&state, Method::GET, &path, Some("bytes=10-19")).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
assert_eq!(body, &data[10..20]);
assert_eq!(
headers["Content-Range"],
format!("bytes 10-19/{}", data.len())
);
let wrong_cookie = format!("/1,{:x}{:08x}", ID, TEST_COOKIE ^ 1);
let (status, _, _) = send_read(&state, Method::GET, &wrong_cookie, None).await;
assert_eq!(status, StatusCode::NOT_FOUND);
let missing = format!("/1,{:x}{:08x}", ID + 1, TEST_COOKIE);
let (status, _, _) = send_read(&state, Method::GET, &missing, None).await;
assert_eq!(status, StatusCode::NOT_FOUND);
}
/// A large compressed needle cannot be streamed as stored: its meta is
/// read first, then the payload exactly once.
#[tokio::test]
async fn test_get_large_compressed_needle_reads_payload_once() {
use crate::storage::volume::needle_read_hook;
use std::sync::Mutex;
const ID: u64 = 0x6e7a_0301;
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
// Incompressible, so the stored gzip stays above the stream threshold.
let mut x = 0x2545_f491_u32;
let plain: Vec<u8> = (0..(STREAMING_THRESHOLD as usize + 64 * 1024))
.map(|_| {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
x as u8
})
.collect();
let gz = try_gzip_data(&plain).unwrap();
assert!(gz.len() > STREAMING_THRESHOLD as usize);
let path = put_test_needle_with(&state, ID, &gz, |n| n.set_is_compressed());
let reads = Arc::new(Mutex::new(Vec::new()));
let _hook = needle_read_hook::register(NeedleId(ID), {
let reads = reads.clone();
move |len| reads.lock().unwrap().push(len)
});
let (status, _, body) = send_read(&state, Method::GET, &path, None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, plain);
let reads = reads.lock().unwrap().clone();
let full = reads.iter().filter(|&&len| len >= gz.len()).count();
assert_eq!(full, 1, "reads: {reads:?}");
}
/// The single full read still verifies the needle checksum.
#[tokio::test]
async fn test_get_small_needle_with_bad_checksum_fails() {
const ID: u64 = 0x6e7a_0401;
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
let data = b"checksummed payload, to be corrupted".to_vec();
let path = put_test_needle(&state, ID, &data);
let dat = tmp.path().join("1.dat");
let mut bytes = std::fs::read(&dat).unwrap();
let at = bytes
.windows(data.len())
.position(|w| w == data.as_slice())
.unwrap();
bytes[at] ^= 0xff;
std::fs::write(&dat, bytes).unwrap();
let (status, _, _) = send_read(&state, Method::GET, &path, None).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
}
}
+397 -40
View File
@@ -24,8 +24,10 @@ use crate::storage::volume_report_hash::report_hash;
const DUPLICATE_UUID_RETRY_MESSAGE: &str = "duplicate UUIDs detected, retrying connection";
const MAX_DUPLICATE_UUID_RETRIES: u32 = 3;
const MAX_TTL_VOLUME_REMOVAL_DELAY: u32 = 10;
/// Configuration for the heartbeat client.
#[derive(Clone)]
pub struct HeartbeatConfig {
pub ip: String,
pub port: u16,
@@ -396,7 +398,8 @@ async fn do_heartbeat(
state.store.read().unwrap().volume_report.reset();
// Keep track of what we sent, to generate delta updates
let (initial_hb, initial_volumes) = collect_heartbeat_with_snapshot(config, state);
let (initial_hb, initial_volumes) =
off_runtime(config, state, collect_heartbeat_with_snapshot).await?;
let mut last_volumes: HashMap<u32, VolumeIdentity> = volume_identities(&initial_volumes);
let mut last_ec_shards = {
let store = state.store.read().unwrap();
@@ -462,7 +465,8 @@ async fn do_heartbeat(
};
if changed {
let (adjusted_hb, adjusted_volumes) =
collect_heartbeat_with_snapshot(config, state);
off_runtime(config, state, collect_heartbeat_with_snapshot)
.await?;
last_volumes = volume_identities(&adjusted_volumes);
last_ec_shards = {
let store = state.store.read().unwrap();
@@ -496,7 +500,8 @@ async fn do_heartbeat(
let s = state.store.read().unwrap();
s.maybe_adjust_volume_max();
}
let (current_hb, current_volumes) = collect_heartbeat_with_snapshot(config, state);
let (current_hb, current_volumes) =
off_runtime(config, state, collect_heartbeat_with_snapshot).await?;
last_volumes = volume_identities(&current_volumes);
last_ec_shards = {
let store = state.store.read().unwrap();
@@ -525,7 +530,7 @@ async fn do_heartbeat(
info!("Heartbeat stopping");
return Ok(None);
}
let held_volumes = collect_volume_snapshot(config, state);
let held_volumes = off_runtime(config, state, collect_volume_snapshot).await?;
let current_volumes = volume_identities(&held_volumes);
let current_ec_shards = {
let store = state.store.read().unwrap();
@@ -781,6 +786,16 @@ fn volume_identities(
.collect()
}
/// Runs a store pass on the blocking pool: it stats every volume's files.
async fn off_runtime<T: Send + 'static>(
config: &HeartbeatConfig,
state: &Arc<VolumeServerState>,
pass: fn(&HeartbeatConfig, &Arc<VolumeServerState>) -> T,
) -> Result<T, tokio::task::JoinError> {
let (config, state) = (config.clone(), state.clone());
tokio::task::spawn_blocking(move || pass(&config, &state)).await
}
/// Collect volume information into a Heartbeat message.
fn collect_heartbeat_with_snapshot(
config: &HeartbeatConfig,
@@ -789,15 +804,32 @@ fn collect_heartbeat_with_snapshot(
master_pb::Heartbeat,
Vec<master_pb::VolumeInformationMessage>,
) {
let mut store = state.store.write().unwrap();
let (ec_shards, deleted_ec_shards) = store.delete_expired_ec_volumes();
build_heartbeat_with_ec_status(
config,
&mut store,
deleted_ec_shards,
ec_shards.is_empty(),
true,
)
let (_, expired_ec) = state.store.read().unwrap().find_expired_ec_volumes();
let mut deleted_ec_shards = Vec::new();
if !expired_ec.is_empty() {
deleted_ec_shards = state
.store
.write()
.unwrap()
.remove_expired_ec_volumes(expired_ec)
.0;
}
#[cfg(test)]
{
let store_id = state.store.read().unwrap().id.clone();
read_phase_hook::park(read_phase_hook::Point::BeforeVolumePass, &store_id);
}
let (heartbeat, volumes, actions) = {
let store = state.store.read().unwrap();
#[cfg(test)]
read_phase_hook::park(read_phase_hook::Point::VolumePass, &store.id);
// Taken with the volume list: a shard mounted since the EC phase must
// not go out as "no EC shards", which clears it on the master.
let has_no_ec_shards = !has_reportable_ec_shards(&store);
build_heartbeat_with_ec_status(config, &store, deleted_ec_shards, has_no_ec_shards, true)
};
apply_volume_actions(state, actions);
(heartbeat, volumes)
}
/// Lists the volumes the server holds without touching reporting state or
@@ -807,8 +839,100 @@ fn collect_volume_snapshot(
config: &HeartbeatConfig,
state: &Arc<VolumeServerState>,
) -> Vec<master_pb::VolumeInformationMessage> {
let mut store = state.store.write().unwrap();
build_heartbeat_with_ec_status(config, &mut store, Vec::new(), true, false).1
let (_, volumes, actions) = build_heartbeat_with_ec_status(
config,
&state.store.read().unwrap(),
Vec::new(),
true,
false,
);
apply_volume_actions(state, actions);
volumes
}
/// Store changes a heartbeat pass decides on under the read lock, applied
/// under a short write lock afterwards. Entries are (disk index, volume id).
#[derive(Default)]
struct VolumeActions {
delete_expired: Vec<(usize, VolumeId)>,
quarantine: Vec<(usize, VolumeId)>,
}
fn apply_volume_actions(state: &VolumeServerState, actions: VolumeActions) {
if actions.delete_expired.is_empty() && actions.quarantine.is_empty() {
return;
}
apply_volume_actions_to(&mut state.store.write().unwrap(), actions);
}
/// Each target is re-checked: it may have been written to, replaced or removed
/// since the read pass chose it.
fn apply_volume_actions_to(store: &mut Store, actions: VolumeActions) {
let volume_size_limit = store.volume_size_limit.load(Ordering::Relaxed);
for (disk_id, vid) in actions.delete_expired {
let Some(loc) = store.locations.get_mut(disk_id) else {
continue;
};
let still_expired = loc.find_volume(vid).is_some_and(|vol| {
!vol.should_quarantine()
&& vol.is_expired(vol.dat_file_size().unwrap_or(0), volume_size_limit)
&& vol.is_expired_long_enough(MAX_TTL_VOLUME_REMOVAL_DELAY)
});
if still_expired {
let _ = loc.delete_volume(vid, false, false, false);
}
}
for (disk_id, vid) in actions.quarantine {
if let Some(vol) = store
.locations
.get_mut(disk_id)
.and_then(|loc| loc.find_volume_mut(vid))
&& vol.should_quarantine()
{
vol.set_no_write_or_delete(true);
}
}
}
#[cfg(test)]
mod read_phase_hook {
use std::sync::Mutex;
use std::sync::mpsc::Receiver;
use tokio::sync::oneshot::Sender;
#[derive(Clone, Copy, PartialEq)]
pub(super) enum Point {
/// Between the EC phase and the volume pass, holding no lock.
BeforeVolumePass,
/// Inside the volume pass, holding the store read lock.
VolumePass,
}
type Park = (Point, String, Sender<()>, Receiver<()>);
static ARMED: Mutex<Vec<Park>> = Mutex::new(Vec::new());
/// Parks the next pass over the store with this id at `point`, announcing
/// itself on `entered` and waiting until `release` is dropped.
pub(super) fn arm(point: Point, store_id: &str, entered: Sender<()>, release: Receiver<()>) {
ARMED
.lock()
.unwrap()
.push((point, store_id.to_string(), entered, release));
}
pub(super) fn park(point: Point, store_id: &str) {
let armed = {
let mut armed = ARMED.lock().unwrap();
armed
.iter()
.position(|(p, id, _, _)| *p == point && !id.is_empty() && id == store_id)
.map(|i| armed.swap_remove(i))
};
if let Some((_, _, entered, release)) = armed {
let _ = entered.send(());
let _ = release.recv();
}
}
}
/// The heartbeat alone, without the volume snapshot the send loop pairs it
@@ -851,27 +975,42 @@ fn collect_location_metadata(
(location_uuids, disk_tags)
}
/// Whether a heartbeat would report any EC shard: Go's non-empty
/// `ecVolumeMessages` from `deleteExpiredEcVolumes`.
fn has_reportable_ec_shards(store: &Store) -> bool {
store.locations.iter().any(|loc| {
loc.ec_volumes().any(|(_, ec_vol)| {
!ec_vol.is_time_to_destroy()
&& !ec_vol.should_quarantine()
&& ec_vol.shards.iter().any(Option::is_some)
})
})
}
#[cfg(test)]
fn build_heartbeat(config: &HeartbeatConfig, store: &mut Store) -> master_pb::Heartbeat {
let has_no_ec_shards = collect_live_ec_shards(store, false).is_empty();
build_heartbeat_with_ec_status(config, store, Vec::new(), has_no_ec_shards, true).0
let (heartbeat, _, actions) =
build_heartbeat_with_ec_status(config, store, Vec::new(), has_no_ec_shards, true);
apply_volume_actions_to(store, actions);
heartbeat
}
/// Returns the heartbeat to send and, separately, every volume held. The
/// caller derives mount and unmount deltas by diffing successive snapshots, so
/// it must not be handed the partial list a heartbeat may carry.
/// Returns the heartbeat to send, every volume held, and the store changes
/// the pass decided on. The caller derives mount and unmount deltas by diffing
/// successive snapshots, so it must not be handed the partial list a heartbeat
/// may carry.
fn build_heartbeat_with_ec_status(
config: &HeartbeatConfig,
store: &mut Store,
store: &Store,
deleted_ec_shards: Vec<master_pb::VolumeEcShardInformationMessage>,
has_no_ec_shards: bool,
commit_report: bool,
) -> (
master_pb::Heartbeat,
Vec<master_pb::VolumeInformationMessage>,
VolumeActions,
) {
const MAX_TTL_VOLUME_REMOVAL_DELAY: u32 = 10;
#[derive(Default)]
struct ReadOnlyCounts {
is_read_only: u32,
@@ -901,8 +1040,9 @@ fn build_heartbeat_with_ec_status(
// Per-disk effective max for DiskTag, captured alongside the per-type sum.
let mut disk_max_by_id = vec![0i32; store.locations.len()];
let mut actions = VolumeActions::default();
for (disk_id, loc) in store.locations.iter_mut().enumerate() {
for (disk_id, loc) in store.locations.iter().enumerate() {
let disk_type_str = loc.disk_type.to_string();
let mut effective_max_count = loc.max_volume_count.load(Ordering::Relaxed);
if loc.is_disk_space_low.load(Ordering::Relaxed) {
@@ -926,8 +1066,6 @@ fn build_heartbeat_with_ec_status(
*disk_free_bytes.entry(disk_type_str).or_insert(0) +=
loc.disk_free_bytes.load(Ordering::Relaxed);
let mut delete_vids = Vec::new();
let mut quarantine_vids: Vec<VolumeId> = Vec::new();
for (_, vol) in loc.iter_volumes() {
let cur_max = vol.max_file_key();
if cur_max > max_file_key {
@@ -947,7 +1085,7 @@ fn build_heartbeat_with_ec_status(
);
}
quarantined_volumes += 1;
quarantine_vids.push(vol.id);
actions.quarantine.push((disk_id, vol.id));
continue;
} else if !vol.is_expired(volume_size, volume_size_limit) {
// Detect phantom volumes: the .dat was unlinked from disk but is still
@@ -1015,7 +1153,7 @@ fn build_heartbeat_with_ec_status(
}
volumes.push(volume_message);
} else if vol.is_expired_long_enough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
delete_vids.push(vol.id);
actions.delete_expired.push((disk_id, vol.id));
should_delete_volume = true;
}
@@ -1046,16 +1184,6 @@ fn build_heartbeat_with_ec_status(
}
}
}
for vid in delete_vids {
let _ = loc.delete_volume(vid, false, false, false);
}
for vid in quarantine_vids {
if let Some(vol) = loc.find_volume_mut(vid) {
vol.set_no_write_or_delete(true);
}
}
}
// Update disk size and read-only gauges
@@ -1152,7 +1280,7 @@ fn build_heartbeat_with_ec_status(
disk_tags,
..Default::default()
};
(heartbeat, volumes)
(heartbeat, volumes, actions)
}
fn collect_live_ec_shards(
@@ -1585,7 +1713,7 @@ mod tests {
// What the notify path does: collect a snapshot, send a message of its own.
let snapshot =
build_heartbeat_with_ec_status(&test_config(), &mut store, Vec::new(), true, false).1;
build_heartbeat_with_ec_status(&test_config(), &store, Vec::new(), true, false).1;
assert_eq!(snapshot.len(), 3);
let heartbeat = build_heartbeat(&test_config(), &mut store);
@@ -1778,7 +1906,7 @@ mod tests {
1.0
);
assert!(store.unmount_volume(VolumeId(21)));
assert!(store.unmount_volume(VolumeId(21)).unwrap());
build_heartbeat(&test_config(), &mut store);
assert_eq!(
@@ -2012,6 +2140,235 @@ mod tests {
assert!(volume.is_no_write_or_delete());
}
// The pass only reads the store, so it must not shut out the readers that
// serve traffic while it stats every volume.
#[tokio::test]
async fn test_heartbeat_collection_leaves_the_store_readable() {
let temp_dir = tempfile::tempdir().unwrap();
let mut store = reporting_store(temp_dir.path().to_str().unwrap(), 2);
store.id = "heartbeat-read-phase-park".to_string();
let state = test_state_with_store(store);
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
read_phase_hook::arm(
read_phase_hook::Point::VolumePass,
"heartbeat-read-phase-park",
entered_tx,
release_rx,
);
let collection = {
let state = state.clone();
tokio::spawn(async move {
off_runtime(&test_config(), &state, collect_heartbeat_with_snapshot).await
})
};
tokio::time::timeout(Duration::from_secs(10), entered_rx)
.await
.expect("the pass never reached its read phase")
.unwrap();
let readable = state.store.try_read().is_ok();
drop(release_tx);
let (heartbeat, volumes) = collection.await.unwrap().unwrap();
assert!(readable, "a parked heartbeat pass shut out store readers");
assert_eq!(heartbeat.volumes.len(), 2);
assert_eq!(volumes.len(), 2);
}
// What the read pass decided on can go stale before the write lock is
// taken: each action must re-check its target, not act on whatever now
// holds the id.
#[test]
fn test_volume_actions_skip_volumes_changed_since_the_read_pass() {
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,
8,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
store.volume_size_limit.store(1, Ordering::Relaxed);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
for id in [61, 62, 63] {
store
.add_volume(
VolumeId(id),
DiskType::HardDrive,
&VolumeSpec {
collection: "stale_action_case",
ttl: Some(crate::storage::needle::ttl::TTL::read("20m").unwrap()),
..Default::default()
},
)
.unwrap();
let (_, volume) = store.find_volume_mut(VolumeId(id)).unwrap();
volume.set_last_io_error_for_test(None);
volume.set_last_modified_ts_for_test(now.saturating_sub(60 * 60));
std::fs::OpenOptions::new()
.write(true)
.open(volume.dat_path())
.unwrap()
.set_len((crate::storage::super_block::SUPER_BLOCK_SIZE + 1) as u64)
.unwrap();
}
store
.add_volume(
VolumeId(64),
DiskType::HardDrive,
&VolumeSpec {
collection: "stale_action_case",
..Default::default()
},
)
.unwrap();
let (_, volume) = store.find_volume_mut(VolumeId(64)).unwrap();
volume.set_last_io_error_for_test(Some("input/output error"));
let (heartbeat, _, actions) =
build_heartbeat_with_ec_status(&test_config(), &store, Vec::new(), true, true);
assert!(heartbeat.volumes.is_empty());
assert_eq!(actions.delete_expired.len(), 3);
assert_eq!(actions.quarantine, vec![(0, VolumeId(64))]);
// Between the phases: 61 is deleted by someone else, 62 and 64 are
// replaced by fresh copies under the same ids; 63 is left alone.
store
.delete_volume(VolumeId(61), false, false, false)
.unwrap();
for id in [62, 64] {
store
.delete_volume(VolumeId(id), false, false, false)
.unwrap();
store
.add_volume(
VolumeId(id),
DiskType::HardDrive,
&VolumeSpec {
collection: "stale_action_case",
..Default::default()
},
)
.unwrap();
}
apply_volume_actions_to(&mut store, actions);
assert!(!store.has_volume(VolumeId(61)));
assert!(store.has_volume(VolumeId(62)), "a fresh copy was deleted");
assert!(
!store.has_volume(VolumeId(63)),
"the expired volume survived"
);
let (_, fresh) = store.find_volume(VolumeId(64)).unwrap();
assert!(
!fresh.is_no_write_or_delete(),
"a fresh copy was quarantined"
);
}
// A shard mounted after the EC phase is held when the volume list is
// taken; reporting "no EC shards" alongside it would clear it on the master.
#[tokio::test]
async fn test_ec_shard_mounted_after_the_ec_phase_is_not_reported_absent() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let mut store = reporting_store(dir, 1);
store.id = "heartbeat-ec-mount-between-passes".to_string();
let state = test_state_with_store(store);
std::fs::write(format!("{}/ec_mount_race_73.ec00", dir), b"shard").unwrap();
std::fs::write(format!("{}/ec_mount_race_73.ecx", dir), [0u8; 16]).unwrap();
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
read_phase_hook::arm(
read_phase_hook::Point::BeforeVolumePass,
"heartbeat-ec-mount-between-passes",
entered_tx,
release_rx,
);
let collection = {
let state = state.clone();
tokio::spawn(async move {
off_runtime(&test_config(), &state, collect_heartbeat_with_snapshot).await
})
};
tokio::time::timeout(Duration::from_secs(10), entered_rx)
.await
.expect("the pass never finished its EC phase")
.unwrap();
state.store.write().unwrap().locations[0]
.mount_ec_shards(VolumeId(73), "ec_mount_race", &[0], "")
.unwrap();
drop(release_tx);
let (heartbeat, _) = collection.await.unwrap().unwrap();
assert!(
!heartbeat.has_no_ec_shards,
"a mounted EC shard was reported absent"
);
}
#[test]
fn test_expired_ec_volume_gone_before_removal_is_not_reported_deleted() {
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,
8,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
for id in [71, 72] {
std::fs::write(format!("{}/stale_ec_case_{}.ec00", dir, id), b"expired").unwrap();
std::fs::write(format!("{}/stale_ec_case_{}.ecx", dir, id), [0u8; 16]).unwrap();
store.locations[0]
.mount_ec_shards(VolumeId(id), "stale_ec_case", &[0], "")
.unwrap();
store
.find_ec_volume_mut(VolumeId(id))
.unwrap()
.expire_at_sec = 1;
}
let (ec_shards, mut expired) = store.find_expired_ec_volumes();
expired.sort();
assert!(ec_shards.is_empty());
assert_eq!(expired, vec![(0, VolumeId(71)), (0, VolumeId(72))]);
// Between the phases: 71 is destroyed by someone else, 72 is remounted
// without an expiry.
store.remove_ec_volume(VolumeId(71)).unwrap().destroy();
store.remove_ec_volume(VolumeId(72)).unwrap();
store.locations[0]
.mount_ec_shards(VolumeId(72), "stale_ec_case", &[0], "")
.unwrap();
let (deleted, still_held) = store.remove_expired_ec_volumes(expired);
assert!(deleted.is_empty());
assert_eq!(still_held.len(), 1);
assert_eq!(still_held[0].id, 72);
assert!(store.has_ec_volume(VolumeId(72)));
}
#[test]
fn test_build_heartbeat_includes_remote_storage_name_and_key() {
let temp_dir = tempfile::tempdir().unwrap();
+25 -1
View File
@@ -1,5 +1,6 @@
use tonic::Status;
use crate::remote_storage::s3_tier::TierError;
use crate::storage::volume::VolumeError;
#[cfg(unix)]
@@ -23,7 +24,9 @@ impl From<VolumeError> for Status {
fn from(err: VolumeError) -> Self {
let message = err.to_string();
match err {
VolumeError::NotFound | VolumeError::VolumeNotFound(_) => Status::not_found(message),
VolumeError::NotFound
| VolumeError::VolumeNotFound(_)
| VolumeError::Tier(TierError::NotFound(_)) => Status::not_found(message),
VolumeError::ReadOnly | VolumeError::NotEmpty => Status::failed_precondition(message),
VolumeError::InsufficientSpace { .. } => Status::resource_exhausted(message),
VolumeError::AlreadyExists => Status::already_exists(message),
@@ -77,6 +80,27 @@ mod tests {
);
assert_eq!(code(VolumeError::AlreadyExists), Code::AlreadyExists);
assert_eq!(code(VolumeError::NotInitialized), Code::Internal);
assert_eq!(
code(TierError::NotFound("gone".into()).into()),
Code::NotFound
);
for tier in [
TierError::Io("io".into()),
TierError::RuntimeUnavailable("rt".into()),
TierError::Aborted("bye".into()),
] {
assert_eq!(code(tier.into()), Code::Internal);
}
let status = status_with_context(
"backend s3.default copy file /data/1.dat",
TierError::NotFound("failed to head object k: NotFound".into()).into(),
);
assert_eq!(status.code(), Code::NotFound);
assert_eq!(
status.message(),
"backend s3.default copy file /data/1.dat: failed to head object k: NotFound"
);
let status = status_with_context(
"compact volume 7",
@@ -479,6 +479,13 @@ impl DiskLocation {
if self.idx_directory != self.directory {
remove_bitrot_sidecars(&idx_base)?;
}
// Staged 2PC generations (<base>.ecNN.v<N>, versioned .ecx/.ecj/.vif)
// belong to this volume's EC state too; leaving them orphans the files.
crate::storage::erasure_coding::ec_shard::remove_ec_generation_files(&base, 0)?;
if self.idx_directory != self.directory {
crate::storage::erasure_coding::ec_shard::remove_ec_generation_files(&idx_base, 0)?;
}
Ok(())
}
@@ -601,6 +608,12 @@ impl DiskLocation {
only_garbage: bool,
keep_remote_data: bool,
) -> Result<(), VolumeError> {
// Refuse before removing: a refused destroy must leave it mounted.
if let Some(v) = self.volumes.get(&vid)
&& v.is_compacting()
{
return Err(v.compacting_error());
}
if let Some(mut v) = self.volumes.remove(&vid) {
crate::metrics::VOLUME_GAUGE
.with_label_values(&[&v.collection, "volume"])
@@ -195,6 +195,104 @@ impl ShardBits {
}
}
/// Parses the generation of a 2PC-staged `<base>.v<N>` file: `None` means the
/// name is not a generation file of `base`.
pub fn ec_file_generation(name: &str, base: &str) -> Option<u32> {
let suffix = name.strip_prefix(&format!("{}.v", base))?;
match suffix.parse::<u32>() {
Ok(g) if g > 0 => Some(g),
_ => None,
}
}
/// Removes 2PC generation files staged under `base`:
/// `<base>.ecNN.v<N>`, `<base>.ecx.v<N>`, `<base>.ecj.v<N>`, `<base>.ecsum.v<N>`
/// and `<base>.vif.v<N>`. `generations_older_than == 0` removes every
/// generation; otherwise only generations strictly below it. Returns the
/// first real removal failure. Mirrors Go's `RemoveEcGenerationFiles`.
pub fn remove_ec_generation_files(base: &str, generations_older_than: u32) -> io::Result<()> {
let path = std::path::Path::new(base);
let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) else {
return Ok(());
};
let ec_prefix = format!("{}.ec", fname.to_string_lossy());
let vif_name = format!("{}.vif", fname.to_string_lossy());
let mut first_err: Option<io::Error> = None;
let mut record = |res: io::Result<()>| {
if let Err(e) = res
&& first_err.is_none()
{
first_err = Some(e);
}
};
match fs::read_dir(parent) {
Ok(entries) => {
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) => {
// A skipped entry means an incomplete sweep; report it
// instead of pretending the cleanup finished.
record(Err(e));
continue;
}
};
let name = entry.file_name().to_string_lossy().into_owned();
let Some((artifact, _)) = name.rsplit_once(".v") else {
continue;
};
if artifact != vif_name && !artifact.starts_with(&ec_prefix) {
continue;
}
let Some(generation) = ec_file_generation(&name, artifact) else {
continue;
};
if generations_older_than > 0 && generation >= generations_older_than {
continue;
}
record(match fs::remove_file(entry.path()) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
});
}
}
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
Err(_) => {}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
/// Removes every staged generation `<shard_file>.v<N>` of one shard file.
/// Returns true when at least one generation file was removed.
pub fn remove_ec_shard_generations(shard_file: &str) -> io::Result<bool> {
let path = std::path::Path::new(shard_file);
let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) else {
return Ok(false);
};
let fname = fname.to_string_lossy().into_owned();
let mut removed = false;
match fs::read_dir(parent) {
Ok(entries) => {
for entry in entries {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
if ec_file_generation(&name, &fname).is_some() {
match fs::remove_file(entry.path()) {
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => removed = true,
}
}
}
}
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
Err(_) => {}
}
Ok(removed)
}
#[cfg(test)]
mod tests {
use super::*;
+14
View File
@@ -247,6 +247,8 @@ impl CompactNeedleMap {
pub fn load_from_idx<R: Read + Seek>(reader: &mut R, version: Version) -> io::Result<Self> {
let mut nm = CompactNeedleMap::new();
idx::walk_index_file(reader, 0, |key, offset, size| {
// A read-only load attaches no writer, so this is its only size.
nm.idx_file_offset += NEEDLE_MAP_ENTRY_SIZE as u64;
nm.metric.maybe_set_max_needle_end(offset, size, version);
if offset.is_zero() || size.is_deleted() {
nm.delete_from_map(key);
@@ -1386,6 +1388,18 @@ impl NeedleMap {
}
}
/// Skew the live file count away from what the `.idx` holds, so tests
/// can build a volume whose reported count disagrees with a reload.
#[cfg(test)]
pub(crate) fn add_file_count_for_test(&self, delta: i64) {
let metric = match self {
NeedleMap::InMemory(nm) => &nm.metric,
NeedleMap::Redb(nm) => &nm.metric,
NeedleMap::SortedFile(_) => panic!("sorted-file needle maps are read-only"),
};
metric.file_count.fetch_add(delta, Ordering::Relaxed);
}
/// Largest (offset + actual size) seen during the load walk; 0 if the
/// map is empty. Used at volume load to detect .idx entries that
/// reference past the end of .dat (issue #8928) without a second scan.
+332 -63
View File
@@ -18,7 +18,7 @@ use crate::storage::needle::needle::Needle;
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::super_block::ReplicaPlacement;
use crate::storage::types::*;
use crate::storage::volume::{VifVolumeInfo, VolumeError, VolumeSpec};
use crate::storage::volume::{CompactionJob, VifVolumeInfo, VolumeError, VolumeSpec};
/// Top-level storage manager containing all disk locations and their volumes.
pub struct Store {
@@ -225,7 +225,13 @@ impl Store {
/// Find a free location matching a predicate.
/// Matches Go's Store.FindFreeLocation: picks the matching location with the
/// most remaining volume capacity, while skipping low-disk locations.
pub fn find_free_location_predicate<F>(&self, pred: F) -> Option<usize>
/// `replace_vid` names a volume about to be replaced: the slot it holds on
/// a location counts as free there.
pub fn find_free_location_predicate<F>(
&self,
pred: F,
replace_vid: Option<VolumeId>,
) -> Option<usize>
where
F: Fn(&DiskLocation) -> bool,
{
@@ -241,8 +247,12 @@ impl Store {
let effective_free = if max == 0 {
i64::MAX
} else {
let free_count = (max - loc.volumes_len() as i64) * DATA_SHARDS_COUNT as i64
- loc.ec_shard_count() as i64;
let mut free_slots = max - loc.volumes_len() as i64;
if replace_vid.is_some_and(|vid| loc.find_volume(vid).is_some()) {
free_slots += 1;
}
let free_count =
free_slots * DATA_SHARDS_COUNT as i64 - loc.ec_shard_count() as i64;
free_count / DATA_SHARDS_COUNT as i64
};
if effective_free <= 0 {
@@ -406,14 +416,20 @@ impl Store {
Err(VolumeError::NotFound)
}
/// Unload (unmount) a volume without deleting its files.
pub fn unmount_volume(&mut self, vid: VolumeId) -> bool {
/// Unload (unmount) a volume without deleting its files. Refused while
/// compacting, since a remount could start a second copy into .cpd.
pub fn unmount_volume(&mut self, vid: VolumeId) -> Result<bool, VolumeError> {
if let Some((_, v)) = self.find_volume(vid)
&& v.is_compacting()
{
return Err(v.compacting_error());
}
for loc in &mut self.locations {
if loc.unload_volume(vid).is_some() {
return true;
return Ok(true);
}
}
false
Ok(false)
}
/// Reports whether any local volume or EC shard is currently quarantined
@@ -699,15 +715,15 @@ impl Store {
vol.read_needle_opt(n, read_deleted)
}
/// Read needle metadata and return streaming info for large file reads.
pub fn read_volume_needle_stream_info(
/// Resolve a needle read under this guard, to run after it is released.
pub(crate) fn needle_read_plan(
&self,
vid: VolumeId,
n: &mut Needle,
id: NeedleId,
read_deleted: bool,
) -> Result<crate::storage::volume::NeedleStreamInfo, VolumeError> {
) -> Result<crate::storage::volume::NeedleReadPlan, VolumeError> {
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
vol.read_needle_stream_info(n, read_deleted)
vol.needle_read_plan(id, read_deleted)
}
/// Re-lookup a needle's data-file offset after compaction may have moved it.
@@ -1206,43 +1222,28 @@ impl Store {
Vec<master_pb::VolumeEcShardInformationMessage>,
Vec<master_pb::VolumeEcShardInformationMessage>,
) {
let mut ec_shards = Vec::new();
let mut deleted = Vec::new();
let (mut ec_shards, expired) = self.find_expired_ec_volumes();
let (deleted, still_held) = self.remove_expired_ec_volumes(expired);
ec_shards.extend(still_held);
(ec_shards, deleted)
}
for (disk_id, loc) in self.locations.iter_mut().enumerate() {
let mut expired_vids = Vec::new();
let mut io_quarantined_vids = Vec::new();
/// The read half of `delete_expired_ec_volumes`: the shards to report, and
/// the expired EC volumes, by disk index, for `remove_expired_ec_volumes`.
pub fn find_expired_ec_volumes(
&self,
) -> (
Vec<master_pb::VolumeEcShardInformationMessage>,
Vec<(usize, VolumeId)>,
) {
let mut ec_shards = Vec::new();
let mut expired = Vec::new();
for (disk_id, loc) in self.locations.iter().enumerate() {
for (vid, ec_vol) in loc.ec_volumes() {
if ec_vol.is_time_to_destroy() {
expired_vids.push(*vid);
expired.push((disk_id, *vid));
} else if ec_vol.should_quarantine() {
io_quarantined_vids.push(*vid);
} else {
ec_shards
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
}
}
for vid in expired_vids {
let messages = loc
.find_ec_volume(vid)
.map(|ec_vol| ec_vol.to_volume_ec_shard_information_messages(disk_id as u32))
.unwrap_or_default();
if let Some(mut ec_vol) = loc.remove_ec_volume(vid) {
for _ in 0..ec_vol.shard_count() {
crate::metrics::VOLUME_GAUGE
.with_label_values(&[&ec_vol.collection, "ec_shards"])
.dec();
}
ec_vol.destroy();
deleted.extend(messages);
} else {
ec_shards.extend(messages);
}
}
for vid in io_quarantined_vids {
if let Some(ec_vol) = loc.find_ec_volume(vid) {
let (_, io_count, quarantined) = ec_vol.get_io_error_state();
if !quarantined {
ec_vol.mark_io_quarantined();
@@ -1252,11 +1253,51 @@ impl Store {
"ec volume quarantined after consecutive IO errors"
);
}
} else {
ec_shards
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
}
}
}
(ec_shards, deleted)
(ec_shards, expired)
}
/// The write half of `delete_expired_ec_volumes`: destroys each volume that
/// is still there and still expired, returning the shards deleted and the
/// shards of any that no longer qualify.
pub fn remove_expired_ec_volumes(
&mut self,
expired: Vec<(usize, VolumeId)>,
) -> (
Vec<master_pb::VolumeEcShardInformationMessage>,
Vec<master_pb::VolumeEcShardInformationMessage>,
) {
let mut deleted = Vec::new();
let mut still_held = Vec::new();
for (disk_id, vid) in expired {
let Some(loc) = self.locations.get_mut(disk_id) else {
continue;
};
let Some(ec_vol) = loc.find_ec_volume(vid) else {
continue;
};
let messages = ec_vol.to_volume_ec_shard_information_messages(disk_id as u32);
if !ec_vol.is_time_to_destroy() {
still_held.extend(messages);
continue;
}
if let Some(mut ec_vol) = loc.remove_ec_volume(vid) {
for _ in 0..ec_vol.shard_count() {
crate::metrics::VOLUME_GAUGE
.with_label_values(&[&ec_vol.collection, "ec_shards"])
.dec();
}
ec_vol.destroy();
deleted.extend(messages);
}
}
(deleted, still_held)
}
/// Remove an EC volume from whichever location has it.
@@ -1293,16 +1334,42 @@ impl Store {
None
}
/// Delete EC shard files from disk.
pub fn delete_ec_shards(&mut self, vid: VolumeId, collection: &str, shard_ids: &[ShardId]) {
/// Delete EC shard files from disk. Staged-generation removal failures are
/// retained and returned after every location has been processed, so a
/// failed sweep never masquerades as a successful delete.
pub fn delete_ec_shards(
&mut self,
vid: VolumeId,
collection: &str,
shard_ids: &[ShardId],
) -> std::io::Result<()> {
// Delete shard files from disk, tracking which locations actually held one.
let mut deleted_at = vec![false; self.locations.len()];
let mut first_err: Option<std::io::Error> = None;
for (i, loc) in self.locations.iter().enumerate() {
for &shard_id in shard_ids {
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
if std::fs::remove_file(shard.file_name()).is_ok() {
deleted_at[i] = true;
}
// The shard and every 2PC generation of it (<name>.v<N>) are
// removed: the shard must not live on this disk at all.
match crate::storage::erasure_coding::ec_shard::remove_ec_shard_generations(
&shard.file_name(),
) {
Ok(true) => deleted_at[i] = true,
Ok(false) => {}
Err(e) => {
tracing::warn!(
"failed to remove staged generations of {}: {}",
shard.file_name(),
e
);
if first_err.is_none() {
first_err = Some(e);
}
}
}
}
}
@@ -1374,6 +1441,11 @@ impl Store {
}
}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
/// True if `loc` still has any on-disk EC shard for this volume. An
@@ -1447,12 +1519,25 @@ impl Store {
&mut self,
vid: VolumeId,
preallocate: u64,
max_bytes_per_second: i64,
_max_bytes_per_second: i64,
progress_fn: F,
) -> Result<(), VolumeError>
where
F: Fn(i64) -> bool,
{
match self.begin_compact_volume(vid, preallocate)? {
Some(job) => job.run(progress_fn),
None => Ok(()),
}
}
/// The part of `compact_volume` that needs the store: check free space and
/// start the compaction. The returned job runs without the store lock.
pub(crate) fn begin_compact_volume(
&mut self,
vid: VolumeId,
preallocate: u64,
) -> Result<Option<CompactionJob>, VolumeError> {
// Required space matches Go's CompactVolume check: the larger of the
// requested preallocation and the estimated volume size.
let (loc_idx, space_needed) = {
@@ -1476,7 +1561,7 @@ impl Store {
let (_, v) = self
.find_volume_mut(vid)
.ok_or(VolumeError::VolumeNotFound(vid))?;
v.compact_by_index(preallocate, max_bytes_per_second, progress_fn)
v.begin_compact_by_index()
}
/// Commit a completed compaction: swap files and reload.
@@ -1776,7 +1861,7 @@ mod tests {
store
.write_volume_needle(VolumeId(7), &mut n, false)
.unwrap();
assert!(store.unmount_volume(VolumeId(7)));
assert!(store.unmount_volume(VolumeId(7)).unwrap());
store.mount_volume_by_id(VolumeId(7), Some("coll")).unwrap();
assert!(store.find_volume(VolumeId(7)).is_some());
@@ -1818,7 +1903,7 @@ mod tests {
store
.write_volume_needle(VolumeId(9), &mut n, false)
.unwrap();
assert!(store.unmount_volume(VolumeId(9)));
assert!(store.unmount_volume(VolumeId(9)).unwrap());
// The hint is accepted and mounts the volume.
store
@@ -1863,7 +1948,7 @@ mod tests {
store
.write_volume_needle(VolumeId(11), &mut n, false)
.unwrap();
assert!(store.unmount_volume(VolumeId(11)));
assert!(store.unmount_volume(VolumeId(11)).unwrap());
// Simulate an interrupted copy: drop a .note marker.
let base = volume_file_name(dir, "coll", VolumeId(11));
@@ -1920,7 +2005,7 @@ mod tests {
store
.write_volume_needle(VolumeId(13), &mut n, false)
.unwrap();
assert!(store.unmount_volume(VolumeId(13)));
assert!(store.unmount_volume(VolumeId(13)).unwrap());
// No hint: the fallback scan finds the sidecar on disk 0 first (skip,
// no .dat), then the real .dat on disk 1 (mount).
@@ -1975,7 +2060,7 @@ mod tests {
store
.write_volume_needle(VolumeId(15), &mut n, false)
.unwrap();
assert!(store.unmount_volume(VolumeId(15)));
assert!(store.unmount_volume(VolumeId(15)).unwrap());
// Clear the low-space flag so mount_volume_by_id considers disk 0.
store.locations[0]
.is_disk_space_low
@@ -2352,7 +2437,7 @@ mod tests {
.unwrap();
let selected =
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive);
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive, None);
assert_eq!(selected, Some(1));
store.locations[1]
@@ -2360,7 +2445,7 @@ mod tests {
.store(true, Ordering::Relaxed);
let selected =
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive);
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive, None);
assert_eq!(selected, Some(0));
}
@@ -2483,6 +2568,162 @@ mod tests {
assert_eq!(v.dat_file_size().unwrap(), volume_size);
}
fn write_test_needle(store: &mut Store, vid: VolumeId, id: u64, data: &[u8]) {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(id as u32),
data_size: data.len() as u32,
data: data.to_vec(),
..Needle::default()
};
store.write_volume_needle(vid, &mut n, true).unwrap();
}
fn read_test_needle(store: &Store, vid: VolumeId, id: u64) -> Result<Vec<u8>, VolumeError> {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(id as u32),
..Needle::default()
};
store.read_volume_needle(vid, &mut n)?;
Ok(n.data)
}
/// While a compaction copy runs off the store lock, nothing may pull the
/// volume's files out from under it or start a second copy into .cpd.
#[test]
fn test_compaction_in_flight_guards_the_volume() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let other = TempDir::new().unwrap();
let mut store = make_test_store(&[dir]);
let vid = VolumeId(1);
store
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
for i in 1..=3u64 {
write_test_needle(&mut store, vid, i, format!("data-{i}").as_bytes());
}
let revision = {
let (_, v) = store.find_volume(vid).unwrap();
v.super_block.compaction_revision
};
let job = store
.begin_compact_volume(vid, 0)
.unwrap()
.expect("the first compaction claims the volume");
assert!(store.begin_compact_volume(vid, 0).unwrap().is_none());
assert!(store.unmount_volume(vid).is_err());
assert!(store.delete_volume(vid, false, false, false).is_err());
store.delete_collection("").unwrap();
assert!(store.cleanup_compact_volume(vid).is_err());
let (_, v) = store.find_volume_mut(vid).unwrap();
assert!(v.relocate_index_to(other.path().to_str().unwrap()).is_err());
// Go parity: a commit that finds the volume compacting is a no-op.
store.commit_compact_volume(vid).unwrap();
let (_, v) = store.find_volume(vid).expect("still mounted");
assert!(v.is_compacting());
assert_eq!(v.super_block.compaction_revision, revision);
job.run(|_| true).unwrap();
assert!(!store.find_volume(vid).unwrap().1.is_compacting());
store.commit_compact_volume(vid).unwrap();
let (_, v) = store.find_volume(vid).unwrap();
assert_eq!(v.super_block.compaction_revision, revision + 1);
assert!(store.unmount_volume(vid).unwrap());
}
/// Writes, overwrites and deletes that land while the copy is parked
/// off the store lock must all survive the commit via makeup_diff.
fn check_writes_during_compaction_survive_commit(kind: NeedleMapKind) {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut store = Store::new(kind);
store
.add_location(
dir,
dir,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
let vid = VolumeId(1);
store
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
let (_, v) = store.find_volume(vid).unwrap();
assert_eq!(
v.live_meta_idx_size_for_test().is_some(),
kind == NeedleMapKind::Redb
);
for i in 1..=6u64 {
write_test_needle(&mut store, vid, i, format!("data-{i}").as_bytes());
}
let mut del = Needle {
id: NeedleId(2),
cookie: Cookie(2),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del).unwrap();
let revision = {
let (_, v) = store.find_volume(vid).unwrap();
v.super_block.compaction_revision
};
let job = store.begin_compact_volume(vid, 0).unwrap().unwrap();
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
let copy = std::thread::spawn(move || {
job.run(move |_| {
let _ = entered_tx.send(());
let _ = release_rx.recv();
true
})
});
entered_rx.recv().unwrap();
write_test_needle(&mut store, vid, 99, b"late-write");
write_test_needle(&mut store, vid, 3, b"overwritten");
let mut del = Needle {
id: NeedleId(4),
cookie: Cookie(4),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del).unwrap();
drop(release_tx);
copy.join().unwrap().unwrap();
store.commit_compact_volume(vid).unwrap();
let (_, v) = store.find_volume(vid).unwrap();
assert_eq!(v.super_block.compaction_revision, revision + 1);
assert_eq!(read_test_needle(&store, vid, 99).unwrap(), b"late-write");
assert_eq!(read_test_needle(&store, vid, 3).unwrap(), b"overwritten");
assert!(read_test_needle(&store, vid, 4).is_err());
assert!(read_test_needle(&store, vid, 2).is_err());
for i in [1u64, 5, 6] {
assert_eq!(
read_test_needle(&store, vid, i).unwrap(),
format!("data-{i}").as_bytes()
);
}
}
#[test]
fn test_writes_during_compaction_survive_commit_in_memory() {
check_writes_during_compaction_survive_commit(NeedleMapKind::InMemory);
}
#[test]
fn test_writes_during_compaction_survive_commit_redb() {
check_writes_during_compaction_survive_commit(NeedleMapKind::Redb);
}
/// Build a Store with N HDD disk locations under a single TempDir.
/// Returns the store and the TempDir guard so callers keep the dirs
/// alive for the test's lifetime.
@@ -2553,13 +2794,13 @@ mod tests {
std::fs::write(format!("{}.ecsum", base1), b"x").unwrap();
// Disk 1 still has .ec01 afterwards: both sidecars survive.
store.delete_ec_shards(vid, collection, &[0]);
store.delete_ec_shards(vid, collection, &[0]).unwrap();
assert!(std::path::Path::new(&format!("{}.ecsum", base0)).exists());
assert!(std::path::Path::new(&format!("{}.ecsum", base1)).exists());
// Disk 1's last shard goes: its sidecar is orphaned and removed, but
// disk 0 was never touched by either delete and keeps its sidecar.
store.delete_ec_shards(vid, collection, &[1]);
store.delete_ec_shards(vid, collection, &[1]).unwrap();
assert!(!std::path::Path::new(&format!("{}.ec01", base1)).exists());
assert!(
!std::path::Path::new(&format!("{}.ecsum", base1)).exists(),
@@ -2604,13 +2845,13 @@ mod tests {
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
std::fs::write(format!("{}.ecsum", idx_base), b"x").unwrap();
store.delete_ec_shards(vid, collection, &[0]);
store.delete_ec_shards(vid, collection, &[0]).unwrap();
assert!(
std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
"shared idx sidecar must survive while a sibling disk still has shards"
);
store.delete_ec_shards(vid, collection, &[1]);
store.delete_ec_shards(vid, collection, &[1]).unwrap();
assert!(
!std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
"shared idx sidecar should go with the last location's last shard"
@@ -2633,7 +2874,7 @@ mod tests {
std::fs::write(format!("{}.vif", base1), b"x").unwrap();
std::fs::write(format!("{}.idx", base1), b"x").unwrap();
store.delete_ec_shards(vid, collection, &[0, 1]);
store.delete_ec_shards(vid, collection, &[0, 1]).unwrap();
assert!(
!std::path::Path::new(&format!("{}.vif", base0)).exists(),
@@ -2645,6 +2886,34 @@ mod tests {
);
}
/// Deleting a shard removes its staged 2PC generations (<name>.v<N>) too:
/// a shard evicted off a disk leaves nothing (Go
/// deleteEcShardIdsForEachLocation).
#[test]
fn test_delete_ec_shards_removes_staged_generations() {
let (mut store, _tmp) = make_ec_target_test_store(1);
let collection = "c";
let vid = VolumeId(7);
let base = volume_file_name(&store.locations[0].directory, collection, vid);
std::fs::write(format!("{}.ec00", base), b"x").unwrap();
std::fs::write(format!("{}.ec05", base), b"x").unwrap();
std::fs::write(format!("{}.ec05.v2", base), b"x").unwrap();
std::fs::write(format!("{}.ecx", base), b"x").unwrap();
store.delete_ec_shards(vid, collection, &[5]).unwrap();
assert!(!std::path::Path::new(&format!("{}.ec05", base)).exists());
assert!(
!std::path::Path::new(&format!("{}.ec05.v2", base)).exists(),
"staged generations of a deleted shard must go with it"
);
assert!(std::path::Path::new(&format!("{}.ec00", base)).exists());
assert!(
std::path::Path::new(&format!("{}.ecx", base)).exists(),
"index must survive while shards remain"
);
}
/// An already-mounted EC volume on disk 1 must win over a stray
/// `.ecx` on disk 2. Protects the post-startup steady state from
/// being perturbed by leftover index files from a prior failed move.
@@ -1476,7 +1476,7 @@ mod tests {
let vid = VolumeId(7004);
let collection = "grafana-loki";
store.delete_ec_shards(vid, collection, &[1]);
store.delete_ec_shards(vid, collection, &[1]).unwrap();
// Shard 1 file is gone on disk 1.
let p1 = format!(
File diff suppressed because it is too large. Load diff
+22 -19
View File
@@ -46,18 +46,19 @@ const (
)
type MasterOptions struct {
port *int
portGrpc *int
ip *string
ipBind *string
metaFolder *string
peers *string
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
volumeSizeLimitMB *uint
fileSizeLimitMB *int
volumePreallocate *bool
maxParallelVacuumPerServer *int
vacuumIntervalSeconds *int
port *int
portGrpc *int
ip *string
ipBind *string
metaFolder *string
peers *string
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
volumeSizeLimitMB *uint
fileSizeLimitMB *int
volumePreallocate *bool
maxParallelVacuumPerServer *int
vacuumIntervalSeconds *int
vacuumDeleteEmptyAfterSeconds *int
// pulseSeconds *int
defaultReplication *string
garbageThreshold *float64
@@ -95,6 +96,7 @@ func init() {
m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server")
m.vacuumIntervalSeconds = cmdMaster.Flag.Int("vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
m.vacuumDeleteEmptyAfterSeconds = cmdMaster.Flag.Int("vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
// m.pulseSeconds = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
m.defaultReplication = cmdMaster.Flag.String("defaultReplication", "", "Default replication type if not specified.")
m.garbageThreshold = cmdMaster.Flag.Float64("garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
@@ -469,13 +471,14 @@ func peerIndex(self pb.ServerAddress, peers []pb.ServerAddress) int {
func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOption {
masterAddress := pb.NewServerAddress(*m.ip, *m.port, *m.portGrpc)
return &weed_server.MasterOption{
Master: masterAddress,
MetaFolder: *m.metaFolder,
VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
FileSizeLimitMB: *m.fileSizeLimitMB,
VolumePreallocate: *m.volumePreallocate,
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
Master: masterAddress,
MetaFolder: *m.metaFolder,
VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
FileSizeLimitMB: *m.fileSizeLimitMB,
VolumePreallocate: *m.volumePreallocate,
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
VacuumDeleteEmptyAfterSeconds: *m.vacuumDeleteEmptyAfterSeconds,
// PulseSeconds: *m.pulseSeconds,
DefaultReplicaPlacement: *m.defaultReplication,
GarbageThreshold: *m.garbageThreshold,
+1
View File
@@ -48,6 +48,7 @@ func init() {
mf.raftResumeState = aws.Bool(false)
mf.maxParallelVacuumPerServer = aws.Int(1)
mf.vacuumIntervalSeconds = aws.Int(840)
mf.vacuumDeleteEmptyAfterSeconds = aws.Int(0)
mf.telemetryUrl = aws.String("https://telemetry.seaweedfs.com/api/collect")
mf.telemetryEnabled = aws.Bool(false)
}
+1
View File
@@ -428,6 +428,7 @@ func initMiniMasterFlags() {
miniMasterOptions.volumePreallocate = cmdMini.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
miniMasterOptions.maxParallelVacuumPerServer = cmdMini.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
miniMasterOptions.vacuumIntervalSeconds = cmdMini.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
miniMasterOptions.vacuumDeleteEmptyAfterSeconds = cmdMini.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
miniMasterOptions.defaultReplication = cmdMini.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
miniMasterOptions.garbageThreshold = cmdMini.Flag.Float64("master.garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
miniMasterOptions.metricsAddress = cmdMini.Flag.String("master.metrics.address", "", "Prometheus gateway address")
+1
View File
@@ -41,6 +41,7 @@ copy_2 = 6 # create 2 x 6 = 12 actual volumes
copy_3 = 3 # create 3 x 3 = 9 actual volumes
copy_other = 1 # create n x 1 = n actual volumes
threshold = 0.9 # create threshold
reservation_timeout = "5m"# capacity reservation timeout before unreleased reservations expire
disable = false # disables volume growth if true
# configuration flags for replication
+1
View File
@@ -99,6 +99,7 @@ func init() {
masterOptions.volumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
masterOptions.maxParallelVacuumPerServer = cmdServer.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
masterOptions.vacuumIntervalSeconds = cmdServer.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
masterOptions.vacuumDeleteEmptyAfterSeconds = cmdServer.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
masterOptions.defaultReplication = cmdServer.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
masterOptions.garbageThreshold = cmdServer.Flag.Float64("master.garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
masterOptions.metricsAddress = cmdServer.Flag.String("master.metrics.address", "", "Prometheus gateway address")
+1 -1
View File
@@ -606,7 +606,7 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) (bool, error) {
select {
case <-ctx.Done():
glog.Errorf("Context is done.")
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() {
+20
View File
@@ -104,3 +104,23 @@ func TestExpiredFileIsDeletedOnRead(t *testing.T) {
require.ErrorIs(t, err, filer_pb.ErrNotFound,
"native TTL lookup should remove the expired metadata row")
}
func TestListDirectoryEntriesContextCanceled(t *testing.T) {
f, store := newTestFilerWithStubStore()
ctx := context.Background()
require.NoError(t, store.InsertEntry(ctx, &Entry{
FullPath: util.FullPath("/dir/file1.txt"),
Attr: Attr{Mode: 0o644},
}))
canceledCtx, cancel := context.WithCancel(ctx)
cancel()
_, _, err := f.doListDirectoryEntries(canceledCtx, util.FullPath("/dir"), "", false, 10, "", func(entry *Entry) (bool, error) {
return true, nil
})
require.Error(t, err)
assert.ErrorContains(t, err, "context canceled")
}
+22 -12
View File
@@ -32,7 +32,9 @@ type ChunkReadAt struct {
fileSize int64
readerCache *ReaderCache
readerPattern *ReaderPattern
lastChunkMu sync.Mutex // guards lastChunkFid; mount issues concurrent ReadAt calls
lastChunkFid string
stream chunkStream // chunk this reader is positioned in, pinned in the shared readerCache
prefetchCount int // Number of chunks to prefetch ahead during sequential reads
ctx context.Context // Context used for cancellation during chunk read operations
}
@@ -167,10 +169,17 @@ func (c *ChunkReadAt) Size() int64 {
}
func (c *ChunkReadAt) Close() error {
c.ReleaseStream()
c.readerCache.destroy()
return nil
}
// ReleaseStream drops this reader's hold on the chunk it is positioned in.
// Unlike Close it leaves the (possibly shared) ReaderCache intact.
func (c *ChunkReadAt) ReleaseStream() {
c.readerCache.releaseStream(&c.stream)
}
func (c *ChunkReadAt) ReadAt(p []byte, offset int64) (n int, err error) {
c.readerPattern.MonitorReadAt(offset, len(p))
@@ -341,6 +350,7 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
if c.readerPattern.IsRandomMode() {
c.readerCache.releaseStream(&c.stream)
n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
if n > 0 {
return n, err
@@ -350,20 +360,20 @@ func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunk
}
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
n, err = c.readerCache.ReadChunkAt(ctx, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
if c.lastChunkFid != chunkView.FileId {
if chunkView.OffsetInChunk == 0 { // start of a new chunk
if c.lastChunkFid != "" {
c.readerCache.UnCache(c.lastChunkFid)
}
if nextChunkViews != nil && c.prefetchCount > 0 {
// Prefetch multiple chunks ahead for better sequential read throughput
// This keeps the network pipeline full with parallel chunk fetches
c.readerCache.MaybeCache(nextChunkViews, c.prefetchCount)
}
// The previous chunk is released through the stream pin rather than
// UnCache: the buffer is shared, and other streams may still be reading it.
n, err = c.readerCache.readChunkAt(ctx, &c.stream, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
c.lastChunkMu.Lock()
enteredChunk := c.lastChunkFid != chunkView.FileId
c.lastChunkFid = chunkView.FileId
c.lastChunkMu.Unlock()
if enteredChunk && chunkView.OffsetInChunk == 0 { // start of a new chunk
if nextChunkViews != nil && c.prefetchCount > 0 {
// Prefetch multiple chunks ahead for better sequential read throughput
// This keeps the network pipeline full with parallel chunk fetches
c.readerCache.MaybeCache(nextChunkViews, c.prefetchCount)
}
}
c.lastChunkFid = chunkView.FileId
return
}
+283
View File
@@ -0,0 +1,283 @@
package filer
import (
"context"
"fmt"
"io"
"sync"
"sync/atomic"
"testing"
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// Two streams (e.g. two S3 GETs) reading the same object through one shared
// ReaderCache, interleaved in small slices, must share each chunk download:
// one stream finishing a chunk, or moving on to the next one, must not drop a
// buffer the other stream is still reading.
func TestChunkReadAtConcurrentStreamsShareChunks(t *testing.T) {
const chunkSize = 64 << 10
const chunkCount = 3
const sliceSize = 16 << 10
var mu sync.Mutex
fetches := map[string]int{}
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
mu.Lock()
fetches[fileId]++
mu.Unlock()
for i := range buffer {
buffer[i] = fileId[len(fileId)-1]
}
return len(buffer), nil
}
newStream := func() *ChunkReadAt {
views := NewIntervalList[*ChunkView]()
for i := 0; i < chunkCount; i++ {
views.AppendInterval(&Interval[*ChunkView]{
StartOffset: int64(i * chunkSize),
StopOffset: int64((i + 1) * chunkSize),
Value: &ChunkView{
FileId: fmt.Sprintf("chunk%d", i),
ViewSize: chunkSize,
ViewOffset: int64(i * chunkSize),
ChunkSize: chunkSize,
},
})
}
return NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
}
streams := []*ChunkReadAt{newStream(), newStream()}
// The streams alternate slice by slice, the second one lagging one slice
// behind, so the leader always finishes a chunk while the follower is
// still inside it.
offsets := make([]int64, len(streams))
offsets[1] = -sliceSize
for offsets[1] < chunkSize*chunkCount {
for i, stream := range streams {
if offsets[i] < 0 || offsets[i] >= chunkSize*chunkCount {
offsets[i] += sliceSize
continue
}
buf := make([]byte, sliceSize)
n, err := stream.ReadAt(buf, offsets[i])
if (err != nil && err != io.EOF) || n != sliceSize {
t.Fatalf("stream %d at %d: n=%d err=%v", i, offsets[i], n, err)
}
if want := byte('0' + offsets[i]/chunkSize); buf[0] != want || buf[n-1] != want {
t.Fatalf("stream %d at %d: got %q, want %q", i, offsets[i], buf[0], want)
}
offsets[i] += sliceSize
}
}
mu.Lock()
defer mu.Unlock()
for i := 0; i < chunkCount; i++ {
fileId := fmt.Sprintf("chunk%d", i)
if fetches[fileId] != 1 {
t.Errorf("%s fetched %d times for two concurrent streams, want 1", fileId, fetches[fileId])
}
}
}
func newStreamTestReaderCache(chunkCache chunk_cache.ChunkCache) *ReaderCache {
rc := NewReaderCache(64, chunkCache, func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
return len(buffer), nil
}
return rc
}
func isRetained(rc *ReaderCache, fileId string) bool {
rc.Lock()
defer rc.Unlock()
_, found := rc.downloaders[fileId]
return found
}
// A stream moving on to a chunk served from the chunk cache must still
// release the chunk it was positioned in before.
func TestChunkStreamReleasesPreviousChunkOnCacheHit(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
cache.SetChunk("chunk1", make([]byte, 4<<10))
rc := newStreamTestReaderCache(cache)
defer rc.destroy()
stream := &chunkStream{}
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
if n, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, true); err != nil || n == 0 {
t.Fatalf("cache hit read: n=%d err=%v", n, err)
}
if isRetained(rc, "chunk0") {
t.Fatal("chunk0 still retained after the stream moved on to a cached chunk")
}
}
// A chunk the stream leaves while another read is in flight must be dropped
// once that read ends, even if it did not read the chunk to the end.
func TestChunkStreamDropsLeftChunkAfterInFlightRead(t *testing.T) {
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
defer rc.destroy()
stream := &chunkStream{}
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
// Another reader is in the middle of a partial read of chunk0.
rc.Lock()
other := rc.downloaders["chunk0"]
other.wg.Add(1)
atomic.AddInt32(&other.readers, 1)
rc.Unlock()
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
if !isRetained(rc, "chunk0") {
t.Fatal("chunk0 dropped while a read was still in flight")
}
// The in-flight read ends without reaching the end of the chunk.
other.wg.Done()
atomic.AddInt32(&other.readers, -1)
rc.removeConsumed(other)
if isRetained(rc, "chunk0") {
t.Fatal("chunk0 retained after the stream left it and the last read ended")
}
}
// Concurrent ReadAt calls on one ChunkReadAt (as mount does) share its stream
// pin; they must neither race on it nor leak or double-release pins.
func TestChunkStreamConcurrentReadsOnOneReader(t *testing.T) {
const chunkSize = 16 << 10
const chunkCount = 4
const sliceSize = 4 << 10
rc := newStreamTestReaderCache((*chunk_cache.TieredChunkCache)(nil))
defer rc.destroy()
views := NewIntervalList[*ChunkView]()
for i := 0; i < chunkCount; i++ {
views.AppendInterval(&Interval[*ChunkView]{
StartOffset: int64(i * chunkSize),
StopOffset: int64((i + 1) * chunkSize),
Value: &ChunkView{
FileId: fmt.Sprintf("chunk%d", i),
ViewSize: chunkSize,
ViewOffset: int64(i * chunkSize),
ChunkSize: chunkSize,
},
})
}
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
var wg sync.WaitGroup
for g := 0; g < 8; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for offset := int64(0); offset < chunkSize*chunkCount; offset += sliceSize {
if _, err := reader.ReadAt(make([]byte, sliceSize), offset); err != nil && err != io.EOF {
t.Error(err)
return
}
}
}()
}
wg.Wait()
// Finishing the last chunk releases the stream's final pin.
if _, err := reader.ReadAt(make([]byte, sliceSize), chunkSize*chunkCount-sliceSize); err != nil && err != io.EOF {
t.Fatal(err)
}
rc.Lock()
defer rc.Unlock()
for fileId, cacher := range rc.downloaders {
t.Errorf("%s retained after all reads finished: pins=%d readers=%d", fileId, atomic.LoadInt32(&cacher.pins), atomic.LoadInt32(&cacher.readers))
}
}
// A chunk a stream is positioned in must outlast downloader-limit eviction:
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
const chunkSize = 64 << 10
var fetches int32
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
if fileId == "chunk0" {
atomic.AddInt32(&fetches, 1)
}
return len(buffer), nil
}
stream := &chunkStream{}
buf := make([]byte, 16<<10)
// One slice in: the stream is positioned in chunk0 but has not left it.
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
t.Fatal(err)
}
// Fill the downloader map past its limit with unpinned chunks.
for _, fileId := range []string{"chunk1", "chunk2", "chunk3"} {
if _, err := rc.ReadChunkAt(context.Background(), buf, fileId, nil, false, 0, chunkSize, true); err != nil {
t.Fatalf("read %s: %v", fileId, err)
}
}
// The stream's next slice must come from the still-pinned buffer.
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 16<<10, chunkSize, false); err != nil {
t.Fatal(err)
}
if got := atomic.LoadInt32(&fetches); got != 1 {
t.Errorf("chunk0 fetched %d times, want 1", got)
}
}
// When every downloader is pinned the limit still applies: the oldest pinned
// buffer is evicted so abandoned streams cannot grow memory past the limit.
func TestChunkReadAtPinnedEvictionFallsBackWhenAllPinned(t *testing.T) {
const chunkSize = 64 << 10
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
return len(buffer), nil
}
buf := make([]byte, 16<<10)
streamA := &chunkStream{}
streamB := &chunkStream{}
if _, err := rc.readChunkAt(context.Background(), streamA, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
t.Fatal(err)
}
if _, err := rc.readChunkAt(context.Background(), streamB, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
t.Fatal(err)
}
// Every downloader is now pinned; the next chunk must still get in.
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil {
t.Fatal(err)
}
if isRetained(rc, "chunk0") {
t.Fatal("oldest pinned downloader was not evicted past the limit")
}
if !isRetained(rc, "chunk2") {
t.Fatal("new downloader missing after pinned fallback eviction")
}
}
+128 -9
View File
@@ -35,6 +35,8 @@ type SingleChunkCacher struct {
completedTimeNew int64
readers int32
consumed int32
pins int32 // streams currently positioned inside this chunk
left int32 // set once the last pinning stream moved on
sync.Mutex
parent *ReaderCache
chunkFileId string
@@ -112,7 +114,19 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
return
}
// chunkStream is one sequential reader's position in a shared ReaderCache.
// The chunk it is reading stays pinned until the stream reads it to the end or
// moves elsewhere, so another stream finishing or leaving the same chunk does
// not drop the buffer from under it.
type chunkStream struct {
cacher *SingleChunkCacher
}
func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
return rc.readChunkAt(ctx, nil, buffer, fileId, cipherKey, isGzipped, offset, chunkSize, shouldCache)
}
func (rc *ReaderCache) readChunkAt(ctx context.Context, stream *chunkStream, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
retry:
rc.Lock()
@@ -130,8 +144,11 @@ retry:
// start wg.Wait() on a zero counter while this read is about to register.
cacher.wg.Add(1)
atomic.AddInt32(&cacher.readers, 1)
previous := stream.pin(cacher)
rc.Unlock()
rc.unpin(previous)
n, err := cacher.readChunkAt(ctx, buffer, offset)
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
if n > 0 || err != nil {
return n, err
}
@@ -144,19 +161,34 @@ retry:
if shouldCache || rc.lookupFileIdFn == nil {
n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset))
if n > 0 {
// Served from the chunk cache: the stream has left its pinned chunk.
previous := stream.unpinLocked()
rc.Unlock()
rc.unpin(previous)
return n, err
}
}
// clean up old downloaders
// clean up old downloaders; prefer one no stream is positioned in, but
// fall back to a pinned one so abandoned pins cannot bypass the limit
if len(rc.downloaders) >= rc.limit {
oldestFid, oldestTime := "", time.Now().UnixNano()
pinnedFid, pinnedTime := "", int64(0)
for fid, downloader := range rc.downloaders {
completedTime := atomic.LoadInt64(&downloader.completedTimeNew)
if completedTime > 0 && completedTime < oldestTime {
oldestFid, oldestTime = fid, completedTime
if completedTime <= 0 {
continue
}
if atomic.LoadInt32(&downloader.pins) == 0 {
if completedTime < oldestTime {
oldestFid, oldestTime = fid, completedTime
}
} else if pinnedFid == "" || completedTime < pinnedTime {
pinnedFid, pinnedTime = fid, completedTime
}
}
if oldestFid == "" {
oldestFid = pinnedFid
}
if oldestFid != "" {
oldDownloader := rc.downloaders[oldestFid]
@@ -175,9 +207,77 @@ retry:
rc.downloaders[fileId] = cacher
cacher.wg.Add(1)
atomic.AddInt32(&cacher.readers, 1)
previous := stream.pin(cacher)
rc.Unlock()
rc.unpin(previous)
return cacher.readChunkAt(ctx, buffer, offset)
n, err := cacher.readChunkAt(ctx, buffer, offset)
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
return n, err
}
// pin makes cacher the stream's current chunk and returns the chunk it was
// pinned to before, which the caller unpins once the ReaderCache lock is
// released. The stream is only touched under the ReaderCache lock, since
// concurrent ReadAt calls on one ChunkReadAt share it.
func (stream *chunkStream) pin(cacher *SingleChunkCacher) (previous *SingleChunkCacher) {
if stream == nil || stream.cacher == cacher {
return nil
}
previous = stream.cacher
stream.cacher = cacher
atomic.AddInt32(&cacher.pins, 1)
return previous
}
// unpinLocked detaches the stream from its chunk and returns that chunk for
// the caller to unpin once the ReaderCache lock is released.
func (stream *chunkStream) unpinLocked() (previous *SingleChunkCacher) {
if stream == nil {
return nil
}
previous = stream.cacher
stream.cacher = nil
return previous
}
// releaseIfFinished unpins the stream's chunk once the stream has read it to
// the end, since the stream will not come back to it.
func (rc *ReaderCache) releaseIfFinished(stream *chunkStream, cacher *SingleChunkCacher, offset int64, n int, err error, chunkSize int) {
if stream == nil || err != nil || offset+int64(n) < int64(chunkSize) {
return
}
var previous *SingleChunkCacher
rc.Lock()
if stream.cacher == cacher {
previous = stream.unpinLocked()
}
rc.Unlock()
rc.unpin(previous)
}
// releaseStream unpins whatever chunk the stream is positioned in.
func (rc *ReaderCache) releaseStream(stream *chunkStream) {
if stream == nil {
return
}
rc.Lock()
previous := stream.unpinLocked()
rc.Unlock()
rc.unpin(previous)
}
// unpin drops one stream's pin. Once no stream is positioned in the chunk it
// is dropped like UnCache would, as soon as no read is in progress either:
// here if none is, otherwise by the last read's removeConsumed.
func (rc *ReaderCache) unpin(downloader *SingleChunkCacher) {
if downloader == nil {
return
}
if atomic.AddInt32(&downloader.pins, -1) == 0 {
atomic.StoreInt32(&downloader.left, 1)
}
rc.removeConsumed(downloader)
}
func (rc *ReaderCache) UnCache(fileId string) {
@@ -202,15 +302,34 @@ func (rc *ReaderCache) remove(downloader *SingleChunkCacher) {
}
}
// removeConsumed drops a cacher once its buffer was fully read and no
// readers remain attached. The checks run under the ReaderCache lock so a
// reader attaching at the same time either wins (the cacher stays and that
// reader's detach retries the removal) or misses the map and refetches.
// removeUnpinned drops a cacher only while no stream is positioned in it.
// Budget eviction picks its victim under the budget lock, so the pin check
// and the map removal must happen together under the ReaderCache lock.
func (rc *ReaderCache) removeUnpinned(downloader *SingleChunkCacher) (removed bool) {
rc.Lock()
removed = rc.downloaders[downloader.chunkFileId] == downloader &&
atomic.LoadInt32(&downloader.pins) == 0
if removed {
delete(rc.downloaders, downloader.chunkFileId)
}
rc.Unlock()
if removed {
downloader.destroy()
}
return
}
// removeConsumed drops a cacher once its buffer was fully read, or the
// streams positioned in it have left, and no readers remain attached or
// pinned. The checks run under the ReaderCache lock so a reader attaching
// at the same time either wins (the cacher stays and that reader's detach
// retries the removal) or misses the map and refetches.
func (rc *ReaderCache) removeConsumed(downloader *SingleChunkCacher) {
rc.Lock()
removed := rc.downloaders[downloader.chunkFileId] == downloader &&
atomic.LoadInt32(&downloader.readers) == 0 &&
atomic.LoadInt32(&downloader.consumed) != 0
atomic.LoadInt32(&downloader.pins) == 0 &&
(atomic.LoadInt32(&downloader.consumed) != 0 || atomic.LoadInt32(&downloader.left) != 0)
if removed {
delete(rc.downloaders, downloader.chunkFileId)
}
+31 -3
View File
@@ -4,6 +4,7 @@ import (
"container/list"
"fmt"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/util/mem"
)
@@ -51,12 +52,39 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error {
b.Unlock()
return nil
}
if entry := b.idle.Front(); entry != nil {
victim := entry.Value.(*SingleChunkCacher)
// Prefer evicting an idle chunk no stream is positioned in; fall back
// to the oldest pinned one so abandoned pins cannot block the budget.
var victim *SingleChunkCacher
var entry *list.Element
pinnedVictim := false
for e := b.idle.Front(); e != nil; e = e.Next() {
c := e.Value.(*SingleChunkCacher)
if atomic.LoadInt32(&c.pins) == 0 {
victim, entry = c, e
pinnedVictim = false
break
}
if victim == nil {
victim, entry = c, e
pinnedVictim = true
}
}
if entry != nil {
b.idle.Remove(entry)
delete(b.idleEntries, victim)
b.Unlock()
victim.parent.remove(victim)
if pinnedVictim {
victim.parent.remove(victim)
} else if !victim.parent.removeUnpinned(victim) {
// The victim was pinned between selection and removal: keep it
// evictable so a pin abandoned in that gap cannot wedge the
// budget, then retry the selection.
b.Lock()
if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil {
b.idleEntries[victim] = b.idle.PushBack(victim)
}
b.Unlock()
}
continue
}
changed := b.changed
@@ -123,9 +123,10 @@ func genericCopyRoleDefinition(role *RoleDefinition) *RoleDefinition {
}
result := &RoleDefinition{
RoleName: role.RoleName,
RoleArn: role.RoleArn,
Description: role.Description,
RoleName: role.RoleName,
RoleArn: role.RoleArn,
Description: role.Description,
MaxSessionDuration: role.MaxSessionDuration,
}
// Deep copy trust policy if it exists
+48 -16
View File
@@ -942,7 +942,7 @@ func (m *IAMManager) AssumeRoleWithWebIdentity(ctx context.Context, request *sts
// Apply role-level MaxSessionDuration cap. The STS service still applies
// the global MaxSessionLength and the source-token-expiry cap on top of
// this; per-role takes precedence whenever it is the tightest bound.
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration, m.defaultTokenDurationSeconds(), m.maxSessionLengthSeconds())
// Use STS service to assume the role
return m.stsService.AssumeRoleWithWebIdentity(ctx, request)
@@ -1005,22 +1005,54 @@ func extractIssuerFromJWT(token string) (string, error) {
return iss, nil
}
// capDurationByRole returns the requested duration clamped to the role's
// MaxSessionDuration. A nil requested duration is left nil so the STS
// service's calculateSessionDuration applies the global default (typically
// 1 hour) — substituting the role's max here would silently mint a 12h
// session for any caller who omitted DurationSeconds, which AWS does not
// do. The role-max upper bound still applies in the downstream cap chain
// once the request has a concrete duration.
func capDurationByRole(requested *int64, roleMax int64) *int64 {
if roleMax <= 0 || requested == nil {
return requested
// capDurationByRole returns the session duration clamped to the role's
// MaxSessionDuration. An omitted DurationSeconds resolves to the configured
// default first, so the role bound caps defaults and explicit values alike.
// A nil request is only materialized when something tightened the default
// and the explicit value still passes the service's own input validation —
// everything else is left nil so the service resolves the default and its
// MaxSessionLength cap itself.
func capDurationByRole(requested *int64, roleMax, defaultSec, serviceMaxSec int64) *int64 {
if requested != nil {
d := *requested
if roleMax > 0 && d > roleMax {
d = roleMax
}
return &d
}
if *requested > roleMax {
v := roleMax
return &v
d := defaultSec
if roleMax > 0 && d > roleMax {
d = roleMax
}
return requested
if d > serviceMaxSec {
d = serviceMaxSec
}
if d < 900 && roleMax > 0 {
d = 900
}
if d >= defaultSec || d < 900 {
return nil
}
return &d
}
func (m *IAMManager) defaultTokenDurationSeconds() int64 {
if m.stsService == nil || m.stsService.Config == nil {
return sts.DefaultTokenDuration
}
return int64(m.stsService.Config.TokenDuration.Duration / time.Second)
}
// maxSessionLengthSeconds mirrors validateSessionDurationSeconds so a
// materialized default stays inside the bound the service will enforce.
func (m *IAMManager) maxSessionLengthSeconds() int64 {
maxSec := int64(sts.DefaultMaxSessionLength)
if m.stsService != nil && m.stsService.Config != nil && m.stsService.Config.MaxSessionLength.Duration > 0 {
if configured := int64(m.stsService.Config.MaxSessionLength.Duration / time.Second); configured >= 900 {
maxSec = configured
}
}
return maxSec
}
// AssumeRoleWithCredentials assumes a role using credentials (LDAP)
@@ -1044,7 +1076,7 @@ func (m *IAMManager) AssumeRoleWithCredentials(ctx context.Context, request *sts
}
// Apply role-level MaxSessionDuration cap.
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration, m.defaultTokenDurationSeconds(), m.maxSessionLengthSeconds())
// Use STS service to assume the role
return m.stsService.AssumeRoleWithCredentials(ctx, request)
+17 -11
View File
@@ -6,21 +6,27 @@ func intPtr(v int64) *int64 { return &v }
func TestCapDurationByRole(t *testing.T) {
cases := []struct {
name string
requested *int64
roleMax int64
want *int64
name string
requested *int64
roleMax int64
defaultSec int64
serviceMaxSec int64
want *int64
}{
{"no cap, no request", nil, 0, nil},
{"no cap, with request", intPtr(7200), 0, intPtr(7200)},
{"cap only, no request -> nil so STS default applies", nil, 3600, nil},
{"request below cap -> request", intPtr(1800), 3600, intPtr(1800)},
{"request equal cap -> request", intPtr(3600), 3600, intPtr(3600)},
{"request above cap -> cap", intPtr(43200), 3600, intPtr(3600)},
{"no cap, no request -> nil keeps service default", nil, 0, 3600, 43200, nil},
{"no cap, with request", intPtr(7200), 0, 3600, 43200, intPtr(7200)},
{"cap below default, no request -> cap", nil, 1800, 3600, 43200, intPtr(1800)},
{"cap above default, no request -> nil", nil, 43200, 3600, 43200, nil},
{"request below cap -> request", intPtr(1800), 3600, 900, 43200, intPtr(1800)},
{"request equal cap -> request", intPtr(3600), 3600, 900, 43200, intPtr(3600)},
{"request above cap -> cap", intPtr(43200), 3600, 900, 43200, intPtr(3600)},
{"default above service max -> service cap materialized", nil, 0, 7200, 3600, intPtr(3600)},
{"role bound above service max -> service cap still applies", nil, 40000, 43200, 3600, intPtr(3600)},
{"role bound below service floor -> tightest issuable", nil, 500, 3600, 43200, intPtr(900)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := capDurationByRole(tc.requested, tc.roleMax)
got := capDurationByRole(tc.requested, tc.roleMax, tc.defaultSec, tc.serviceMaxSec)
switch {
case got == nil && tc.want == nil:
return
+4 -3
View File
@@ -112,9 +112,10 @@ func copyRoleDefinition(original *RoleDefinition) *RoleDefinition {
}
copied := &RoleDefinition{
RoleName: original.RoleName,
RoleArn: original.RoleArn,
Description: original.Description,
RoleName: original.RoleName,
RoleArn: original.RoleArn,
Description: original.Description,
MaxSessionDuration: original.MaxSessionDuration,
}
// Deep copy trust policy if it exists
+4 -4
View File
@@ -604,7 +604,7 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
}
// 4. Calculate session duration
sessionDuration := s.calculateSessionDuration(request.DurationSeconds)
sessionDuration := s.CalculateSessionDuration(request.DurationSeconds)
expiresAt := time.Now().Add(sessionDuration)
// 5. Generate session ID and credentials
@@ -769,7 +769,7 @@ func (s *STSService) AssumeRoleWithCredentials(ctx context.Context, request *Ass
func (s *STSService) issueSession(roleArn, roleSessionName, sessionPolicy string,
durationSeconds *int64, providerName, subject string) (*AssumeRoleResponse, error) {
sessionDuration := s.calculateSessionDuration(durationSeconds)
sessionDuration := s.CalculateSessionDuration(durationSeconds)
expiresAt := time.Now().Add(sessionDuration)
sessionId, err := GenerateSessionId()
@@ -1120,11 +1120,11 @@ func (s *STSService) validateRoleAssumptionForCredentials(ctx context.Context, r
return nil
}
// calculateSessionDuration returns the requested DurationSeconds, or the
// CalculateSessionDuration returns the requested DurationSeconds, or the
// configured TokenDuration default, capped at MaxSessionLength. The source
// token's exp deliberately plays no part: per AWS semantics the session
// outlives the (already verified) web identity token.
func (s *STSService) calculateSessionDuration(durationSeconds *int64) time.Duration {
func (s *STSService) CalculateSessionDuration(durationSeconds *int64) time.Duration {
var duration time.Duration
if durationSeconds != nil {
duration = time.Duration(*durationSeconds) * time.Second
+2 -2
View File
@@ -30,8 +30,8 @@ func TestCalculateSessionDuration(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := svc.calculateSessionDuration(tc.durationSeconds); got != tc.want {
t.Errorf("calculateSessionDuration(%v) = %v, want %v", tc.durationSeconds, got, tc.want)
if got := svc.CalculateSessionDuration(tc.durationSeconds); got != tc.want {
t.Errorf("CalculateSessionDuration(%v) = %v, want %v", tc.durationSeconds, got, tc.want)
}
})
}
+1
View File
@@ -477,6 +477,7 @@ message VolumeEcShardsDeleteRequest {
repeated uint32 shard_ids = 3;
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
uint32 delete_generations_older_than = 6; // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
}
message VolumeEcShardsDeleteResponse {
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
+22 -12
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v6.33.4
// protoc v3.21.12
// source: volume_server.proto
package volume_server_pb
@@ -1469,7 +1469,8 @@ type VolumeDeleteRequest struct {
// used for moves where another server is taking over the same .vif.
KeepRemoteData bool `protobuf:"varint,3,opt,name=keep_remote_data,json=keepRemoteData,proto3" json:"keep_remote_data,omitempty"`
// when true, delete only if every needle is deleted: the volume held
// data once but nothing is live anymore.
// data once but nothing is live anymore. Passing either check,
// only_empty or this one, is enough to delete.
OnlyGarbage bool `protobuf:"varint,4,opt,name=only_garbage,json=onlyGarbage,proto3" json:"only_garbage,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -3732,14 +3733,15 @@ func (*VolumeEcShardsCopyResponse) Descriptor() ([]byte, []int) {
}
type VolumeEcShardsDeleteRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
DeleteGenerationsOlderThan uint32 `protobuf:"varint,6,opt,name=delete_generations_older_than,json=deleteGenerationsOlderThan,proto3" json:"delete_generations_older_than,omitempty"` // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *VolumeEcShardsDeleteRequest) Reset() {
@@ -3807,6 +3809,13 @@ func (x *VolumeEcShardsDeleteRequest) GetEncodeTsNs() int64 {
return 0
}
func (x *VolumeEcShardsDeleteRequest) GetDeleteGenerationsOlderThan() uint32 {
if x != nil {
return x.DeleteGenerationsOlderThan
}
return 0
}
type VolumeEcShardsDeleteResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
FullTeardownDone bool `protobuf:"varint,1,opt,name=full_teardown_done,json=fullTeardownDone,proto3" json:"full_teardown_done,omitempty"` // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
@@ -7505,7 +7514,7 @@ const file_volume_server_proto_rawDesc = "" +
"\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\x12+\n" +
"\x12io_byte_per_second\x18\n" +
" \x01(\x03R\x0fioBytePerSecond\"\x1c\n" +
"\x1aVolumeEcShardsCopyResponse\"\xbe\x01\n" +
"\x1aVolumeEcShardsCopyResponse\"\x81\x02\n" +
"\x1bVolumeEcShardsDeleteRequest\x12\x1b\n" +
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
"\n" +
@@ -7514,7 +7523,8 @@ const file_volume_server_proto_rawDesc = "" +
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12#\n" +
"\rfull_teardown\x18\x04 \x01(\bR\ffullTeardown\x12 \n" +
"\fencode_ts_ns\x18\x05 \x01(\x03R\n" +
"encodeTsNs\"L\n" +
"encodeTsNs\x12A\n" +
"\x1ddelete_generations_older_than\x18\x06 \x01(\rR\x1adeleteGenerationsOlderThan\"L\n" +
"\x1cVolumeEcShardsDeleteResponse\x12,\n" +
"\x12full_teardown_done\x18\x01 \x01(\bR\x10fullTeardownDone\"\xd4\x01\n" +
"\x1aVolumeEcShardsMountRequest\x12\x1b\n" +
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v6.33.4
// - protoc v3.21.12
// source: volume_server.proto
package volume_server_pb
@@ -74,7 +74,7 @@ const (
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type VolumeServerClient interface {
// Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
BatchDelete(ctx context.Context, in *BatchDeleteRequest, opts ...grpc.CallOption) (*BatchDeleteResponse, error)
VacuumVolumeCheck(ctx context.Context, in *VacuumVolumeCheckRequest, opts ...grpc.CallOption) (*VacuumVolumeCheckResponse, error)
VacuumVolumeCompact(ctx context.Context, in *VacuumVolumeCompactRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[VacuumVolumeCompactResponse], error)
@@ -727,7 +727,7 @@ func (c *volumeServerClient) Ping(ctx context.Context, in *PingRequest, opts ...
// All implementations must embed UnimplementedVolumeServerServer
// for forward compatibility.
type VolumeServerServer interface {
// Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
BatchDelete(context.Context, *BatchDeleteRequest) (*BatchDeleteResponse, error)
VacuumVolumeCheck(context.Context, *VacuumVolumeCheckRequest) (*VacuumVolumeCheckResponse, error)
VacuumVolumeCompact(*VacuumVolumeCompactRequest, grpc.ServerStreamingServer[VacuumVolumeCompactResponse]) error
+37
View File
@@ -144,6 +144,43 @@ func TestAuditRequesterIdentityEmptyForNonFederatedSession(t *testing.T) {
assert.Empty(t, log.RequesterIdentity, "non-federated session must not surface the session id as a requester_identity")
}
// Authentication resolves the identity before the policy verdict, so a denied
// request still has a requester and the audit entry must name it. See issue
// #11474.
func TestAuditRequesterForDeniedRequest(t *testing.T) {
iam := &IdentityAccessManagement{}
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{{
Name: "read_only_user",
Credentials: []*iam_pb.Credential{{AccessKey: "readonly_access_key", SecretKey: "readonly_secret_key"}},
Actions: []string{"Read", "List"},
}},
}))
denied, err := newTestRequest(http.MethodDelete, "http://s3/bucket/obj", 0, nil)
require.NoError(t, err)
require.NoError(t, signRequestV4(denied, "readonly_access_key", "readonly_secret_key"))
denied = s3_constants.EnsureIdentityHolder(denied)
rec := httptest.NewRecorder()
iam.Auth(func(http.ResponseWriter, *http.Request) {
t.Error("denied request must not reach the handler")
}, s3_constants.ACTION_WRITE)(rec, denied)
require.Equal(t, http.StatusForbidden, rec.Code)
log := s3err.GetAccessLog(denied, rec.Code, s3err.ErrAccessDenied)
assert.Equal(t, "read_only_user", log.Requester, "denied request must still audit the requester")
assert.Equal(t, "arn:aws:iam::"+defaultAccountID+":user/read_only_user", log.RequesterArn)
anonymous := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodDelete, "http://s3/bucket/obj", nil))
rec = httptest.NewRecorder()
iam.handleAuthResult(rec, anonymous, nil, s3err.ErrAccessDenied, func(http.ResponseWriter, *http.Request) {
t.Error("denied request must not reach the handler")
})
log = s3err.GetAccessLog(anonymous, rec.Code, s3err.ErrAccessDenied)
assert.Empty(t, log.Requester, "unauthenticated denial must not attribute a requester")
}
// A JWT-authenticated identity carries no PrincipalArn of its own — the auth
// layer hands the principal over in a request header — so the audit entry has to
// resolve the ARN the same way policy evaluation does.
+44 -22
View File
@@ -1565,7 +1565,10 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt
return
}
identity, errCode := iam.authRequest(r, action)
// authRequestWithAuthType keeps the resolved identity when authN
// succeeds but authZ denies, so the denied request still audits its
// requester; a failed authN resolves no identity at all.
identity, errCode, _ := iam.authRequestWithAuthType(r, action)
if errCode != s3err.ErrNone {
glog.V(3).Infof("auth error: %v", errCode)
}
@@ -1631,11 +1634,12 @@ func recordIdentityInContext(r *http.Request, identity *Identity) context.Contex
}
func (iam *IdentityAccessManagement) handleAuthResult(w http.ResponseWriter, r *http.Request, identity *Identity, errCode s3err.ErrorCode, f http.HandlerFunc) {
// Store the authenticated identity in request context (secure, cannot be spoofed)
// even on the deny path so audit records for rejected requests keep requester attribution
if identity != nil && identity.Name != "" {
r = r.WithContext(recordIdentityInContext(r, identity))
}
if errCode == s3err.ErrNone {
// Store the authenticated identity in request context (secure, cannot be spoofed)
if identity != nil && identity.Name != "" {
r = r.WithContext(recordIdentityInContext(r, identity))
}
f(w, r)
return
}
@@ -1749,6 +1753,23 @@ func (iam *IdentityAccessManagement) authenticateRequestInternal(r *http.Request
return identity, s3Err, reqAuthType
}
// isBucketListingRequest reports whether the request lists bucket contents:
// the ACTION_LIST routes, and ListMultipartUploads (GET ?uploads), which the
// router registers under ACTION_READ without an object-path constraint.
// GET /bucket/key?uploads therefore also reaches the listing handler. Route
// vars are used so a prefix promoted into the authorization object does not
// hide the bucket-level shape.
func isBucketListingRequest(r *http.Request, action Action) bool {
if action == s3_constants.ACTION_LIST {
return true
}
if r.Method != http.MethodGet || r.URL == nil || !r.URL.Query().Has("uploads") {
return false
}
_, object := s3_constants.GetBucketAndObject(r)
return object == "" || object == "/"
}
// authRequestWithAuthType authenticates and then authorizes a request for a given action.
func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, action Action) (*Identity, s3err.ErrorCode, authType) {
identity, s3Err, reqAuthType := iam.authenticateRequestInternal(r)
@@ -1759,13 +1780,13 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
bucket, object := s3_constants.GetBucketAndObject(r)
prefix := s3_constants.GetPrefix(r)
// For List operations, use prefix for permission checking if available
if action == s3_constants.ACTION_LIST && object == "" && prefix != "" {
// List operation with prefix - check permission for the prefix path
object = prefix
} else if (object == "/" || object == "") && prefix != "" {
// Using the aws cli with s3, and s3api, and with boto3, the object is often set to "/" or empty
// but the prefix is set to the actual object key for permission checking
// For bucket listings, use prefix for permission checking if available:
// the aws cli, s3api, and boto3 carry the key scope in ?prefix= rather
// than the URL path. Other actions must not promote it — a bucket-level
// request has no object, and a promoted prefix would let an object-scoped
// grant (e.g. Write:bucket/*) authorize bucket-subresource operations
// like ?versioning or ?lifecycle as if they were object writes.
if isBucketListingRequest(r, action) && (object == "" || object == "/") && prefix != "" {
object = prefix
}
@@ -1806,11 +1827,11 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
if identity != nil {
claims = identity.Claims
}
// List is bucket-level; the prefix promoted into object (for the
// legacy CanDo path) must not scope the resource ARN. Prefix is
// matched via the s3:prefix Condition.
// Bucket listings are bucket-level; the prefix promoted into
// object (for the legacy CanDo path) must not scope the resource
// ARN. Prefix is matched via the s3:prefix Condition.
policyObject := object
if action == s3_constants.ACTION_LIST {
if isBucketListingRequest(r, action) {
policyObject = ""
}
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, policyObject, string(action), principal, r, claims, nil)
@@ -2513,11 +2534,12 @@ func (iam *IdentityAccessManagement) evaluateAttachedIAMPolicies(r *http.Request
return attachedIAMPolicyNoMatch
}
// List is bucket-level; the prefix promoted into object (for the legacy
// CanDo path) must not scope the resource ARN or the resolved action
// (e.g. ListBucketVersions on ?versions). Prefix is matched via s3:prefix.
// Bucket listings are bucket-level; the prefix promoted into object (for
// the legacy CanDo path) must not scope the resource ARN or the resolved
// action (e.g. ListBucketVersions on ?versions). Prefix is matched via
// s3:prefix.
resourceObject := object
if action == s3_constants.ACTION_LIST {
if isBucketListingRequest(r, action) {
resourceObject = ""
}
resource := buildResourceARN(bucket, resourceObject)
@@ -3017,11 +3039,11 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
// check evaluates the same action and resource ARN as the policy engine.
func resolveS3AuthTarget(action Action, bucket, object string, r *http.Request) (s3Action, resourceArn string) {
resourceObjectKey := object
if action == s3_constants.ACTION_LIST {
if isBucketListingRequest(r, action) {
resourceObjectKey = ""
}
resourceArn = buildS3ResourceArn(bucket, resourceObjectKey)
s3Action = ResolveS3Action(r, string(action), bucket, object)
s3Action = ResolveS3Action(r, string(action), bucket, resourceObjectKey)
return
}
@@ -124,3 +124,54 @@ func TestAttachedPolicyExplicitDenyOverridesNativeAdmin(t *testing.T) {
assert.Equal(t, s3err.ErrAccessDenied, errCode,
"explicit Deny in an attached policy must override native Admin")
}
// GET ?uploads lists multipart uploads at bucket level but routes under Read,
// so the prefix promoted into object must not change the evaluated action or
// resource: an explicit Deny on s3:ListBucketMultipartUploads must still
// constrain a native admin, and an Allow on the bucket ARN must satisfy a
// plain attached-policy identity.
func TestMultipartListingResolvesBucketAction(t *testing.T) {
mgr := newTestIAMManager(t)
iam := &IdentityAccessManagement{}
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
denyDoc, _ := json.Marshal(map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Deny", "Action": "s3:ListBucketMultipartUploads", "Resource": "arn:aws:s3:::mybucket"},
},
})
require.NoError(t, iam.PutPolicy("DenyUploadsListing", string(denyDoc)))
allowDoc, _ := json.Marshal(map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:ListBucketMultipartUploads", "Resource": "arn:aws:s3:::mybucket"},
},
})
require.NoError(t, iam.PutPolicy("AllowUploadsListing", string(allowDoc)))
uploadsReq := func() *http.Request {
return httptest.NewRequest(http.MethodGet, "/mybucket?uploads&prefix=x/", nil)
}
admin := &Identity{
Name: "admin",
Account: &Account{DisplayName: "admin", Id: "admin"},
Actions: []Action{s3_constants.ACTION_ADMIN},
PolicyNames: []string{"DenyUploadsListing"},
PrincipalArn: "arn:aws:iam::111122223333:user/admin",
}
reader := &Identity{
Name: "reader",
Account: &Account{DisplayName: "reader", Id: "reader"},
PolicyNames: []string{"AllowUploadsListing"},
PrincipalArn: "arn:aws:iam::111122223333:user/reader",
}
// object carries the promoted prefix, matching authRequestWithAuthType
assert.Equal(t, s3err.ErrAccessDenied,
iam.VerifyActionPermission(uploadsReq(), admin, s3_constants.ACTION_READ, "mybucket", "x/"),
"explicit Deny on the uploads listing must override native Admin")
assert.Equal(t, s3err.ErrNone,
iam.VerifyActionPermission(uploadsReq(), reader, s3_constants.ACTION_READ, "mybucket", "x/"),
"s3:ListBucketMultipartUploads on the bucket must allow the uploads listing")
}
+106
View File
@@ -12,6 +12,7 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
@@ -557,3 +558,108 @@ func TestRealSDKSignerWithForwardedHeaders(t *testing.T) {
})
}
}
// GHSA-8rrx-349w-6396: ?prefix= was promoted into the object for every action,
// so PUT /cache?versioning&prefix=x authorized as Write:cache/x. An identity
// holding only Write:cache/* could then change bucket versioning, lifecycle,
// cors, and object-lock configuration.
func TestPrefixParameterDoesNotEscalateBucketActions(t *testing.T) {
resetMemoryStore()
defer resetMemoryStore()
configContent := `{
"identities": [
{"name":"admin","credentials":[{"accessKey":"ADMINKEY","secretKey":"adminsecret0000000000000000000001"}],"actions":["Admin"]},
{"name":"writer","credentials":[{"accessKey":"WRITERKEY","secretKey":"writersecret000000000000000000001"}],"actions":["Read:cache","Write:cache/*","List:cache"]},
{"name":"uploadreader","credentials":[{"accessKey":"UPREADERKEY","secretKey":"upreadersecret00000000000000001"}],"actions":["Read:cache/uploads/*"]},
{"name":"policywriter","credentials":[{"accessKey":"POLICYKEY","secretKey":"policysecret00000000000000000001"}],"policyNames":["WriterPolicy"]},
{"name":"uploadlister","credentials":[{"accessKey":"UPLISTERKEY","secretKey":"uplistersecret00000000000000001"}],"policyNames":["UploadsPolicy"]},
{"name":"getonly","credentials":[{"accessKey":"GETONLYKEY","secretKey":"getonlysecret0000000000000000001"}],"policyNames":["GetOnlyPolicy"]}
],
"policies":[
{"name":"WriterPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::cache/*\"]}]}"},
{"name":"UploadsPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::cache\"]}]}"},
{"name":"GetOnlyPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::cache/*\"]}]}"}
]
}`
tmpFile, err := os.CreateTemp("", "s3-config-*.json")
require.NoError(t, err)
defer os.Remove(tmpFile.Name())
_, err = tmpFile.Write([]byte(configContent))
require.NoError(t, err)
require.NoError(t, tmpFile.Close())
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{Config: tmpFile.Name()}, nil, "memory")
require.True(t, iam.isEnabled(), "Auth should be enabled")
for _, tc := range []struct {
name string
access string
secret string
object string
query string
action Action
want s3err.ErrorCode
}{
{"writer put object", "WRITERKEY", "writersecret000000000000000000001", "key", "", s3_constants.ACTION_WRITE, s3err.ErrNone},
{"writer put versioning", "WRITERKEY", "writersecret000000000000000000001", "", "versioning", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
{"writer put versioning with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "versioning&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
{"writer put lifecycle with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "lifecycle&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
{"writer list with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "list-type=2&prefix=x", s3_constants.ACTION_LIST, s3err.ErrNone},
{"policywriter put object", "POLICYKEY", "policysecret00000000000000000001", "key", "", s3_constants.ACTION_WRITE, s3err.ErrNone},
{"policywriter put versioning with prefix", "POLICYKEY", "policysecret00000000000000000001", "", "versioning&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
{"uploadreader lists uploads under prefix", "UPREADERKEY", "upreadersecret00000000000000001", "", "uploads&prefix=uploads/foo", s3_constants.ACTION_READ, s3err.ErrNone},
{"uploadreader cannot list outside prefix", "UPREADERKEY", "upreadersecret00000000000000001", "", "uploads&prefix=other/", s3_constants.ACTION_READ, s3err.ErrAccessDenied},
{"uploadlister lists uploads", "UPLISTERKEY", "uplistersecret00000000000000001", "", "uploads&prefix=x", s3_constants.ACTION_READ, s3err.ErrNone},
{"getonly cannot list uploads", "GETONLYKEY", "getonlysecret0000000000000000001", "", "uploads&prefix=x", s3_constants.ACTION_READ, s3err.ErrAccessDenied},
} {
t.Run(tc.name, func(t *testing.T) {
url := "http://localhost:8333/cache"
if tc.object != "" {
url += "/" + tc.object
}
if tc.query != "" {
url += "?" + tc.query
}
r := httptest.NewRequest(http.MethodPut, url, nil)
if tc.action == s3_constants.ACTION_LIST || tc.action == s3_constants.ACTION_READ {
r.Method = http.MethodGet
}
r = mux.SetURLVars(r, map[string]string{"bucket": "cache", "object": tc.object})
require.NoError(t, signRawHTTPRequest(context.Background(), r, tc.access, tc.secret, "us-east-1"))
_, errCode := iam.authRequest(r, tc.action)
assert.Equal(t, tc.want, errCode)
})
}
}
// The admin explicit-deny path resolves the same action and resource the
// policy engine sees, so a promoted prefix must not hide a listing variant:
// ?uploads resolves s3:ListBucketMultipartUploads on the bucket ARN, and
// ?versions resolves s3:ListBucketVersions, both at bucket level.
func TestResolveS3AuthTarget_BucketListings(t *testing.T) {
for _, tt := range []struct {
name string
url string
action Action
object string
wantAction string
wantResource string
}{
{"uploads listing keeps its action", "/cache?uploads&prefix=uploads/", s3_constants.ACTION_READ, "uploads/",
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS, "arn:aws:s3:::cache"},
{"versions listing keeps its action", "/cache?versions&prefix=a/", s3_constants.ACTION_LIST, "a/",
s3_constants.S3_ACTION_LIST_BUCKET_VERSIONS, "arn:aws:s3:::cache"},
{"plain list keeps its action", "/cache?list-type=2&prefix=a/", s3_constants.ACTION_LIST, "a/",
s3_constants.S3_ACTION_LIST_BUCKET, "arn:aws:s3:::cache"},
} {
t.Run(tt.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, tt.url, nil)
r = mux.SetURLVars(r, map[string]string{"bucket": "cache"})
action, resource := resolveS3AuthTarget(tt.action, "cache", tt.object, r)
assert.Equal(t, tt.wantAction, action)
assert.Equal(t, tt.wantResource, resource)
})
}
}
@@ -1,11 +1,17 @@
package s3api
import (
"context"
"encoding/json"
"net/http/httptest"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/require"
)
@@ -106,6 +112,152 @@ func TestEvaluateIAMPolicies_ListBucketVersionsWithPrefix(t *testing.T) {
"s3:ListBucketVersions must still resolve when listing with a prefix")
}
// GET ?uploads routes under ACTION_READ, not ACTION_LIST, but it is a bucket
// listing: a promoted prefix must not resolve it to s3:GetObject, and only
// s3:ListBucketMultipartUploads on the bucket ARN may allow it.
func TestEvaluateIAMPolicies_ListMultipartUploadsWithPrefix(t *testing.T) {
const bucket = "test-bucket"
iam := &IdentityAccessManagement{}
require.NoError(t, iam.PutPolicy("list-uploads", mustPolicy(t, map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{{
"Effect": "Allow",
"Action": "s3:ListBucketMultipartUploads",
"Resource": "arn:aws:s3:::" + bucket,
}},
})))
require.NoError(t, iam.PutPolicy("get-object", mustPolicy(t, map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::" + bucket + "/*",
}},
})))
uploadsReader := &Identity{
Name: "dave",
Account: &AccountAdmin,
PolicyNames: []string{"list-uploads"},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
getReader := &Identity{
Name: "erin",
Account: &AccountAdmin,
PolicyNames: []string{"get-object"},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
r := httptest.NewRequest("GET", "/"+bucket+"?uploads&prefix=uploads/", nil)
require.True(t, iam.evaluateIAMPolicies(r, uploadsReader, s3_constants.ACTION_READ, bucket, "uploads/"),
"s3:ListBucketMultipartUploads on the bucket must allow the uploads listing")
require.False(t, iam.evaluateIAMPolicies(r, getReader, s3_constants.ACTION_READ, bucket, "uploads/"),
"s3:GetObject must not satisfy the uploads listing")
}
// The IAM-integration authorizer must resolve the listing variant the same way
// evaluateIAMPolicies does: a prefix promoted into the object argument is not
// part of the request URL, so ?versions&prefix=... still resolves to
// s3:ListBucketVersions and an s3:ListBucket grant must not cover it.
func TestAuthorizeAction_ListVersionsWithPromotedPrefix(t *testing.T) {
const bucket = "test-bucket"
ctx := context.Background()
iamManager := integration.NewIAMManager()
require.NoError(t, iamManager.Initialize(&integration.IAMConfig{
STS: &sts.STSConfig{
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
Issuer: "test-sts",
SigningKey: []byte("test-signing-key-32-characters-long"),
},
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
}, func() string { return "localhost:8888" }))
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListBucketOnly", &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Action: []string{"s3:ListBucket"},
Resource: []string{"arn:aws:s3:::" + bucket},
Condition: map[string]map[string]interface{}{"StringLike": {"s3:prefix": "b/*"}},
}},
}))
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListVersionsOnly", &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Action: []string{"s3:ListBucketVersions"},
Resource: []string{"arn:aws:s3:::" + bucket},
}},
}))
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListUploadsOnly", &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Action: []string{"s3:ListBucketMultipartUploads"},
Resource: []string{"arn:aws:s3:::" + bucket},
}},
}))
require.NoError(t, iamManager.CreatePolicy(ctx, "", "GetObjectOnly", &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"arn:aws:s3:::" + bucket + "/*"},
}},
}))
s3iam := NewS3IAMIntegration(iamManager, "localhost:8888")
reader := &IAMIdentity{
Name: "reader",
Principal: "arn:aws:iam::000000000000:user/reader",
PolicyNames: []string{"ListBucketOnly"},
}
versionsReq := httptest.NewRequest("GET", "/"+bucket+"?versions&prefix=b/", nil)
// object carries the promoted prefix, matching authRequestWithAuthType
require.Equal(t, s3err.ErrAccessDenied,
s3iam.AuthorizeAction(ctx, reader, s3_constants.ACTION_LIST, bucket, "b/", versionsReq),
"an s3:ListBucket grant must not cover ?versions listing")
listReq := httptest.NewRequest("GET", "/"+bucket+"?list-type=2&prefix=b/", nil)
require.Equal(t, s3err.ErrNone,
s3iam.AuthorizeAction(ctx, reader, s3_constants.ACTION_LIST, bucket, "b/", listReq),
"s3:ListBucket with a matching s3:prefix still lists")
versionsReader := &IAMIdentity{
Name: "versions-reader",
Principal: "arn:aws:iam::000000000000:user/versions-reader",
PolicyNames: []string{"ListVersionsOnly"},
}
require.Equal(t, s3err.ErrNone,
s3iam.AuthorizeAction(ctx, versionsReader, s3_constants.ACTION_LIST, bucket, "b/", versionsReq),
"s3:ListBucketVersions allows the versions listing")
// GET ?uploads routes under ACTION_READ; a promoted prefix must still
// resolve it to s3:ListBucketMultipartUploads, not s3:GetObject.
uploadsReq := httptest.NewRequest("GET", "/"+bucket+"?uploads&prefix=b/", nil)
uploadsReader := &IAMIdentity{
Name: "uploads-reader",
Principal: "arn:aws:iam::000000000000:user/uploads-reader",
PolicyNames: []string{"ListUploadsOnly"},
}
require.Equal(t, s3err.ErrNone,
s3iam.AuthorizeAction(ctx, uploadsReader, s3_constants.ACTION_READ, bucket, "b/", uploadsReq),
"s3:ListBucketMultipartUploads allows the uploads listing")
getReader := &IAMIdentity{
Name: "get-reader",
Principal: "arn:aws:iam::000000000000:user/get-reader",
PolicyNames: []string{"GetObjectOnly"},
}
require.Equal(t, s3err.ErrAccessDenied,
s3iam.AuthorizeAction(ctx, getReader, s3_constants.ACTION_READ, bucket, "b/", uploadsReq),
"s3:GetObject must not satisfy the uploads listing")
}
func mustPolicy(t *testing.T, doc map[string]any) string {
t.Helper()
b, err := json.Marshal(doc)
+16
View File
@@ -33,6 +33,22 @@ func ResolveS3Action(r *http.Request, baseAction string, bucket string, object s
return baseAction
}
// Dedicated object-lock actions already name the operation — a query
// parameter must not re-map them. In particular the governance-bypass
// check authorizes against a synthetic DELETE ?versionId request, whose
// shape would otherwise resolve to s3:DeleteObjectVersion and satisfy
// the bypass check with the delete-version permission alone.
switch baseAction {
case s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
s3_constants.ACTION_GET_OBJECT_RETENTION,
s3_constants.ACTION_PUT_OBJECT_RETENTION,
s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD,
s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD,
s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG,
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG:
return mapBaseActionToS3Format(baseAction)
}
if r == nil || r.URL == nil {
// No HTTP context available: fall back to coarse-grained mapping
// This ensures consistent behavior and avoids returning empty strings
+41
View File
@@ -212,6 +212,47 @@ func TestResolveS3Action_Quota(t *testing.T) {
}
}
// Dedicated object-lock actions already name the operation being authorized;
// competing query parameters must not re-map them. Notably the synthetic
// DELETE ?versionId request behind the governance-bypass check must stay
// s3:BypassGovernanceRetention rather than resolving to s3:DeleteObjectVersion.
func TestResolveS3ActionDedicatedObjectLockActions(t *testing.T) {
tests := []struct {
name string
method string
object string
query string
baseAction string
want string
}{
{"bypass on versioned delete shape", http.MethodDelete, "key", "versionId=abc123",
s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION, s3_constants.S3_ACTION_BYPASS_GOVERNANCE},
{"bypass on batch delete shape", http.MethodPost, "", "delete",
s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION, s3_constants.S3_ACTION_BYPASS_GOVERNANCE},
{"get retention with versionId", http.MethodGet, "key", "retention&versionId=abc123",
s3_constants.ACTION_GET_OBJECT_RETENTION, s3_constants.S3_ACTION_GET_OBJECT_RETENTION},
{"put retention with versionId", http.MethodPut, "key", "retention&versionId=abc123",
s3_constants.ACTION_PUT_OBJECT_RETENTION, s3_constants.S3_ACTION_PUT_OBJECT_RETENTION},
{"get legal hold with versionId", http.MethodGet, "key", "legal-hold&versionId=abc123",
s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD, s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD},
{"put legal hold with versionId", http.MethodPut, "key", "legal-hold&versionId=abc123",
s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD, s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD},
{"get object-lock config", http.MethodGet, "", "object-lock&versioning",
s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG, s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK},
{"put object-lock config", http.MethodPut, "", "object-lock",
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG, s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
if got := ResolveS3Action(r, tt.baseAction, "bucket", tt.object); got != tt.want {
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
}
})
}
}
// A base action naming another service carries no S3 request shape, so a query
// parameter on the request must not redirect it to an S3 action.
func TestResolveS3ActionKeepsNonS3Service(t *testing.T) {
+5 -3
View File
@@ -222,7 +222,7 @@ func (s3iam *S3IAMIntegration) AuthorizeAction(ctx context.Context, identity *IA
// resource ARN stays at bucket level (matching AWS ListBucket semantics).
// See https://github.com/seaweedfs/seaweedfs/issues/8969
resourceObjectKey := objectKey
if action == "List" {
if isBucketListingRequest(r, action) {
listPrefix := r.URL.Query().Get("prefix")
if listPrefix != "" {
requestContext["s3:prefix"] = listPrefix
@@ -258,8 +258,10 @@ func (s3iam *S3IAMIntegration) AuthorizeAction(ctx context.Context, identity *IA
}
}
// Determine the specific S3 action based on the HTTP request details
specificAction := ResolveS3Action(r, string(action), bucket, objectKey)
// Determine the specific S3 action based on the HTTP request details. The
// prefix promoted into objectKey is not part of the URL; resolve against
// the bucket-level object so ?versions and ?uploads keep their own action.
specificAction := ResolveS3Action(r, string(action), bucket, resourceObjectKey)
// Create action request
actionRequest := &integration.ActionRequest{
+343
View File
@@ -0,0 +1,343 @@
package s3api
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type fakeBucketDeleteFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
entriesByDir map[string][]*filer_pb.Entry
deleteReq *filer_pb.DeleteEntryRequest
}
func (f *fakeBucketDeleteFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
entries, ok := f.entriesByDir[req.Directory]
if !ok {
return nil, filer_pb.ErrNotFound
}
for _, e := range entries {
if e.Name == req.Name {
return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil
}
}
return nil, filer_pb.ErrNotFound
}
func (f *fakeBucketDeleteFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
entries := f.entriesByDir[req.Directory]
if inPrefix := req.Prefix; inPrefix != "" && inPrefix != "/" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
if strings.HasPrefix(e.Name, inPrefix) {
filtered = append(filtered, e)
}
}
entries = filtered
}
if req.StartFromFileName != "" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
if e.Name > req.StartFromFileName || (req.InclusiveStartFrom && e.Name == req.StartFromFileName) {
filtered = append(filtered, e)
}
}
entries = filtered
}
if req.Limit > 0 && int(req.Limit) < len(entries) {
entries = entries[:req.Limit]
}
for _, entry := range entries {
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
return err
}
}
return nil
}
func (f *fakeBucketDeleteFiler) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
f.deleteReq = req
return &filer_pb.DeleteEntryResponse{}, nil
}
func newBucketDeleteTestServer(t *testing.T, f *fakeBucketDeleteFiler, allowDeleteBucketNotEmpty bool) *S3ApiServer {
t.Helper()
s3a := newFailoverTestServer(t, startFakeFiler(t, f))
s3a.option.BucketsPath = "/buckets"
s3a.option.AllowDeleteBucketNotEmpty = allowDeleteBucketNotEmpty
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
s3a.iam = &IdentityAccessManagement{}
return s3a
}
func TestBucketHasUserObjects_EmptyDirectories(t *testing.T) {
cases := []struct {
name string
entriesByDir map[string][]*filer_pb.Entry
wantHasUser bool
}{
{
name: "completely empty bucket",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {},
},
wantHasUser: false,
},
{
name: "bucket with root file",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "file.txt", IsDirectory: false},
},
},
wantHasUser: true,
},
{
name: "bucket with leftover empty directory from rm --recursive",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/b/data": {},
},
wantHasUser: false,
},
{
name: "bucket with nested leftover empty directories",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/b/data": {
{Name: "2026", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/b/data/2026": {},
},
wantHasUser: false,
},
{
name: "bucket with nested directory containing a file",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/b/data": {
{Name: "2026", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/b/data/2026": {
{Name: "report.pdf", IsDirectory: false},
},
},
wantHasUser: true,
},
{
name: "bucket with explicit directory object (MIME set)",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "logs", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"}},
},
"/buckets/b/logs": {},
},
wantHasUser: true,
},
{
name: "bucket with only reserved folders (.uploads, *.versions)",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true},
{Name: "oldfile.txt" + s3_constants.VersionsFolder, IsDirectory: true},
},
},
wantHasUser: false,
},
{
name: "nested versions-named directories are internal",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "logs", IsDirectory: true},
},
"/buckets/b/logs": {
{Name: "foo" + s3_constants.VersionsFolder, IsDirectory: true},
},
"/buckets/b/logs/foo" + s3_constants.VersionsFolder: {
{Name: "v1", IsDirectory: false},
},
},
wantHasUser: false,
},
{
name: "nested uploads-named directories are internal",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "data", IsDirectory: true},
},
"/buckets/b/data": {
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true},
},
"/buckets/b/data/" + s3_constants.MultipartUploadsFolder: {
{Name: "part-1", IsDirectory: false},
},
},
wantHasUser: false,
},
{
name: "directory object with a reserved name counts",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "data", IsDirectory: true},
},
"/buckets/b/data": {
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: s3_constants.FolderMimeType}},
},
},
wantHasUser: true,
},
{
name: "file with a reserved name counts",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: "dir", IsDirectory: true},
},
"/buckets/b/dir": {
{Name: "data" + s3_constants.VersionsFolder, IsDirectory: false},
},
},
wantHasUser: true,
},
{
name: "file with backslash in name",
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/b": {
{Name: `a\b`, IsDirectory: false},
},
},
wantHasUser: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := &fakeBucketDeleteFiler{entriesByDir: tc.entriesByDir}
s3a := newBucketDeleteTestServer(t, f, false)
got, err := s3a.bucketHasUserObjects("b")
require.NoError(t, err)
assert.Equal(t, tc.wantHasUser, got)
})
}
}
func TestBucketHasUserObjects_DeepEmptyChain(t *testing.T) {
entriesByDir := map[string][]*filer_pb.Entry{
"/buckets/b": {{Name: "d0", IsDirectory: true}},
}
dir := "/buckets/b/d0"
for i := 1; i < 500; i++ {
child := fmt.Sprintf("d%d", i)
entriesByDir[dir] = []*filer_pb.Entry{{Name: child, IsDirectory: true}}
dir = dir + "/" + child
}
entriesByDir[dir] = []*filer_pb.Entry{}
f := &fakeBucketDeleteFiler{entriesByDir: entriesByDir}
s3a := newBucketDeleteTestServer(t, f, false)
got, err := s3a.bucketHasUserObjects("b")
require.NoError(t, err)
assert.False(t, got)
}
func TestDeleteBucketHandler_EmptyDirectoriesAllowedWhenNotEmptyFalse(t *testing.T) {
// A bucket that holds only an empty directory leftover from deleted objects
// must succeed when AllowDeleteBucketNotEmpty is false.
f := &fakeBucketDeleteFiler{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets": {
{Name: "repro-bucket", IsDirectory: true},
},
"/buckets/repro-bucket": {
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/repro-bucket/data": {},
},
}
s3a := newBucketDeleteTestServer(t, f, false)
s3a.bucketConfigCache.Set("repro-bucket", &BucketConfig{Name: "repro-bucket"})
req := httptest.NewRequest(http.MethodDelete, "/repro-bucket", nil)
req = mux.SetURLVars(req, map[string]string{"bucket": "repro-bucket"})
rr := httptest.NewRecorder()
s3a.DeleteBucketHandler(rr, req)
assert.Equal(t, http.StatusNoContent, rr.Code, "deleting bucket with only empty directory must succeed: %s", rr.Body.String())
assert.NotNil(t, f.deleteReq)
assert.Equal(t, "/buckets", f.deleteReq.Directory)
assert.Equal(t, "repro-bucket", f.deleteReq.Name)
assert.True(t, f.deleteReq.IsRecursive)
}
func TestDeleteBucketHandler_RefusesBucketWithFilesWhenNotEmptyFalse(t *testing.T) {
f := &fakeBucketDeleteFiler{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets": {
{Name: "non-empty-bucket", IsDirectory: true},
},
"/buckets/non-empty-bucket": {
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
},
"/buckets/non-empty-bucket/data": {
{Name: "hello.txt", IsDirectory: false},
},
},
}
s3a := newBucketDeleteTestServer(t, f, false)
s3a.bucketConfigCache.Set("non-empty-bucket", &BucketConfig{Name: "non-empty-bucket"})
req := httptest.NewRequest(http.MethodDelete, "/non-empty-bucket", nil)
req = mux.SetURLVars(req, map[string]string{"bucket": "non-empty-bucket"})
rr := httptest.NewRecorder()
s3a.DeleteBucketHandler(rr, req)
assert.Equal(t, http.StatusConflict, rr.Code)
assert.Contains(t, rr.Body.String(), "<Code>BucketNotEmpty</Code>")
assert.Nil(t, f.deleteReq, "delete request must not have been sent to filer")
}
func TestDeleteBucketHandler_RefusesBucketWithDirectoryObjectWhenNotEmptyFalse(t *testing.T) {
f := &fakeBucketDeleteFiler{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets": {
{Name: "dir-obj-bucket", IsDirectory: true},
},
"/buckets/dir-obj-bucket": {
{Name: "photos", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"}},
},
"/buckets/dir-obj-bucket/photos": {},
},
}
s3a := newBucketDeleteTestServer(t, f, false)
s3a.bucketConfigCache.Set("dir-obj-bucket", &BucketConfig{Name: "dir-obj-bucket"})
req := httptest.NewRequest(http.MethodDelete, "/dir-obj-bucket", nil)
req = mux.SetURLVars(req, map[string]string{"bucket": "dir-obj-bucket"})
rr := httptest.NewRecorder()
s3a.DeleteBucketHandler(rr, req)
assert.Equal(t, http.StatusConflict, rr.Code)
assert.Contains(t, rr.Body.String(), "<Code>BucketNotEmpty</Code>")
assert.Nil(t, f.deleteReq, "delete request must not have been sent to filer")
}
+46 -21
View File
@@ -503,31 +503,56 @@ func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Reque
s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
}
// bucketHasUserObjects checks whether a bucket contains any non-special entries.
// Special entries (.uploads, *.versions) are internal to S3 and don't count as user objects.
// bucketHasUserObjects checks whether a bucket contains any user objects.
// Empty directories left behind by deleted objects and internal folders
// (.uploads, *.versions) do not count as user objects.
func (s3a *S3ApiServer) bucketHasUserObjects(bucket string) (bool, error) {
bucketPath := s3a.option.BucketsPath + "/" + bucket
startFrom := ""
// Start with a small batch — most non-empty buckets have a real object early.
// If we only find special entries, switch to larger batches to page through quickly.
limit := uint32(10)
for {
entries, isLast, err := s3a.list(bucketPath, "", startFrom, false, limit)
if err != nil {
return false, err
}
for _, entry := range entries {
if entry.Name != s3_constants.MultipartUploadsFolder &&
!strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
return true, nil
return s3a.dirHasUserObjects(s3a.option.BucketsPath + "/" + bucket)
}
func (s3a *S3ApiServer) dirHasUserObjects(root string) (bool, error) {
dirs := []string{root}
for len(dirs) > 0 {
dir := dirs[len(dirs)-1]
dirs = dirs[:len(dirs)-1]
startFrom := ""
// Start with a small batch — most non-empty buckets have a real object
// early; switch to larger batches to page through quickly.
limit := uint32(10)
for {
entries, isLast, err := s3a.list(dir, "", startFrom, false, limit)
if err != nil {
if isFilerNotFound(err) {
break // the directory was deleted between listing and walking it
}
return false, err
}
startFrom = entry.Name
for _, entry := range entries {
startFrom = entry.Name
if entry.Name == "" || entry.Name == "." || entry.Name == ".." || strings.Contains(entry.Name, "/") {
continue
}
if !entry.IsDirectory {
return true, nil
}
// An explicit directory object counts even under a reserved name.
if entry.IsDirectoryKeyObject() {
return true, nil
}
// Internal folders are skipped by object listing at every level,
// so a directory with a reserved name never counts.
if isReservedDirectoryName(entry.Name) {
continue
}
dirs = append(dirs, dir+"/"+entry.Name)
}
if isLast || len(entries) == 0 {
break
}
limit = 1000
}
if isLast {
return false, nil
}
limit = 1000
}
return false, nil
}
// hasObjectsWithActiveLocks checks if any objects in the bucket have active retention or legal hold
+1
View File
@@ -1103,6 +1103,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
tStreamPrep := time.Now()
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, offset, size)
reader := filer.NewChunkReaderAtFromClient(ctx, s3a.readerCache, chunkViews, totalSize, filer.DefaultPrefetchCount)
defer reader.ReleaseStream()
streamPrepTime = time.Since(tStreamPrep)
// A cached chunk whose volume server is down, or whose needle was evicted and
+20
View File
@@ -813,6 +813,19 @@ func markerSortsBeforePrefix(prefix, marker string) bool {
return !strings.HasPrefix(marker, prefix) && marker < prefix
}
// markerSortsPastPrefix reports whether marker lies beyond the last key the
// prefix can match. A marker that diverges from the prefix at a larger byte
// is after every key under it, so the listing is empty no matter where the
// walk would resume.
func markerSortsPastPrefix(prefix, marker string) bool {
prefix = strings.TrimLeft(prefix, "/")
marker = strings.TrimLeft(marker, "/")
if marker == "" || prefix == "" {
return false
}
return !strings.HasPrefix(marker, prefix) && marker > prefix
}
// the prefix and marker may be in different directories
// normalizePrefixMarker ensures the prefix and marker both starts from the same directory.
// prefixEndsOnDelimiter tells the walk that the prefix names one directory, whose own key
@@ -912,6 +925,13 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
return // Don't set isTruncated here - let caller decide based on whether more entries exist
}
// A marker past the prefix's range leaves nothing under the prefix to
// resume at, and descending into the marker's own directory below would
// drop the prefix filter entirely.
if markerSortsPastPrefix(prefix, marker) {
return
}
if strings.Contains(marker, "/") {
subDir, subMarker := toParentAndDescendants(marker)
// println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
@@ -36,6 +36,75 @@ func Test_markerSortsBeforePrefix(t *testing.T) {
}
}
// A marker that sorts past the prefix leaves no key under the prefix to resume
// at, so the listing is empty instead of continuing into later prefixes.
func Test_markerSortsPastPrefix(t *testing.T) {
tests := []struct {
name string
prefix string
marker string
want bool
}{
{"marker is a later directory", "b/", "c/", true},
{"marker is a later key without a slash", "b/", "c", true},
{"marker shares the parent dir but sorts past", "data/a", "data/b", true},
{"marker diverges after the prefix", "b/", "b0/x", true},
{"leading slashes are ignored on both sides", "/b/", "/c/", true},
{"empty marker is in range", "b/", "", false},
{"empty prefix: every key is in scope", "", "c/", false},
{"marker under the prefix resumes inside it", "b/", "b/allowed-1", false},
{"marker equal to the prefix stands", "b/", "b/", false},
{"partial name prefix: marker under the match set stands", "parent", "parentDir/data/0e", false},
{"marker before the prefix is not past it", "b/", "a/", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, markerSortsPastPrefix(tt.prefix, tt.marker), "markerSortsPastPrefix(%q, %q)", tt.prefix, tt.marker)
})
}
}
// TestListWithMarkerPastPrefix walks the listing the way listFilerEntries does
// for a start position past the requested prefix. normalizePrefixMarker hands
// such a marker through at the bucket root, where the walk's marker descent
// would otherwise drop the prefix filter and continue into a later prefix.
func TestListWithMarkerPastPrefix(t *testing.T) {
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test": {newDir("a"), newDir("b"), newDir("c")},
"/buckets/test/b": {{Name: "allowed-1", Attributes: &filer_pb.FuseAttributes{}}},
"/buckets/test/c": {{Name: "other-2", Attributes: &filer_pb.FuseAttributes{}}},
"/buckets/test/c/z": {{Name: "deep", Attributes: &filer_pb.FuseAttributes{}}},
},
}
for _, tt := range []struct {
name string
marker string
want []string
}{
{"marker is a later directory", "c/", nil},
{"marker is a deeper path in a later directory", "c/z", nil},
{"marker is a later bare key", "c", nil},
{"marker inside the prefix resumes normally", "b/", []string{"allowed-1"}},
} {
t.Run(tt.name, func(t *testing.T) {
requestDir, entryPrefix, entryMarker, prefixEndsOnDelimiter := normalizePrefixMarker("b/", tt.marker)
dir := "/buckets/test"
if requestDir != "" {
dir += "/" + requestDir
}
seen := listedNames(t, client, listDirectoryRequest{
dir: dir,
prefix: entryPrefix,
marker: entryMarker,
bucket: "test",
}, &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: prefixEndsOnDelimiter})
assert.Equal(t, tt.want, seen)
})
}
}
// A marker ending on the delimiter is trimmed to a shorter cutoff for the walk, which no
// longer excludes the key the client named, so that key is skipped as it streams.
func Test_excludedMarkerKey(t *testing.T) {
@@ -69,7 +69,7 @@ func (s3a *S3ApiServer) NewMultipartUploadHandler(w http.ResponseWriter, r *http
}
// Validate object lock headers before processing
if err := s3a.validateObjectLockHeaders(r, versioningEnabled); err != nil {
if err := s3a.validateObjectLockHeaders(r, bucket, object, versioningEnabled); err != nil {
glog.V(2).Infof("NewMultipartUploadHandler: object lock header validation failed for bucket %s, object %s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(err))
return
@@ -86,7 +86,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
return
}
if identity != nil {
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), identity.Name))
r = r.WithContext(recordIdentityInContext(r, identity))
}
policyBytes, err := base64.StdEncoding.DecodeString(formValues.Get("Policy"))
@@ -160,7 +160,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
if err := s3a.validateObjectLockHeaders(r, objectLockEnabled); err != nil {
if err := s3a.validateObjectLockHeaders(r, bucket, object, objectLockEnabled); err != nil {
glog.V(2).Infof("PostPolicyBucketHandler: object lock header validation failed for %s/%s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(err))
return
+37 -3
View File
@@ -45,6 +45,7 @@ var (
ErrObjectLockModeRequiresDate = errors.New("object lock mode requires retention until date")
ErrRetentionDateRequiresMode = errors.New("retention until date requires object lock mode")
ErrGovernanceBypassVersioningRequired = errors.New("governance bypass header can only be used on buckets with Object Lock enabled")
ErrObjectLockNotAuthorized = errors.New("object lock headers require the corresponding object lock permission")
ErrInvalidObjectLockDuration = errors.New("object lock duration must be greater than 0 days")
ErrObjectLockDurationExceeded = errors.New("object lock duration exceeds maximum allowed days")
ErrObjectLockConfigurationMissingEnabled = errors.New("object lock configuration must specify ObjectLockEnabled")
@@ -152,7 +153,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
if validationErr := s3a.validateObjectLockHeaders(r, objectLockEnabled); validationErr != nil {
if validationErr := s3a.validateObjectLockHeaders(r, bucket, object, objectLockEnabled); validationErr != nil {
glog.V(2).Infof("PutObjectHandler: object lock header validation failed for %s/%s: %v", bucket, object, validationErr)
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(validationErr))
return
@@ -281,7 +282,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
}
// Validate object lock headers before processing
if err := s3a.validateObjectLockHeaders(r, objectLockEnabled); err != nil {
if err := s3a.validateObjectLockHeaders(r, bucket, object, objectLockEnabled); err != nil {
glog.V(2).Infof("PutObjectHandler: object lock header validation failed for bucket %s, object %s: %v", bucket, object, err)
s3err.WriteErrorResponse(w, r, mapValidationErrorToS3Error(err))
return
@@ -2129,9 +2130,29 @@ func (s3a *S3ApiServer) applyBucketDefaultRetention(bucket string, entry *filer_
return nil
}
// checkObjectLockHeaderPermission reports whether the caller may set object
// lock through PutObject-style request headers. On AWS these headers require
// the dedicated s3:PutObjectRetention / s3:PutObjectLegalHold permissions;
// s3:PutObject alone must not be enough, or any writer can pin data with
// COMPLIANCE retention. Without auth there is nothing to check against.
func (s3a *S3ApiServer) checkObjectLockHeaderPermission(r *http.Request, bucket, object string, action Action) bool {
if s3a.iam == nil || !s3a.iam.isEnabled() {
return true
}
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
if identity == nil {
var errCode s3err.ErrorCode
identity, errCode, _ = s3a.iam.authenticateRequestInternal(r)
if errCode != s3err.ErrNone {
return false
}
}
return s3a.iam.authorizeObjectKeyAction(r, identity, r.Method, action, bucket, s3_constants.NormalizeObjectKey(object), "") == s3err.ErrNone
}
// validateObjectLockHeaders validates object lock headers in PUT requests
// objectLockEnabled should be true only if the bucket has Object Lock configured
func (s3a *S3ApiServer) validateObjectLockHeaders(r *http.Request, objectLockEnabled bool) error {
func (s3a *S3ApiServer) validateObjectLockHeaders(r *http.Request, bucket, object string, objectLockEnabled bool) error {
// Extract object lock headers from request
mode := r.Header.Get(s3_constants.AmzObjectLockMode)
retainUntilDateStr := r.Header.Get(s3_constants.AmzObjectLockRetainUntilDate)
@@ -2193,6 +2214,17 @@ func (s3a *S3ApiServer) validateObjectLockHeaders(r *http.Request, objectLockEna
return ErrGovernanceBypassVersioningRequired
}
if mode != "" || retainUntilDateStr != "" {
if !s3a.checkObjectLockHeaderPermission(r, bucket, object, s3_constants.ACTION_PUT_OBJECT_RETENTION) {
return ErrObjectLockNotAuthorized
}
}
if legalHold != "" {
if !s3a.checkObjectLockHeaderPermission(r, bucket, object, s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD) {
return ErrObjectLockNotAuthorized
}
}
return nil
}
@@ -2232,6 +2264,8 @@ func mapValidationErrorToS3Error(err error) s3err.ErrorCode {
// For governance bypass on non-versioned bucket, return InvalidRequest
// This matches the test expectations
return s3err.ErrInvalidRequest
case errors.Is(err, ErrObjectLockNotAuthorized):
return s3err.ErrAccessDenied
case errors.Is(err, ErrMalformedXML):
// For malformed XML in request body, return MalformedXML
// This matches the test expectations for invalid retention mode and legal hold status
@@ -2,9 +2,11 @@ package s3api
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gorilla/mux"
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
@@ -55,6 +57,86 @@ func TestGovernanceBypassUsesDedicatedAuthorization(t *testing.T) {
}
}
// The bypass check authorizes against a synthetic request shaped like the
// real one; DELETE ?versionId used to re-resolve to s3:DeleteObjectVersion,
// so the delete-version grant silently satisfied the bypass check.
func TestGovernanceBypassDoesNotInheritDeleteObjectVersion(t *testing.T) {
iam := &IdentityAccessManagement{}
require.NoError(t, iam.PutPolicy("DeleteVersions",
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:DeleteObject","s3:DeleteObjectVersion"],"Resource":"arn:aws:s3:::worm/*"}]}`))
require.NoError(t, iam.PutPolicy("BypassGovernance",
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:DeleteObject","s3:DeleteObjectVersion","s3:BypassGovernanceRetention"],"Resource":"arn:aws:s3:::worm/*"}]}`))
s3a := &S3ApiServer{iam: iam}
req := httptest.NewRequest(http.MethodDelete, "http://localhost:8333/worm/doc.txt?versionId=abc123", nil)
req = mux.SetURLVars(req, map[string]string{"bucket": "worm", "object": "doc.txt"})
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), &Identity{
Name: "deleter",
PolicyNames: []string{"DeleteVersions"},
Account: &Account{Id: "test-account"},
}))
if s3a.checkGovernanceBypassPermission(req, "worm", "/doc.txt") {
t.Fatal("s3:DeleteObjectVersion alone satisfied the governance bypass check")
}
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), &Identity{
Name: "breaker",
PolicyNames: []string{"BypassGovernance"},
Account: &Account{Id: "test-account"},
}))
if !s3a.checkGovernanceBypassPermission(req, "worm", "/doc.txt") {
t.Fatal("s3:BypassGovernanceRetention did not satisfy the governance bypass check")
}
}
// The object-lock request headers on PutObject/CreateMultipartUpload must be
// authorized as s3:PutObjectRetention / s3:PutObjectLegalHold; s3:PutObject
// alone used to set retention and legal hold on new versions.
func TestObjectLockHeadersRequireDedicatedActions(t *testing.T) {
iam := &IdentityAccessManagement{isAuthEnabled: true}
require.NoError(t, iam.PutPolicy("Writer",
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject"],"Resource":"arn:aws:s3:::worm/*"}]}`))
require.NoError(t, iam.PutPolicy("Locked",
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:PutObjectRetention","s3:PutObjectLegalHold"],"Resource":"arn:aws:s3:::worm/*"}]}`))
s3a := &S3ApiServer{iam: iam}
retainUntil := time.Now().Add(24 * time.Hour).Format(time.RFC3339)
for _, tc := range []struct {
name string
policy string
headers map[string]string
wantErr error
}{
{"writer sets retention", "Writer",
map[string]string{s3_constants.AmzObjectLockMode: "COMPLIANCE", s3_constants.AmzObjectLockRetainUntilDate: retainUntil},
ErrObjectLockNotAuthorized},
{"writer sets legal hold", "Writer",
map[string]string{s3_constants.AmzObjectLockLegalHold: s3_constants.LegalHoldOn},
ErrObjectLockNotAuthorized},
{"writer plain put", "Writer", nil, nil},
{"locked principal sets both", "Locked",
map[string]string{s3_constants.AmzObjectLockMode: "GOVERNANCE", s3_constants.AmzObjectLockRetainUntilDate: retainUntil, s3_constants.AmzObjectLockLegalHold: s3_constants.LegalHoldOn},
nil},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPut, "http://localhost:8333/worm/doc.txt", nil)
req = mux.SetURLVars(req, map[string]string{"bucket": "worm", "object": "doc.txt"})
for k, v := range tc.headers {
req.Header.Set(k, v)
}
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), &Identity{
Name: "caller",
PolicyNames: []string{tc.policy},
Account: &Account{Id: "test-account"},
}))
if err := s3a.validateObjectLockHeaders(req, "worm", "doc.txt", true); !errors.Is(err, tc.wantErr) {
t.Errorf("validateObjectLockHeaders() = %v, want %v", err, tc.wantErr)
}
})
}
}
func TestGovernanceBypassUsesBodyObjectKey(t *testing.T) {
iam := newTestIAM()
iam.identities[0].Actions = []Action{
+15 -15
View File
@@ -410,7 +410,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req.Header.Set(s3_constants.AmzObjectLockMode, "COMPLIANCE")
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, retainUntilDate.Format(time.RFC3339))
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
@@ -420,7 +420,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req.Header.Set(s3_constants.AmzObjectLockMode, "GOVERNANCE")
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, retainUntilDate.Format(time.RFC3339))
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
@@ -428,7 +428,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
req.Header.Set(s3_constants.AmzObjectLockLegalHold, "ON")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
@@ -436,7 +436,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
req.Header.Set(s3_constants.AmzObjectLockLegalHold, "OFF")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
@@ -446,7 +446,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
retainUntilDate := time.Now().Add(24 * time.Hour)
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, retainUntilDate.Format(time.RFC3339))
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrInvalidObjectLockMode))
})
@@ -455,7 +455,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
req.Header.Set(s3_constants.AmzObjectLockLegalHold, "INVALID_STATUS")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrInvalidLegalHoldStatus))
})
@@ -466,7 +466,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
retainUntilDate := time.Now().Add(24 * time.Hour)
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, retainUntilDate.Format(time.RFC3339))
err := s3a.validateObjectLockHeaders(req, false) // non-versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", false) // non-versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrObjectLockVersioningRequired))
})
@@ -476,7 +476,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req.Header.Set(s3_constants.AmzObjectLockMode, "COMPLIANCE")
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, "invalid-date-format")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrInvalidRetentionDateFormat))
})
@@ -487,7 +487,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
pastDate := time.Now().Add(-24 * time.Hour)
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, pastDate.Format(time.RFC3339))
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrRetentionDateMustBeFuture))
})
@@ -496,7 +496,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
req.Header.Set(s3_constants.AmzObjectLockMode, "COMPLIANCE")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrObjectLockModeRequiresDate))
})
@@ -506,7 +506,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
retainUntilDate := time.Now().Add(24 * time.Hour)
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, retainUntilDate.Format(time.RFC3339))
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrRetentionDateRequiresMode))
})
@@ -515,7 +515,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
req.Header.Set("x-amz-bypass-governance-retention", "true")
err := s3a.validateObjectLockHeaders(req, false) // non-versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", false) // non-versioned bucket
assert.Error(t, err)
assert.True(t, errors.Is(err, ErrGovernanceBypassVersioningRequired))
})
@@ -524,7 +524,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
req.Header.Set("x-amz-bypass-governance-retention", "true")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
@@ -532,7 +532,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req := httptest.NewRequest("PUT", "/bucket/object", nil)
// No object lock headers set
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
@@ -543,7 +543,7 @@ func TestValidateObjectLockHeaders(t *testing.T) {
req.Header.Set(s3_constants.AmzObjectLockRetainUntilDate, retainUntilDate.Format(time.RFC3339))
req.Header.Set(s3_constants.AmzObjectLockLegalHold, "ON")
err := s3a.validateObjectLockHeaders(req, true) // versioned bucket
err := s3a.validateObjectLockHeaders(req, "bucket", "object", true) // versioned bucket
assert.NoError(t, err)
})
}
+21 -3
View File
@@ -834,12 +834,30 @@ func (h *STSHandlers) handleGetFederationToken(w http.ResponseWriter, r *http.Re
func (h *STSHandlers) prepareSTSCredentials(ctx context.Context, roleArn, roleSessionName string,
durationSeconds *int64, sessionPolicy string, modifyClaims func(*sts.STSSessionClaims)) (STSCredentials, *AssumedRoleUser, error) {
// Calculate duration
duration := time.Hour // Default 1 hour
if durationSeconds != nil {
duration := time.Hour
if h.stsService != nil && h.stsService.Config != nil {
duration = h.stsService.CalculateSessionDuration(durationSeconds)
} else if durationSeconds != nil {
duration = time.Duration(*durationSeconds) * time.Second
}
// A named role's MaxSessionDuration bounds the resolved duration the same
// way capDurationByRole does on the SDK paths; self-assumption has no role
// definition to consult.
if h.iam != nil && h.iam.iamIntegration != nil {
if roleName := utils.ExtractRoleNameFromArn(roleArn); roleName != "" {
if provider, ok := h.iam.iamIntegration.(IAMManagerProvider); ok {
if mgr := provider.GetIAMManager(); mgr != nil {
if roleDef, roleErr := mgr.GetRole(ctx, roleName); roleErr == nil && roleDef.MaxSessionDuration > 0 {
if roleMax := time.Duration(roleDef.MaxSessionDuration) * time.Second; duration > roleMax {
duration = roleMax
}
}
}
}
}
}
// Generate session ID
sessionId, err := sts.GenerateSessionId()
if err != nil {
+61
View File
@@ -241,3 +241,64 @@ func newTestSTSIntegrationManager(t *testing.T) *integration.IAMManager {
require.NoError(t, manager.Initialize(config, func() string { return "" }))
return manager
}
// AssumeRole derives its session length from the same default-then-cap rule as
// the service layer (#11473): an omitted DurationSeconds yields TokenDuration,
// and either path is capped at MaxSessionLength.
func TestPrepareSTSCredentialsHonorsConfiguredDurations(t *testing.T) {
stsService := sts.NewSTSService()
require.NoError(t, stsService.Initialize(&sts.STSConfig{
TokenDuration: sts.FlexibleDuration{Duration: 15 * time.Minute},
MaxSessionLength: sts.FlexibleDuration{Duration: 20 * time.Minute},
Issuer: "test-issuer",
SigningKey: []byte("test-signing-key-at-least-32-bytes-long-for-security"),
}))
stsHandlers := NewSTSHandlers(stsService, nil)
roleArn := fmt.Sprintf("arn:aws:iam::%s:role/test-role", defaultAccountID)
expiresIn := func(durationSeconds *int64) time.Duration {
stsCreds, _, err := stsHandlers.prepareSTSCredentials(context.Background(), roleArn, "test-session", durationSeconds, "", nil)
require.NoError(t, err)
exp, err := time.Parse(time.RFC3339, stsCreds.Expiration)
require.NoError(t, err)
return time.Until(exp)
}
oneHour := int64(3600)
assert.InDelta(t, (15 * time.Minute).Seconds(), expiresIn(nil).Seconds(), 60)
assert.InDelta(t, (20 * time.Minute).Seconds(), expiresIn(&oneHour).Seconds(), 60)
}
// A named role's MaxSessionDuration bounds the session however DurationSeconds
// was resolved, matching the SDK paths' capDurationByRole.
func TestPrepareSTSCredentialsCapsAtRoleMaxDuration(t *testing.T) {
ctx := context.Background()
manager := newTestSTSIntegrationManager(t)
require.NoError(t, manager.CreateRole(ctx, "", "ShortLivedRole", &integration.RoleDefinition{
RoleName: "ShortLivedRole",
MaxSessionDuration: 3600,
}))
stsService := sts.NewSTSService()
require.NoError(t, stsService.Initialize(&sts.STSConfig{
TokenDuration: sts.FlexibleDuration{Duration: 2 * time.Hour},
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
Issuer: "test-issuer",
SigningKey: []byte("test-signing-key-at-least-32-bytes-long-for-security"),
}))
iam := &IdentityAccessManagement{iamIntegration: NewS3IAMIntegration(manager, "")}
stsHandlers := NewSTSHandlers(stsService, iam)
roleArn := fmt.Sprintf("arn:aws:iam::%s:role/ShortLivedRole", defaultAccountID)
expiresIn := func(durationSeconds *int64) time.Duration {
stsCreds, _, err := stsHandlers.prepareSTSCredentials(ctx, roleArn, "test-session", durationSeconds, "", nil)
require.NoError(t, err)
exp, err := time.Parse(time.RFC3339, stsCreds.Expiration)
require.NoError(t, err)
return time.Until(exp)
}
twoHours := int64(7200)
assert.InDelta(t, float64(3600), expiresIn(nil).Seconds(), 60, "omitted duration resolves to the 2h default but the role caps it at 1h")
assert.InDelta(t, float64(3600), expiresIn(&twoHours).Seconds(), 60, "explicit duration above the role max is capped")
}
+1 -1
View File
@@ -382,7 +382,7 @@ func (ms *MasterServer) VacuumVolume(ctx context.Context, req *master_pb.VacuumV
resp := &master_pb.VacuumVolumeResponse{}
ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, req.VolumeId, req.Collection, ms.preallocateSize, false)
ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, req.VolumeId, req.Collection, ms.preallocateSize, false, 0)
return resp, nil
}
+24 -7
View File
@@ -45,13 +45,14 @@ const (
)
type MasterOption struct {
Master pb.ServerAddress
MetaFolder string
VolumeSizeLimitMB uint32
FileSizeLimitMB int
VolumePreallocate bool
MaxParallelVacuumPerServer int
VacuumIntervalSeconds int
Master pb.ServerAddress
MetaFolder string
VolumeSizeLimitMB uint32
FileSizeLimitMB int
VolumePreallocate bool
MaxParallelVacuumPerServer int
VacuumIntervalSeconds int
VacuumDeleteEmptyAfterSeconds int
// PulseSeconds int
DefaultReplicaPlacement string
GarbageThreshold float64
@@ -118,6 +119,7 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
v.SetDefault("master.volume_growth.copy_3", topology.VolumeGrowStrategy.Copy3Count)
v.SetDefault("master.volume_growth.copy_other", topology.VolumeGrowStrategy.CopyOtherCount)
v.SetDefault("master.volume_growth.threshold", topology.VolumeGrowStrategy.Threshold)
v.SetDefault("master.volume_growth.reservation_timeout", "5m")
v.SetDefault("master.volume_growth.disable", false)
option.VolumeGrowthDisabled = v.GetBool("master.volume_growth.disable")
@@ -126,6 +128,7 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
topology.VolumeGrowStrategy.Copy3Count = v.GetUint32("master.volume_growth.copy_3")
topology.VolumeGrowStrategy.CopyOtherCount = v.GetUint32("master.volume_growth.copy_other")
topology.VolumeGrowStrategy.Threshold = v.GetFloat64("master.volume_growth.threshold")
topology.VolumeGrowStrategy.ReservationTimeout = parseReservationTimeout(v)
whiteList := util.StringSplit(v.GetString("guard.white_list"), ",")
var preallocateSize int64
@@ -204,6 +207,7 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
topology.VolumeGrowStrategy.Threshold,
ms.preallocateSize,
time.Duration(ms.option.VacuumIntervalSeconds)*time.Second,
time.Duration(ms.option.VacuumDeleteEmptyAfterSeconds)*time.Second,
)
ms.ProcessGrowRequest()
@@ -661,3 +665,16 @@ func (ms *MasterServer) Reload() {
v.GetInt("jwt.signing.read.expires_after_seconds"),
)
}
func parseReservationTimeout(v *util.ViperProxy) time.Duration {
if str := strings.TrimSpace(v.GetString("master.volume_growth.reservation_timeout")); str != "" {
if d, err := time.ParseDuration(str); err == nil && d > 0 {
return d
}
}
// A bare number in the config means seconds; GetDuration would read it as nanoseconds.
if sec := v.GetInt("master.volume_growth.reservation_timeout"); sec > 0 {
return time.Duration(sec) * time.Second
}
return topology.DefaultReservationTimeout
}
+1 -1
View File
@@ -61,7 +61,7 @@ func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Reque
}
}
// glog.Infoln("garbageThreshold =", gcThreshold)
ms.Topo.Vacuum(ms.grpcDialOption, gcThreshold, ms.option.MaxParallelVacuumPerServer, 0, "", ms.preallocateSize, false)
ms.Topo.Vacuum(ms.grpcDialOption, gcThreshold, ms.option.MaxParallelVacuumPerServer, 0, "", ms.preallocateSize, false, 0)
ms.dirStatusHandler(w, r)
}
@@ -0,0 +1,85 @@
package weed_server
import (
"testing"
"time"
"github.com/spf13/viper"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestParseReservationTimeout(t *testing.T) {
tests := []struct {
name string
setup func(v *util.ViperProxy)
expected time.Duration
}{
{
name: "unset defaults to 5 minutes",
setup: func(v *util.ViperProxy) {},
expected: 5 * time.Minute,
},
{
name: "duration string 10m",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", "10m")
},
expected: 10 * time.Minute,
},
{
name: "duration string 30s",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", "30s")
},
expected: 30 * time.Second,
},
{
name: "integer seconds 300",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", 300)
},
expected: 300 * time.Second,
},
{
name: "large integer stays seconds not nanoseconds",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", 1000000000)
},
expected: 1000000000 * time.Second,
},
{
name: "non-positive zero defaults to 5 minutes",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", 0)
},
expected: 5 * time.Minute,
},
{
name: "negative seconds defaults to 5 minutes",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", -10)
},
expected: 5 * time.Minute,
},
{
name: "invalid string defaults to 5 minutes",
setup: func(v *util.ViperProxy) {
v.Set("master.volume_growth.reservation_timeout", "invalid")
},
expected: 5 * time.Minute,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rawViper := viper.New()
vp := util.NewViperProxy(rawViper)
tt.setup(vp)
actual := parseReservationTimeout(vp)
if actual != tt.expected {
t.Errorf("expected %v, got %v", tt.expected, actual)
}
})
}
}
@@ -149,6 +149,92 @@ func TestUnmountEcShardsFencedByGeneration(t *testing.T) {
require.False(t, mountedEcShardIds(t, vs, vid)[1], "a strictly-older generation shard must be unmounted")
}
// TestTeardownRemovesStagedGenerations pins that a full teardown wipes the
// 2PC-staged <base>.*.v<N> files together with the canonical ones: they are
// invisible to EC bookkeeping, so anything left behind leaks forever.
func TestTeardownRemovesStagedGenerations(t *testing.T) {
const collection = "ec-gen-leak"
vid := needle.VolumeId(57)
dir := t.TempDir()
vs := &VolumeServer{store: buildEcStoreWithGeneration(t, dir, collection, vid, 100, []erasure_coding.ShardId{0, 1})}
base := erasure_coding.EcShardFileName(collection, dir, int(vid))
for _, name := range []string{
base + ".ec00.v3", base + ".ec01.v3", base + ".ecx.v3", base + ".vif.v3", base + ".ecsum.v3",
} {
require.NoError(t, os.WriteFile(name, []byte("staged"), 0o644))
}
_, err := vs.VolumeEcShardsDelete(context.Background(), &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: uint32(vid),
Collection: collection,
FullTeardown: true,
EncodeTsNs: 200,
})
require.NoError(t, err)
left, err := filepath.Glob(base + "*")
require.NoError(t, err)
require.Empty(t, left, "teardown must leave no EC files, staged generations included: %v", left)
}
// TestDeleteGenerationsOlderThan covers the post-commit cleanup: staged
// generations below the threshold are removed while the committed generation
// and the live canonical files stay untouched.
func TestDeleteGenerationsOlderThan(t *testing.T) {
const collection = "ec-gen-gc"
vid := needle.VolumeId(58)
dir := t.TempDir()
vs := &VolumeServer{store: buildEcStoreWithGeneration(t, dir, collection, vid, 100, []erasure_coding.ShardId{0, 1})}
base := erasure_coding.EcShardFileName(collection, dir, int(vid))
stale := []string{base + ".ec00.v3", base + ".ecx.v3", base + ".vif.v3"}
fresh := []string{base + ".ec00.v7", base + ".vif.v7"}
for _, name := range append(stale, fresh...) {
require.NoError(t, os.WriteFile(name, []byte("staged"), 0o644))
}
_, err := vs.VolumeEcShardsDelete(context.Background(), &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: uint32(vid),
Collection: collection,
DeleteGenerationsOlderThan: 5,
})
require.NoError(t, err)
for _, name := range stale {
require.False(t, util.FileExists(name), "%s must be removed", name)
}
for _, name := range fresh {
require.True(t, util.FileExists(name), "%s must be preserved", name)
}
require.True(t, util.FileExists(base+".ec00"), "canonical shards must be preserved")
require.True(t, util.FileExists(base+".ecx"))
require.True(t, util.FileExists(base+".vif"))
require.True(t, mountedEcShardIds(t, vs, vid)[0], "mounted shards must stay mounted")
}
// TestShardDeleteRemovesStagedGenerations pins that deleting a shard removes
// its staged generations too: a shard evicted off a disk leaves nothing.
func TestShardDeleteRemovesStagedGenerations(t *testing.T) {
const collection = "ec-shard-gen"
vid := needle.VolumeId(59)
dir := t.TempDir()
vs := &VolumeServer{store: buildEcStoreWithGeneration(t, dir, collection, vid, 100, []erasure_coding.ShardId{0, 5})}
base := erasure_coding.EcShardFileName(collection, dir, int(vid))
require.NoError(t, os.WriteFile(base+".ec05.v2", []byte("staged"), 0o644))
require.NoError(t, vs.store.UnmountEcShards(vid, 5, 0))
_, err := vs.VolumeEcShardsDelete(context.Background(), &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: uint32(vid),
Collection: collection,
ShardIds: []uint32{5},
})
require.NoError(t, err)
require.False(t, util.FileExists(base+".ec05"))
require.False(t, util.FileExists(base+".ec05.v2"))
require.True(t, util.FileExists(base+".ec00"), "sibling shards must be preserved")
require.True(t, util.FileExists(base+".ecx"), "index must survive while shards remain")
}
// TestReadEcGenerationTsNs covers the per-disk .vif generation read used by the
// fenced teardown: a present .vif yields its generation (or 0 when it has no EC
// config), and a missing .vif is reported unreadable (preserved, fail-safe).
+57 -5
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"math"
"io/fs"
"os"
"path"
"path/filepath"
@@ -517,6 +518,27 @@ func (vs *VolumeServer) VolumeEcShardsDelete(ctx context.Context, req *volume_se
return &volume_server_pb.VolumeEcShardsDeleteResponse{FullTeardownDone: true}, nil
}
if req.DeleteGenerationsOlderThan > 0 {
// Post-commit cleanup of a 2PC generation switch: the committed
// generation has been promoted to the canonical names, so only the
// staged <base>.*.v<N> files strictly older than the threshold are
// superseded and safe to remove. Versioned files are never mounted,
// so nothing needs to be unloaded first.
for _, location := range vs.store.Locations {
dataBase := storage.VolumeFileName(location.Directory, req.Collection, int(req.VolumeId))
idxBase := storage.VolumeFileName(location.IdxDirectory, req.Collection, int(req.VolumeId))
if err := erasure_coding.RemoveEcGenerationFiles(dataBase, req.DeleteGenerationsOlderThan); err != nil {
return nil, fmt.Errorf("ec generation cleanup of volume %d on %s: %w", req.VolumeId, location.Directory, err)
}
if dataBase != idxBase {
if err := erasure_coding.RemoveEcGenerationFiles(idxBase, req.DeleteGenerationsOlderThan); err != nil {
return nil, fmt.Errorf("ec generation cleanup of volume %d on %s: %w", req.VolumeId, location.IdxDirectory, err)
}
}
}
return &volume_server_pb.VolumeEcShardsDeleteResponse{}, nil
}
glog.V(0).Infof("ec volume %s shard delete %v", bName, req.ShardIds)
// Pass 1: delete the requested shard files (and any now-orphaned per-disk bitrot
@@ -569,14 +591,37 @@ func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocatio
// Delete the requested shard files unconditionally. Gating on a local .ecx
// (still used for index-file routing below) would leak an orphan shard left
// by a failed copy that reconciliation later mounts under a foreign index.
shardFileNames := make([]string, 0, len(shardIds))
for _, shardId := range shardIds {
shardFileName := dataBaseFilename + erasure_coding.ToExt(int(shardId))
if util.FileExists(shardFileName) {
found = true
if err := removeFileIfExists(shardFileName); err != nil {
return fmt.Errorf("remove ec shard %s: %w", shardFileName, err)
shardFileNames = append(shardFileNames, dataBaseFilename+erasure_coding.ToExt(int(shardId)))
}
// The shard and every 2PC generation of it (<name>.v<N>) are removed:
// the shard must not live on this disk at all. Names match literally —
// a glob would let glob metacharacters in the collection part of bName
// leak into another volume's files.
entries, readErr := os.ReadDir(location.Directory)
switch {
case readErr == nil:
for _, entry := range entries {
for _, shardFileName := range shardFileNames {
name := filepath.Join(location.Directory, entry.Name())
if name != shardFileName && erasure_coding.EcFileGeneration(entry.Name(), filepath.Base(shardFileName)) < 0 {
continue
}
if util.FileExists(name) {
found = true
if err := removeFileIfExists(name); err != nil {
return fmt.Errorf("remove ec shard %s: %w", name, err)
}
}
}
}
case errors.Is(readErr, fs.ErrNotExist):
// No such directory means no shard files on this disk.
default:
// A listing failure must not fall back to canonical names only:
// staged .v<N> files would survive while the RPC reports success.
return fmt.Errorf("list %s for ec shards of %s: %w", location.Directory, bName, readErr)
}
if !found {
@@ -711,6 +756,13 @@ func removeStaleEcArtifacts(dataBaseFileName, indexBaseFileName string, total in
record(removeBitrotSidecars(dataBaseFileName))
}
// Generations staged by the 2PC switch are <base>.ecNN.v<N> plus the
// versioned .ecx/.ecj/.vif/.ecsum: a teardown of this disk leaves none.
record(erasure_coding.RemoveEcGenerationFiles(dataBaseFileName, 0))
if dataBaseFileName != indexBaseFileName {
record(erasure_coding.RemoveEcGenerationFiles(indexBaseFileName, 0))
}
// Canonical <base>.vif. A shard copy installs shards + .ecx before .vif, so an
// interrupted copy can leave a stale .vif whose run identity / shard ratio /
// dat_file_size a fresh generation would inherit. Remove it only on a shard-only
+4 -1
View File
@@ -130,7 +130,7 @@ type WebDavFile struct {
off int64
entry *filer_pb.Entry
visibleIntervals *filer.IntervalList[*filer.VisibleInterval]
reader io.ReaderAt
reader *filer.ChunkReadAt
bufWriter *buffered_writer.BufferedWriteCloser
ctx context.Context
}
@@ -537,6 +537,9 @@ func (f *WebDavFile) Write(buf []byte) (int, error) {
func (f *WebDavFile) Close() error {
glog.V(2).Infof("WebDavFileSystem.Close %v", f.name)
if f.reader != nil {
f.reader.ReleaseStream()
}
if f.bufWriter == nil {
return nil
}
+8
View File
@@ -650,4 +650,12 @@ func (l *DiskLocation) removeEcVolumeFiles(collection string, vid needle.VolumeI
for i := 0; i < erasure_coding.MaxShardCount; i++ {
removeFile(baseFileName+erasure_coding.ToExt(i), "EC shard file")
}
// Staged 2PC generations (<base>.ecNN.v<N>, versioned .ecx/.ecj/.vif)
// belong to this volume's EC state too; leaving them orphans the files.
for _, dir := range []string{indexBaseFileName, baseFileName} {
if err := erasure_coding.RemoveEcGenerationFiles(dir, 0); err != nil {
glog.Warningf("Failed to remove EC generation files for %s: %v", dir, err)
}
}
}
@@ -4,6 +4,10 @@ import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
@@ -74,3 +78,57 @@ func UnmountAndDeleteEcShards(
return nil
})
}
// EcFileGeneration parses the generation of a 2PC-staged <base>.v<N> file:
// -1 means the name is not a generation file of base.
func EcFileGeneration(name, base string) int64 {
suffix, ok := strings.CutPrefix(name, base+".v")
if !ok {
return -1
}
generation, err := strconv.ParseInt(suffix, 10, 64)
if err != nil || generation <= 0 {
return -1
}
return generation
}
// RemoveEcGenerationFiles removes 2PC generation files staged under base:
// <base>.ecNN.v<N>, <base>.ecx.v<N>, <base>.ecj.v<N>, <base>.ecsum.v<N> and
// <base>.vif.v<N>. generationsOlderThan == 0 removes every generation;
// otherwise only generations strictly below it. Returns the first real
// removal failure.
func RemoveEcGenerationFiles(baseFileName string, generationsOlderThan uint32) error {
var firstErr error
record := func(err error) {
if err != nil && firstErr == nil {
firstErr = err
}
}
dir, fileName := filepath.Dir(baseFileName), filepath.Base(baseFileName)
ecPrefix, vifName := fileName+".ec", fileName+".vif"
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
for _, entry := range entries {
name := entry.Name()
// A generation file is <artifact>.v<N>; the last dot separates the
// staged-generation suffix from the artifact name.
artifact := name[:max(strings.LastIndexByte(name, '.'), 0)]
if artifact != vifName && !strings.HasPrefix(artifact, ecPrefix) {
continue
}
generation := EcFileGeneration(name, artifact)
if generation < 0 || (generationsOlderThan > 0 && generation >= int64(generationsOlderThan)) {
continue
}
if err := os.Remove(filepath.Join(dir, name)); err != nil && !os.IsNotExist(err) {
record(err)
}
}
return firstErr
}
+5 -4
View File
@@ -349,17 +349,18 @@ func (n *NodeImpl) CapacityForAnyDisk() (total int64) {
// AvailableSpaceForReservation returns available space considering existing reservations
func (n *NodeImpl) AvailableSpaceForReservation(option *VolumeGrowOption) int64 {
// Expire here as well: a node whose reservations fill it is filtered out
// before TryReserveCapacity could clean them, stranding the capacity.
n.capacityReservations.cleanExpiredReservations(VolumeGrowStrategy.GetReservationTimeout())
baseAvailable := n.AvailableSpaceFor(option)
reservedCount := n.capacityReservations.getReservedCount(option.DiskType)
return baseAvailable - reservedCount
}
// TryReserveCapacity attempts to atomically reserve capacity for volume creation
// TryReserveCapacity attempts to atomically reserve capacity for volume creation using the configured timeout
func (n *NodeImpl) TryReserveCapacity(diskType types.DiskType, count int64) (reservationId string, success bool) {
const reservationTimeout = 5 * time.Minute // TODO: make this configurable
// Clean up any expired reservations first
n.capacityReservations.cleanExpiredReservations(reservationTimeout)
n.capacityReservations.cleanExpiredReservations(VolumeGrowStrategy.GetReservationTimeout())
// Atomically check and reserve space
option := &VolumeGrowOption{DiskType: diskType}
+2 -2
View File
@@ -13,7 +13,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/storage"
)
func (t *Topology) StartRefreshWritableVolumes(grpcDialOption grpc.DialOption, garbageThreshold float64, concurrentVacuumLimitPerVolumeServer int, growThreshold float64, preallocate int64, vacuumInterval time.Duration) {
func (t *Topology) StartRefreshWritableVolumes(grpcDialOption grpc.DialOption, garbageThreshold float64, concurrentVacuumLimitPerVolumeServer int, growThreshold float64, preallocate int64, vacuumInterval time.Duration, deleteEmptyAfter time.Duration) {
if vacuumInterval <= 0 {
vacuumInterval = 14 * time.Minute
}
@@ -39,7 +39,7 @@ func (t *Topology) StartRefreshWritableVolumes(grpcDialOption grpc.DialOption, g
t.EnableVacuumByPlugin()
}
if !t.IsVacuumDisabled() {
t.Vacuum(grpcDialOption, garbageThreshold, concurrentVacuumLimitPerVolumeServer, 0, "", preallocate, true)
t.Vacuum(grpcDialOption, garbageThreshold, concurrentVacuumLimitPerVolumeServer, 0, "", preallocate, true, deleteEmptyAfter)
}
} else {
stats.MasterReplicaPlacementMismatch.Reset()
+82 -3
View File
@@ -13,7 +13,9 @@ import (
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
@@ -214,7 +216,7 @@ func (t *Topology) batchVacuumVolumeCleanup(grpcDialOption grpc.DialOption, vl *
}
}
func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float64, maxParallelVacuumPerServer int, volumeId uint32, collection string, preallocate int64, automatic bool) {
func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float64, maxParallelVacuumPerServer int, volumeId uint32, collection string, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) {
// if there is vacuum going on, return immediately
swapped := atomic.CompareAndSwapInt64(&t.vacuumLockCounter, 0, 1)
@@ -248,7 +250,7 @@ func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float
t.vacuumOneVolumeId(grpcDialOption, volumeLayout, c, garbageThreshold, locationList, vid, preallocate, false)
}
} else {
t.vacuumOneVolumeLayout(grpcDialOption, volumeLayout, c, garbageThreshold, maxParallelVacuumPerServer, preallocate, automatic)
t.vacuumOneVolumeLayout(grpcDialOption, volumeLayout, c, garbageThreshold, maxParallelVacuumPerServer, preallocate, automatic, deleteEmptyAfter)
}
}
if automatic && t.IsVacuumDisabled() {
@@ -262,7 +264,7 @@ func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float
}
}
func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeLayout *VolumeLayout, c *Collection, garbageThreshold float64, maxParallelVacuumPerServer int, preallocate int64, automatic bool) {
func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeLayout *VolumeLayout, c *Collection, garbageThreshold float64, maxParallelVacuumPerServer int, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) {
volumeLayout.accessLock.RLock()
todoVolumeMap := make(map[needle.VolumeId]*VolumeLocationList)
@@ -271,6 +273,12 @@ func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeL
}
volumeLayout.accessLock.RUnlock()
// Empty volumes hold their slots forever: deleting them here also spares
// compacting bytes that are all deleted already.
if deleteEmptyAfter > 0 {
t.deleteEmptyVolumes(grpcDialOption, volumeLayout, todoVolumeMap, deleteEmptyAfter)
}
// limiter for each volume server
limiter := make(map[NodeId]int)
var limiterLock sync.Mutex
@@ -377,3 +385,74 @@ func (t *Topology) vacuumOneVolumeId(grpcDialOption grpc.DialOption, volumeLayou
}
}
}
// deleteEmptyVolumes removes a volume whose every replica copy has stayed
// empty and quiet for quietPeriod, the same rule volume.deleteEmpty applies
// on demand. A copy that still holds data or was written recently keeps the
// whole volume: deleting only the empty copies would silently cut the
// surviving copy's replica count. Fully deleted vids leave the sweep's work
// map; anything else falls through to the normal compaction path.
func (t *Topology) deleteEmptyVolumes(grpcDialOption grpc.DialOption, vl *VolumeLayout, todoVolumeMap map[needle.VolumeId]*VolumeLocationList, quietPeriod time.Duration) {
quietSeconds := int64(quietPeriod / time.Second)
nowUnixSeconds := time.Now().Unix()
for vid, locationList := range todoVolumeMap {
eligible := true
for _, dn := range locationList.list {
v, err := dn.GetVolumesById(vid)
if err != nil || !isEmptyVolumeDeleteCandidate(v, quietSeconds, nowUnixSeconds) {
eligible = false
break
}
}
if !eligible {
continue
}
// keep the volume out of assignments for the whole delete: a heartbeat
// landing mid-delete must not re-add it while replicas are dropping
vl.MarkDeleting(vid)
remaining := 0
kept := locationList.list[:0]
for _, dn := range locationList.list {
v, err := dn.GetVolumesById(vid)
if err == nil {
onlyGarbage := v.FileCount > 0 && v.FileCount <= v.DeleteCount
glog.V(0).Infof("deleting empty volume %d on %s", vid, dn.ServerAddress())
if err = t.deleteEmptyVolume(grpcDialOption, dn, vid, onlyGarbage); err == nil {
t.UnRegisterVolumeLayout(v, dn)
continue
}
}
glog.Warningf("delete empty volume %d on %s: %v", vid, dn.ServerAddress(), err)
kept = append(kept, dn)
remaining++
}
vl.UnmarkDeleting(vid)
locationList.list = kept
if remaining == 0 {
delete(todoVolumeMap, vid)
}
}
}
func (t *Topology) deleteEmptyVolume(grpcDialOption grpc.DialOption, dn *DataNode, vid needle.VolumeId, onlyGarbage bool) error {
return operation.WithVolumeServerClient(false, dn.ServerAddress(), grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
// onlyEmpty stays set so a pre-upgrade server checks emptiness and
// refuses instead of deleting a volume that changed since the report.
ctx, cancel := context.WithTimeout(context.Background(), allocateVolumeTimeout)
defer cancel()
_, err := client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
VolumeId: uint32(vid),
OnlyEmpty: true,
OnlyGarbage: onlyGarbage,
})
return err
})
}
func isEmptyVolumeDeleteCandidate(v storage.VolumeInfo, quietSeconds, nowUnixSeconds int64) bool {
return v.RemoteStorageName == "" &&
(!v.ReadOnly || v.ReadOnlyCanDelete) &&
(v.Size <= super_block.SuperBlockSize || v.FileCount > 0 && v.FileCount <= v.DeleteCount) &&
v.ModifiedAtSecond > 0 &&
v.ModifiedAtSecond+quietSeconds < nowUnixSeconds
}
+255
View File
@@ -0,0 +1,255 @@
package topology
import (
"context"
"errors"
"fmt"
"net"
"sync"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/sequence"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
func TestIsEmptyVolumeDeleteCandidate(t *testing.T) {
now := time.Now().Unix()
old := now - 7200
base := storage.VolumeInfo{
Size: 0,
ModifiedAtSecond: old,
}
for _, tc := range []struct {
name string
v storage.VolumeInfo
quiet int64
want bool
}{
{"empty and quiet", base, 3600, true},
{"all garbage and quiet", storage.VolumeInfo{Size: 1 << 20, FileCount: 100, DeleteCount: 100, ModifiedAtSecond: old}, 3600, true},
{"remote-backed", storage.VolumeInfo{Size: 0, ModifiedAtSecond: old, RemoteStorageName: "s3"}, 3600, false},
{"read-only without delete permission", storage.VolumeInfo{Size: 0, ModifiedAtSecond: old, ReadOnly: true}, 3600, false},
{"read-only can delete", storage.VolumeInfo{Size: 0, ModifiedAtSecond: old, ReadOnly: true, ReadOnlyCanDelete: true}, 3600, true},
{"live files", storage.VolumeInfo{Size: 1 << 20, FileCount: 100, DeleteCount: 50, ModifiedAtSecond: old}, 3600, false},
{"no live files but oversized is fine", storage.VolumeInfo{Size: 1 << 20, FileCount: 100, DeleteCount: 100, ModifiedAtSecond: old}, 3600, true},
{"unreported mtime", storage.VolumeInfo{Size: 0}, 3600, false},
{"still quiet-recent", storage.VolumeInfo{Size: 0, ModifiedAtSecond: now - 60}, 3600, false},
} {
t.Run(tc.name, func(t *testing.T) {
if got := isEmptyVolumeDeleteCandidate(tc.v, tc.quiet, now); got != tc.want {
t.Errorf("isEmptyVolumeDeleteCandidate() = %v, want %v", got, tc.want)
}
})
}
}
type fakeVolumeDeleteServer struct {
volume_server_pb.UnimplementedVolumeServerServer
mu sync.Mutex
deletes []*volume_server_pb.VolumeDeleteRequest
}
func (f *fakeVolumeDeleteServer) VolumeDelete(ctx context.Context, req *volume_server_pb.VolumeDeleteRequest) (*volume_server_pb.VolumeDeleteResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.deletes = append(f.deletes, req)
return &volume_server_pb.VolumeDeleteResponse{}, nil
}
func startFakeVolumeServer(t *testing.T, vs *fakeVolumeDeleteServer) (grpcPort int, dialOption grpc.DialOption) {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
volume_server_pb.RegisterVolumeServerServer(srv, vs)
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(lis) }()
t.Cleanup(func() {
srv.Stop()
if err := <-serveErr; err != nil && !errors.Is(err, grpc.ErrServerStopped) {
t.Errorf("fake volume server: %v", err)
}
})
return lis.Addr().(*net.TCPAddr).Port, grpc.WithTransportCredentials(insecure.NewCredentials())
}
func TestDeleteEmptyVolumesDeletesOnlyQuietEmptyCopies(t *testing.T) {
fake := &fakeVolumeDeleteServer{}
grpcPort, dialOption := startFakeVolumeServer(t, fake)
topo := NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
rack := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1")
dn := rack.GetOrCreateDataNode("127.0.0.1", 8080, grpcPort, "127.0.0.1", fmt.Sprintf("dn-%d", grpcPort), map[string]uint32{"": 10})
now := time.Now().Unix()
old := now - 7200
volume := func(id int, size uint64, files, deleted uint32, mtime int64) storage.VolumeInfo {
return storage.VolumeInfo{
Id: needle.VolumeId(id),
Size: size,
Collection: "c",
FileCount: files,
DeleteCount: deleted,
ModifiedAtSecond: mtime,
Version: needle.GetCurrentVersion(),
ReplicaPlacement: &super_block.ReplicaPlacement{},
Ttl: needle.EMPTY_TTL,
}
}
quietEmpty := volume(1, 0, 0, 0, old)
quietGarbage := volume(2, 1<<20, 100, 100, old)
recentEmpty := volume(3, 0, 0, 0, now)
live := volume(4, 1<<20, 100, 50, old)
todo := make(map[needle.VolumeId]*VolumeLocationList)
dn.UpdateVolumes([]storage.VolumeInfo{quietEmpty, quietGarbage, recentEmpty, live})
for _, v := range []storage.VolumeInfo{quietEmpty, quietGarbage, recentEmpty, live} {
topo.RegisterVolumeLayout(v, dn)
ll := NewVolumeLocationList()
ll.list = append(ll.list, dn)
todo[v.Id] = ll
}
vl := topo.GetVolumeLayout("c", &super_block.ReplicaPlacement{}, needle.EMPTY_TTL, types.ToDiskType(""))
topo.deleteEmptyVolumes(dialOption, vl, todo, time.Hour)
if _, ok := todo[quietEmpty.Id]; ok {
t.Error("quiet empty volume stayed in the sweep map")
}
if _, ok := todo[quietGarbage.Id]; ok {
t.Error("quiet all-garbage volume stayed in the sweep map")
}
for _, v := range []storage.VolumeInfo{recentEmpty, live} {
if _, ok := todo[v.Id]; !ok {
t.Errorf("volume %d was deleted though not an empty-quiet candidate", v.Id)
}
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.deletes) != 2 {
t.Fatalf("VolumeDelete calls = %d, want 2", len(fake.deletes))
}
got := map[uint32]*volume_server_pb.VolumeDeleteRequest{}
for _, d := range fake.deletes {
if !d.OnlyEmpty {
t.Errorf("VolumeDelete %d missing the onlyEmpty guard", d.VolumeId)
}
got[d.VolumeId] = d
}
if got[uint32(quietEmpty.Id)].OnlyGarbage {
t.Error("truly empty volume deleted with onlyGarbage")
}
if !got[uint32(quietGarbage.Id)].OnlyGarbage {
t.Error("all-garbage volume should carry onlyGarbage")
}
}
// A volume whose sibling replica holds live files is not "empty": deleting
// the empty copy would silently cut the live copy's replica count, so the
// whole vid is left alone.
func TestDeleteEmptyVolumesSkipsVidWithLiveReplica(t *testing.T) {
fake := &fakeVolumeDeleteServer{}
grpcPort, dialOption := startFakeVolumeServer(t, fake)
topo := NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
rack := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1")
emptyDn := rack.GetOrCreateDataNode("127.0.0.1", 8080, grpcPort, "127.0.0.1", "dn-empty", map[string]uint32{"": 10})
liveDn := rack.GetOrCreateDataNode("127.0.0.2", 8080, 1, "127.0.0.2", "dn-live", map[string]uint32{"": 10})
now := time.Now().Unix()
v := storage.VolumeInfo{
Id: needle.VolumeId(1),
Size: 0,
Collection: "c",
ModifiedAtSecond: now - 7200,
Version: needle.GetCurrentVersion(),
ReplicaPlacement: &super_block.ReplicaPlacement{},
Ttl: needle.EMPTY_TTL,
}
live := storage.VolumeInfo{
Id: v.Id,
Size: 1 << 20,
Collection: "c",
FileCount: 100,
DeleteCount: 50,
ModifiedAtSecond: now - 7200,
Version: needle.GetCurrentVersion(),
ReplicaPlacement: &super_block.ReplicaPlacement{},
Ttl: needle.EMPTY_TTL,
}
emptyDn.UpdateVolumes([]storage.VolumeInfo{v})
liveDn.UpdateVolumes([]storage.VolumeInfo{live})
topo.RegisterVolumeLayout(v, emptyDn)
topo.RegisterVolumeLayout(live, liveDn)
ll := NewVolumeLocationList()
ll.list = append(ll.list, emptyDn, liveDn)
todo := map[needle.VolumeId]*VolumeLocationList{v.Id: ll}
vl := topo.GetVolumeLayout("c", &super_block.ReplicaPlacement{}, needle.EMPTY_TTL, types.ToDiskType(""))
topo.deleteEmptyVolumes(dialOption, vl, todo, time.Hour)
if _, ok := todo[v.Id]; !ok {
t.Fatal("vid left the sweep map while a live replica keeps it")
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.deletes) != 0 {
t.Fatalf("VolumeDelete calls = %d, want 0 (a live sibling keeps the whole vid)", len(fake.deletes))
}
}
// With every copy eligible a copy whose delete RPC fails keeps the vid in the
// sweep map; the deleted copy is gone but the vid falls through to the normal
// compaction path for its surviving replicas.
func TestDeleteEmptyVolumesKeepsVidWhenCopyDeleteFails(t *testing.T) {
fake := &fakeVolumeDeleteServer{}
grpcPort, dialOption := startFakeVolumeServer(t, fake)
topo := NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
rack := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1")
emptyDn := rack.GetOrCreateDataNode("127.0.0.1", 8080, grpcPort, "127.0.0.1", "dn-empty", map[string]uint32{"": 10})
deadDn := rack.GetOrCreateDataNode("127.0.0.2", 8080, 1, "127.0.0.2", "dn-dead", map[string]uint32{"": 10})
now := time.Now().Unix()
v := storage.VolumeInfo{
Id: needle.VolumeId(1),
Size: 0,
Collection: "c",
ModifiedAtSecond: now - 7200,
Version: needle.GetCurrentVersion(),
ReplicaPlacement: &super_block.ReplicaPlacement{},
Ttl: needle.EMPTY_TTL,
}
emptyDn.UpdateVolumes([]storage.VolumeInfo{v})
deadDn.UpdateVolumes([]storage.VolumeInfo{v})
topo.RegisterVolumeLayout(v, emptyDn)
topo.RegisterVolumeLayout(v, deadDn)
ll := NewVolumeLocationList()
ll.list = append(ll.list, emptyDn, deadDn)
todo := map[needle.VolumeId]*VolumeLocationList{v.Id: ll}
vl := topo.GetVolumeLayout("c", &super_block.ReplicaPlacement{}, needle.EMPTY_TTL, types.ToDiskType(""))
topo.deleteEmptyVolumes(dialOption, vl, todo, time.Hour)
if _, ok := todo[v.Id]; !ok {
t.Fatal("vid left the sweep map while a replica delete failed")
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.deletes) != 1 {
t.Fatalf("VolumeDelete calls = %d, want 1 (only the reachable copy)", len(fake.deletes))
}
}
+21 -10
View File
@@ -39,21 +39,32 @@ func (vg *VolumeGrowRequest) Equals(req *VolumeGrowRequest) bool {
return reflect.DeepEqual(vg.Option, req.Option) && vg.Count == req.Count && vg.Force == req.Force
}
const DefaultReservationTimeout = 5 * time.Minute
type volumeGrowthStrategy struct {
Copy1Count uint32
Copy2Count uint32
Copy3Count uint32
CopyOtherCount uint32
Threshold float64
Copy1Count uint32
Copy2Count uint32
Copy3Count uint32
CopyOtherCount uint32
Threshold float64
ReservationTimeout time.Duration
}
func (s *volumeGrowthStrategy) GetReservationTimeout() time.Duration {
if s != nil && s.ReservationTimeout > 0 {
return s.ReservationTimeout
}
return DefaultReservationTimeout
}
var (
VolumeGrowStrategy = volumeGrowthStrategy{
Copy1Count: 7,
Copy2Count: 6,
Copy3Count: 3,
CopyOtherCount: 1,
Threshold: 0.9,
Copy1Count: 7,
Copy2Count: 6,
Copy3Count: 3,
CopyOtherCount: 1,
Threshold: 0.9,
ReservationTimeout: DefaultReservationTimeout,
}
)
@@ -293,3 +293,111 @@ func TestVolumeGrowth_ReservationTimeout(t *testing.T) {
t.Errorf("Expected 2 available slots after cleanup and new reservation, got %d", available)
}
}
func TestVolumeGrowth_ConfigurableReservationTimeout(t *testing.T) {
origTimeout := VolumeGrowStrategy.ReservationTimeout
defer func() {
VolumeGrowStrategy.ReservationTimeout = origTimeout
}()
dn := NewDataNode("server1")
diskType := types.HardDriveType
// Set up capacity of 5
diskUsage := dn.diskUsages.getOrCreateDisk(diskType)
diskUsage.maxVolumeCount = 5
// 1. Verify default timeout (5 minutes)
VolumeGrowStrategy.ReservationTimeout = 5 * time.Minute
resId1, ok := dn.TryReserveCapacity(diskType, 2)
if !ok {
t.Fatal("Expected reservation 1 to succeed")
}
// Set reservation createdAt to 4 minutes ago (not expired under 5m timeout)
dn.capacityReservations.Lock()
if r, exists := dn.capacityReservations.reservations[resId1]; exists {
r.createdAt = time.Now().Add(-4 * time.Minute)
}
dn.capacityReservations.Unlock()
// Available space should be 5 - 2 = 3. Trying to reserve 4 must fail.
_, ok = dn.TryReserveCapacity(diskType, 4)
if ok {
t.Error("Expected reservation of 4 to fail when 2 slots are still reserved")
}
// Set reservation createdAt to 6 minutes ago (expired under 5m timeout)
dn.capacityReservations.Lock()
if r, exists := dn.capacityReservations.reservations[resId1]; exists {
r.createdAt = time.Now().Add(-6 * time.Minute)
}
dn.capacityReservations.Unlock()
// Now reserving 4 should clean up the expired reservation and succeed
resId2, ok := dn.TryReserveCapacity(diskType, 4)
if !ok {
t.Fatal("Expected reservation of 4 to succeed after 6m expired reservation was cleaned up")
}
dn.ReleaseReservedCapacity(resId2)
// 2. Verify custom timeout (1 minute)
VolumeGrowStrategy.ReservationTimeout = 1 * time.Minute
resId3, ok := dn.TryReserveCapacity(diskType, 2)
if !ok {
t.Fatal("Expected reservation 3 to succeed")
}
// Set createdAt to 45 seconds ago (not expired under 1m timeout)
dn.capacityReservations.Lock()
if r, exists := dn.capacityReservations.reservations[resId3]; exists {
r.createdAt = time.Now().Add(-45 * time.Second)
}
dn.capacityReservations.Unlock()
_, ok = dn.TryReserveCapacity(diskType, 4)
if ok {
t.Error("Expected reservation of 4 to fail when 2 slots are reserved 45s ago with 1m timeout")
}
// Set createdAt to 75 seconds ago (expired under 1m timeout)
dn.capacityReservations.Lock()
if r, exists := dn.capacityReservations.reservations[resId3]; exists {
r.createdAt = time.Now().Add(-75 * time.Second)
}
dn.capacityReservations.Unlock()
resId4, ok := dn.TryReserveCapacity(diskType, 4)
if !ok {
t.Fatal("Expected reservation of 4 to succeed after 75s reservation expired under 1m timeout")
}
dn.ReleaseReservedCapacity(resId4)
// 3. Verify non-positive timeout fallback to 5 minutes
VolumeGrowStrategy.ReservationTimeout = 0
if VolumeGrowStrategy.GetReservationTimeout() != 5*time.Minute {
t.Errorf("Expected 0 timeout to fall back to 5m, got %v", VolumeGrowStrategy.GetReservationTimeout())
}
VolumeGrowStrategy.ReservationTimeout = -10 * time.Second
if VolumeGrowStrategy.GetReservationTimeout() != 5*time.Minute {
t.Errorf("Expected negative timeout to fall back to 5m, got %v", VolumeGrowStrategy.GetReservationTimeout())
}
// 4. Expired reservations must not strand capacity: the selection filter
// reads AvailableSpaceForReservation without calling TryReserveCapacity.
VolumeGrowStrategy.ReservationTimeout = 1 * time.Minute
resId5, ok := dn.TryReserveCapacity(diskType, 5)
if !ok {
t.Fatal("Expected reservation 5 to succeed")
}
dn.capacityReservations.Lock()
if r, exists := dn.capacityReservations.reservations[resId5]; exists {
r.createdAt = time.Now().Add(-2 * time.Minute)
}
dn.capacityReservations.Unlock()
option := &VolumeGrowOption{DiskType: diskType}
if available := dn.AvailableSpaceForReservation(option); available != 5 {
t.Errorf("Expected expired reservation to free capacity in AvailableSpaceForReservation, got %d", available)
}
}
+29
View File
@@ -65,6 +65,7 @@ type VolumeLayout struct {
writableMembers map[needle.VolumeId]struct{}
crowded map[needle.VolumeId]struct{}
vacuumedVolumes map[needle.VolumeId]time.Time
deletingVolumes map[needle.VolumeId]struct{}
volumeSizeLimit uint64
replicationAsMin bool
accessLock sync.RWMutex
@@ -92,6 +93,7 @@ func NewVolumeLayout(rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType
writableMembers: make(map[needle.VolumeId]struct{}),
crowded: make(map[needle.VolumeId]struct{}),
vacuumedVolumes: make(map[needle.VolumeId]time.Time),
deletingVolumes: make(map[needle.VolumeId]struct{}),
volumeSizeLimit: volumeSizeLimit,
replicationAsMin: replicationAsMin,
sizeTracking: make(map[needle.VolumeId]*volumeSizeTracking),
@@ -553,6 +555,30 @@ func (vl *VolumeLayout) DrainAndRemoveFromWritable(vid needle.VolumeId) {
vl.waitForPendingDrain(context.Background(), vid)
}
// MarkDeleting pins a volume out of the writable list for the duration of a
// sweep delete. DrainAndRemoveFromWritable alone is not enough here: unlike a
// compaction the volume disappears, so a heartbeat landing mid-delete must not
// re-add it and let a write reach a replica whose siblings are already gone.
func (vl *VolumeLayout) MarkDeleting(vid needle.VolumeId) {
vl.accessLock.Lock()
vl.deletingVolumes[vid] = struct{}{}
vl.removeFromWritable(vid)
vl.accessLock.Unlock()
vl.waitForPendingDrain(context.Background(), vid)
}
func (vl *VolumeLayout) UnmarkDeleting(vid needle.VolumeId) {
vl.accessLock.Lock()
delete(vl.deletingVolumes, vid)
// Re-run the standard writable gate so a surviving volume regains
// assignment immediately; digest heartbeats only re-report changed
// volumes, so waiting on them could strand it unwritable indefinitely.
if !vl.vid2location[vid].AnyOversized() && vl.enoughCopies(vid) && vl.isAllWritable(vid) {
vl.setVolumeWritable(vid)
}
vl.accessLock.Unlock()
}
func (vl *VolumeLayout) isEmpty() bool {
vl.accessLock.RLock()
defer vl.accessLock.RUnlock()
@@ -920,6 +946,9 @@ func (vl *VolumeLayout) removeFromWritable(vid needle.VolumeId) bool {
return false
}
func (vl *VolumeLayout) setVolumeWritable(vid needle.VolumeId) bool {
if _, ok := vl.deletingVolumes[vid]; ok {
return false
}
if _, ok := vl.writableMembers[vid]; ok {
return false
}
+37
View File
@@ -4,6 +4,7 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
@@ -259,3 +260,39 @@ func TestSetVolumeReadOnly_PreservesPending(t *testing.T) {
t.Errorf("expected 5000 pending (not drained), got %d", p)
}
}
// A heartbeat landing mid-delete re-evaluates writability; a marked volume
// must stay out of the writable list until the sweep finishes with it.
func TestMarkDeletingKeepsVolumeUnwritableAcrossHeartbeats(t *testing.T) {
layout := `
{
"dc1":{
"rack1":{
"server1":{
"volumes":[
{"id":1, "size":1000, "replication":"000"}
],
"limit":10
}
}
}
}
`
_, vl := setupPickTest(t, layout, 10000)
if writable, _ := vl.GetWritableVolumeCount(); writable != 1 {
t.Fatalf("volume not writable before mark, got %d", writable)
}
vl.MarkDeleting(1)
vl.EnsureCorrectWritables(&storage.VolumeInfo{Id: 1})
if writable, _ := vl.GetWritableVolumeCount(); writable != 0 {
t.Fatal("marked volume became writable again")
}
vl.UnmarkDeleting(1)
if writable, _ := vl.GetWritableVolumeCount(); writable != 1 {
t.Fatal("unmarked volume did not regain writability without a heartbeat")
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
var (
MAJOR_VERSION = int32(4)
MINOR_VERSION = int32(47)
MINOR_VERSION = int32(48)
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
VERSION = util.SizeLimit + " " + VERSION_NUMBER
COMMIT = ""