Compare commits

...
42 Commits
Author SHA1 Message Date
Chris Lu 3ff92f797d 4.21 2026-04-19 14:38:29 -07:00
Chris Lu a8ba9d106e peer chunk sharing 7/8: tryPeerRead read-path hook (#9136)
* mount: batched announcer + pooled peer conns for mount-to-mount RPCs

* peer_announcer.go: non-blocking EnqueueAnnounce + ticker flush that
  groups fids by HRW owner, fans out one ChunkAnnounce per owner in
  parallel. announcedAt is pruned at 2× TTL so it stays bounded.

* peer_dialer.go: PeerConnPool caches one grpc.ClientConn per peer
  address; the announcer and (next PR) the fetcher share it so
  steady-state owner RPCs skip the handshake cost entirely. Bounded
  at 4096 cached entries; shutdown conns are transparently replaced.

* WFS starts both alongside the gRPC server; stops them on unmount.

* mount: wire tryPeerRead via FetchChunk streaming gRPC

Replaces the HTTP GET byte-transfer path with a gRPC server-stream
FetchChunk call. Same fall-through semantics: any failure drops
through to entryChunkGroup.ReadDataAt, so reads never slow below
status quo.

* peer_fetcher.go: tryPeerRead resolves the offset to a leaf chunk
  (flattening manifests), asks the HRW owner for holders via
  ChunkLookup, then opens FetchChunk on each holder in LRU order
  (PR #5) until one succeeds. Assembled bytes are verified against
  FileChunk.ETag end-to-end — the peer is still treated as
  untrusted. Reuses the shared PeerConnPool from PR #6 for all
  outbound gRPC.

* peer_grpc.go: expose SelfAddr() so the fetcher can avoid dialing
  itself on a self-owned fid.

* filehandle_read.go: tryPeerRead slot between tryRDMARead and
  entryChunkGroup.ReadDataAt. Gated by option.PeerEnabled and the
  presence of peerGrpcServer (the single identity test).

Read ordering with the feature enabled is now:
   local cache -> RDMA sidecar -> peer mount (gRPC stream) -> volume server

One port, one identity, one connection pool — no more HTTP bytecast.

* test(fuse_p2p): end-to-end CI test for peer chunk sharing

Adds a FUSE-backed integration test that proves mount B can satisfy a
read from mount A's chunk cache instead of the volume tier.

Layout (modelled on test/fuse_dlm):

  test/fuse_p2p/framework_test.go        — cluster harness (1 master,
                                           1 volume, 1 filer, N mounts,
                                           all with -peer.enable)
  test/fuse_p2p/peer_chunk_sharing_test.go
                                         — writer-reader scenario

The test (TestPeerChunkSharing_ReadersPullFromPeerCache):

  1. Starts 3 mounts. Three is the sweet spot: with 2 mounts, HRW owner
     of a chunk is self ~50 % of the time (peer path short-circuits);
     with 3+ it drops to ≤ 1/3, so a multi-chunk file almost certainly
     exercises the remote-owner fan-out.
  2. Mount 0 writes a ~8 MiB file, then reads it back through its own
     FUSE to warm its chunk cache.
  3. Waits for seed convergence (one full MountList refresh) plus an
     announcer flush cycle, so chunk-holder entries have reached each
     HRW owner.
  4. Mount 1 reads the same file.
  5. Verifies byte-for-byte equality AND greps mount 1's log for
     "peer read successful" — content matching alone is not proof
     (the volume fallback would also succeed), so the log marker is
     what distinguishes p2p from fallback.

Workflow .github/workflows/fuse-p2p-integration.yml triggers on any
change to mount/filer peer code, the p2p protos, or the test itself.
Failure artifacts (server + mount logs) are uploaded for 3 days.

Mounts run with -v=4 so the tryPeerRead success/failure glog messages
land in the log file the test greps.
2026-04-19 00:53:12 -07:00
Chris Lu 73f10fa528 peer chunk sharing 6/8: announce queue + batched flush (#9135)
mount: batched announcer + pooled peer conns for mount-to-mount RPCs

* peer_announcer.go: non-blocking EnqueueAnnounce + ticker flush that
  groups fids by HRW owner, fans out one ChunkAnnounce per owner in
  parallel. announcedAt is pruned at 2× TTL so it stays bounded.

* peer_dialer.go: PeerConnPool caches one grpc.ClientConn per peer
  address; the announcer and (next PR) the fetcher share it so
  steady-state owner RPCs skip the handshake cost entirely. Bounded
  at 4096 cached entries; shutdown conns are transparently replaced.

* WFS starts both alongside the gRPC server; stops them on unmount.
2026-04-18 21:42:36 -07:00
Chris Lu fe9ca35bbd peer chunk sharing 5/8: mount chunk-directory shard (#9134)
mount: tier-2 chunk directory + FetchChunk streaming on one gRPC port

Collapses the old two-port design (HTTP peer-serve + separate gRPC
directory) into a single gRPC service that handles every mount-to-
mount exchange: ChunkAnnounce, ChunkLookup, and the new FetchChunk
byte stream.

* peer_directory.go: fid -> holders shard, HRW-gated; returns holders
  in LRU order; capacity-bounded; Sweep handles eviction under
  write-lock while Lookup runs under RLock (hot path is concurrent).

* peer_grpc.go: single MountPeer gRPC server implementing all three
  RPCs. FetchChunk frames bytes at 1 MiB per Send so the default
  4 MiB message cap does not constrain chunk size; cache miss
  returns gRPC NOT_FOUND so clients distinguish miss from transport
  error. Reuses pb.NewGrpcServer for consistent keepalive + msg-size
  tuning.

* peer_bytepool.go: sync.Pool wrapper around *[]byte that the server
  uses to avoid a fresh 8 MiB allocation per FetchChunk call.

* WFS wiring starts the gRPC server on option.PeerListen (the single
  peer port) using the advertise address resolved in PR #3 as the
  HRW identity. A background sweeper evicts expired directory
  entries every 60 s.
2026-04-18 20:18:38 -07:00
Chris Lu 8a6348d3e9 peer chunk sharing 4/8: mount registrar + HRW owner selection (#9133)
* proto: define MountRegister/MountList and MountPeer service

Adds the wire types for peer chunk sharing between weed mount clients:

* filer.proto: MountRegister / MountList RPCs so each mount can heartbeat
  its peer-serve address into a filer-hosted registry, and refresh the
  list of peers. Tiny payload; the filer stores only O(fleet_size) state.

* mount_peer.proto (new): ChunkAnnounce / ChunkLookup RPCs for the
  mount-to-mount chunk directory. Each fid's directory entry lives on
  an HRW-assigned mount; announces and lookups route to that mount.

No behavior yet — later PRs wire the RPCs into the filer and mount.
See design-weed-mount-peer-chunk-sharing.md for the full design.

* filer: add mount-server registry behind -peer.registry.enable

Implements tier 1 of the peer chunk sharing design: an in-memory registry
of live weed mount servers, keyed by peer address, refreshed by
MountRegister heartbeats and served by MountList.

* weed/filer/peer_registry.go: thread-safe map with TTL eviction; lazy
  sweep on List plus a background sweeper goroutine for bounded memory.

* weed/server/filer_grpc_server_peer.go: MountRegister / MountList RPC
  handlers. When -peer.registry.enable is false (the default), both RPCs
  are silent no-ops so probing older filers is harmless.

* -peer.registry.enable flag on weed filer; FilerOption.PeerRegistryEnabled
  wires it through.

Phase 1 is single-filer (no cross-filer replication of the registry);
mounts that fail over to another filer will re-register on the next
heartbeat, so the registry self-heals within one TTL cycle.

Part of the peer-chunk-sharing design; no behavior change at runtime
until a later PR enables the flag on both filer and mount.

* filer: nil-safe peerRegistryEnable + registry hardening

Addresses review feedback on PR #9131.

* Fix: nil pointer deref in the mini cluster. FilerOptions instances
  constructed outside weed/command/filer.go (e.g. miniFilerOptions in
  mini.go) do not populate peerRegistryEnable, so dereferencing the
  pointer panics at Filer startup. Use the same
  `nil && deref` idiom already used for distributedLock / writebackCache.

* Hardening (gemini review): registry now enforces three invariants:
  - empty peer_addr is silently rejected (no client-controlled sentinel
    mass-inserts)
  - TTL is capped at 1 hour so a runaway client cannot pin entries
  - new-entry count is capped at 10000 to bound memory; renewals of
    existing entries are always honored, so a full registry still
    heartbeats its existing members correctly

Covered by new unit tests.

* filer: rename -peer.registry.enable flag to -mount.p2p

Per review feedback: the old name "peer.registry.enable" leaked
the implementation ("registry") into the CLI surface. "mount.p2p"
is shorter and describes what it actually controls — whether this
filer participates in mount-to-mount peer chunk sharing.

Flag renames (all three keep default=true, idle cost is near-zero):
  -peer.registry.enable        ->  -mount.p2p         (weed filer)
  -filer.peer.registry.enable  ->  -filer.mount.p2p   (weed mini, weed server)

Internal variable names (mountPeerRegistryEnable, MountPeerRegistry)
keep their longer form — they describe the component, not the knob.

* filer: MountList returns DataCenter + List uses RLock

Two review follow-ups on the mount peer registry:

* weed/server/filer_grpc_server_mount_peer.go: MountList was dropping
  the DataCenter on the wire. The whole point of carrying DC separately
  from Rack is letting the mount-side fetcher re-rank peers by the
  two-level locality hierarchy (same-rack > same-DC > cross-DC); without
  DC in the response every remote peer collapsed to "unknown locality."

* weed/filer/mount_peer_registry.go: List() was taking a write lock so
  it could lazy-delete expired entries inline. But MountList is a
  read-heavy RPC hit on every mount's 30 s refresh loop, and Sweep is
  already wired as the sole reclamation path (same pattern as the
  mount-side PeerDirectory). Switch List to RLock + filter, let Sweep
  do the map mutation, so concurrent MountList callers don't serialize
  on each other.

Test updated to reflect the new contract (List no longer mutates the
map; Sweep is what drops expired entries).

* mount: add peer chunk sharing options + advertise address resolver

First cut at the peer chunk sharing wiring on the mount side. No
functional behavior yet — this PR just introduces the option fields,
the -peer.* flags, and the helper that resolves a reachable
host:port from them. The server implementation arrives in PR #5
(gRPC service) and the fetcher in PR #7.

* ResolvePeerAdvertiseAddr: an explicit -peer.advertise wins; else we
  use -peer.listen's bind host if specific; else util.DetectedHostAddress
  combined with the port. This is what gets registered with the filer
  and announced to peers, so wildcard binds no longer result in
  unreachable identities like "[::]:18080".

* Option fields: PeerEnabled, PeerListen, PeerAdvertise, PeerRack.
  One port handles both directory RPCs and streaming chunk fetches
  (see PR #1 FetchChunk proto), so there is no second -peer.grpc.*
  flag — the old HTTP byte-transfer path is gone.

* New flags on weed mount: -peer.enable, -peer.listen (default :18080),
  -peer.advertise (default auto), -peer.rack.

* mount: register with filer and maintain HRW seed view

Adds the mount-side tier-1 client. On startup the mount calls
MountRegister with its advertise address (PR #3) and keeps both the
filer entry and the local seed view fresh via background tickers
(30 s register / 30 s list, 90 s filer TTL).

* peer_hrw.go: pure rendezvous-hashing helper picking a single owner
  per fid via top-1 HRW. Adding or removing one seed moves only
  ~1/N fids.

* peer_registrar.go: heartbeat + list poller. Seeds() returns the
  slice directly (no per-call copy) since listOnce atomically swaps;
  background RPCs bind their context to Stop() so unmount doesn't
  hang on a slow filer.

* WFS wiring uses ResolvePeerAdvertiseAddr from PR #3 for the
  identity registered with the filer. No HTTP server, no second
  port — one reachable address represents the mount.

* mount: broadcast MountRegister/MountList to every filer

Previously the registrar called through wfs.WithFilerClient, which only
reaches whichever filer the WFS filer-client session happens to be on.
That meant two mounts pointing at different filers would never see each
other: the filer mount registries are in-memory and per-filer (no
filer-to-filer sync), so each mount's MountList only returned peers
that had also registered through the same filer.

This commit makes the registrar multi-filer aware:

  * NewPeerRegistrar now takes the full FilerAddresses slice and a
    per-filer dial function. The old single-filer peerFilerClient
    interface is gone.

  * registerOnce fans a MountRegister RPC out to every filer in
    parallel. Succeeds if at least one filer accepted — an unreachable
    filer is tolerated, logged, and retried on the next heartbeat.

  * listOnce polls every filer's MountList in parallel and merges the
    responses by peer_addr, keeping the newest LastSeenNs on duplicates.
    Mounts talking to different filers therefore converge once every
    filer has been polled once.

The merged-list property is what lets a fleet of mounts spread across
multiple filers still form a single HRW seed view. Each filer only ever
sees the subset of mounts that heartbeat through it, but the registrar
reconstructs the union client-side.

New unit tests guard both properties:
  - RegisterBroadcastsToAllFilers: one registerOnce hits all N filers.
  - ListMergesAcrossFilers: mount-a on filer-1 and mount-b on filer-2
    both appear in the merged seed set.
  - ListMergeKeepsNewestLastSeen: the same mount reported by two
    filers collapses to one entry with the freshest timestamp.
2026-04-18 20:03:45 -07:00
Chris Lu af1e571297 peer chunk sharing 3/8: mount peer-serve HTTP endpoint (#9132)
* proto: define MountRegister/MountList and MountPeer service

Adds the wire types for peer chunk sharing between weed mount clients:

* filer.proto: MountRegister / MountList RPCs so each mount can heartbeat
  its peer-serve address into a filer-hosted registry, and refresh the
  list of peers. Tiny payload; the filer stores only O(fleet_size) state.

* mount_peer.proto (new): ChunkAnnounce / ChunkLookup RPCs for the
  mount-to-mount chunk directory. Each fid's directory entry lives on
  an HRW-assigned mount; announces and lookups route to that mount.

No behavior yet — later PRs wire the RPCs into the filer and mount.
See design-weed-mount-peer-chunk-sharing.md for the full design.

* filer: add mount-server registry behind -peer.registry.enable

Implements tier 1 of the peer chunk sharing design: an in-memory registry
of live weed mount servers, keyed by peer address, refreshed by
MountRegister heartbeats and served by MountList.

* weed/filer/peer_registry.go: thread-safe map with TTL eviction; lazy
  sweep on List plus a background sweeper goroutine for bounded memory.

* weed/server/filer_grpc_server_peer.go: MountRegister / MountList RPC
  handlers. When -peer.registry.enable is false (the default), both RPCs
  are silent no-ops so probing older filers is harmless.

* -peer.registry.enable flag on weed filer; FilerOption.PeerRegistryEnabled
  wires it through.

Phase 1 is single-filer (no cross-filer replication of the registry);
mounts that fail over to another filer will re-register on the next
heartbeat, so the registry self-heals within one TTL cycle.

Part of the peer-chunk-sharing design; no behavior change at runtime
until a later PR enables the flag on both filer and mount.

* filer: nil-safe peerRegistryEnable + registry hardening

Addresses review feedback on PR #9131.

* Fix: nil pointer deref in the mini cluster. FilerOptions instances
  constructed outside weed/command/filer.go (e.g. miniFilerOptions in
  mini.go) do not populate peerRegistryEnable, so dereferencing the
  pointer panics at Filer startup. Use the same
  `nil && deref` idiom already used for distributedLock / writebackCache.

* Hardening (gemini review): registry now enforces three invariants:
  - empty peer_addr is silently rejected (no client-controlled sentinel
    mass-inserts)
  - TTL is capped at 1 hour so a runaway client cannot pin entries
  - new-entry count is capped at 10000 to bound memory; renewals of
    existing entries are always honored, so a full registry still
    heartbeats its existing members correctly

Covered by new unit tests.

* filer: rename -peer.registry.enable flag to -mount.p2p

Per review feedback: the old name "peer.registry.enable" leaked
the implementation ("registry") into the CLI surface. "mount.p2p"
is shorter and describes what it actually controls — whether this
filer participates in mount-to-mount peer chunk sharing.

Flag renames (all three keep default=true, idle cost is near-zero):
  -peer.registry.enable        ->  -mount.p2p         (weed filer)
  -filer.peer.registry.enable  ->  -filer.mount.p2p   (weed mini, weed server)

Internal variable names (mountPeerRegistryEnable, MountPeerRegistry)
keep their longer form — they describe the component, not the knob.

* filer: MountList returns DataCenter + List uses RLock

Two review follow-ups on the mount peer registry:

* weed/server/filer_grpc_server_mount_peer.go: MountList was dropping
  the DataCenter on the wire. The whole point of carrying DC separately
  from Rack is letting the mount-side fetcher re-rank peers by the
  two-level locality hierarchy (same-rack > same-DC > cross-DC); without
  DC in the response every remote peer collapsed to "unknown locality."

* weed/filer/mount_peer_registry.go: List() was taking a write lock so
  it could lazy-delete expired entries inline. But MountList is a
  read-heavy RPC hit on every mount's 30 s refresh loop, and Sweep is
  already wired as the sole reclamation path (same pattern as the
  mount-side PeerDirectory). Switch List to RLock + filter, let Sweep
  do the map mutation, so concurrent MountList callers don't serialize
  on each other.

Test updated to reflect the new contract (List no longer mutates the
map; Sweep is what drops expired entries).

* mount: add peer chunk sharing options + advertise address resolver

First cut at the peer chunk sharing wiring on the mount side. No
functional behavior yet — this PR just introduces the option fields,
the -peer.* flags, and the helper that resolves a reachable
host:port from them. The server implementation arrives in PR #5
(gRPC service) and the fetcher in PR #7.

* ResolvePeerAdvertiseAddr: an explicit -peer.advertise wins; else we
  use -peer.listen's bind host if specific; else util.DetectedHostAddress
  combined with the port. This is what gets registered with the filer
  and announced to peers, so wildcard binds no longer result in
  unreachable identities like "[::]:18080".

* Option fields: PeerEnabled, PeerListen, PeerAdvertise, PeerRack.
  One port handles both directory RPCs and streaming chunk fetches
  (see PR #1 FetchChunk proto), so there is no second -peer.grpc.*
  flag — the old HTTP byte-transfer path is gone.

* New flags on weed mount: -peer.enable, -peer.listen (default :18080),
  -peer.advertise (default auto), -peer.rack.
2026-04-18 20:03:34 -07:00
Chris Lu e24a443b17 peer chunk sharing 2/8: filer mount registry (#9131)
* proto: define MountRegister/MountList and MountPeer service

Adds the wire types for peer chunk sharing between weed mount clients:

* filer.proto: MountRegister / MountList RPCs so each mount can heartbeat
  its peer-serve address into a filer-hosted registry, and refresh the
  list of peers. Tiny payload; the filer stores only O(fleet_size) state.

* mount_peer.proto (new): ChunkAnnounce / ChunkLookup RPCs for the
  mount-to-mount chunk directory. Each fid's directory entry lives on
  an HRW-assigned mount; announces and lookups route to that mount.

No behavior yet — later PRs wire the RPCs into the filer and mount.
See design-weed-mount-peer-chunk-sharing.md for the full design.

* filer: add mount-server registry behind -peer.registry.enable

Implements tier 1 of the peer chunk sharing design: an in-memory registry
of live weed mount servers, keyed by peer address, refreshed by
MountRegister heartbeats and served by MountList.

* weed/filer/peer_registry.go: thread-safe map with TTL eviction; lazy
  sweep on List plus a background sweeper goroutine for bounded memory.

* weed/server/filer_grpc_server_peer.go: MountRegister / MountList RPC
  handlers. When -peer.registry.enable is false (the default), both RPCs
  are silent no-ops so probing older filers is harmless.

* -peer.registry.enable flag on weed filer; FilerOption.PeerRegistryEnabled
  wires it through.

Phase 1 is single-filer (no cross-filer replication of the registry);
mounts that fail over to another filer will re-register on the next
heartbeat, so the registry self-heals within one TTL cycle.

Part of the peer-chunk-sharing design; no behavior change at runtime
until a later PR enables the flag on both filer and mount.

* filer: nil-safe peerRegistryEnable + registry hardening

Addresses review feedback on PR #9131.

* Fix: nil pointer deref in the mini cluster. FilerOptions instances
  constructed outside weed/command/filer.go (e.g. miniFilerOptions in
  mini.go) do not populate peerRegistryEnable, so dereferencing the
  pointer panics at Filer startup. Use the same
  `nil && deref` idiom already used for distributedLock / writebackCache.

* Hardening (gemini review): registry now enforces three invariants:
  - empty peer_addr is silently rejected (no client-controlled sentinel
    mass-inserts)
  - TTL is capped at 1 hour so a runaway client cannot pin entries
  - new-entry count is capped at 10000 to bound memory; renewals of
    existing entries are always honored, so a full registry still
    heartbeats its existing members correctly

Covered by new unit tests.

* filer: rename -peer.registry.enable flag to -mount.p2p

Per review feedback: the old name "peer.registry.enable" leaked
the implementation ("registry") into the CLI surface. "mount.p2p"
is shorter and describes what it actually controls — whether this
filer participates in mount-to-mount peer chunk sharing.

Flag renames (all three keep default=true, idle cost is near-zero):
  -peer.registry.enable        ->  -mount.p2p         (weed filer)
  -filer.peer.registry.enable  ->  -filer.mount.p2p   (weed mini, weed server)

Internal variable names (mountPeerRegistryEnable, MountPeerRegistry)
keep their longer form — they describe the component, not the knob.

* filer: MountList returns DataCenter + List uses RLock

Two review follow-ups on the mount peer registry:

* weed/server/filer_grpc_server_mount_peer.go: MountList was dropping
  the DataCenter on the wire. The whole point of carrying DC separately
  from Rack is letting the mount-side fetcher re-rank peers by the
  two-level locality hierarchy (same-rack > same-DC > cross-DC); without
  DC in the response every remote peer collapsed to "unknown locality."

* weed/filer/mount_peer_registry.go: List() was taking a write lock so
  it could lazy-delete expired entries inline. But MountList is a
  read-heavy RPC hit on every mount's 30 s refresh loop, and Sweep is
  already wired as the sole reclamation path (same pattern as the
  mount-side PeerDirectory). Switch List to RLock + filter, let Sweep
  do the map mutation, so concurrent MountList callers don't serialize
  on each other.

Test updated to reflect the new contract (List no longer mutates the
map; Sweep is what drops expired entries).
2026-04-18 20:03:23 -07:00
Chris Lu d7d834b8f9 peer chunk sharing 1/8: proto definitions (#9130)
proto: define MountRegister/MountList and MountPeer service

Adds the wire types for peer chunk sharing between weed mount clients:

* filer.proto: MountRegister / MountList RPCs so each mount can heartbeat
  its peer-serve address into a filer-hosted registry, and refresh the
  list of peers. Tiny payload; the filer stores only O(fleet_size) state.

* mount_peer.proto (new): ChunkAnnounce / ChunkLookup RPCs for the
  mount-to-mount chunk directory. Each fid's directory entry lives on
  an HRW-assigned mount; announces and lookups route to that mount.

No behavior yet — later PRs wire the RPCs into the filer and mount.
See design-weed-mount-peer-chunk-sharing.md for the full design.
2026-04-18 20:02:55 -07:00
Chris Lu 6787a4b4e8 fix kafka gateway and consumer group e2e flakes (#9129)
* fix(test): reduce kafka gateway and consumer group flakes

* fix(kafka): make broker health-check backoff respect context

Replace time.Sleep in the retry loop with a select on bc.ctx.Done() and
time.After so the backoff is interruptible during shutdown, per review
feedback on PR #9129.

* fix(kafka): guard broker HealthCheck against nil client

Return the same "broker client not connected" error used by the other
exported BrokerClient methods instead of panicking on a partially
initialized client, per CodeRabbit review feedback on PR #9129.
2026-04-18 10:03:24 -07:00
Chris Lu 6832b9945b ci(s3tests): install libxml2/libxslt dev headers before pip install
ceph/s3-tests pins lxml without an upper bound. When pip picks a release
whose prebuilt wheel isn't published for Python 3.9 on the runner, it
falls back to sdist and fails without libxml2-dev / libxslt1-dev.
2026-04-18 01:06:39 -07:00
Chris Lu 1c130c2d47 fix(mount): close inodeLocks cleanup race that let two flock holders coexist (#9128)
* fix(mount): close inodeLocks cleanup race that allowed two flock holders

PosixLockTable.getOrCreateInodeLocks released plt.mu before the caller
acquired il.mu. A concurrent maybeCleanupInode could delete the map
entry in that window; the first caller would then insert its lock into
the orphaned inodeLocks while a later caller created a fresh entry in
the map, so findConflict never observed the orphaned lock and two
owners could simultaneously believe they held the same exclusive flock.

This matches the flaky CI failure seen in
TestPosixFileLocking/ConcurrentLockContention:

    Error: Should be empty, but was [worker N: flock overlap detected with 2 holders]

Mark removed inodeLocks as dead under plt.mu+il.mu, and have SetLk /
SetLkw recheck the flag after locking il.mu, refetching the live entry
from the map when orphaned. Also delete the map entry only if it still
points to this il, so a racing recreate is not clobbered.

Adds TestConcurrentFlockChurnPreservesMutualExclusion: 16 goroutines x
500 flock/unflock iterations on one inode. Reliably reports 500+
overlaps per run before the fix; clean across 100 race-enabled runs
after.

* fix(mount): extend dead-flag contract to GetLk and self-heal primitives

Address review feedback on the initial cleanup-race fix:

1. GetLk had the same stale-pointer bug as SetLk. A caller could grab
   an inodeLocks pointer, have cleanup orphan it and a replacement il
   receive a conflicting lock, then answer F_UNLCK off the empty dead
   pointer. Add the same dead recheck + refetch loop.

2. getOrCreateInodeLocks and getInodeLocks now treat a dead map entry
   as defective: the former replaces it with a fresh inodeLocks, the
   latter drops it and returns nil. Production cannot reach that state
   (maybeCleanupInode atomically deletes under plt.mu when it sets
   dead), but the hardening guarantees the SetLk / SetLkw / GetLk
   retry loops always make progress even if a future refactor reorders
   those operations, and it lets the white-box tests set up a stale
   dead entry without spinning.

3. Strengthen the regression suite:
   - TestSetLkRetriesPastDeadInodeLocks: deterministic white-box test
     that installs a dead il in the map and asserts SetLk routes the
     new lock into a fresh il (not the orphan), that GetLk reports the
     resulting conflict, and that a different-owner acquire is rejected
     with EAGAIN.
   - TestGetInodeLocksEvictsDeadEntry: verifies both map-read primitives
     drop or replace dead entries.
   - TestConcurrentFlockChurnPreservesMutualExclusion: replace the
     timing-fragile Add(1)-and-check counter with a Swap+CAS detector.
     Each worker claims a slot after SetLk OK and releases it before
     UN, flagging both an observed predecessor and a lost CAS on
     release. Against a reverted fix the detector fires 1000+ times per
     run; with the fix clean across 100 race-enabled iterations.

* test(mount): fail fast on unexpected SetLk statuses in churn loop

The stress test blindly spun on any non-OK SetLk status and discarded
the unlock return. If SetLk ever returns something other than OK or
EAGAIN (e.g. after a future refactor introduces a new error), the
acquire loop would spin forever and an unlock failure would be
silently swallowed.

Capture the acquire status, retry only on the expected EAGAIN, and
assert unlock returns OK. Use t.Errorf + return (not t.Fatalf) because
the checks run on worker goroutines where FailNow is unsafe. The
Swap+CAS overlap detector is unchanged.
2026-04-17 23:12:26 -07:00
Chris Lu c1ccbe97dd feat(filer.backup): -initialSnapshot seeds destination from live tree (#9126)
* feat(filer.backup): -initialSnapshot seeds destination from live tree

Replaying the metadata event log on a fresh sync only leaves files that
still exist on the source at replay time: any entry that was created and
later deleted is replayed as a create/delete pair and never materializes
on the destination. Users who wipe the destination and re-run
filer.backup therefore see "only new files" instead of a full backup,
even when -timeAgo=876000h is passed and the subscription genuinely
starts from epoch (ref discussion #8672).

Add a -initialSnapshot opt-in flag: when set on a fresh sync (no prior
checkpoint, -timeAgo unset), walk the live filer tree under -filerPath
via TraverseBfs and seed the destination through sink.CreateEntry, then
persist the walk-start timestamp as the checkpoint and subscribe from
there. Capturing the timestamp before the walk lets the subscription
catch any create/update/delete racing with the walk — sink CreateEntry
is idempotent across the builtin sinks so replay is safe.

Honors existing -filerExcludePaths / -filerExcludeFileNames /
-filerExcludePathPatterns filters and skips /topics/.system/log the
same way the subscription path does.

Also log "starting from <t> (no prior checkpoint)" instead of a
misleading "resuming from 1970-01-01" when the KV has no stored offset.

* fix(filer.backup): guard initialSnapshot counters under TraverseBfs workers

TraverseBfs fans the callback out across 5 worker goroutines, so the
entryCount / byteCount updates and the 5-second progress-log gate in
runInitialSnapshot were racing. Switch the counters to atomic.Int64 and
protect the lastLog check/update with a short-scoped mutex so the heavy
sink.CreateEntry call stays outside the critical section.

Flagged by gemini-code-assist on #9126; verified with go test -race.

* fix(filer.backup): harden initialSnapshot against transient errors and path edge cases

Three review items from CodeRabbit on #9126:

1. getOffset errors no longer leave isFreshSync=true. Before, a transient
   KV read failure would cause runFilerBackup's retry loop to redo the
   full -initialSnapshot walk on every retry. Treat any offset-read
   error as "not fresh" so the snapshot only runs when we've verified
   there really is no prior checkpoint.

2. initialSnapshotTargetKey now normalizes sourcePath to a trailing-
   slash base before stripping the prefix, so edge cases where
   sourceKey equals sourcePath (trailing-slash mismatch or root-entry
   emission) no longer index past the end. Unit tests cover both
   forms.

3. Documented the TraverseBfs-enumerates-excluded-subtrees performance
   characteristic on runInitialSnapshot, since pruning requires a
   separate change to TraverseBfs itself.

* fix(filer.backup): retry setOffset after initialSnapshot to avoid full re-walks

If the snapshot walk finishes but the subsequent setOffset fails, the
retry loop in runFilerBackup will re-enter doFilerBackup with an empty
checkpoint and run the full BFS again — on a multi-million-entry tree
that's hours of wasted work over a 100-byte KV write. Retry the write a
handful of times with exponential backoff before giving up, and log
loudly at the final failure (with snapshotTsNs + sinkId) so operators
recognize the symptom instead of guessing at mysterious repeated walks.

Nitpick raised by CodeRabbit on #9126.

* fix(filer.backup): initialSnapshot ignore404, skew margin, exclude dir-entry itself

Three review items from CodeRabbit on #9126:

1. ignore404Error now threads into runInitialSnapshot. If a file is listed
   by TraverseBfs and then deleted before CreateEntry reads its chunks,
   the follow path already ignores 404s — the snapshot path was aborting
   and triggering a full re-walk. Treat an ignorable 404 as "skip this
   entry, continue."

2. snapshotTsNs now uses `time.Now() - 1min` instead of `time.Now()`.
   Metadata events are stamped server-side, so a fast backup-host clock
   could skip events that fire during or right after the walk. Matches
   the 1-minute margin meta_aggregator.go applies on initial peer
   traversal; duplicate replay is harmless because CreateEntry is
   idempotent.

3. Exclude checks now run against the entry's own full path, not just
   its parent. A walked directory whose full path matches SystemLogDir
   or -filerExcludePaths was being seeded to the destination; only its
   descendants were being skipped. Verified with a manual repro where
   -filerExcludePaths=/data/skipdir now keeps the skipdir entry itself
   off the destination.

* refactor(filer): share destKey helper between buildKey and initialSnapshot

Extract destKey(dataSink, targetPath, sourcePath, sourceKey, mTime) from
buildKey in filer_sync.go. Both the event-log path (buildKey) and the
initialSnapshot walk (initialSnapshotTargetKey) now go through the same
helper, so a walk-seeded file and an event-replayed file always resolve
to the same destination key.

As a bonus, buildKey picks up the defensive trailing-slash normalization
that initialSnapshotTargetKey introduced — no more index-past-end risk
when sourceKey happens to equal sourcePath. Also tightens the mTime
lookup to guard against nil Attributes (caught by an existing test
against buildKey when I first moved the lookup out of the incremental
branch).
2026-04-17 21:21:32 -07:00
Chris Lu d57fc67022 fix(shell): fs.mergeVolumes now rewrites manifest chunks for large files (#9127)
* fix(shell): fs.mergeVolumes now rewrites manifest chunks for large files

Previously fs.mergeVolumes skipped any chunk whose IsChunkManifest flag was
true, printing "Change volume id for large file is not implemented yet" and
continuing. Because the BFS traversal only looks at top-level
entry.Chunks, sub-chunks referenced inside a manifest were never
considered either. For any file stored as a chunk manifest (large files
go this path), chunks in the source volume stayed put, leaving behind a
few MB of live data that vacuum and volume.deleteEmpty couldn't clean
up.

This change resolves each manifest chunk recursively, moves any
sub-chunk whose volume id is in the merge plan via the existing
moveChunk path, and re-serializes the manifest. If the manifest chunk
itself lives in a source volume, or any sub-chunk moved, the new
manifest blob is uploaded to a freshly assigned file id (the old
needle becomes orphaned and is reclaimed by vacuum like any other
moved chunk).

Fixes #9116.

* address review: batch UpdateEntry, fix dry-run, defer restore, avoid source volumes

- Call UpdateEntry once per entry after the chunk loop instead of once per
  moved chunk (gemini nit).
- In dry-run mode, mark anySubChanged when a sub-chunk in the plan is
  encountered and return changed=true after printing "rewrite manifest",
  so nested manifests also surface their would-rewrites (gemini nit).
- Defer filer_pb.AfterEntryDeserialization so the manifest chunk list is
  restored even when proto.Marshal fails (coderabbit nit).
- Reject AssignVolume results whose file id lands on a volume that is a
  source in the merge plan, and retry — otherwise the replacement
  manifest could be written to the volume being emptied (coderabbit).
2026-04-17 21:17:51 -07:00
Jaehoon KimandChris Lu 96af27a131 feat(shell): add fs.distributeChunks command for even chunk distribution (#9117)
* feat(shell): add fs.distributeChunks command for even chunk distribution

Add a new weed shell command that redistributes a file's chunks evenly
across volume server nodes.

Supports three distribution modes via -mode flag:
- primary:     balance chunk ownership across nodes (default)
- replica:     balance both ownership and replica copies
- round-robin: assign chunks by offset order for sequential read
               optimization (chunk[0]->A, chunk[1]->B, chunk[2]->C, ...)

Additional options:
- -nodes=N to target specific number of nodes
- -apply to execute (dry-run by default)

Usage:
  fs.distributeChunks -path=/buckets/file.dat
  fs.distributeChunks -path=/buckets/file.dat -mode=round-robin -apply
  fs.distributeChunks -path=/buckets/file.dat -mode=replica -apply
  fs.distributeChunks -path=/buckets/file.dat -nodes=5 -apply

* fix(shell): improve fs.distributeChunks robustness and code quality

- Propagate flag parse errors instead of swallowing them (return err)
- Handle nil chunk.Fid by falling back to legacy FileId string parsing
- Simplify node membership check using slices.Contains

* fix(shell): fix dead round-robin print loop in fs.distributeChunks

The loop was computing targetNode with sc.index%totalNodes (original
chunk index) instead of the sequential position, and discarding it via
_ = targetNode without printing anything. Replace with a correct loop
using pos%totalNodes and actually print the first 12 node assignments.

* fix(shell): compute replication/collection per-chunk in fs.distributeChunks

Previously replication and collection were derived once from chunks[0]
and reused for all moves, causing wrong volume placement for chunks
belonging to different volumes or collections. Now each chunk looks up
its own volumeInfoMap entry immediately before calling operation.Assign.

* fix(shell): prefer assignResult.Auth JWT over local signing key in fs.distributeChunks

When the master returns an Auth token in the Assign response, use it
directly for the upload instead of generating a new JWT from the local
viper signing key. Fall back to local key generation only when Auth is
empty, matching the pattern used by other upload paths.

* fix(shell): add timeout and error handling to delete requests in fs.distributeChunks

The delete loop was ignoring http.NewRequest errors and had no timeout,
risking a nil-request panic or indefinite block. Replace with
http.NewRequestWithContext and a 30s timeout, handle request creation
errors by incrementing deleteFailCount, and cancel the context
immediately after Do returns.

* feat(shell): parallelize chunk moves in fs.distributeChunks using ErrorWaitGroup

Sequential chunk moves are a bottleneck for large LLM model files with
hundreds or thousands of chunks. Use ErrorWaitGroup with
DefaultMaxParallelization (10) to run download/assign/upload concurrently.
Guard movedRecords appends, chunk.Fid updates, and writer output with a
mutex. Individual chunk failures are non-fatal and logged inline; only
successfully moved chunks are included in the metadata update.

* fix(shell): try all replica URLs on download in fs.distributeChunks

Previously only the first volume server URL was attempted, causing chunk
moves to fail if that replica was unreachable. Now iterates through all
URLs returned by LookupVolumeServerUrl and stops at the first success.

* refactor(shell): apply extract method pattern to fs.distributeChunks

Do() was a single ~615-line function. Break it into focused helpers:
- lookupFileEntry: filer entry lookup
- validateChunks: chunk manifest guard
- collectVolumeTopology: master topology query + ownership mapping
- buildDistributionCounts: chunk→node mapping and owner/copy tallies
- selectActiveNodes: target node selection
- printCurrentDistribution: per-node distribution table
- planDistribution: mode-switch planning (primary/replica/round-robin)
- printRedistributionPlan: before/after plan table
- relevantNodes: active-or-occupied node filter

Do() is now ~100 lines of orchestration; each helper has a single
clear responsibility.

* test(shell): add unit tests for fs.distributeChunks algorithms

Cover all three distribution modes and supporting helpers:
- shortName, relevantNodes
- computeOwnerTarget (even/uneven split, inactive node drain)
- buildDistributionCounts (normal + nil Fid fallback)
- selectActiveNodes (all nodes / limited count)
- planOwnerMoves (imbalanced → balanced, already balanced)
- planDistribution primary (chunks balanced, no-op when even)
- planDistribution round-robin (offset ordering, correct assignment)
- planDistribution replica (owner + copy balancing)
- printRedistributionPlan (output format)

* fix(shell): add 5-minute timeout to chunk downloads in fs.distributeChunks

Download requests had no per-request timeout, unlike delete operations
which already use 30s. Replace readUrl() calls with inline
http.NewRequestWithContext + context.WithTimeout(5m) so a hung volume
server cannot block a goroutine indefinitely during redistribution.

* fix(shell): remove redundant deleteOldChunks in fs.distributeChunks

filer.UpdateEntry already calls deleteChunksIfNotNew internally, which
computes the diff between old and new entry chunks and deletes the ones
no longer referenced. Our explicit deleteOldChunks was racing with this
filer-side cleanup, causing spurious 404 warnings on ~75% of deletes.

Remove deleteOldChunks, movedChunkRecord type, and reduce
executeChunkMoves return type to (int, error) for the moved count.

* fix(shell): handle nil chunk.Fid via chunkVolumeId helper in fs.distributeChunks

chunk.Fid.GetVolumeId() silently returns 0 for legacy chunks stored with
a FileId string instead of a Fid struct, causing them to be skipped in
the replica balancing loop and looked up incorrectly in volumeInfoMap.

Introduce chunkVolumeId() that uses Fid when present and falls back to
parsing the legacy FileId string, matching the logic in
buildDistributionCounts. Apply it in the replica-mode copies loop and
in executeChunkMoves' replication/collection lookup.

* fix(shell): use already-parsed oldFid for volumeInfoMap lookup in fs.distributeChunks

chunkVolumeId(chunk) was being called to look up replication/collection
after oldFid had already been parsed and validated. Use oldFid.VolumeId
directly to avoid redundant parsing and guarantee the correct volume ID
regardless of whether chunk.Fid is nil.

* fix(shell): improve correctness and robustness in fs.distributeChunks

- Buffer download body before upload so dlCtx timeout only covers the
  GET request; upload runs with context.Background() via bytes.NewReader
- Replace 'before, after := strings.Cut(...)' + '_ = before' with '_'
  as the first return value directly
- Clone copiesCount before replica planner mutates it, keeping the
  caller's map immutable
- Add nil-entry guard after filer LookupEntry to prevent panic on
  unexpected nil response

* feat(shell): support chunk manifests in fs.distributeChunks

Large files stored as chunk manifests were previously rejected. Resolve
manifests up front via filer.ResolveChunkManifest, redistribute the
underlying data chunks, then re-pack through filer.MaybeManifestize
before UpdateEntry. The filer's MinusChunks resolves manifests on both
sides of the diff, so old manifest and inner data chunks are GC'd
automatically.

* fix(shell): match master's SaveDataAsChunkFunctionType 5-param signature

Master added expectedDataSize uint64; ignore it in shell-side saveAsChunk.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-04-17 21:09:36 -07:00
Lisandro PinandLisandro Pin 6bcacedda9 Export master_disconnections metrics on volume servers. (#9104)
This allows to track connection issues and master failovers in real time via Prometheus metrics.

Co-authored-by: Lisandro Pin <lisandro.pin@proton.ch>
2026-04-17 15:15:26 -07:00
Chris Lu 0315da9022 fix(s3api): self-heal stale .versions latest-version pointer on read (#9125)
* fix(s3api): self-heal stale .versions latest-version pointer on read

When the `.versions` directory metadata points at a version file that has
gone missing (e.g. a crash between deleting the latest version and
rewriting the pointer, or a concurrent delete racing with a read),
`getLatestObjectVersion` bailed with a hard error that required manual
repair. Tagging, ACL, retention, copy-source, and HEAD/GET all surfaced
NoSuchKey even though other versions remained on disk.

On `ErrNotFound`/`codes.NotFound` from the pointed-at version lookup,
rescan the `.versions` directory, pick the newest remaining non-delete-
marker entry, persist the repaired pointer (best-effort), and return
that entry. If only delete markers (or nothing) remain, the caller still
sees an error and the object correctly appears absent.

Extracted the selection logic into a pure `selectLatestContentVersion`
helper so `updateLatestVersionAfterDeletion` and the new self-heal path
share a single implementation. A warning is logged whenever the heal
kicks in so stale-pointer incidents remain visible in operator logs.

* fix(s3api): self-heal must promote newest version even if delete marker

Review feedback (gemini-code-assist): the self-heal path used
`selectLatestContentVersion`, which skips delete markers. That had two
bugs:

1. If the chronologically newest entry was a delete marker, an older
   content version would be promoted, effectively "undeleting" an
   object that was actually deleted.
2. If only delete markers remained, heal returned an error and the
   caller surfaced a hard 500 instead of the correct 404-with-
   x-amz-delete-marker response.

Add `selectLatestVersion` that picks the newest entry regardless of
type (content or delete marker) and use it in
`healStaleLatestVersionPointer`. The promoted entry flows back through
`doGetLatestObjectVersion` unchanged; downstream handlers already
detect `ExtDeleteMarkerKey` on the returned entry and render
NoSuchKey + `x-amz-delete-marker: true` (see
`s3api_object_handlers.go:722-728`).

Kept `selectLatestContentVersion` in place for
`updateLatestVersionAfterDeletion`, which deliberately limits the
pointer to a live content version in the post-deletion flow — changing
that is out of scope for this fix.

Added four tests for the new selector:
- promotes newest delete marker over older content (the reviewer case)
- picks content when content is newest
- promotes newest delete marker when only delete markers remain
- returns nil latestEntry on empty/untagged input

* fix(s3api): paginate .versions scan in self-heal path

Review feedback (gemini-code-assist, coderabbitai): the self-heal rescan
did a single-shot list(..., 1000). For objects whose version ids use the
old raw-timestamp format, filer ordering is lexicographic-ascending =
oldest-first. If the .versions directory held more than one page of
entries, the first page contained only the oldest, and the heal would
promote an older version as the new "latest" — silently surfacing stale
data on subsequent reads.

Paginate through the whole directory with `filer.PaginationSize`,
running `selectLatestVersion` per page and keeping a single running
best candidate across pages (via `compareVersionIds`). This mirrors the
pagination pattern already used by `getObjectVersionList` in the same
file and closes the window for old-format stacks larger than one page.

New-format (inverted-timestamp) ids were not affected because their
lexicographic order matches newest-first, but paginating is still the
right fix.

Also updated the function doc to reflect that self-heal now promotes
the newest entry regardless of type (content version or delete marker).

* fix(s3api): don't resurrect deleted objects; wrap ErrNotFound sentinel

Two review findings addressed:

1. `updateLatestVersionAfterDeletion` was using `selectLatestContentVersion`
   which skipped delete markers. Scenario: PUT v1, DELETE (dm1 written,
   pointer->dm1), PUT v3 (pointer->v3), user explicitly deletes v3 by
   versionId. Remaining files: v1, dm1. S3 semantics say the current
   version is the chronologically newest = dm1 (object appears deleted).
   Old code would promote v1, "undeleting" the object silently.

   Switched to `selectLatestVersion`, which picks the newest entry
   regardless of type. Also paginated the scan the same way the self-heal
   path does — otherwise a single-page `list(1000)` still mis-selects the
   latest for old-format version id stacks that exceed one page.

   Removed the `hasDeleteMarkers || !isLast` branch: with `selectLatestVersion`
   any delete marker participates in the comparison and shows up as the
   latest when it is newest, so the "keep the directory on ambiguity"
   guard becomes unreachable. Full pagination also makes the `!isLast`
   guard unnecessary — we either see every entry or surface a list error.

2. `healStaleLatestVersionPointer`'s "no remaining version" error was a
   plain `fmt.Errorf`, so callers could not distinguish genuine
   object-absence from a scan failure via `errors.Is`. Wrap it with
   `filer_pb.ErrNotFound` so the sentinel flows through the chain (the
   outer wrap already uses `%w`).

No test additions needed — `TestSelectLatestVersion_PromotesNewestDeleteMarker`
already asserts the "newer delete marker beats older content" invariant
that drives both fixes.

* refactor(s3api): drop unused selectLatestContentVersion after review

Review feedback flagged a stale comment claiming
selectLatestContentVersion "mirrors" the post-deletion semantics of
updateLatestVersionAfterDeletion. That claim became false when the
post-deletion path switched to selectLatestVersion in the previous
commit. Verified no production callers remain — only the helper's own
tests referenced it — so the cleaner fix is to delete the dead code
rather than rewrite the comment to explain "this exists but isn't
used."

- Removed selectLatestContentVersion.
- Removed the four TestSelectLatestContentVersion_* tests.
- Preserved a renamed TestSelectLatestVersion_MixedFormats so the
  mixed-format comparator coverage still runs against the active
  selector.
2026-04-17 14:57:59 -07:00
Chris Lu bfea14320a fix(s3): reject unknown POST policy conditions and extra x-amz form fields (#9124)
* fix(s3): reject unknown POST policy conditions and extra x-amz form fields

CheckPostPolicy previously accepted policy conditions with unknown $keys
(e.g. "$foo") as satisfied, and only rejected stray X-Amz-Meta-* form
fields. Reject unknown condition keys outright, and extend the extra-
input-fields check to all X-Amz-* form fields except the reserved
auth/signing headers. Matches AWS S3 POST Object behavior.

* refactor(s3): drop redundant $x-amz-meta- prefix check in CheckPostPolicy

The $x-amz- prefix already subsumes $x-amz-meta-, so the explicit
$x-amz-meta- check adds no coverage. Simplify the else-if condition.
Addresses gemini-code-assist review on PR #9124.

* style(s3): align unknown-key policy error with [op, key, value] trailer

Reformat the unknown-condition-key error in CheckPostPolicy to include
the same "[op, key, value]" trailer used by the other condition-failed
messages. The value slot is empty because no comparison occurs for an
unknown key. The descriptive "unknown condition key" suffix is kept so
operators can still tell this failure from a mismatched value.

* fix(s3): honor starts-with prefix-stem POST policies when checking extras

AWS POST policies use ["starts-with","$x-amz-meta-",""] to allow any
X-Amz-Meta-* form field. The previous exact-match policyXAmzKeys would
flag every X-Amz-Meta-Foo as an "Extra input fields" failure because
only the stem X-Amz-Meta- was stored. Track starts-with conditions whose
key ends in "-" with an empty value as prefix stems, and accept any
X-Amz-* form field matching one of those stems.

* fix(s3): validate value prefix for starts-with POST policy stems

Drop the policy.Value == "" gate when detecting prefix-stem conditions
so that ["starts-with","$x-amz-meta-","pfx-"] is recognized as a prefix
rule. Track the required value prefix alongside the name prefix, enforce
it against every matching form field in the extras loop, and skip the
prefix-stem condition in the main iteration (it has no single form
field to evaluate). Also include policy.Value in the unknown-condition
error trailer for clearer debugging. Addresses gemini-code-assist
review on PR #9124.

* fix(s3): check every matching POST policy rule, not just the first

The extras loop exited early on exact-key match and broke on the first
matching prefix stem. Per AWS, a form field must satisfy every policy
condition that applies to it, so an exact-match field must still honor
any overlapping starts-with stem's value prefix, and multiple stems on
the same field must all hold. Drop both early exits: start matched from
the exact-key lookup, iterate all prefix stems, and fail on the first
value-prefix violation. Addresses gemini-code-assist review on PR
#9124.
2026-04-17 14:55:12 -07:00
Chris Lu 0bddc2652e fix(s3): propagate validated POST form fields to upload headers (#9123)
* fix(s3): propagate validated POST form fields to upload headers

POST Object form fields like acl, Content-Encoding, x-amz-storage-class,
x-amz-tagging, and x-amz-server-side-encryption were validated against
the POST policy but never forwarded to the underlying PUT, so the
validated values had no effect. Forward all non-reserved x-amz-* fields
plus acl (as x-amz-acl) and Content-Encoding. Reserved POST policy
mechanism fields (Policy, Signature, Key, etc.) are still excluded.

* fix(s3): also forward Content-Language from POST form to upload headers

AWS S3 POST Object supports Content-Language; add it to the set of
content headers forwarded by applyPostPolicyFormHeaders alongside
Cache-Control, Expires, Content-Disposition, and Content-Encoding.
Addresses gemini-code-assist review on PR #9123.

* refactor(s3): only look up form value in branches that use it

applyPostPolicyFormHeaders previously called formValues.Get(k) for every
form field, including fields that fall through the switch (non-reserved
fields that are neither Acl, a forwarded content header, nor X-Amz-*).
Move the lookup inside the switch cases that actually use it.
2026-04-17 14:55:06 -07:00
Chris Lu 2da24cc230 fix(s3): return 403 on POST policy violation instead of 307 redirect (#9122)
* fix(s3): return 403 on POST policy violation instead of 307 redirect

CheckPostPolicy failures previously responded with HTTP 307 Temporary
Redirect to the request URL, which causes clients to re-POST and
obscures the failure. Return 403 AccessDenied so the client surfaces
the error.

* test(s3): exercise PostPolicyBucketHandler end-to-end for 403 mapping

Replace the shallow ErrAccessDenied tautology test with one that builds
a signed POST multipart request whose policy conditions cannot be
satisfied, calls PostPolicyBucketHandler directly, and asserts HTTP 403
with no Location redirect header. Addresses gemini-code-assist review on
PR #9122.

* fix(s3): surface POST policy failure reason in AccessDenied response

Add s3err.WriteErrorResponseWithMessage so a caller can keep the
standard error code mapping while providing a specific Message. Use it
from PostPolicyBucketHandler so the XML body carries the CheckPostPolicy
error (e.g. which condition failed or that the policy expired) rather
than the generic "Access Denied." description. Addresses gemini-code-
assist review on PR #9122.

* refactor(s3err): delegate WriteErrorResponse to WriteErrorResponseWithMessage

The two helpers shared every line except the Message override. Fold
WriteErrorResponse into a one-line delegation that passes an empty
message, so the request-id/mux/apiError logic lives in exactly one
place. Addresses gemini-code-assist review on PR #9122.
2026-04-17 14:54:58 -07:00
Chris Lu 32cbed9658 fix(fuse-tests): avoid ephemeral port reuse racing weed mini bind
freePort allocated in [20000, 55535], which overlaps the Linux ephemeral
range (32768-60999). The kernel could reuse the chosen port for an
outbound connection between the test closing its listener and weed mini
re-checking availability, causing:

  Port allocation failed: port N for Filer (specified by flag
  filer.port) is not available on 0.0.0.0 and cannot be used

Narrow the range to [20000, 32000] to stay below the ephemeral floor,
and pass -ip.bind=127.0.0.1 so mini's pre-check runs on the same IP the
test actually reserved the port on.
2026-04-17 13:47:17 -07:00
Chris Lu cce98fcecf fix(s3): strip client-supplied X-SeaweedFS-Principal/Session-Token in AuthSignatureOnly (#9120)
* fix(s3): strip client-supplied X-SeaweedFS-Principal/Session-Token in AuthSignatureOnly

AuthSignatureOnly is the only auth gate in front of S3Tables routes
(incl. CreateTableBucket) and UnifiedPostHandler, but unlike
authenticateRequestInternal it did not clear the internal IAM
trust headers before running signature verification. S3Tables
authorizeIAMAction reads X-SeaweedFS-Principal directly from the
request and prefers it over the authenticated identity's PrincipalArn,
so a signed low-privilege caller could append that header after signing
(unsigned header, SigV4 still verifies) and have IAM policy evaluated
against a spoofed principal, bypassing authorization.

Clear both X-SeaweedFS-Principal and X-SeaweedFS-Session-Token at the
top of AuthSignatureOnly, mirroring the existing guard in
authenticateRequestInternal. Add a regression test covering the
header-injection path.

* refactor(s3): route AuthSignatureOnly through authenticateRequestInternal

Addresses review feedback: both entry points were independently
maintaining the internal-IAM-header stripping and the auth-type dispatch
switch. Collapse AuthSignatureOnly into a thin wrapper around
authenticateRequestInternal so the security-critical header scrub and
the signature-verify switch live in one place. Post-auth behavior
unique to AuthSignatureOnly (AmzAccountId header) stays inline.

No functional change beyond two harmless telemetry tweaks that now
match authenticateRequestInternal: the per-branch glog verbosity shifts
from V(3) to V(4), and the anonymous-found path now sets AmzAuthType.

* refactor(s3): centralize X-SeaweedFS-Principal/Session-Token header names

Introduce SeaweedFSPrincipalHeader and SeaweedFSSessionTokenHeader in
weed/s3api/s3_constants so the trust-header literals are defined once and
referenced consistently by the auth scrub, JWT auth path, bucket policy
principal resolution, IAM authorization, and S3Tables IAM evaluation.
Replace every remaining usage in weed/s3api and weed/s3api/s3tables.
This removes the drift risk the reviewer called out: adding another call
site with a typo can no longer silently bypass the scrub.

Pure rename, no behavior change. No-op integration-test helper in
test/s3/iam/s3_iam_framework.go left untouched (separate module, and the
server now strips the client-supplied value regardless).
2026-04-17 12:23:21 -07:00
Chris Lu 88ac2d0431 security(s3api): reject unsigned x-amz-* headers in SigV4 requests (#9121)
A presigned URL holder could attach arbitrary x-amz-* headers to a PUT
request (e.g. x-amz-tagging, x-amz-acl, x-amz-storage-class,
x-amz-server-side-encryption*, x-amz-object-lock-*, x-amz-meta-*,
x-amz-website-redirect-location, x-amz-grant-*). Because only the
headers declared in SignedHeaders participate in signature
verification, the added headers bypass authentication; the PUT handler
then persists them into the object's Extended metadata.

Match the AWS SigV4 rule: every x-amz-* header present in the request
must appear in SignedHeaders. Exempt x-amz-content-sha256 (already
tamper-protected via the canonical request's payload-hash line) and,
for presigned URLs, the SigV4 protocol parameters that live in the
query string (X-Amz-Algorithm/Credential/Date/Expires/SignedHeaders/
Signature) in case they are duplicated as headers.

Applies to both header-based and presigned SigV4; non-amz headers are
unaffected.
2026-04-17 12:20:28 -07:00
Chris Lu e8767f42b6 Add security policy for vulnerability reporting 2026-04-17 09:51:21 -07:00
Chris Lu f720f559cb ci(kafka-loadtest): switch off Ubuntu/Debian base images to avoid apt mirror flakes (#9119)
* ci(kafka-loadtest): retry apt-get to survive Ubuntu mirror flakes

The Kafka Quick Test workflow's Docker build of Dockerfile.loadtest
keeps hitting "Connection failed [IP: ...]" on archive.ubuntu.com /
security.ubuntu.com mid-build, e.g.:

    failed to solve: process "/bin/sh -c apt-get update && \
      apt-get install -y ca-certificates curl jq bash netcat ..."
      did not complete successfully: exit code: 100

Same class of failure PR #9106 fixed for pjdfstest. Apply the same
two retry knobs to Dockerfile.loadtest and Dockerfile.seektest so a
transient mirror flake retries five times with a 30s timeout instead
of failing the whole workflow.

(The fuller pjdfstest fix also restructured the build to use
docker/build-push-action with type=gha cache. Doing that for
kafka-client-loadtest would mean rewriting the make/docker-compose
build path; defer until the apt-retry alone proves insufficient.)

* ci(kafka-loadtest): also drop recommends/suggests + apt-get clean

Address PR review (gemini-code-assist): fully align with PR #9106's
pattern by adding --no-install-recommends / --no-install-suggests so
the runtime images stay small and don't pull in extra packages, plus
apt-get clean before rm -rf /var/lib/apt/lists/* in Dockerfile.seektest.

* ci(kafka-loadtest): use alpine / maven base images instead of apt

The previous rounds of apt-retry / apt-clean knobs aren't enough:
the Ubuntu mirror is persistently unreachable from the GitHub runner
for minutes at a time, which blows past the 5-retry / 30-second
Acquire configuration and still kills the build (see run 24551809614).

Switch both runtime images so no apt fetch is needed at all:

- Dockerfile.loadtest now runs on alpine:3.20. All runtime deps
  (ca-certificates, curl, jq, bash, netcat-openbsd) are in the
  Alpine main repo, fetched from Alpine's CDN rather than the
  Ubuntu archive that keeps going dark.
- Dockerfile.seektest now uses maven:3.9-eclipse-temurin-11, which
  ships JDK 11 and Maven preinstalled — no apt-get maven step.

This also means the runtime images no longer care about
Acquire::Retries / DEBIAN_FRONTEND / apt-get clean, so those lines
are removed with the apt call they were configuring.
2026-04-17 07:43:19 -07:00
Chris Lu 45578a42e9 fix(volume): keep vacuum running past dangling .idx entries (#9115)
* fix(volume): keep vacuum running past dangling .idx entries

Vacuum compaction aborted entirely on the first .idx entry whose offset
pointed past the end of the .dat file, surfacing as `cannot hydrate
needle from file: EOF` and stalling progress on every other volume.

In both Go and Rust:

- During compaction, skip an unreadable needle and continue. The bytes
  it pointed at were already unreachable via reads, so dropping the
  index reference makes the post-vacuum volume consistent. Real EIO
  still bails out so a disk fault is not silently papered over.

- At volume load, do a single linear scan of the .idx and confirm
  every (offset + actual size) fits inside .dat. The pre-existing
  integrity check only looked at the last 10 entries, so deeper
  corruption (e.g. left over from a crashed batched write) went
  undetected and only surfaced later as a vacuum EOF. A failure now
  marks the volume read-only at load time so an operator can react.

Refs #8928

* fix(volume): only skip permanent-corruption needle reads during vacuum

Address PR review feedback (gemini-code-assist + coderabbit):

The original patch skipped any non-EIO read failure, which would silently
drop needles on transient errors — Windows hardware bad-sector errors
(ERROR_CRC etc.) never surface as syscall.EIO; tiered-storage network
timeouts and EROFS would also slip through and shrink the volume.

Switch to an explicit whitelist of permanent-corruption shapes:

- Add needle.ErrorCorrupted sentinel and wrap CRC and "index out of
  range" errors with %w so callers can match via errors.Is.
- copyDataBasedOnIndexFile now skips only when the read failure is
  io.EOF, io.ErrUnexpectedEOF, ErrorSizeMismatch, ErrorSizeInvalid,
  or ErrorCorrupted. Anything else (real disk faults, environmental
  errors, Windows hardware codes) aborts the compaction so an
  operator notices.
- Mirror the same whitelist in the Rust volume server, matching on
  io::ErrorKind::UnexpectedEof and the NeedleError corruption variants
  (SizeMismatch, CrcMismatch, IndexOutOfRange, TailTooShort).

Also add `defer v.Close()` in TestVerifyIndexFitsInDat so Windows
t.TempDir() cleanup can release the .dat/.idx handles.

Refs #8928

* fix(volume): wrap entry-not-found size-mismatch with ErrorSizeMismatch

Address PR review: the fallback branch in ReadBytes returned an
unwrapped fmt.Errorf, so isSkippableNeedleReadError (and any caller
using errors.Is(..., ErrorSizeMismatch)) could not match it. Wrap
with %w so the whitelist applies, while leaving the existing direct
sentinel return for the OffsetSize==4 / offset<MaxPossibleVolumeSize
retry path unchanged so ReadData's `err == ErrorSizeMismatch` retry
still triggers.

Refs #8928

* fix(volume): integrate dangling-idx check into existing index load walk

Address PR review (gemini-code-assist, medium): the structural .idx
check used to do a second linear scan of the index file at every volume
load, doubling the disk-I/O cost on servers managing many volumes.

Track the largest (offset + actual size) seen during the existing
needle-map load walks (`LoadCompactNeedleMap`, `NewLevelDbNeedleMap`,
`NewSortedFileNeedleMap`'s `newNeedleMapMetricFromIndexFile`,
`DoOffsetLoading`) on a new `MaximumNeedleEnd` field on `mapMetric`,
exposed as `MaxNeedleEnd()` on the NeedleMapper interface.
`volume.load()` then compares `nm.MaxNeedleEnd()` to the .dat size
after the load is complete — pure numeric comparison, no extra I/O.

The standalone `verifyIndexFitsInDat` helper and its caller in
`CheckVolumeDataIntegrity` are removed; the test that used to drive
the helper directly now exercises the new path via
`LoadCompactNeedleMap`.

Mirror the same change in the Rust volume server: track
`max_needle_end` on `NeedleMapMetric`, expose via `max_needle_end()`
on `CompactNeedleMap`, `RedbNeedleMap`, and the `NeedleMap` enum.
The Rust load walk already happens in `load_from_idx` for both map
kinds, so the structural check becomes free.

Refs #8928
2026-04-16 22:01:34 -07:00
Chris Lu 664ae64646 ci(binaries_dev): serialize concurrent runs to prevent asset name collisions
Multiple master pushes within the same minute produced identical BUILD_TIME
values, causing concurrent workflow runs to race on identically-named release
assets. Upload retries hit 422 already_exists and failed the build. Adding a
concurrency group with cancel-in-progress ensures only the latest dev build
runs at a time, which is fine since only the latest dev artifacts matter.
2026-04-16 18:09:57 -07:00
dependabot[bot] 018e648d00 build(deps): bump github.com/jackc/pgx/v5 from 5.8.0 to 5.9.0 (#9113)
Bumps [github.com/jackc/pgx/v5](https://github.com/jackc/pgx) from 5.8.0 to 5.9.0.
- [Changelog](https://github.com/jackc/pgx/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jackc/pgx/compare/v5.8.0...v5.9.0)

---
updated-dependencies:
- dependency-name: github.com/jackc/pgx/v5
  dependency-version: 5.9.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 16:28:18 -07:00
Lars Lehtonen 66ce0c29cf fix(weed/query/engine): check for nil pointers (#9114) 2026-04-16 16:27:55 -07:00
Chris Lu 108e6b0d5f Delete scheduled_tasks.lock 2026-04-16 16:16:25 -07:00
Chris Lu 9d15705c16 fix(mini): shut down admin/s3/webdav/filer before volume/master on Ctrl+C (#9112)
* fix(mini): shut down admin/s3/webdav/filer before volume/master on Ctrl+C

Interrupts fired grace hooks in registration order, so master (started
first) shut down before its clients, producing heartbeat-canceled errors
and masterClient reconnection noise during weed mini shutdown. Admin/s3/
webdav had no interrupt hooks at all and were killed at os.Exit.

- grace: execute interrupt hooks in LIFO (defer-style) order so later-
  started services tear down first.
- filer: consolidate the three separate interrupt hooks (gRPC / HTTP /
  DB) into one that runs in order, so filer shutdown stays correct
  independent of FIFO/LIFO semantics.
- mini: add MiniClientsShutdownCtx (separate from test-facing
  MiniClusterCtx) plus an OnMiniClientsShutdown helper. Admin, S3,
  WebDAV and the maintenance worker observe it; runMini registers a
  cancel hook after startup so under LIFO it fires first and waits up to
  10s on a WaitGroup for those services to drain before filer, volume,
  and master shut down.

Resulting order on Ctrl+C: admin/s3/webdav/worker -> filer (gRPC -> HTTP
-> DB) -> volume -> master.

* refactor(mini): group mini-client shutdown into one state struct

The first pass spread the shutdown plumbing across three globals
(MiniClientsShutdownCtx, miniClientsWg, cancelMiniClients) and two
ctx-derivation sites (OnMiniClientsShutdown and startMiniAdminWithWorker).

Group into a private miniClientsState (ctx/cancel/wg) rebuilt per runMini
invocation, and chain its ctx from MiniClusterCtx so clients only observe
one signal. Tests that cancel MiniClusterCtx still trigger client
shutdown via parent-child propagation.

- resetMiniClients() installs fresh state at the top of runMini, so
  in-process test reruns don't inherit stale ctx/wg.
- onMiniClientsShutdown(fn) replaces the exported OnMiniClientsShutdown
  and only observes one ctx.
- trackMiniClient() replaces the manual wg.Add/Done dance for the admin
  goroutine.
- miniClientsCtx() gives the admin startup a ctx without re-deriving.
- triggerMiniClientsShutdown(timeout) is the interrupt hook body.

No behaviour change; existing tests pass.

* refactor: generalize shutdown ctx as an option, not a mini-specific helper

Several service files (s3, webdav, filer, master, volume) observed the
mini-specific MiniClusterCtx or called onMiniClientsShutdown directly.
That leaked mini orchestration into code that also runs under weed s3,
weed webdav, weed filer, weed master, and weed volume standalone.

Replace with a generic `shutdownCtx context.Context` field on each
service's Options struct. When non-nil, the server watches it and shuts
down gracefully; when nil (standalone), the shutdown path is a no-op.

Mini wires the contexts up from a single place (runMini):
 - miniMasterOptions/miniOptions.v/miniFilerOptions.shutdownCtx =
   MiniClusterCtx (drives test-triggered teardown)
 - miniS3Options/miniWebDavOptions.shutdownCtx = miniClientsCtx() (drives
   Ctrl+C teardown before filer/volume/master)

All knowledge of MiniClusterCtx now lives in mini.go.

* fix(mini): stop worker before clients ctx so admin shutdown isn't blocked

Symptom on Ctrl+C of a clean weed mini: mini's Shutting down admin/s3/
webdav hook sat for 10s then logged "timed out". Admin had started its
shutdown but was blocked inside StopWorkerGrpcServer's GracefulStop,
waiting for the still-connected worker stream. That in turn left filer
clients connected and cascaded into filer's own 10s gRPC graceful-stop
timeout.

Two causes, both fixed:

1. worker.Stop() deadlocked on clean shutdown. It sent ActionStop (which
   makes managerLoop `break out` and exit), then called getTaskLoad()
   which sends to the same unbuffered cmd channel — no receiver, hangs
   forever. Reorder Stop() to snapshot the admin client and drain tasks
   BEFORE sending ActionStop, and call Disconnect() via the local
   snapshot afterwards.

2. Worker's taskRequestLoop raced with Disconnect(): RequestTask reads
   from c.incoming, which Disconnect closes, yielding a nil response and
   a panic on response.Message. Handle the closed channel explicitly.

3. Mini now has a preCancel phase (beforeMiniClientsShutdown) that runs
   synchronously BEFORE the clients ctx is cancelled. Register worker
   shutdown there so admin's worker-gRPC GracefulStop finds the worker
   already disconnected and returns immediately, instead of waiting on
   a stream that is about to close anyway.

Observed shutdown of a clean mini: admin/s3/webdav down in <10ms; full
process exit in ~11s (the remaining 10s is a pre-existing filer gRPC
graceful-stop timeout, not cascaded from the clients tier).

* feat(mini): cap filer gRPC graceful stop at 1s under weed mini

Full weed mini shutdown was ~11s on a clean exit, dominated by the
filer's default 10s gRPC GracefulStop timeout while background
SubscribeLocalMetadata streams drained.

Expose the timeout as a FilerOptions.gracefulStopTimeout field (default
10s for standalone weed filer) and set it to 1s in mini. Clean weed mini
shutdown now takes ~2s.
2026-04-16 16:11:01 -07:00
Chris Lu 9554e259dd fix(iceberg): route catalog clients to the right bucket and vend S3 endpoint (#9109)
* fix(iceberg): route catalog clients to the right bucket and vend S3 endpoint

DuckDB ATTACH 's3://<bucket>/' AS cat (TYPE 'ICEBERG', ...) was failing
with "schema does not exist" because GET /v1/config ignored the warehouse
query parameter and returned no overrides.prefix, so subsequent requests
fell through to the hard-coded "warehouse" default bucket instead of the
one the client attached. LoadTable also returned an empty config, forcing
clients to discover the S3 endpoint out-of-band and producing 403s on
direct iceberg_scan calls.

- handleConfig now echoes overrides.prefix = bucket and defaults.warehouse
  when ?warehouse=s3://<bucket>/ is supplied.
- getBucketFromPrefix honors a warehouse query parameter as a fallback for
  clients that skip the /v1/config handshake.
- LoadTable responses advertise s3.endpoint and s3.path-style-access so
  clients can reach data files without separate configuration.

Refs #9103

* address review feedback on iceberg S3 endpoint vending

- deriveS3AdvertisedEndpoint is now a method on S3Options; honors
  externalUrl / S3_EXTERNAL_URL, switches to https when -s3.key.file is
  set, uses the https port when configured, and brackets IPv6 literals
  via util.JoinHostPort.
- handleCreateTable returns s.buildFileIOConfig() in both its staged and
  final LoadTableResult branches so create and load flows see the same
  FileIO hints.
- Add unit test coverage for the endpoint derivation scenarios.

* address CI and review feedback for #9109

- DuckDB integration test now runs under its own newOAuthTestEnv (with a
  valid IAM config) so the OAuth2 client_credentials flow DuckDB requires
  actually works; the shared env has no registered credentials, which was
  the cause of the CI failure. Helper createTableWithToken was added to
  create tables via Bearer auth.
- Tighten TestIssue9103_LoadTableDoesNotVendS3FileIOCredentials to also
  assert s3.path-style-access = "true", so a partial regression where the
  endpoint is vended but path-style is dropped still fails.
- deriveS3AdvertisedEndpoint now logs a startup hint when it infers the
  host from os.Hostname because the bind IP is a wildcard, pointing
  operators at -s3.externalUrl / S3_EXTERNAL_URL for reverse-proxy
  deployments where the inferred name is not externally reachable.
- handleConfig has a comment explaining that any sub-path in the
  warehouse URL is dropped because catalog routing is bucket-scoped.

* fix(iceberg): make advertised S3 endpoint strictly opt-in; add region

The wildcard-bind fallback to os.Hostname() in deriveS3AdvertisedEndpoint
was hijacking correctly-configured clients: on the CI runner it produced
http://runnervmrc6n4:<port>, which Spark (running in Docker) could not
resolve, so Spark iceberg tests began failing after the endpoint started
being vended in LoadTable responses.

Change the rule so advertising is opt-in and never guesses a host that
might not be routable:
  - -s3.externalUrl / S3_EXTERNAL_URL wins (covers reverse-proxy).
  - Otherwise, only an explicit, non-wildcard -s3.bindIp is used.
  - Wildcard / empty bind returns "" so no FileIO endpoint is vended and
    existing clients keep using their own configuration.

buildFileIOConfig additionally vends s3.region (defaulting to the same
value baked into table bucket ARNs) whenever it vends an endpoint, so
DuckDB's attach does not fail with "No region was provided via the
vended credentials" when the operator has opted in.

The DuckDB issue-9103 integration test runs under an env with a
wildcard bind, so it explicitly sets AWS_REGION in the docker run to
pick up the same default. The HTTP-level LoadTable-vending test was
dropped because its expectation is now conditional and already covered
by unit tests in iceberg_issue_9103_test.go.
2026-04-16 15:51:43 -07:00
Chris Lu 00a2e22478 fix(mount): remove fid pool to stop master over-allocating volumes (#9111)
* fix(mount): remove fid pool to stop master over-allocating volumes

The writeback-cache fid pool pre-allocated file IDs with
ExpectedDataSize = ChunkSizeLimit (typically 8+ MB). The master's
PickForWrite charges count * expectedDataSize against the volume's
effectiveSize, so a full pool refill could charge hundreds of MB
against a single volume before any bytes were actually written.
That tripped RecordAssign's hard-limit path and eagerly removed
volumes from writable, causing the master to grow new volumes
even when the real data being written was tiny.

Drop the pool entirely. Every chunk upload goes through
UploadWithRetry -> AssignVolume with no ExpectedDataSize hint,
letting the master fall back to the 1 MB default estimate. The
mount->filer grpc connection is already cached in pb.WithGrpcClient
(non-streaming mode), so per-chunk AssignVolume is a unary RPC
over an existing HTTP/2 stream, not a full dial. Path-based
filer.conf storage rules now apply to mount chunk assigns again,
which the pool had to skip.

Also remove the now-unused operation.UploadWithAssignFunc and its
AssignFunc type.

* fix(upload): populate ExpectedDataSize from actual chunk bytes

UploadWithRetry already buffers the full chunk into `data` before
calling AssignVolume, so the real size is known. Previously the
assign request went out with ExpectedDataSize=0, making the master
fall back to the 1 MB DefaultNeedleSizeEstimate per fid — same
over-reservation symptom the pool had, just smaller per call.

Stamp ExpectedDataSize = len(data) before the assign RPC when the
caller hasn't already set it. This covers mount chunk uploads,
filer_copy, filersink, mq/logstore, broker_write, gateway_upload,
and nfs — all the UploadWithRetry paths.

* fix(assign): pass real ExpectedDataSize at every assign call site

After removing the mount fid pool, per-chunk AssignVolume calls went
out with ExpectedDataSize=0, making the master fall back to its 1 MB
DefaultNeedleSizeEstimate. That's still an over-estimate for small
writes. Thread the real payload size through every remaining assign
site so RecordAssign charges effectiveSize accurately and stops
prematurely marking volumes full.

- filer: assignNewFileInfo now takes expectedDataSize and stamps it
  on both primary and alternate VolumeAssignRequests. Callers pass:
  - SSE data-to-chunk: len(data)
  - copy manifest save: len(data)
  - streamCopyChunk: srcChunk.Size
  - TUS sub-chunk: bytes read
  - saveAsChunk (autochunk/manifestize): 0 (small, size unknown
    until the reader is drained; master uses 1 MB default)
- filer gRPC remote fetch-and-write: ExpectedDataSize = chunkSize
  after the adaptive chunkSize is computed.
- ChunkedUploadOption.AssignFunc gains an expectedDataSize parameter;
  upload_chunked.go passes the buffered dataSize at the call site.
  S3 PUT assignFunc stamps it on the AssignVolumeRequest.
- S3 copy: assignNewVolume / prepareChunkCopy take expectedDataSize;
  all seven call sites pass the source chunk's Size.
- operation.SubmitFiles / FilePart.Upload: derive per-fid size from
  FileSize (average for batched requests, real per-chunk size for
  sequential chunk assigns).
- benchmark: pass fileSize.
- filer append-to-file: pass len(data).

* fix(assign): thread size through SaveDataAsChunkFunctionType

The saveAsChunk path (autochunk, filer_copy, webdav, mount) ran
AssignVolume before the reader was drained, so it had to pass
ExpectedDataSize=0 and fall back to the master's 1 MB default.

Add an expectedDataSize parameter to SaveDataAsChunkFunctionType.
- mergeIntoManifest already has the serialized manifest bytes, so
  it passes uint64(len(data)) directly.
- Mount's saveDataAsChunk ignores the parameter because it uses
  UploadWithRetry, which already stamps len(data) on the assign
  after reading the payload.
- webdav and filer_copy saveDataAsChunk follow the same UploadWithRetry
  path and also ignore the hint.
- Filer's saveAsChunk (used for manifestize) plumbs the value to
  assignNewFileInfo so manifest-chunk assigns get a real size.

Callers of saveFunc-as-value (weedfs_file_sync, dirty_pages_chunked)
pass the chunk size they're about to upload.
2026-04-16 15:51:13 -07:00
Chris Lu 7916e61c08 fix(mount): avoid self-notify deadlock in Link and CopyFileRange handlers (#9110)
The Link and CopyFileRange FUSE request handlers were calling
fuseServer.InodeNotify (and EntryNotify for copy) synchronously while
the kernel was still waiting for the request's reply on the same
/dev/fuse fd. Notifications share that fd, so the syscall.Write can
block indefinitely when the kernel hasn't drained its queue yet,
hanging the entire mount. A goroutine dump from a stuck mount showed
the Link handler blocked in syscall.Write inside InodeNotify while the
server's read loop kept waiting for new requests.

Drop the synchronous notifies. The local meta cache is still updated
inline, so subsequent filesystem ops see the fresh state; the kernel's
attr/dentry caches re-fetch once their TTL expires.
2026-04-16 14:09:32 -07:00
Chris Lu ecc0390795 fix(master): eagerly remove volume from writable when assign hits limit (#9108)
* fix(master): eagerly remove volume from writable when RecordAssign hits limit

Previously, a volume was only removed from the writable list by the
heartbeat-driven CollectDeadNodeAndFullVolumes pass, which runs every
pulse (5s) after a 5s heartbeat. Under sustained concurrent writes,
fio-style workloads observed in the field grew volumes 8-20x past the
configured 100MB limit (median 530MB, peak 1.98GB) during that
5-15s detection window.

RecordAssign already tracks effective size (reported + pending) on each
/dir/assign. It now also removes the volume from writable the moment
effectiveSize reaches volumeSizeLimit, and mirrors the activeVolumeCount
decrement that Topology.SetVolumeCapacityFull would have done on the
next heartbeat. The heartbeat path remains unchanged and idempotent
(vl.SetVolumeCapacityFull returns false if already removed, so no
double-decrement).

Recovery still works: if a heartbeat later reports size < limit and
the volume is not oversized, EnsureCorrectWritables adds it back.

- weed/topology/volume_layout.go: RecordAssign returns reachedCapacity
  bool; adds AdjustActiveVolumeCountForFull helper.
- weed/topology/topology.go: PickForWrite invokes the decrement on
  eager full transitions.
- TestPickForWrite: pass a 1024-byte hint instead of 0 so the default
  1MB pendingDelta does not immediately bust the test's 32KB limit.
- New TestRecordAssignReachingCapacityRemovesFromWritable covers the
  eager removal, active count accounting, and no-double-accounting.

* fix(master): recover eagerly-removed volume once decay clears pending

After RecordAssign eagerly removes a volume from writables because
effectiveSize reached the limit, decay can later bring effectiveSize
back under the limit (e.g., when a burst of assigns didn't all result
in uploads). Without recovery the volume would stay non-writable until
vacuum or a ReadOnly flip.

UpdateVolumeSize now re-adds the volume to writables once all of the
following hold:

  * RecordAssign is what removed it (tracked via fullSince timestamp)
  * at least capacityRecoveryDelay has elapsed since the removal (30s)
    — this prevents bouncing during a steady stream of assigns near
    the limit
  * effectiveSize has decayed below the crowded threshold (90% of limit)
  * reportedSize is under the limit (actual disk is not over)
  * standard EnsureCorrectWritables preconditions: enough copies, all
    copies writable, not oversized

The caller (SyncDataNodeRegistration) re-increments activeVolumeCount
symmetrically with the decrement done on eager removal.

* review: release VolumeLayout lock before UpAdjustDiskUsageDelta

adjustActiveVolumeCount held vl.accessLock across the tree-climbing
UpAdjustDiskUsageDelta walk. That walk takes per-level DiskUsages
locks and could be re-entered from other call paths that hold a
node-level lock and then acquire vl.accessLock. Copy the node list
under the VolumeLayout lock and release it before the tree walk to
eliminate the lock-ordering hazard.
2026-04-16 12:50:30 -07:00
Chris Lu 40ffc73aa8 ci(pjdfstest): cache docker layers via GHA to avoid apt mirror flakes (#9106)
* ci(pjdfstest): cache docker layers via GHA to avoid apt mirror flakes

Replace the local buildx cache + manual fallback with docker/setup-buildx-action
and docker/build-push-action using type=gha cache. The e2e and pjdfstest Dockerfile
layers now persist across runs in GitHub's own cache backend, so apt-get update
only hits Ubuntu mirrors when the Dockerfiles change. Also add Acquire::Retries
and Timeout so first-run cache-miss builds survive transient mirror sync errors.

* ci(pjdfstest): use local registry to share e2e image across buildx builds

The docker-container buildx driver cannot see images loaded into the host
Docker daemon, so the second build's FROM chrislusf/seaweedfs:e2e failed with
"not found" on registry-1.docker.io.

Run a local registry:2 on the runner, push both images to localhost:5000,
remap the FROM via build-contexts so the Dockerfile stays unchanged, then
tag the pulled images locally for docker compose to consume.
2026-04-16 12:50:19 -07:00
Chris Lu ff4f96c71f fix(filer): drop stale master gRPC cache on stream death (#9102) (#9107)
* fix(filer): drop stale master gRPC cache on stream death (#9102)

When the master server restarts behind a stable L4 endpoint (e.g. a
Kubernetes ClusterIP Service), the filer's streaming KeepConnected
channel detects the disconnect and reconnects, but the shared
request-path ClientConn cached in pb.grpcClients can remain in READY
state while actually being dead. New AssignVolume/LookupVolume calls
reuse that cached channel and return `rpc error: code = Canceled desc
= context canceled` for every request, until the filer pod is
restarted.

- Expose pb.InvalidateGrpcConnection(address) to drop a cached
  ClientConn when a higher-level signal says it is stale.
- In MasterClient.tryConnectToMaster, invalidate the cached
  request-path channel whenever the KeepConnected stream returns, so
  unrelated callers dial fresh on their next RPC.
- Extend operation.Assign's retry predicate to cover Canceled and
  DeadlineExceeded while the caller context is still live: the first
  failure invalidates the stale ClientConn via
  shouldInvalidateConnection, and the retry dials a new channel.

* fix(grpc): invalidate cached peer conn on streaming death in other paths

Extends the master-client fix to the other streaming-caller + cached
non-streaming-peer pairs that share the same stale-channel failure mode
when the peer restarts behind a stable L4 endpoint (k8s Service VIP,
external load balancer):

- pb.FollowMetadata (s3, mount, webdav, mq broker, filer remote gateway,
  etc. → filer): invalidate the filer's cached ClientConn when the
  SubscribeMetadata stream returns an error.
- filer.MetaAggregator.loopSubscribeToOneFiler (filer → peer filer):
  invalidate the peer's cached ClientConn after doSubscribeToOneFiler
  fails, so the next iteration's readFilerStoreSignature / updateOffset
  calls dial fresh.
- mq sub_client.onEachPartition and doKeepConnectedToSubCoordinator
  (subscriber → broker): invalidate the broker's cached ClientConn when
  the SubscribeMessage / SubscriberToSubCoordinator stream errors.
- mq broker.BrokerConnectToBalancer (broker → broker-balancer):
  invalidate the balancer's cached ClientConn after the
  PublisherToPubBalancer stream errors.

* address review feedback on InvalidateGrpcConnection

- pb.InvalidateGrpcConnection: drop the cache entry under grpcClientsLock
  but call ClientConn.Close() after releasing the lock, so Close's
  internal synchronisation/IO doesn't serialise unrelated callers on the
  global map lock.
- wdclient.tryConnectToMaster: only invalidate the cached request-path
  channel when the streaming call returned an error. On a healthy leader
  redirect (gprcErr == nil) the cached channel is still usable and
  invalidating it just causes a needless re-dial from concurrent callers.

* refactor(grpc): centralize peer-conn invalidation in streaming path

Previously every streaming caller duplicated the same invalidate-cached-
non-streaming-peer-conn wrapper around their WithGrpcClient(true, ...)
call. Move that logic into WithGrpcClient itself: when the streaming
fn returns an error, invalidate any cached ClientConn for the same
address. This removes six near-identical call-site wrappers and gives
every current and future streaming caller the fix by default.

Also aligns the non-streaming branch with the new Invalidate helper's
lock discipline: delete the cache entry under grpcClientsLock, then
Close the ClientConn after releasing the lock.
2026-04-16 12:10:25 -07:00
Chris Lu 9896eade51 feat(mount): set FOPEN_KEEP_CACHE on re-open of unchanged files (#9097)
* feat(mount): set FOPEN_KEEP_CACHE when file mtime is unchanged

On re-open of an unmodified file, signal the kernel to preserve its
existing page cache. This eliminates redundant volume server reads for
workloads that repeatedly open-read-close the same files (build systems,
config readers, etc.).

* fix(mount): use guarded type assertion for openMtimeCache load

Use the two-value form of type assertion when loading from sync.Map
to prevent potential panics if a non-int64 value is ever stored.

* fix(mount): skip redundant mtime store and invalidate on truncation

- Avoid redundant sync.Map Store when cached mtime already matches
  the current mtime, reducing contention on the hot open path.
- Invalidate openMtimeCache in SetAttr when file size changes
  (truncation), preventing stale kernel page cache after ftruncate.

* fix(mount): use nanosecond mtime precision and bounded cache for FOPEN_KEEP_CACHE

- Compare both Mtime (seconds) and MtimeNs (nanoseconds) to detect
  sub-second modifications common in automated workloads.
- Replace unbounded sync.Map with a bounded map + mutex (8192 entries,
  random eviction when full), following the existing atimeMap pattern.
- Extract applyKeepCacheFlag and invalidateOpenMtimeCache methods for
  clarity and testability.
- Add tests for nanosecond precision and cache eviction.

* fix(mount): invalidate mtime cache in truncateEntry for O_TRUNC consistency

Add invalidateOpenMtimeCache call to truncateEntry so the Create path
with O_TRUNC follows the same explicit invalidation pattern as SetAttr
and Write.
2026-04-16 11:37:52 -07:00
Chris Lu ceae01d05b test(kafka): retry ConsumeWithGroup on failed initial join (#9105)
The consumer group resumption flow in TestOffsetManagement occasionally fails
with `read tcp ... i/o timeout` on the second consumer's first FetchMessage.
Re-joining an existing group races with the previous member's LeaveGroup and
session cleanup; the new reader can observe transient coordinator state that
the kafka-go client surfaces as a connection read timeout.

Wrap ConsumeWithGroup in a 3-attempt retry that rebuilds the reader only when
no message was received yet, so a transient join failure doesn't fail the
whole test. Partial progress (at least one message consumed) still returns
immediately, preserving the original error semantics for post-join failures.
2026-04-16 11:31:26 -07:00
Chris Lu 216b52c13a perf(mount): add graduated write backpressure (#9099)
* perf(mount): add graduated write backpressure before buffer cap

Introduce soft (80%) and hard (95%) throttling thresholds in
WriteBufferAccountant. When write buffer usage approaches the cap,
Reserve() inserts brief sleeps to slow writers gradually rather than
blocking them completely at the cap. This smooths out write latency
under sustained load.

* fix(mount): address review feedback for graduated backpressure

- Use projected usage (used + n) for threshold checks so a single
  reservation crossing a threshold is throttled immediately.
- Widen no-throttle test timing tolerance to softThrottleDelay to
  avoid CI flakes from scheduling jitter.
- Replace fragile timing upper-bound in recovery test with
  counter-based invariant (hardThrottleCount stays at 1).

* docs(mount): clarify single-shot throttle design in WriteBufferAccountant

Add a comment explaining why graduated throttling runs once per Reserve
call rather than inside the blocking loop: once at the cap, the evictor
+ cond.Wait mechanism frees actual capacity, which time-based sleeps
cannot do.
2026-04-16 11:30:23 -07:00
Chris Lu 886d50a6a5 feat(mount): singleflight dedup for concurrent chunk reads (#9100)
* feat(mount): add singleflight deduplication for concurrent chunk reads

When multiple FUSE readers request the same uncached chunk concurrently,
only one network fetch is performed. Other readers wait and share the
downloaded data, reducing redundant volume server traffic under parallel
read workloads.

* fix(util): make singleflight panic-safe with defer cleanup

If the provided function panics, the WaitGroup and map entry are now
cleaned up via defer, preventing other waiters from hanging forever.

* fix(filer): remove singleflight from reader_cache to fix buffer ownership

The singleflight wrapper around chunk fetches returned the same []byte
buffer to concurrent callers. Since each SingleChunkCacher owns and
frees its data buffer in destroy(), sharing the same slice would cause
a use-after-free or double-free with the mem allocator.

The downloaders map already deduplicates in-flight downloads for the
same fileId, so the singleflight was redundant at this layer. The
SingleFlightGroup utility is retained for use elsewhere.
2026-04-16 10:18:05 -07:00
Chris Lu e1fa4ec756 perf(cache): drop OS page cache after disk cache reads (#9098)
* perf(cache): drop OS page cache after disk cache reads

After reading from the on-disk chunk cache, advise the kernel via
FADV_DONTNEED to release the corresponding page cache pages. This
prevents double-caching the same data in both user-space and kernel
page caches, freeing RAM for other uses on systems with large disk
caches.

* fix(cache): guard dropReadCache against zero length and invalid fd

A zero-length fadvise is interpreted as "to end of file" on Linux,
which would inadvertently drop the page cache for the entire remainder
of the cache volume. Also check fd >= 0 to avoid unnecessary syscalls
when the backend file is closed.

* perf(cache): only apply FADV_DONTNEED for reads >= 1 MiB

For small needle reads the syscall overhead outweighs the memory
savings, and the kernel page cache is more beneficial for warm data.
Restrict fadvise to reads of at least 1 MiB where the freed page
cache is meaningful.
2026-04-16 09:38:42 -07:00
Chris Lu 213b6c3107 fix(mount): count manifest sizes in merge condition to prevent accumulation (#9101)
* fix(mount): count manifest sizes in merge condition to prevent manifest accumulation

shouldMergeChunks only counted non-manifest chunk sizes toward the bloat
threshold, so overlapping manifests accumulated undetected across flush
cycles.

During sustained random writes (e.g. fio), each metadata flush compacts
non-manifest chunks and may group them into a new manifest via
MaybeManifestize, while carrying forward all existing manifests. Since
the merge condition only checked non-manifest totals against 2x file
size, the growing pile of redundant manifests never triggered a merge.

In a real workload: 4 GB file, 25 manifests each covering ~4 GB
(107 GB manifest data on volume servers), but shouldMergeChunks saw only
4.2 GB of non-manifest chunks vs the 8.6 GB threshold -- no merge.

Fix: include manifest coverage sizes in totalChunkSize. This correctly
detects the 111 GB total vs 8.6 GB threshold and triggers the merge,
which re-reads the file as clean chunks and lets the filer's MinusChunks
(which resolves manifests) garbage-collect all redundant sub-chunks.

* test(mount,filer): add manifest chunk correctness tests

Filer-level tests (filechunk_manifest_test.go):
- TestManifestRoundTripPreservesChunks: create -> serialize -> deserialize
  preserves fileId, offset, size, and timestamp for all sub-chunks
- TestCompactResolvedOverlappingManifests: two manifests covering the same
  range, older sub-chunks correctly identified as garbage after compaction
- TestDoMinusChunksWithResolvedManifests: old manifest sub-chunks detected
  as garbage when compared against new clean chunks (mirrors filer cleanup)
- TestManifestizeSmallBatchWithRemainder: batch=3 with 7 chunks produces
  2 manifests + 1 remainder, all data recoverable after resolve
- TestCompactMultipleOverlappingManifestGenerations: 5 generations of
  full-file manifests, compaction keeps only the newest generation
- TestManifestBloatDetection: with N overlapping manifests, merge triggers
  at N >= 2 (stored > 2x file size)

Mount-level test (weedfs_file_sync_test.go):
- TestFlushCycleManifestAccumulation: simulates the flushMetadataToFiler
  pipeline over multiple cycles with a small manifest batch (5 chunks).
  Verifies merge triggers at cycle 2 when accumulated manifests exceed
  the 2x threshold. Uses SeparateManifestChunks + CompactFileChunks +
  shouldMergeChunks to mirror the real code path.
2026-04-16 03:33:08 -07:00
161 changed files with 12795 additions and 1169 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
{"sessionId":"81536282-6277-4e32-9922-37c6e3a01b1f","pid":84648,"acquiredAt":1776208413235}
+4
View File
@@ -4,6 +4,10 @@ on:
push:
branches: [ master ]
concurrency:
group: binaries-dev-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
@@ -0,0 +1,69 @@
name: "FUSE P2P Peer Chunk Sharing Integration Tests"
on:
pull_request:
paths:
- 'weed/command/mount*.go'
- 'weed/mount/**'
- 'weed/filer/mount_peer_registry*.go'
- 'weed/server/filer_grpc_server_mount_peer.go'
- 'weed/pb/mount_peer.proto'
- 'weed/pb/filer.proto'
- 'test/fuse_p2p/**'
- '.github/workflows/fuse-p2p-integration.yml'
push:
branches: [master]
paths:
- 'weed/command/mount*.go'
- 'weed/mount/**'
- 'weed/filer/mount_peer_registry*.go'
- 'weed/server/filer_grpc_server_mount_peer.go'
- 'weed/pb/mount_peer.proto'
- 'weed/pb/filer.proto'
- 'test/fuse_p2p/**'
concurrency:
group: ${{ github.head_ref || github.ref }}/fuse-p2p-integration
cancel-in-progress: true
permissions:
contents: read
jobs:
fuse-p2p-integration:
name: FUSE P2P Peer Chunk Sharing
runs-on: ubuntu-22.04
timeout-minutes: 20
steps:
- name: Check out code
uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: 'go.mod'
- name: Install FUSE dependencies
run: |
sudo apt-get update
sudo apt-get install -y libfuse3-dev
echo 'user_allow_other' | sudo tee -a /etc/fuse.conf
sudo chmod 644 /etc/fuse.conf
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Run P2P integration tests
timeout-minutes: 15
env:
WEED_BINARY: ${{ github.workspace }}/weed/weed
run: go test -v -count=1 -timeout=12m ./test/fuse_p2p/...
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: fuse-p2p-test-logs
path: /tmp/seaweedfs-fuse-p2p-logs/
retention-days: 3
+38 -7
View File
@@ -39,18 +39,49 @@ jobs:
with:
go-version-file: 'go.mod'
- name: Build SeaweedFS e2e image
- name: Start local Docker registry
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
driver-opts: network=host
- name: Build weed race binary
run: |
cd docker
make build_e2e || {
echo "Retrying without buildx cache..."
make binary_race
docker build --no-cache -t chrislusf/seaweedfs:e2e -f Dockerfile.e2e .
}
make binary_race
- name: Build SeaweedFS e2e image
uses: docker/build-push-action@v6
with:
context: docker
file: docker/Dockerfile.e2e
tags: localhost:5000/chrislusf/seaweedfs:e2e
push: true
cache-from: type=gha,scope=pjdfstest-e2e
cache-to: type=gha,mode=max,scope=pjdfstest-e2e
- name: Tag e2e image for docker compose
run: |
docker pull localhost:5000/chrislusf/seaweedfs:e2e
docker tag localhost:5000/chrislusf/seaweedfs:e2e chrislusf/seaweedfs:e2e
- name: Build pjdfstest image
uses: docker/build-push-action@v6
with:
context: test/pjdfstest
build-contexts: |
chrislusf/seaweedfs:e2e=docker-image://localhost:5000/chrislusf/seaweedfs:e2e
tags: localhost:5000/chrislusf/seaweedfs:pjdfstest
push: true
cache-from: type=gha,scope=pjdfstest-harness
cache-to: type=gha,mode=max,scope=pjdfstest-harness
- name: Tag pjdfstest image for docker compose
run: |
docker build -t chrislusf/seaweedfs:pjdfstest test/pjdfstest/
docker pull localhost:5000/chrislusf/seaweedfs:pjdfstest
docker tag localhost:5000/chrislusf/seaweedfs:pjdfstest chrislusf/seaweedfs:pjdfstest
- name: Start SeaweedFS cluster
run: |
+8
View File
@@ -37,6 +37,8 @@ jobs:
run: |
git clone https://github.com/ceph/s3-tests.git
cd s3-tests
sudo apt-get update -qq
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
pip install -r requirements.txt
pip install tox
pip install -e .
@@ -339,6 +341,8 @@ jobs:
run: |
git clone https://github.com/ceph/s3-tests.git
cd s3-tests
sudo apt-get update -qq
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
pip install -r requirements.txt
pip install tox
pip install -e .
@@ -507,6 +511,8 @@ jobs:
run: |
git clone https://github.com/ceph/s3-tests.git
cd s3-tests
sudo apt-get update -qq
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
pip install -r requirements.txt
pip install tox
pip install -e .
@@ -730,6 +736,8 @@ jobs:
run: |
git clone https://github.com/ceph/s3-tests.git
cd s3-tests
sudo apt-get update -qq
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
pip install -r requirements.txt
pip install tox
pip install -e .
+24
View File
@@ -0,0 +1,24 @@
# Security Policy
## Reporting a Vulnerability
If you find a security issue in SeaweedFS, please report it privately:
- Email: support@seaweedfs.com
- Do not open a public GitHub issue
Please include:
- A clear description of the issue
- Steps to reproduce (if possible)
- Affected versions
## Response
- We will respond as soon as possible (usually within 1 business day)
- We will investigate and work on a fix
- We may coordinate disclosure with you
## Notes
- Please allow time for a fix before public disclosure
- If you’re unsure whether something is a security issue, feel free to reach out
+2 -2
View File
@@ -7,8 +7,8 @@ LABEL author="Chris Lu"
# Production images (Dockerfile.go_build) use proper user isolation with su-exec.
# For testing purposes, running as root avoids permission complexities and dependency
# on Alpine-specific tools like su-exec (not available in Ubuntu repos).
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive apt-get install -y \
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
--no-install-recommends \
--no-install-suggests \
curl \
+3 -3
View File
@@ -39,7 +39,7 @@ require (
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/jackc/pgx/v5 v5.8.0
github.com/jackc/pgx/v5 v5.9.0
github.com/jcmturner/gofork v1.7.6 // indirect
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
github.com/jinzhu/copier v0.4.0
@@ -130,6 +130,7 @@ require (
github.com/cognusion/imaging v1.0.2
github.com/fluent/fluent-logger-golang v1.10.1
github.com/getsentry/sentry-go v0.44.1
github.com/go-git/go-billy/v5 v5.6.2
github.com/go-ldap/ldap/v3 v3.4.13
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
@@ -153,6 +154,7 @@ require (
github.com/testcontainers/testcontainers-go v0.40.0
github.com/tikv/client-go/v2 v2.0.7
github.com/willscott/go-nfs v0.0.3
github.com/willscott/go-nfs-client v0.0.0-20251022144359-801f10d98886
github.com/xeipuuv/gojsonschema v1.2.0
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1
github.com/ydb-platform/ydb-go-sdk/v3 v3.134.0
@@ -210,7 +212,6 @@ require (
github.com/dromara/dongle v1.0.1 // indirect
github.com/gin-gonic/gin v1.11.0 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
github.com/go-git/go-billy/v5 v5.6.2 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
github.com/google/go-cmp v0.7.0 // indirect
@@ -272,7 +273,6 @@ require (
github.com/twpayne/go-kml/v3 v3.2.1 // indirect
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/willscott/go-nfs-client v0.0.0-20251022144359-801f10d98886 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
+2 -2
View File
@@ -1403,8 +1403,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
github.com/jackc/pgx/v5 v5.9.0 h1:T/dI+2TvmI2H8s/KH1/lXIbz1CUFk3gn5oTjr0/mBsE=
github.com/jackc/pgx/v5 v5.9.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.20"
appVersion: "4.21"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.20.0
version: 4.21.0
@@ -86,6 +86,13 @@ service SeaweedFiler {
}
rpc ReplicateLock(ReplicateLockRequest) returns (ReplicateLockResponse) {
}
// Peer chunk sharing — tier 1: mount-server registry.
// See design-weed-mount-peer-chunk-sharing.md for details.
rpc MountRegister (MountRegisterRequest) returns (MountRegisterResponse) {
}
rpc MountList (MountListRequest) returns (MountListResponse) {
}
}
//////////////////////////////////////////////////
@@ -197,6 +204,10 @@ message FuseAttributes {
bytes md5 = 14;
uint32 rdev = 16;
uint64 inode = 17;
int64 ctime = 18; // unix time in seconds, inode change time
int32 mtime_ns = 19; // nanosecond component of mtime (0-999999999)
int32 ctime_ns = 20; // nanosecond component of ctime (0-999999999)
int32 crtime_ns = 21; // nanosecond component of crtime (0-999999999)
}
message CreateEntryRequest {
@@ -597,3 +608,31 @@ message StreamMutateEntryResponse {
string error = 7; // human-readable error message when the operation failed
int32 errno = 8; // POSIX errno (e.g. ENOENT=2, ENOTEMPTY=66) for direct FUSE status mapping
}
//////////////////////////////////////////////////
// Peer chunk sharing — mount-server registry
//////////////////////////////////////////////////
message MountRegisterRequest {
string peer_addr = 1; // host:port where this mount serves peer chunk requests
string rack = 2; // locality label (rack); used for peer ranking
int32 ttl_seconds = 3; // how long the filer should keep this entry without a heartbeat
string data_center = 4; // locality label (data center); coarser than rack
}
message MountRegisterResponse {
}
message MountListRequest {
}
message MountListResponse {
repeated MountInfo mounts = 1;
}
message MountInfo {
string peer_addr = 1;
string rack = 2;
int64 last_seen_ns = 3;
string data_center = 4;
}
+71 -9
View File
@@ -19,6 +19,7 @@ use compact_map::CompactMap;
use redb::{Database, Durability, ReadableDatabase, ReadableTable, TableDefinition};
use crate::storage::idx;
use crate::storage::needle::needle::get_actual_size;
use crate::storage::types::*;
// ============================================================================
@@ -63,6 +64,11 @@ pub struct NeedleMapMetric {
pub deletion_count: AtomicI64,
pub deletion_byte_count: AtomicU64,
pub max_file_key: AtomicU64,
/// Largest (offset.to_actual_offset() + get_actual_size(size, version))
/// observed during the load walk. Used at volume load to verify that no
/// .idx entry references bytes past the end of .dat (issue #8928)
/// without paying for a second linear scan.
pub max_needle_end: AtomicI64,
}
impl NeedleMapMetric {
@@ -108,6 +114,29 @@ impl NeedleMapMetric {
}
}
}
/// Update `max_needle_end` if this entry's (offset + actual size) exceeds
/// the running maximum. Skips deleted/zero-offset entries because they
/// don't reserve space in .dat.
fn maybe_set_max_needle_end(&self, offset: Offset, size: Size, version: Version) {
if offset.is_zero() || !size.is_valid() {
return;
}
let end = offset.to_actual_offset() + get_actual_size(size, version);
loop {
let current = self.max_needle_end.load(Ordering::Relaxed);
if end <= current {
break;
}
if self
.max_needle_end
.compare_exchange(current, end, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
break;
}
}
}
}
// ============================================================================
@@ -163,9 +192,10 @@ impl CompactNeedleMap {
}
/// Load from an .idx file, building the in-memory map.
pub fn load_from_idx<R: Read + Seek>(reader: &mut R) -> io::Result<Self> {
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| {
nm.metric.maybe_set_max_needle_end(offset, size, version);
if offset.is_zero() || size.is_deleted() {
nm.delete_from_map(key);
} else {
@@ -284,6 +314,12 @@ impl CompactNeedleMap {
NeedleId(self.metric.max_file_key.load(Ordering::Relaxed))
}
/// Largest (offset + actual size) seen during the load walk; 0 if the
/// map is empty. See `NeedleMapMetric::maybe_set_max_needle_end`.
pub fn max_needle_end(&self) -> i64 {
self.metric.max_needle_end.load(Ordering::Relaxed)
}
pub fn index_file_size(&self) -> u64 {
self.idx_file_offset
}
@@ -431,7 +467,7 @@ impl RedbNeedleMap {
/// Rebuild metrics by scanning all entries in the redb table.
/// Called when reusing an existing .rdb without a full rebuild.
fn rebuild_metrics_from_db(&self) -> io::Result<()> {
fn rebuild_metrics_from_db(&self, version: Version) -> io::Result<()> {
let txn = self
.db
.begin_read()
@@ -453,6 +489,8 @@ impl RedbNeedleMap {
arr.copy_from_slice(bytes);
let nv = unpack_needle_value(&arr);
self.metric.maybe_set_max_file_key(key);
self.metric
.maybe_set_max_needle_end(nv.offset, nv.size, version);
if nv.size.is_valid() {
self.metric.file_count.fetch_add(1, Ordering::Relaxed);
self.metric
@@ -477,20 +515,24 @@ impl RedbNeedleMap {
/// 2. If .idx size matches → reuse .rdb, rebuild metrics from scan
/// 3. If .idx is larger → replay new entries incrementally
/// 4. Otherwise (missing, corrupted, .idx smaller) → full rebuild
pub fn load_from_idx<R: Read + Seek>(db_path: &str, reader: &mut R) -> io::Result<Self> {
pub fn load_from_idx<R: Read + Seek>(
db_path: &str,
reader: &mut R,
version: Version,
) -> io::Result<Self> {
let idx_size = reader.seek(io::SeekFrom::End(0))?;
reader.seek(io::SeekFrom::Start(0))?;
// Try to reuse existing .rdb
if Path::new(db_path).exists() {
if let Ok(nm) = Self::try_reuse_rdb(db_path, reader, idx_size) {
if let Ok(nm) = Self::try_reuse_rdb(db_path, reader, idx_size, version) {
return Ok(nm);
}
// Reuse failed — fall through to full rebuild
reader.seek(io::SeekFrom::Start(0))?;
}
Self::full_rebuild(db_path, reader, idx_size)
Self::full_rebuild(db_path, reader, idx_size, version)
}
/// Try to reuse an existing .rdb file. Returns Ok if successful,
@@ -499,6 +541,7 @@ impl RedbNeedleMap {
db_path: &str,
reader: &mut R,
idx_size: u64,
version: Version,
) -> io::Result<Self> {
let db = Database::open(db_path)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("redb open: {}", e)))?;
@@ -523,7 +566,7 @@ impl RedbNeedleMap {
}
// Rebuild metrics from existing data
nm.rebuild_metrics_from_db()?;
nm.rebuild_metrics_from_db(version)?;
if stored_idx_size < idx_size {
// .idx grew — replay new entries incrementally
@@ -534,6 +577,7 @@ impl RedbNeedleMap {
io::Error::new(io::ErrorKind::Other, format!("redb open_table: {}", e))
})?;
idx::walk_index_file(reader, start_entry, |key, offset, size| {
nm.metric.maybe_set_max_needle_end(offset, size, version);
let key_u64: u64 = key.into();
if offset.is_zero() || size.is_deleted() {
// Delete: look up old value for metric update, then
@@ -607,6 +651,7 @@ impl RedbNeedleMap {
db_path: &str,
reader: &mut R,
idx_size: u64,
version: Version,
) -> io::Result<Self> {
let _ = std::fs::remove_file(db_path);
let nm = RedbNeedleMap::new(db_path)?;
@@ -614,6 +659,7 @@ impl RedbNeedleMap {
// Collect entries from idx file, resolving duplicates/deletions
let mut entries: HashMap<NeedleId, Option<NeedleValue>> = HashMap::new();
idx::walk_index_file(reader, 0, |key, offset, size| {
nm.metric.maybe_set_max_needle_end(offset, size, version);
if offset.is_zero() || size.is_deleted() {
entries.insert(key, None);
} else {
@@ -788,6 +834,12 @@ impl RedbNeedleMap {
NeedleId(self.metric.max_file_key.load(Ordering::Relaxed))
}
/// Largest (offset + actual size) seen during the load walk; 0 if the
/// map is empty. See `NeedleMapMetric::maybe_set_max_needle_end`.
pub fn max_needle_end(&self) -> i64 {
self.metric.max_needle_end.load(Ordering::Relaxed)
}
pub fn index_file_size(&self) -> u64 {
self.idx_file_offset
}
@@ -988,6 +1040,16 @@ impl NeedleMap {
}
}
/// 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.
pub fn max_needle_end(&self) -> i64 {
match self {
NeedleMap::InMemory(nm) => nm.max_needle_end(),
NeedleMap::Redb(nm) => nm.max_needle_end(),
}
}
/// Index file size in bytes.
pub fn index_file_size(&self) -> u64 {
match self {
@@ -1157,7 +1219,7 @@ mod tests {
.unwrap();
let mut cursor = Cursor::new(idx_data);
let nm = CompactNeedleMap::load_from_idx(&mut cursor).unwrap();
let nm = CompactNeedleMap::load_from_idx(&mut cursor, Version::current()).unwrap();
assert!(nm.get(NeedleId(1)).is_some());
assert!(nm.get(NeedleId(2)).is_none()); // deleted
@@ -1300,7 +1362,7 @@ mod tests {
.unwrap();
let mut cursor = Cursor::new(idx_data);
let nm = RedbNeedleMap::load_from_idx(db_path.to_str().unwrap(), &mut cursor).unwrap();
let nm = RedbNeedleMap::load_from_idx(db_path.to_str().unwrap(), &mut cursor, Version::current()).unwrap();
assert!(nm.get(NeedleId(1)).is_some());
assert!(nm.get(NeedleId(2)).is_none()); // deleted and removed
@@ -1377,7 +1439,7 @@ mod tests {
// Load back with CompactNeedleMap to verify
let mut idx_file = std::fs::File::open(&idx_path).unwrap();
let loaded = CompactNeedleMap::load_from_idx(&mut idx_file).unwrap();
let loaded = CompactNeedleMap::load_from_idx(&mut idx_file, Version::current()).unwrap();
assert_eq!(loaded.file_count(), 2); // only live entries
assert!(loaded.get(NeedleId(1)).is_some());
assert!(loaded.get(NeedleId(2)).is_none()); // deleted, not saved
+229 -5
View File
@@ -19,6 +19,8 @@ use std::time::{SystemTime, UNIX_EPOCH};
use tracing::warn;
#[cfg(test)]
use crate::storage::idx;
use crate::storage::needle::needle::{self, get_actual_size, Needle, NeedleError};
use crate::storage::needle_map::{CompactNeedleMap, NeedleMap, NeedleMapKind, RedbNeedleMap};
use crate::storage::super_block::{ReplicaPlacement, SuperBlock, SUPER_BLOCK_SIZE};
@@ -73,6 +75,24 @@ pub enum VolumeError {
StreamingUnsupported,
}
/// Returns true when a needle read failed because the on-disk bytes are
/// unreadable in a permanent way (offset past EOF, header corruption, CRC
/// mismatch, malformed v2/v3/v4 fields). Vacuum can safely drop such entries
/// during compaction. Anything else (real disk EIO, ERROR_CRC on Windows,
/// network timeouts, EROFS, etc.) is transient or environmental and must
/// abort the compaction so an operator notices.
fn is_skippable_needle_read_error(e: &VolumeError) -> bool {
match e {
VolumeError::Io(io_err) => io_err.kind() == io::ErrorKind::UnexpectedEof,
VolumeError::Needle(NeedleError::SizeMismatch { .. }) => true,
VolumeError::Needle(NeedleError::CrcMismatch { .. }) => true,
VolumeError::Needle(NeedleError::IndexOutOfRange(_)) => true,
VolumeError::Needle(NeedleError::TailTooShort) => true,
VolumeError::SizeMismatch => true,
_ => false,
}
}
// ============================================================================
// VolumeInfo (.vif persistence)
// ============================================================================
@@ -712,6 +732,28 @@ impl Volume {
"volumeDataIntegrityChecking failed"
);
}
// Structural check: no .idx entry may reference bytes past the
// end of .dat. The needle map's load walk above already
// populated max_needle_end, so this is a numeric comparison
// — no extra disk I/O. A violation marks the volume read-only
// so vacuum doesn't silently drop reachable data based on a
// corrupt .idx left over from a crashed batched write.
// See issue #8928.
if let Some(ref nm) = self.nm {
if let Ok(dat_size) = self.current_dat_file_size() {
let max_end = nm.max_needle_end();
if dat_size > 0 && max_end > dat_size as i64 {
self.no_write_or_delete = true;
warn!(
volume_id = self.id.0,
max_needle_end = max_end,
dat_size,
"idx references bytes past end of .dat; marking volume read-only"
);
}
}
}
}
}
@@ -759,7 +801,7 @@ impl Volume {
// Open read-only
if Path::new(&idx_path).exists() {
let mut idx_file = File::open(&idx_path)?;
let nm = CompactNeedleMap::load_from_idx(&mut idx_file)?;
let nm = CompactNeedleMap::load_from_idx(&mut idx_file, self.version())?;
self.nm = Some(NeedleMap::InMemory(nm));
} else {
// Missing .idx with existing .dat could orphan needles
@@ -785,7 +827,7 @@ impl Volume {
let idx_size = idx_file.metadata()?.len();
let mut idx_reader = io::BufReader::new(&idx_file);
let mut nm = CompactNeedleMap::load_from_idx(&mut idx_reader)?;
let mut nm = CompactNeedleMap::load_from_idx(&mut idx_reader, self.version())?;
// Re-open for append-only writes
let write_file = OpenOptions::new()
@@ -808,7 +850,7 @@ impl Volume {
// Open read-only
if Path::new(&idx_path).exists() {
let mut idx_file = File::open(&idx_path)?;
let nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_file)?;
let nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_file, self.version())?;
self.nm = Some(NeedleMap::Redb(nm));
} else {
// Missing .idx with existing .dat could orphan needles
@@ -834,7 +876,7 @@ impl Volume {
let idx_size = idx_file.metadata()?.len();
let mut idx_reader = io::BufReader::new(&idx_file);
let mut nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_reader)?;
let mut nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_reader, self.version())?;
// Re-open for append-only writes
let write_file = OpenOptions::new()
@@ -1752,6 +1794,11 @@ impl Volume {
let version = self.version();
// The deeper-than-tail structural check (every (offset + actual size)
// fits inside .dat — issue #8928) is now handled in load() via the
// needle map's max_needle_end accumulator, so we don't pay for a
// second linear scan of the .idx here.
// Check last 10 index entries (matching Go's CheckVolumeDataIntegrity).
// Go starts healthyIndexSize = indexSize and reduces on EOF.
// On success: break (err != ErrorSizeMismatch when err == nil).
@@ -2683,6 +2730,8 @@ impl Volume {
}
entries.sort_by_key(|(_, offset, _)| *offset);
let mut skipped_needles: u64 = 0;
let mut skipped_data_bytes: u64 = 0;
for (id, offset, size) in entries {
// Progress callback
if !progress_fn(offset.to_actual_offset()) {
@@ -2699,7 +2748,41 @@ impl Volume {
id,
..Needle::default()
};
self.read_needle_data_at(&mut n, offset.to_actual_offset(), size)?;
match self.read_needle_data_at(&mut n, offset.to_actual_offset(), size) {
Ok(()) => {}
Err(e) => {
// Record EIO for health monitoring (parity with Go's checkReadWriteError).
if let VolumeError::Io(ref io_err) = e {
self.check_read_write_error(Some(io_err));
}
// Only drop the entry when the failure is one of the well-
// known permanent-corruption shapes. A transient disk fault,
// a tiered-read timeout, or a Windows hardware error (which
// surfaces as a generic Io rather than UnexpectedEof) must
// abort so an operator notices, rather than silently
// compacting away data that might come back on retry.
// See issue #8928.
if !is_skippable_needle_read_error(&e) {
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::Other,
format!("cannot hydrate needle from file: {}", e),
)));
}
skipped_needles += 1;
if size.is_valid() {
skipped_data_bytes += size.0 as u64;
}
warn!(
volume_id = self.id.0,
key = id.0,
offset = offset.to_actual_offset(),
size = size.0,
error = %e,
"vacuum: dropping unreadable needle"
);
continue;
}
}
// Skip TTL-expired needles using the volume's TTL (matches Go's volume_vacuum.go)
if n.has_ttl() {
@@ -2721,6 +2804,15 @@ impl Volume {
new_offset += bytes.len() as i64;
}
if skipped_needles > 0 {
warn!(
volume_id = self.id.0,
skipped_needles,
skipped_data_bytes,
"vacuum: dropped unreadable index entries during compaction"
);
}
dst.sync_all()?;
// Save new index
@@ -3710,6 +3802,138 @@ mod tests {
v.cleanup_compact().unwrap();
}
/// Vacuum compaction must tolerate an .idx entry whose offset points past
/// the end of the .dat file (the failure mode in issue #8928). The bad
/// entry is silently dropped from the resulting .cpx; healthy needles
/// survive untouched.
#[test]
fn test_compact_by_index_drops_dangling_needle() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = make_test_volume(dir);
// Write a handful of healthy needles to establish a baseline .dat/.idx.
for i in 1..=5u64 {
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: format!("payload-{}", i).into_bytes(),
data_size: format!("payload-{}", i).len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
}
v.sync_to_disk().unwrap();
let dat_size = v.dat_file_size().unwrap();
let bad_key = NeedleId(9999);
let bad_offset = Offset::from_actual_offset((dat_size + 1024 * 1024) as i64);
let bad_size = Size(2048);
v.nm
.as_mut()
.expect("needle map present")
.put(bad_key, bad_offset, bad_size)
.unwrap();
v.nm.as_ref().unwrap().sync().unwrap();
// Vacuum must succeed in spite of the dangling entry.
v.compact_by_index(0, 0, |_| true)
.expect("compact_by_index should tolerate dangling entries");
// Walk the resulting .cpx and confirm the bad key was dropped while
// every healthy key made it through.
let cpx_path = v.file_name(".cpx");
let mut cpx = File::open(&cpx_path).unwrap();
let mut kept: Vec<u64> = Vec::new();
idx::walk_index_file(&mut cpx, 0, |key, _, size| {
if !size.is_deleted() {
kept.push(key.0);
}
Ok(())
})
.unwrap();
assert!(
!kept.contains(&bad_key.0),
"dangling key {} should have been dropped from .cpx, got {:?}",
bad_key.0,
kept
);
for i in 1..=5u64 {
assert!(
kept.contains(&i),
"healthy key {} missing from compacted .cpx, got {:?}",
i,
kept
);
}
}
/// The needle map's max_needle_end accumulator must let volume.load
/// detect an .idx whose entries point past the end of the .dat — the
/// deeper-than-tail corruption shape from issue #8928 that the existing
/// last-10-entries scan cannot see. The check is populated by the load
/// walk and read in volume.load() to flip the volume read-only.
#[test]
fn test_max_needle_end_detects_dangling_entry() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = make_test_volume(dir);
for i in 1..=4u64 {
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: format!("data-{}", i).into_bytes(),
data_size: format!("data-{}", i).len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
}
v.sync_to_disk().unwrap();
let dat_size = v.dat_file_size().unwrap() as i64;
let idx_path = v.file_name(".idx");
let version = v.version();
// Sanity: a fresh load walk over the healthy .idx puts max_needle_end
// somewhere inside the .dat.
let mut idx_reader = File::open(&idx_path).unwrap();
let healthy_nm =
CompactNeedleMap::load_from_idx(&mut idx_reader, version).unwrap();
let healthy_end = healthy_nm.max_needle_end();
assert!(
healthy_end > 0 && healthy_end <= dat_size,
"healthy volume should have max_needle_end ({}) in [1, dat_size={}]",
healthy_end,
dat_size
);
// Inject a dangling entry by appending a bogus 16/17-byte record
// directly to the .idx, then reload. The load walk should observe
// max_needle_end past dat_size — which is exactly the signal
// volume.load uses to mark the volume read-only.
let bad_offset = Offset::from_actual_offset(dat_size + 4 * 1024 * 1024);
let mut idx_append = OpenOptions::new()
.write(true)
.append(true)
.open(&idx_path)
.unwrap();
idx::write_index_entry(&mut idx_append, NeedleId(9999), bad_offset, Size(1024))
.unwrap();
idx_append.sync_all().unwrap();
let mut idx_reread = File::open(&idx_path).unwrap();
let bad_nm = CompactNeedleMap::load_from_idx(&mut idx_reread, version).unwrap();
let bad_end = bad_nm.max_needle_end();
assert!(
bad_end > dat_size,
"after dangling-entry inject max_needle_end ({}) should exceed dat_size ({})",
bad_end,
dat_size
);
}
#[test]
fn test_compaction_revision_relookup() {
// Verifies that re_lookup_needle_data_offset returns the correct data offset
+5 -1
View File
@@ -84,11 +84,14 @@ func NewFuseTestFramework(t *testing.T, config *TestConfig) *FuseTestFramework {
// freePort asks the OS for a free TCP port in a range where the gRPC
// offset (port + 10000) won't collide with well-known ports.
// Stay below the Linux ephemeral floor (32768) so the kernel does not
// reuse the chosen port for an outbound connection between close() here
// and re-bind in the child "weed mini" process.
func freePort(t *testing.T) int {
t.Helper()
const (
minServicePort = 20000
maxServicePort = 55535
maxServicePort = 32000
)
portCount := maxServicePort - minServicePort + 1
@@ -247,6 +250,7 @@ func (f *FuseTestFramework) startMini(config *TestConfig) error {
"mini",
"-dir=" + f.dataDir,
"-ip=127.0.0.1",
"-ip.bind=127.0.0.1",
"-filer.port=" + strconv.Itoa(f.filerPort),
"-s3=false",
"-webdav=false",
+390
View File
@@ -0,0 +1,390 @@
//go:build linux || darwin
package fuse_p2p
import (
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"syscall"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/testutil"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/stretchr/testify/require"
)
// p2pTestCluster manages a minimal SeaweedFS cluster exercising the peer
// chunk-sharing (p2p) read path: 1 master, 1 volume, 1 filer, and N FUSE
// mounts that all have -peer.enable set. Three mounts is the sweet spot
// for integration testing — with 2 mounts the HRW owner of a chunk is
// ~50% the reader itself (which short-circuits the peer path); with 3+
// mounts it's ≤ 1/3, so a multi-chunk file almost certainly exercises
// the remote-owner fan-out.
type p2pTestCluster struct {
t testing.TB
baseDir string
weedBinary string
masterPort int
masterGrpcPort int
volumePort int
volumeGrpcPort int
filerPort int
filerGrpcPort int
mountPeerPorts []int
mountPoints []string
masterCmd *exec.Cmd
volumeCmd *exec.Cmd
filerCmd *exec.Cmd
mountCmds []*exec.Cmd
logFiles []*os.File
cleanupOnce sync.Once
}
// startP2PTestCluster brings up a cluster with numMounts FUSE mounts,
// every one advertising on its own -peer.listen port. All mounts register
// with the same filer. Verbose logging (-v=4) is enabled on each mount so
// peer-read success/failure messages land in the log file and the test
// can grep them to verify the p2p path fired.
func startP2PTestCluster(t testing.TB, numMounts int) *p2pTestCluster {
require.GreaterOrEqual(t, numMounts, 2, "need at least 2 mounts to exercise p2p")
binary := findWeedBinary()
if binary == "" {
t.Skip("weed binary not found; set WEED_BINARY or ensure it is on PATH")
}
baseDir, err := os.MkdirTemp("", "seaweedfs_fuse_p2p_test_")
require.NoError(t, err)
c := &p2pTestCluster{
t: t,
baseDir: baseDir,
weedBinary: binary,
mountPeerPorts: make([]int, numMounts),
mountPoints: make([]string, numMounts),
mountCmds: make([]*exec.Cmd, numMounts),
}
t.Cleanup(c.Stop)
// master(2) + volume(2) + filer(2) + one peer port per mount.
// testutil.AllocatePorts holds all listeners open until every port
// is reserved, avoiding the brief close→bind race that would
// happen with a per-listener close loop.
ports, err := testutil.AllocatePorts(6 + numMounts)
require.NoError(t, err)
c.masterPort = ports[0]
c.masterGrpcPort = ports[1]
c.volumePort = ports[2]
c.volumeGrpcPort = ports[3]
c.filerPort = ports[4]
c.filerGrpcPort = ports[5]
for i := 0; i < numMounts; i++ {
c.mountPeerPorts[i] = ports[6+i]
}
configDir := filepath.Join(baseDir, "config")
require.NoError(t, os.MkdirAll(configDir, 0755))
require.NoError(t, os.WriteFile(filepath.Join(configDir, "security.toml"), []byte(""), 0644))
require.NoError(t, c.startMaster(configDir))
require.NoError(t, c.waitForTCP(c.masterCmd, "master",
fmt.Sprintf("127.0.0.1:%d", c.masterPort), 30*time.Second))
require.NoError(t, c.startVolume(configDir))
require.NoError(t, c.waitForTCP(c.volumeCmd, "volume",
fmt.Sprintf("127.0.0.1:%d", c.volumePort), 30*time.Second))
require.NoError(t, c.startFiler(configDir))
require.NoError(t, c.waitForTCP(c.filerCmd, "filer",
fmt.Sprintf("127.0.0.1:%d", c.filerGrpcPort), 30*time.Second))
for i := 0; i < numMounts; i++ {
mp := filepath.Join(baseDir, fmt.Sprintf("mount%d", i))
require.NoError(t, os.MkdirAll(mp, 0755))
c.mountPoints[i] = mp
require.NoError(t, c.startMount(i, configDir))
require.NoError(t, c.waitForMount(mp, 30*time.Second),
"mount %d not ready\n%s", i, c.tailLog(fmt.Sprintf("mount%d", i)))
}
return c
}
func (c *p2pTestCluster) Stop() {
if c == nil {
return
}
c.cleanupOnce.Do(func() {
for i := len(c.mountCmds) - 1; i >= 0; i-- {
stopCmd(c.mountCmds[i])
// Backup unmount in case the FUSE teardown didn't clean up.
exec.Command("fusermount3", "-u", c.mountPoints[i]).Run()
exec.Command("fusermount", "-u", c.mountPoints[i]).Run()
}
stopCmd(c.filerCmd)
stopCmd(c.volumeCmd)
stopCmd(c.masterCmd)
for _, f := range c.logFiles {
f.Close()
}
c.copyLogsForCI()
if !c.t.Failed() {
os.RemoveAll(c.baseDir)
}
time.Sleep(2 * time.Second) // let ports drain
})
}
// MountDir returns the filesystem path of the i-th mount.
func (c *p2pTestCluster) MountDir(i int) string { return c.mountPoints[i] }
// masterAddress / filerAddress return SeaweedFS-style addresses encoding
// both ports as "host:httpPort.grpcPort". Without this, downstream
// components fall back to the grpcPort = httpPort + 10000 default,
// which doesn't match the random port we allocate.
func (c *p2pTestCluster) masterAddress() string {
return string(pb.NewServerAddress("127.0.0.1", c.masterPort, c.masterGrpcPort))
}
func (c *p2pTestCluster) filerAddress() string {
return string(pb.NewServerAddress("127.0.0.1", c.filerPort, c.filerGrpcPort))
}
// MountLog returns the contents of mount i's log file.
func (c *p2pTestCluster) MountLog(i int) string {
return c.tailLogFull(fmt.Sprintf("mount%d", i))
}
func (c *p2pTestCluster) startMaster(configDir string) error {
c.masterCmd = exec.Command(c.weedBinary,
"-logdir="+filepath.Join(c.baseDir, "logs"),
"master",
"-ip=127.0.0.1",
"-ip.bind=127.0.0.1",
"-port="+strconv.Itoa(c.masterPort),
"-port.grpc="+strconv.Itoa(c.masterGrpcPort),
"-mdir="+filepath.Join(c.baseDir, "master"),
)
return c.startCmd(c.masterCmd, "master")
}
func (c *p2pTestCluster) startVolume(configDir string) error {
volDir := filepath.Join(c.baseDir, "volume")
if err := os.MkdirAll(volDir, 0755); err != nil {
return fmt.Errorf("create volume dir: %w", err)
}
c.volumeCmd = exec.Command(c.weedBinary,
"-logdir="+filepath.Join(c.baseDir, "logs"),
"volume",
"-ip=127.0.0.1",
"-ip.bind=127.0.0.1",
"-port="+strconv.Itoa(c.volumePort),
"-port.grpc="+strconv.Itoa(c.volumeGrpcPort),
"-master="+c.masterAddress(),
"-dir="+volDir,
"-max=10",
)
return c.startCmd(c.volumeCmd, "volume")
}
func (c *p2pTestCluster) startFiler(configDir string) error {
filerDir := filepath.Join(c.baseDir, "filer")
if err := os.MkdirAll(filerDir, 0755); err != nil {
return fmt.Errorf("create filer dir: %w", err)
}
c.filerCmd = exec.Command(c.weedBinary,
"-logdir="+filepath.Join(c.baseDir, "logs"),
"filer",
"-ip=127.0.0.1",
"-ip.bind=127.0.0.1",
"-port="+strconv.Itoa(c.filerPort),
"-port.grpc="+strconv.Itoa(c.filerGrpcPort),
"-master="+c.masterAddress(),
"-defaultStoreDir="+filerDir,
// default is -mount.p2p=true; be explicit so the intent is grep-able.
"-mount.p2p=true",
)
return c.startCmd(c.filerCmd, "filer")
}
func (c *p2pTestCluster) startMount(idx int, configDir string) error {
cacheDir := filepath.Join(c.baseDir, fmt.Sprintf("cache%d", idx))
if err := os.MkdirAll(cacheDir, 0755); err != nil {
return fmt.Errorf("create cache dir: %w", err)
}
c.mountCmds[idx] = exec.Command(c.weedBinary,
"-logdir="+filepath.Join(c.baseDir, "logs"),
"-v=4",
"mount",
"-filer="+c.filerAddress(),
"-dir="+c.mountPoints[idx],
"-filer.path=/",
"-dirAutoCreate",
"-allowOthers=false",
"-cacheDir="+cacheDir,
"-peer.enable=true",
fmt.Sprintf("-peer.listen=127.0.0.1:%d", c.mountPeerPorts[idx]),
fmt.Sprintf("-peer.advertise=127.0.0.1:%d", c.mountPeerPorts[idx]),
"-peer.dataCenter=dc1",
fmt.Sprintf("-peer.rack=rack%d", idx),
)
return c.startCmd(c.mountCmds[idx], fmt.Sprintf("mount%d", idx))
}
func (c *p2pTestCluster) startCmd(cmd *exec.Cmd, name string) error {
logPath := filepath.Join(c.baseDir, "logs")
if err := os.MkdirAll(logPath, 0755); err != nil {
return fmt.Errorf("create log dir: %w", err)
}
logFile, err := os.Create(filepath.Join(logPath, name+".log"))
if err != nil {
return err
}
c.logFiles = append(c.logFiles, logFile)
cmd.Stdout = logFile
cmd.Stderr = logFile
return cmd.Start()
}
func (c *p2pTestCluster) tailLog(name string) string {
data, err := os.ReadFile(filepath.Join(c.baseDir, "logs", name+".log"))
if err != nil {
return fmt.Sprintf("(log %s not available: %v)", name, err)
}
const maxTail = 8192
if len(data) > maxTail {
data = data[len(data)-maxTail:]
}
return string(data)
}
func (c *p2pTestCluster) tailLogFull(name string) string {
data, err := os.ReadFile(filepath.Join(c.baseDir, "logs", name+".log"))
if err != nil {
return ""
}
return string(data)
}
func (c *p2pTestCluster) copyLogsForCI() {
ciLogDir := "/tmp/seaweedfs-fuse-p2p-logs"
os.MkdirAll(ciLogDir, 0755)
logsDir := filepath.Join(c.baseDir, "logs")
entries, err := os.ReadDir(logsDir)
if err != nil {
return
}
for _, e := range entries {
data, err := os.ReadFile(filepath.Join(logsDir, e.Name()))
if err != nil {
continue
}
os.WriteFile(filepath.Join(ciLogDir, e.Name()), data, 0644)
}
}
// waitForTCP polls addr until it accepts a connection, OR the supplied
// subprocess exits — whichever comes first. Short-circuiting on child
// exit turns a 30 s-spin-on-dead-process into an immediate failure with
// the tail of its log. cmd may be nil for callers that don't track a
// process; in that case we fall back to pure polling.
//
// Liveness is checked with signal 0 (POSIX "is this process alive").
// We deliberately do NOT call cmd.Wait() in a goroutine here because
// stopCmd() later calls Wait() at shutdown, and only one Wait per
// process is allowed.
func (c *p2pTestCluster) waitForTCP(cmd *exec.Cmd, name, addr string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
conn, err := net.DialTimeout("tcp", addr, time.Second)
if err == nil {
conn.Close()
return nil
}
if cmd != nil && cmd.Process != nil {
// signal 0 doesn't actually send anything; it just asks
// the kernel whether the process exists. An error here
// (typically "process already finished" or ESRCH) means
// the child died before coming up.
if sigErr := cmd.Process.Signal(syscall.Signal(0)); sigErr != nil {
return fmt.Errorf("%s exited before listening on %s: %v\n%s",
name, addr, sigErr, c.tailLog(name))
}
}
time.Sleep(200 * time.Millisecond)
}
return fmt.Errorf("service at %s not ready within timeout\n%s", addr, c.tailLog(name))
}
// waitForMount waits for a FUSE filesystem to actually be mounted by
// watching the device id flip (FUSE mounts have a different Dev than
// their parent dir).
func (c *p2pTestCluster) waitForMount(mountPoint string, timeout time.Duration) error {
parentDir := filepath.Dir(mountPoint)
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
parentStat, err := os.Stat(parentDir)
if err != nil {
time.Sleep(200 * time.Millisecond)
continue
}
mountStat, err := os.Stat(mountPoint)
if err != nil {
time.Sleep(200 * time.Millisecond)
continue
}
parentSys := parentStat.Sys().(*syscall.Stat_t)
mountSys := mountStat.Sys().(*syscall.Stat_t)
if parentSys.Dev != mountSys.Dev {
return nil
}
time.Sleep(200 * time.Millisecond)
}
return fmt.Errorf("mount point %s not ready within timeout (FUSE not detected)", mountPoint)
}
// --- utilities (binary discovery, process shutdown) ---
//
// Port allocation is delegated to testutil.MustAllocatePorts, which
// holds all listeners open until every port is reserved before
// returning them in a batch — safer than the per-listener
// close-then-reserve pattern fuse_dlm originally used.
func findWeedBinary() string {
if env := os.Getenv("WEED_BINARY"); env != "" {
if _, err := os.Stat(env); err == nil {
return env
}
}
if p, err := exec.LookPath("weed"); err == nil {
return p
}
return ""
}
// stopCmd kills a child process with SIGTERM and waits up to 5 s, then
// escalates to SIGKILL. Tolerates nil and already-exited processes.
func stopCmd(cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
}
cmd.Process.Signal(syscall.SIGTERM)
done := make(chan struct{})
go func() {
cmd.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
cmd.Process.Signal(syscall.SIGKILL)
<-done
}
}
+147
View File
@@ -0,0 +1,147 @@
package fuse_p2p
import (
"bytes"
"crypto/md5"
"fmt"
"math/rand/v2"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// peerReadSuccessMarker is the log line tryPeerRead emits when a peer
// fetch succeeded. The test greps non-writer mount logs for it to
// prove the p2p path fired. At glog verbosity 4 (framework sets -v=4).
const peerReadSuccessMarker = "peer read successful"
// seedConvergenceTimeout bounds how long the test waits for:
// - the filer registry to list all mounts,
// - every mount's seed view (via MountList poll) to include all peers,
// - the first announcer flush cycle to publish chunk holders.
//
// With defaults the mount polls MountList every 30 s and flushes
// ChunkAnnounce every 15 s. Allowing 45 s absorbs one MountList refresh
// plus one announce cycle plus some slop for CI variance.
const seedConvergenceTimeout = 90 * time.Second
// TestPeerChunkSharing_ReadersPullFromPeerCache is the headline p2p
// integration test. It proves at least one non-writer mount can satisfy
// a read from the writer's chunk cache instead of the volume tier.
//
// 1. Bring up 1 master/volume/filer + 3 mounts, all with -peer.enable.
// 2. Mount 0 writes a ~8 MiB file and reads it back so chunks land in
// its local cache and the announcer publishes them.
// 3. Wait for seed convergence + at least one announcer flush cycle.
// 4. BOTH mount 1 and mount 2 read the file.
//
// Why both readers: with 3 mounts, HRW picks one owner for the chunk.
// If that owner is mount 1, only mount 2's read will hit the peer
// path (mount 1's tryPeerRead bails on owner==self). If that owner is
// mount 2, only mount 1's read will. If that owner is mount 0 (the
// writer), both can. So by reading from both, we deterministically
// guarantee at least one non-writer mount exercises the peer path.
//
// Once the peer fetch populates its local cache, subsequent reads
// short-circuit on IsInCache — so we only get one real shot per mount
// per chunk. That's fine: one success is all the test needs.
func TestPeerChunkSharing_ReadersPullFromPeerCache(t *testing.T) {
c := startP2PTestCluster(t, 3)
// ~8 MiB, pseudo-random so compression doesn't collapse it to one block.
payload := make([]byte, 8*1024*1024)
rng := rand.New(rand.NewPCG(1, 2))
for i := range payload {
payload[i] = byte(rng.Uint32())
}
const relPath = "p2p-test.bin"
writer := c.MountDir(0)
require.NoError(t, os.WriteFile(filepath.Join(writer, relPath), payload, 0644))
// Warm mount 0's chunk cache by reading back through its own FUSE.
// Without this the chunks are on the volume server but not yet
// in anyone's peer-servable cache.
readBack, err := os.ReadFile(filepath.Join(writer, relPath))
require.NoError(t, err)
require.True(t, bytes.Equal(readBack, payload), "write-then-read on writer mount should match")
waitForSeedConvergence(t, c, seedConvergenceTimeout)
// Give the announcer several flush windows to push chunk-holder
// entries to the HRW owners. First flush may see the writer's seed
// view incomplete (only self) and defer all fids; subsequent
// flushes re-check against a refreshed seed view. announce interval
// is 15 s, so 45 s covers three attempts.
time.Sleep(45 * time.Second)
// Read from both non-writer mounts. For any HRW outcome on any
// chunk, at least one of these reads will NOT have the reader as
// the HRW owner, so its tryPeerRead will proceed to ChunkLookup +
// FetchChunk.
for _, idx := range []int{1, 2} {
got, err := os.ReadFile(filepath.Join(c.MountDir(idx), relPath))
require.NoError(t, err, "read from mount %d must succeed\n--- mount%d ---\n%s",
idx, idx, tailLines(c.MountLog(idx), 80))
require.Equal(t, md5.Sum(payload), md5.Sum(got),
"mount %d returned mismatched bytes (len got=%d want=%d)", idx, len(got), len(payload))
}
// Content matches alone doesn't prove p2p — the volume fallback
// would also satisfy the reads. Require at least one non-writer
// mount's log to contain the peer-read success marker.
var sawPeerRead bool
for _, idx := range []int{1, 2} {
if strings.Contains(c.MountLog(idx), peerReadSuccessMarker) {
sawPeerRead = true
break
}
}
if !sawPeerRead {
t.Fatalf("no non-writer mount logged %q — peer read path never fired.\n"+
"--- mount0 (writer) tail ---\n%s\n--- mount1 tail ---\n%s\n--- mount2 tail ---\n%s",
peerReadSuccessMarker,
tailLines(c.MountLog(0), 60), tailLines(c.MountLog(1), 60), tailLines(c.MountLog(2), 60))
}
}
// waitForSeedConvergence polls each mount's log looking for any sign
// that MountList returned a peer list containing the other mounts.
func waitForSeedConvergence(t *testing.T, c *p2pTestCluster, timeout time.Duration) {
t.Helper()
// The first MountRegister happens synchronously during mount startup,
// and the first MountList is pulled right after. 30 s is the refresh
// interval; waiting one full cycle here guarantees every mount has
// at minimum observed the others in its seed view.
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
ready := true
for i := range c.mountCmds {
if !strings.Contains(c.MountLog(i), "peer-grpc listening on") {
ready = false
break
}
}
if ready {
time.Sleep(30 * time.Second)
return
}
time.Sleep(500 * time.Millisecond)
}
t.Fatalf("peer-grpc servers did not come up within %s", timeout)
}
// tailLines returns the last n newline-delimited lines of s, or the
// whole thing if shorter. Keeps test failures readable.
func tailLines(s string, n int) string {
lines := strings.Split(s, "\n")
if len(lines) <= n {
return s
}
return fmt.Sprintf("... (%d earlier lines omitted) ...\n%s",
len(lines)-n, strings.Join(lines[len(lines)-n:], "\n"))
}
+11 -10
View File
@@ -45,7 +45,7 @@ require (
github.com/aws/aws-sdk-go v1.55.8 // indirect
github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.13 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.14 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 // indirect
@@ -57,7 +57,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.98.0 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
@@ -70,6 +70,7 @@ require (
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
github.com/buengese/sgzip v0.1.1 // indirect
github.com/buger/jsonparser v1.1.2 // indirect
github.com/bwmarrin/snowflake v0.3.0 // indirect
github.com/calebcase/tmpfile v1.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chilts/sid v0.0.0-20190607042430-660e94789ec9 // indirect
@@ -241,20 +242,20 @@ require (
go.mongodb.org/mongo-driver v1.17.9 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect
go.opentelemetry.io/otel v1.42.0 // indirect
go.opentelemetry.io/otel/metric v1.42.0 // indirect
go.opentelemetry.io/otel/trace v1.42.0 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/metric v1.43.0 // indirect
go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.49.0 // indirect
golang.org/x/crypto v0.50.0 // indirect
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
golang.org/x/image v0.38.0 // indirect
golang.org/x/net v0.52.0 // indirect
golang.org/x/net v0.53.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/term v0.41.0 // indirect
golang.org/x/text v0.35.0 // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/term v0.42.0 // indirect
golang.org/x/text v0.36.0 // indirect
golang.org/x/time v0.15.0 // indirect
google.golang.org/api v0.274.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 // indirect
+28 -26
View File
@@ -116,8 +116,8 @@ github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV
github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
github.com/aws/aws-sdk-go-v2/config v1.32.13 h1:5KgbxMaS2coSWRrx9TX/QtWbqzgQkOdEa3sZPhBhCSg=
github.com/aws/aws-sdk-go-v2/config v1.32.13/go.mod h1:8zz7wedqtCbw5e9Mi2doEwDyEgHcEE9YOJp6a8jdSMY=
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
github.com/aws/aws-sdk-go-v2/config v1.32.14/go.mod h1:U4/V0uKxh0Tl5sxmCBZ3AecYny4UNlVmObYjKuuaiOo=
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8THYELoX6gVcUvgl6fI=
github.com/aws/aws-sdk-go-v2/credentials v1.19.14/go.mod h1:cJKuyWB59Mqi0jM3nFYQRmnHVQIcgoxjEMAbLkpr62w=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeDLaS3bmHD0YndtA6UP884g=
@@ -140,8 +140,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3x
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
github.com/aws/aws-sdk-go-v2/service/s3 v1.98.0 h1:foqo/ocQ7WqKwy3FojGtZQJo0FR4vto9qnz9VaumbCo=
github.com/aws/aws-sdk-go-v2/service/s3 v1.98.0/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0 h1:hlSuz394kV0vhv9drL5lhuEFbEOEP1VyQpy15qWh1Pk=
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 h1:QKZH0S178gCmFEgst8hN0mCX1KxLgHBKKY/CLqwP8lg=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9/go.mod h1:7yuQJoT+OoH8aqIxw9vwF+8KpvLZ8AWmvmUWHsGQZvI=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 h1:lFd1+ZSEYJZYvv9d6kXzhkZu07si3f+GQ1AaYwa2LUM=
@@ -170,6 +170,8 @@ github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
@@ -752,16 +754,16 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
@@ -785,8 +787,8 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -867,8 +869,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -944,8 +946,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -957,8 +959,8 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -974,8 +976,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1028,8 +1030,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+65 -17
View File
@@ -10,6 +10,14 @@ import (
"github.com/segmentio/kafka-go"
)
const (
consumerGroupHeartbeatInterval = 2 * time.Second
consumerGroupSessionTimeout = 6 * time.Second
consumerGroupRebalanceTimeout = 6 * time.Second
consumerGroupJoinBackoff = 250 * time.Millisecond
consumerGroupAttemptTimeout = 15 * time.Second
)
// KafkaGoClient wraps kafka-go client with test utilities
type KafkaGoClient struct {
brokerAddr string
@@ -128,40 +136,81 @@ func (k *KafkaGoClient) ConsumeMessages(topicName string, expectedCount int) ([]
return messages, nil
}
// ConsumeWithGroup consumes messages using consumer group
// ConsumeWithGroup consumes messages using consumer group.
// Retries the initial join+fetch with a fresh reader if it fails before any
// message is received — re-joining an existing group races with the previous
// member's LeaveGroup / session cleanup and can surface as an i/o timeout on
// the first FetchMessage.
func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCount int) ([]kafka.Message, error) {
k.t.Helper()
const maxJoinAttempts = 5
var lastErr error
for attempt := 1; attempt <= maxJoinAttempts; attempt++ {
messages, err, progressed := k.consumeWithGroupOnce(topicName, groupID, expectedCount)
if err == nil {
return messages, nil
}
lastErr = err
// Only retry if we failed before any message was received. Once we've
// fetched at least one message, a partial result is more useful than a
// full retry (which would start over from the last committed offset).
if progressed {
return messages, err
}
if attempt == maxJoinAttempts {
break
}
backoff := time.Duration(500*(1<<(attempt-1))) * time.Millisecond
k.t.Logf("ConsumeWithGroup join attempt %d/%d failed (%v) — retrying after %v", attempt, maxJoinAttempts, err, backoff)
time.Sleep(backoff)
}
return nil, lastErr
}
// consumeWithGroupOnce runs a single consume attempt. Returns the messages
// fetched, any error, and whether any message was received (used to decide
// whether a retry is safe).
func (k *KafkaGoClient) consumeWithGroupOnce(topicName, groupID string, expectedCount int) ([]kafka.Message, error, bool) {
// Give each reader its own ClientID so restarts do not get mistaken for the
// still-shutting-down reader they are replacing.
dialer := &kafka.Dialer{
ClientID: fmt.Sprintf("seaweedfs-e2e-%s-%d", groupID, time.Now().UnixNano()),
Timeout: 10 * time.Second,
}
reader := kafka.NewReader(kafka.ReaderConfig{
Brokers: []string{k.brokerAddr},
Topic: topicName,
GroupID: groupID,
MinBytes: 1,
MaxBytes: 10e6,
CommitInterval: 500 * time.Millisecond,
Brokers: []string{k.brokerAddr},
Dialer: dialer,
Topic: topicName,
GroupID: groupID,
MinBytes: 1,
MaxBytes: 10e6,
CommitInterval: 500 * time.Millisecond,
HeartbeatInterval: consumerGroupHeartbeatInterval,
SessionTimeout: consumerGroupSessionTimeout,
RebalanceTimeout: consumerGroupRebalanceTimeout,
JoinGroupBackoff: consumerGroupJoinBackoff,
})
defer reader.Close()
// Log the initial offset position
offset := reader.Offset()
k.t.Logf("Consumer group reader created for group %s, initial offset: %d", groupID, offset)
// Increased timeout for consumer groups - they require coordinator discovery,
// offset fetching, and offset commits which can be slow in CI environments
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
// Keep each attempt short enough that a retry can outlive a stale group
// member instead of burning most of the overall test timeout on one try.
ctx, cancel := context.WithTimeout(context.Background(), consumerGroupAttemptTimeout)
defer cancel()
var messages []kafka.Message
for i := 0; i < expectedCount; i++ {
// Fetch then explicitly commit to better control commit timing
msg, err := reader.FetchMessage(ctx)
if err != nil {
return messages, fmt.Errorf("read message %d: %w", i, err)
return messages, fmt.Errorf("read message %d: %w", i, err), len(messages) > 0
}
messages = append(messages, msg)
k.t.Logf(" Fetched message %d: offset=%d, partition=%d", i, msg.Offset, msg.Partition)
// Commit with simple retry to handle transient connection churn
var commitErr error
for attempt := 0; attempt < 3; attempt++ {
commitErr = reader.CommitMessages(ctx, msg)
@@ -170,16 +219,15 @@ func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCoun
break
}
k.t.Logf(" Commit attempt %d failed for offset %d: %v", attempt+1, msg.Offset, commitErr)
// brief backoff
time.Sleep(time.Duration(50*(1<<attempt)) * time.Millisecond)
}
if commitErr != nil {
return messages, fmt.Errorf("committing message %d: %w", i, commitErr)
return messages, fmt.Errorf("committing message %d: %w", i, commitErr), true
}
}
k.t.Logf("Consumed %d messages from topic %s with group %s", len(messages), topicName, groupID)
return messages, nil
return messages, nil, true
}
// CreateTopic creates a topic using Sarama
@@ -17,16 +17,18 @@ COPY test/kafka/kafka-client-loadtest/ ./
RUN CGO_ENABLED=0 GOOS=linux go build -o /kafka-loadtest ./cmd/loadtest
# Stage 2: Runtime
FROM ubuntu:22.04
# Use alpine so we don't depend on Ubuntu apt mirrors, which intermittently
# refuse connections from GitHub Actions runners and fail the CI build.
# All runtime dependencies we need (ca-certificates, curl, jq, bash, nc)
# are in the Alpine main repo.
FROM alpine:3.20
# Install runtime dependencies
RUN apt-get update && apt-get install -y \
RUN apk add --no-cache \
ca-certificates \
curl \
jq \
bash \
netcat \
&& rm -rf /var/lib/apt/lists/*
netcat-openbsd
# Copy built binary from builder stage
COPY --from=builder /kafka-loadtest /usr/local/bin/kafka-loadtest
@@ -1,7 +1,8 @@
FROM openjdk:11-jdk-slim
# Install Maven
RUN apt-get update && apt-get install -y maven && rm -rf /var/lib/apt/lists/*
# Use the official Eclipse Temurin + Maven image so we don't depend on
# Debian apt mirrors, which intermittently refuse connections from
# GitHub Actions runners and fail the CI build. This image already has
# JDK 11 and Maven installed.
FROM maven:3.9-eclipse-temurin-11
WORKDIR /app
+2 -2
View File
@@ -1,7 +1,7 @@
FROM chrislusf/seaweedfs:e2e
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive apt-get install -y \
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
--no-install-recommends \
--no-install-suggests \
autoconf \
+283
View File
@@ -0,0 +1,283 @@
// Reproduction tests for https://github.com/seaweedfs/seaweedfs/issues/9103
//
// The issue reports two distinct failure modes when using DuckDB against the
// SeaweedFS Iceberg REST catalog:
//
// 1. `ATTACH 's3://test/' AS cat (TYPE 'ICEBERG', ...); SELECT * FROM cat.ovirt.disk;`
// fails with "Table with name 'ovirt.disk' does not exist because schema
// 'ovirt' does not exist." The namespace "ovirt" does exist in the bucket.
//
// 2. `SELECT * FROM iceberg_scan('s3://test/ovirt/disk');` fails with HTTP 403
// AccessDenied when DuckDB tries to glob `s3://test/ovirt/disk/metadata/v*`
// because the LoadTable response does not vend S3 file-io credentials back
// to the client.
//
// These tests reproduce the underlying catalog-level misbehavior at the REST
// protocol layer so they run quickly and deterministically. A DuckDB-based
// end-to-end reproduction is also included (gated on Docker availability).
package catalog
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/test/testutil"
)
// TestIssue9103_ConfigDoesNotVendWarehousePrefix reproduces failure mode #2.
//
// Per the Iceberg REST spec, a client attaching with warehouse=s3://<bucket>/
// calls GET /v1/config?warehouse=s3://<bucket>/ and expects the server to
// return an `overrides.prefix` that identifies the catalog namespace for
// subsequent requests. Without it the client falls back to unprefixed paths
// like /v1/namespaces, which on SeaweedFS resolve to the hard-coded default
// bucket ("warehouse") and therefore do not list the user's namespaces.
//
// Currently the handler ignores the warehouse query parameter and returns
// empty defaults/overrides. That is exactly what makes DuckDB's ATTACH flow
// report `schema "ovirt" does not exist`.
func TestIssue9103_ConfigDoesNotVendWarehousePrefix(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
env := sharedEnv
bucketName := "warehouse-9103cfg-" + randomSuffix()
createTableBucket(t, env, bucketName)
warehouse := fmt.Sprintf("s3://%s/", bucketName)
u := fmt.Sprintf("%s/v1/config?warehouse=%s", env.IcebergURL(), url.QueryEscape(warehouse))
status, body, err := doIcebergJSONRequest(env, http.MethodGet, fmt.Sprintf("/v1/config?warehouse=%s", url.QueryEscape(warehouse)), nil)
if err != nil {
t.Fatalf("GET %s failed: %v", u, err)
}
if status != http.StatusOK {
t.Fatalf("GET %s status = %d, want 200", u, status)
}
overrides, _ := body["overrides"].(map[string]any)
gotPrefix, _ := overrides["prefix"].(string)
if gotPrefix != bucketName {
t.Fatalf("GET /v1/config?warehouse=%s: overrides.prefix = %q, want %q (catalog must echo the warehouse's table bucket so clients like DuckDB know which /v1/{prefix}/namespaces to use)",
warehouse, gotPrefix, bucketName)
}
}
// TestIssue9103_BareNamespacesListMissesNamespaceInAttachedBucket
// demonstrates the downstream effect of the /v1/config bug.
//
// The client created the namespace "ovirt" inside bucket "test" (via
// /v1/{bucket}/namespaces), but when it later issues GET /v1/namespaces (no
// prefix, because /v1/config didn't give it one), that request resolves to
// the default bucket and returns no namespaces. DuckDB surfaces this as
// `schema "ovirt" does not exist`.
func TestIssue9103_BareNamespacesListMissesNamespaceInAttachedBucket(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
env := sharedEnv
bucketName := "warehouse-9103ns-" + randomSuffix()
createTableBucket(t, env, bucketName)
namespace := "ovirt"
status, _, err := doIcebergJSONRequest(env, http.MethodPost,
icebergPath(bucketName, "/v1/namespaces"),
map[string]any{"namespace": []string{namespace}})
if err != nil {
t.Fatalf("create namespace: %v", err)
}
if status != http.StatusOK && status != http.StatusConflict {
t.Fatalf("create namespace status = %d, want 200 or 409", status)
}
// Sanity: prefixed listing finds the namespace.
status, prefixedBody, err := doIcebergJSONRequest(env, http.MethodGet,
icebergPath(bucketName, "/v1/namespaces"), nil)
if err != nil {
t.Fatalf("list namespaces with prefix: %v", err)
}
if status != http.StatusOK {
t.Fatalf("prefixed list status = %d, want 200", status)
}
if !containsNamespace(prefixedBody, namespace) {
t.Fatalf("prefixed list missing namespace %q: %v", namespace, prefixedBody)
}
// Simulate what a DuckDB-style client does when /v1/config did not vend a
// prefix: it falls back to the unprefixed listing. It should still be
// able to discover the namespace (e.g. via a warehouse query parameter),
// but today it cannot, which is the user-visible bug.
bareWarehouse := "s3://" + bucketName + "/"
status, bareBody, err := doIcebergJSONRequest(env, http.MethodGet,
fmt.Sprintf("/v1/namespaces?warehouse=%s", url.QueryEscape(bareWarehouse)), nil)
if err != nil {
t.Fatalf("bare list namespaces: %v", err)
}
switch {
case status != http.StatusOK:
t.Fatalf("GET /v1/namespaces?warehouse=%s status = %d, want 200 (server ignores the warehouse query parameter and falls back to the default %q bucket, causing DuckDB to see no schemas)",
bareWarehouse, status, "warehouse")
case !containsNamespace(bareBody, namespace):
t.Fatalf("GET /v1/namespaces?warehouse=%s did not return %q: %v (server must honor the warehouse query parameter here or vend overrides.prefix from /v1/config so the client can route to the right bucket)",
bareWarehouse, namespace, bareBody)
}
}
// TestIssue9103_DuckDBAttachCannotResolveNamespace is the end-to-end
// reproduction of the issue using DuckDB in Docker, mirroring the exact
// sequence of commands from the bug report. It runs under its own weed
// mini with IAM configured so the OAuth2 client_credentials flow that
// DuckDB's iceberg extension requires actually works (the shared env has
// no credentials registered). Gated on Docker availability.
func TestIssue9103_DuckDBAttachCannotResolveNamespace(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !testutil.HasDocker() {
t.Skip("Docker not available, skipping DuckDB integration reproduction")
}
env := newOAuthTestEnv(t)
defer env.cleanup(t)
env.start(t)
bucketName := "test9103-" + randomSuffix()
createTableBucketViaShell(t, env, bucketName)
namespace := "ovirt"
tableName := "disk"
token := requestOAuthToken(t, env, env.accessKey, env.secretKey)
createNamespaceWithToken(t, env, token, bucketName, namespace)
createTableWithToken(t, env, token, bucketName, namespace, tableName)
sql := fmt.Sprintf(`
INSTALL iceberg;
LOAD iceberg;
CREATE SECRET test_berg (
TYPE ICEBERG,
ENDPOINT 'http://host.docker.internal:%d',
SCOPE 's3://%s/',
CLIENT_ID '%s',
CLIENT_SECRET '%s'
);
CREATE SECRET s3_berg (
TYPE S3,
KEY_ID '%s',
SECRET '%s',
ENDPOINT 'host.docker.internal:%d',
URL_STYLE 'path',
USE_SSL false,
SCOPE 's3://%s/'
);
ATTACH 's3://%s/' AS test_catalog (TYPE 'ICEBERG', secret test_berg);
SELECT * FROM test_catalog.%s.%s LIMIT 0;
`, env.icebergPort, bucketName,
env.accessKey, env.secretKey,
env.accessKey, env.secretKey, env.s3Port, bucketName,
bucketName, namespace, tableName)
sqlFile := filepath.Join(env.dataDir, "issue_9103.sql")
if err := os.WriteFile(sqlFile, []byte(sql), 0644); err != nil {
t.Fatalf("write SQL: %v", err)
}
cmd := exec.Command("docker", "run", "--rm",
"-v", fmt.Sprintf("%s:/test", env.dataDir),
"--add-host", "host.docker.internal:host-gateway",
"-e", "AWS_REGION=us-east-1",
"--entrypoint", "duckdb",
"duckdb/duckdb:latest",
"-init", "/test/issue_9103.sql",
"-c", "SELECT 1",
)
out, runErr := cmd.CombinedOutput()
outStr := string(out)
t.Logf("DuckDB output:\n%s", outStr)
if strings.Contains(outStr, "iceberg extension is not available") ||
strings.Contains(outStr, "Failed to load") ||
strings.Contains(outStr, "could not fetch extension") ||
strings.Contains(outStr, "failed to download") {
t.Skip("Iceberg extension not available in DuckDB Docker image")
}
if runErr != nil {
if strings.Contains(outStr, "does not exist because schema") &&
strings.Contains(outStr, namespace) {
t.Fatalf("reproduced issue #9103: DuckDB cannot see namespace %q after ATTACH 's3://%s/'; see output above",
namespace, bucketName)
}
t.Fatalf("DuckDB run failed for an unexpected reason: %v", runErr)
}
}
// createTableWithToken creates an Iceberg table using an OAuth bearer token.
func createTableWithToken(t *testing.T, env *oauthTestEnv, token, bucketName, namespace, tableName string) {
t.Helper()
payload := map[string]any{
"name": tableName,
"schema": map[string]any{
"type": "struct",
"schema-id": 0,
"fields": []map[string]any{
{"id": 1, "name": "id", "required": true, "type": "long"},
},
},
}
body, err := json.Marshal(payload)
if err != nil {
t.Fatalf("marshal create-table payload: %v", err)
}
url := fmt.Sprintf("%s/v1/%s/namespaces/%s/tables", env.icebergURL(), bucketName, namespace)
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
t.Fatalf("create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("create table: %v", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("create table failed: status=%d body=%s", resp.StatusCode, respBody)
}
t.Logf("Created table %s.%s in bucket %s", namespace, tableName, bucketName)
}
// containsNamespace checks whether an Iceberg REST ListNamespaces response
// contains the given single-level namespace.
func containsNamespace(body map[string]any, name string) bool {
arr, _ := body["namespaces"].([]any)
for _, item := range arr {
parts, _ := item.([]any)
if len(parts) == 1 {
if s, ok := parts[0].(string); ok && s == name {
return true
}
}
}
return false
}
+5 -4
View File
@@ -256,10 +256,11 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
Fsync: *b.fsync,
}
ar := &operation.VolumeAssignRequest{
Count: 1,
Collection: *b.collection,
Replication: *b.replication,
DiskType: *b.diskType,
Count: 1,
Collection: *b.collection,
Replication: *b.replication,
DiskType: *b.diskType,
ExpectedDataSize: uint64(fileSize),
}
if assignResult, err := operation.Assign(context.Background(), b.masterClient.GetMaster, b.grpcDialOption, ar); err == nil {
fp.Server, fp.Fid, fp.Pref.Collection = assignResult.Url, assignResult.Fid, *b.collection
+35 -15
View File
@@ -84,6 +84,14 @@ type FilerOptions struct {
tusBasePath *string
certProvider certprovider.Provider
s3ConfigFile *string // optional path to static S3 identity config
mountPeerRegistryEnable *bool // accept MountRegister/MountList RPCs (peer chunk sharing tier 1)
// shutdownCtx, when non-nil, tells startFiler to gracefully shut down its
// HTTP/gRPC servers once the ctx is cancelled. Used by integration tests
// and by weed mini; nil for standalone weed filer.
shutdownCtx context.Context
// gracefulStopTimeout caps how long startFiler waits for gRPC graceful
// stop before forcing the server to stop. Zero means the default of 10s.
gracefulStopTimeout time.Duration
}
func init() {
@@ -119,6 +127,7 @@ func init() {
f.allowedOrigins = cmdFiler.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
f.exposeDirectoryData = cmdFiler.Flag.Bool("exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
f.tusBasePath = cmdFiler.Flag.String("tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
f.mountPeerRegistryEnable = cmdFiler.Flag.Bool("mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
// start s3 on filer
filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
@@ -379,6 +388,7 @@ func (fo *FilerOptions) startFiler() {
AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
TusBasePath: *fo.tusBasePath,
CredentialManager: credentialManager,
MountPeerRegistryEnabled: fo.mountPeerRegistryEnable != nil && *fo.mountPeerRegistryEnable,
})
if nfs_err != nil {
glog.Fatalf("Filer startup error: %v", nfs_err)
@@ -446,8 +456,12 @@ func (fo *FilerOptions) startFiler() {
go grpcS.Serve(grpcL)
pb.ServeGrpcOnLocalSocket(grpcS, grpcPort)
// Register graceful shutdown for gRPC server to wait for active RPCs
grace.OnInterrupt(func() {
// Helper to gracefully stop the gRPC server, waiting for active RPCs.
gracefulTimeout := fo.gracefulStopTimeout
if gracefulTimeout <= 0 {
gracefulTimeout = 10 * time.Second
}
stopGrpcServer := func() {
glog.V(0).Infof("Gracefully stopping gRPC server")
stopped := make(chan struct{})
go func() {
@@ -457,11 +471,11 @@ func (fo *FilerOptions) startFiler() {
select {
case <-stopped:
glog.V(0).Infof("gRPC server stopped gracefully")
case <-time.After(10 * time.Second):
glog.V(0).Infof("gRPC server graceful stop timed out, forcing stop")
case <-time.After(gracefulTimeout):
glog.V(0).Infof("gRPC server graceful stop timed out after %s, forcing stop", gracefulTimeout)
grpcS.Stop()
}
})
}
var socketServer *http.Server
if runtime.GOOS != "windows" {
@@ -528,8 +542,12 @@ func (fo *FilerOptions) startFiler() {
}
httpS := newHttpServer(defaultMux, tlsConfig)
// Register shutdown hooks: stop all HTTP servers, then close filer database
// Register a single shutdown hook that runs the steps in the correct order:
// stop accepting new gRPC/HTTP requests, then close the filer database.
// Combining them into one hook keeps ordering intact regardless of how
// grace fires interrupt hooks (FIFO vs LIFO).
grace.OnInterrupt(func() {
stopGrpcServer()
glog.V(0).Infof("Gracefully stopping all HTTP servers")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
@@ -542,13 +560,12 @@ func (fo *FilerOptions) startFiler() {
if err := httpS.Shutdown(shutdownCtx); err != nil {
glog.Warningf("HTTPS server shutdown: %v", err)
}
shutdownFiler()
})
grace.OnInterrupt(shutdownFiler)
if MiniClusterCtx != nil {
ctx := MiniClusterCtx
if fo.shutdownCtx != nil {
go func() {
<-ctx.Done()
<-fo.shutdownCtx.Done()
httpS.Shutdown(context.Background())
grpcS.Stop()
}()
@@ -570,8 +587,12 @@ func (fo *FilerOptions) startFiler() {
}
httpS := newHttpServer(defaultMux, nil)
// Register shutdown hooks: stop all HTTP servers, then close filer database
// Register a single shutdown hook that runs the steps in the correct order:
// stop accepting new gRPC/HTTP requests, then close the filer database.
// Combining them into one hook keeps ordering intact regardless of how
// grace fires interrupt hooks (FIFO vs LIFO).
grace.OnInterrupt(func() {
stopGrpcServer()
glog.V(0).Infof("Gracefully stopping all HTTP servers")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
@@ -584,13 +605,12 @@ func (fo *FilerOptions) startFiler() {
if err := httpS.Shutdown(shutdownCtx); err != nil {
glog.Warningf("HTTP server shutdown: %v", err)
}
shutdownFiler()
})
grace.OnInterrupt(shutdownFiler)
if MiniClusterCtx != nil {
ctx := MiniClusterCtx
if fo.shutdownCtx != nil {
go func() {
<-ctx.Done()
<-fo.shutdownCtx.Done()
httpS.Shutdown(context.Background())
grpcS.Stop()
}()
+194 -2
View File
@@ -1,17 +1,22 @@
package command
import (
"context"
"errors"
"fmt"
nethttp "net/http"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/replication/repl_util"
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
"github.com/seaweedfs/seaweedfs/weed/replication/source"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -35,6 +40,7 @@ type FilerBackupOptions struct {
ignore404Error *bool
timeAgo *time.Duration
retentionDays *int
initialSnapshot *bool
}
var (
@@ -57,6 +63,7 @@ func init() {
filerBackupOptions.retentionDays = cmdFilerBackup.Flag.Int("retentionDays", 0, "incremental backup retention days")
filerBackupOptions.disableErrorRetry = cmdFilerBackup.Flag.Bool("disableErrorRetry", false, "disables errors retry, only logs will print")
filerBackupOptions.ignore404Error = cmdFilerBackup.Flag.Bool("ignore404Error", true, "ignore 404 errors from filer")
filerBackupOptions.initialSnapshot = cmdFilerBackup.Flag.Bool("initialSnapshot", false, "before subscribing to metadata updates, walk the live filer tree under -filerPath and seed the destination. Only runs on a fresh sync (no prior checkpoint and -timeAgo is 0). After the walk, subscription starts from the walk-start timestamp so concurrent changes are still captured.")
}
var cmdFilerBackup = &Command{
@@ -70,6 +77,11 @@ var cmdFilerBackup = &Command{
If restarted and "-timeAgo" is not set, the synchronization will resume from the previous checkpoints, persisted every minute.
A fresh sync will start from the earliest metadata logs. To reset the checkpoints, just set "-timeAgo" to a high value.
On a fresh sync the metadata event log only re-materializes files that still exist on the source; entries that were
created and later deleted are replayed as a create-then-delete pair and therefore never appear on the destination.
Pass "-initialSnapshot" to walk the live filer tree first and seed the destination with the current tree, then
subscribe from the walk-start timestamp. The walk only runs when there is no prior checkpoint.
`,
}
@@ -123,17 +135,27 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
// get start time for the data sink
startFrom := time.Unix(0, 0)
isFreshSync := true
sinkId := util.HashStringToLong(dataSink.GetName() + dataSink.GetSinkToDirectory())
if timeAgo.Milliseconds() == 0 {
lastOffsetTsNs, err := getOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, int32(sinkId))
if err != nil {
glog.V(0).Infof("starting from %v", startFrom)
} else {
// A KV read failure is ambiguous — a checkpoint may well exist but the
// source filer is temporarily unreachable. Don't treat that as a fresh
// sync; otherwise runFilerBackup's retry loop would redo the full
// -initialSnapshot walk on every transient error.
isFreshSync = false
glog.V(0).Infof("starting from %v (offset read failed: %v)", startFrom, err)
} else if lastOffsetTsNs > 0 {
startFrom = time.Unix(0, lastOffsetTsNs)
isFreshSync = false
glog.V(0).Infof("resuming from %v", startFrom)
} else {
glog.V(0).Infof("starting from %v (no prior checkpoint)", startFrom)
}
} else {
startFrom = time.Now().Add(-timeAgo)
isFreshSync = false
glog.V(0).Infof("start time is set to %v", startFrom)
}
@@ -150,6 +172,28 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
}
dataSink.SetSourceFiler(filerSource)
// When the destination has no prior checkpoint and the user opted in to an
// initial snapshot, walk the live filer tree first and seed the destination
// with the current entries. This avoids the "only new files appear" pitfall
// of replaying the metadata event log: entries created-then-deleted before
// the walk leave no trace, so a re-backup after wiping the destination
// reflects what is actually live on the source instead of an empty tree.
if *backupOption.initialSnapshot && isFreshSync {
snapshotTsNs, err := runInitialSnapshot(sourceFiler.ToGrpcAddress(), filerSource, sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.ignore404Error)
if err != nil {
return fmt.Errorf("initial snapshot: %w", err)
}
// The walk can take hours on large trees; retry the tiny KV write a
// handful of times before giving up so a flaky filer KV doesn't force
// the whole walk to repeat on the next retry loop iteration.
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, int32(sinkId), snapshotTsNs); err != nil {
glog.Errorf("initialSnapshot: FAILED to persist offset %d for sinkId %d after retries: %v — the next retry will redo the full walk", snapshotTsNs, sinkId, err)
return fmt.Errorf("persist initial snapshot offset: %w", err)
}
startFrom = time.Unix(0, snapshotTsNs)
glog.V(0).Infof("initialSnapshot done; subscribing from %v", startFrom)
}
var processEventFn func(*filer_pb.SubscribeMetadataResponse) error
if *backupOption.ignore404Error {
processEventFnGenerated := genProcessFunction(sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.doDeleteFiles, debug)
@@ -241,3 +285,151 @@ func isIgnorable404(err error) bool {
strings.Contains(errStr, "LookupFileId") ||
(strings.Contains(errStr, "volume id") && strings.Contains(errStr, "not found"))
}
// persistSnapshotOffset writes the snapshot high-water mark to the source
// filer's KV, retrying a few times with exponential backoff on transient
// errors. Losing this write forces a full re-walk on the next retry loop
// iteration, so a small retry budget here is far cheaper than paying the
// walk cost again on a large tree.
func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64) error {
const attempts = 4
backoff := 500 * time.Millisecond
var lastErr error
for i := 1; i <= attempts; i++ {
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, tsNs); err == nil {
return nil
} else {
lastErr = err
if i == attempts {
break
}
glog.V(0).Infof("initialSnapshot: setOffset attempt %d/%d failed: %v (retrying in %v)", i, attempts, err, backoff)
time.Sleep(backoff)
backoff *= 2
}
}
return lastErr
}
// runInitialSnapshot walks the live filer tree under sourcePath and seeds the
// destination via the sink. The snapshot timestamp is captured before the walk
// starts so any create/update/delete that races with the walk is still caught
// by the subscription that runs afterward (sink CreateEntry is idempotent for
// all builtin sinks, so replaying a concurrent create from the subscription
// over an entry already written by the walk is safe).
//
// Note on excludes: TraverseBfs enumerates every directory and enqueues its
// children unconditionally before the callback runs, so the exclude filters
// below only prevent *processing* of excluded entries — they do not prune the
// listing RPCs for excluded subtrees. For small system excludes (SystemLogDir)
// that is fine; for large user-supplied excludes (say an archive directory
// with millions of files), the listing cost can dominate the snapshot. A
// proper prune signal through TraverseBfs is a separate change.
func runInitialSnapshot(
grpcAddress string,
filerSource *source.FilerSource,
sourcePath string,
targetPath string,
excludePaths []string,
reExcludeFileName *regexp.Regexp,
excludeFileNames []*wildcard.WildcardMatcher,
excludePathPatterns []*wildcard.WildcardMatcher,
dataSink sink.ReplicationSink,
ignore404Error bool,
) (int64, error) {
// Metadata events are stamped server-side, so the backup host clock may be
// ahead of the filer's. Take `now - 1min` as the subscription watermark so
// a fast client clock can't skip events that fire during/right-after the
// walk. meta_aggregator.go uses the same 1-minute margin on initial peer
// traversal; see the note there on why duplicate replay is harmless.
snapshotTsNs := time.Now().Add(-time.Minute).UnixNano()
glog.V(0).Infof("initialSnapshot: walking %s on %s -> %s (snapshotTsNs=%d, -1m skew margin applied)", sourcePath, grpcAddress, targetPath, snapshotTsNs)
// TraverseBfs fans the callback out across 5 worker goroutines, so counter
// updates and the progress-log gate need to be safe under concurrent access.
var entryCount, byteCount atomic.Int64
start := time.Now()
var logMu sync.Mutex
lastLog := start
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := filer_pb.TraverseBfs(ctx, filerSource, util.FullPath(sourcePath), func(parentPath util.FullPath, entry *filer_pb.Entry) error {
parent := string(parentPath)
sourceKey := parentPath.Child(entry.Name)
source := string(sourceKey)
// Check exclusion on the entry's own path too — otherwise a walked
// directory whose full path is SystemLogDir or a user-excluded path
// still gets seeded (only its children would be skipped by the parent
// check).
if parent == filer.SystemLogDir || strings.HasPrefix(parent, filer.SystemLogDir+"/") ||
source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") {
return nil
}
if matchesExcludePath(parent, excludePaths) || matchesExcludePath(source, excludePaths) {
return nil
}
if isEntryExcluded(parent, entry, reExcludeFileName, excludeFileNames, excludePathPatterns) {
return nil
}
if !util.IsEqualOrUnder(source, sourcePath) {
return nil
}
targetKey := initialSnapshotTargetKey(dataSink, targetPath, sourcePath, sourceKey, entry)
if err := dataSink.CreateEntry(targetKey, entry, nil); err != nil {
// A file can be listed by TraverseBfs and then deleted before
// CreateEntry reads its chunks. The follow phase ignores 404s when
// -ignore404Error is set; apply the same policy here so the walk
// doesn't abort (and trigger a full re-walk on retry) just because
// a single entry disappeared mid-snapshot.
if ignore404Error && isIgnorable404(err) {
glog.V(0).Infof("initialSnapshot: source entry %s disappeared, ignore it: %s", sourceKey, err.Error())
return nil
}
return fmt.Errorf("seed %s: %w", targetKey, err)
}
curEntries := entryCount.Add(1)
var curBytes int64
if entry.Attributes != nil {
curBytes = byteCount.Add(int64(entry.Attributes.FileSize))
} else {
curBytes = byteCount.Load()
}
now := time.Now()
logMu.Lock()
shouldLog := now.Sub(lastLog) >= 5*time.Second
if shouldLog {
lastLog = now
}
logMu.Unlock()
if shouldLog {
elapsed := now.Sub(start).Seconds()
if elapsed == 0 {
elapsed = 1
}
glog.V(0).Infof("initialSnapshot: %d entries / %d bytes seeded (%.1f/sec)", curEntries, curBytes, float64(curEntries)/elapsed)
}
return nil
})
if err != nil {
return 0, err
}
glog.V(0).Infof("initialSnapshot: done — %d entries / %d bytes in %v", entryCount.Load(), byteCount.Load(), time.Since(start))
return snapshotTsNs, nil
}
// initialSnapshotTargetKey pulls the entry mtime and delegates to the shared
// destKey helper in filer_sync.go so the walk and the event-log path produce
// the same destination key for the same source entry.
func initialSnapshotTargetKey(dataSink sink.ReplicationSink, targetPath, sourcePath string, sourceKey util.FullPath, entry *filer_pb.Entry) string {
var mTime int64
if entry.Attributes != nil {
mTime = entry.Attributes.Mtime
}
return destKey(dataSink, targetPath, sourcePath, sourceKey, mTime)
}
+68
View File
@@ -7,7 +7,12 @@ import (
"net/http/httptest"
"os"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
"github.com/seaweedfs/seaweedfs/weed/replication/source"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
@@ -71,3 +76,66 @@ func TestIsIgnorable404_NonIgnorableError(t *testing.T) {
t.Errorf("expected not ignorable, got ignorable: %v", genErr)
}
}
// stubSink is a minimal ReplicationSink used to exercise initialSnapshotTargetKey
// without standing up a real sink. Only the two methods read by the key builder
// (GetName, IsIncremental) need meaningful behavior; the rest satisfy the interface.
type stubSink struct {
name string
isIncremental bool
}
func (s *stubSink) GetName() string { return s.name }
func (s *stubSink) Initialize(util.Configuration, string) error { return nil }
func (s *stubSink) DeleteEntry(string, bool, bool, []int32) error {
return nil
}
func (s *stubSink) CreateEntry(string, *filer_pb.Entry, []int32) error { return nil }
func (s *stubSink) UpdateEntry(string, *filer_pb.Entry, string, *filer_pb.Entry, bool, []int32) (bool, error) {
return false, nil
}
func (s *stubSink) GetSinkToDirectory() string { return "" }
func (s *stubSink) SetSourceFiler(*source.FilerSource) {}
func (s *stubSink) IsIncremental() bool { return s.isIncremental }
var _ sink.ReplicationSink = (*stubSink)(nil)
func TestInitialSnapshotTargetKey(t *testing.T) {
// Mirror the non-incremental path of buildKey so a refactor of one without
// the other will fail this test.
mirror := &stubSink{name: "mirror", isIncremental: false}
got := initialSnapshotTargetKey(mirror, "/backup", "/data", util.FullPath("/data/sub/file.txt"), &filer_pb.Entry{})
if got != "/backup/sub/file.txt" {
t.Errorf("mirror sink: got %q, want %q", got, "/backup/sub/file.txt")
}
// Incremental sinks partition by entry mtime, so the seed must use the same
// YYYY-MM-DD prefix a replayed CreateEntry would produce. buildKey in
// filer_sync.go formats the date in local time, so compute the expected
// key the same way to keep the test timezone-independent.
inc := &stubSink{name: "inc", isIncremental: true}
mtime := int64(1704196800) // 2024-01-02T12:00:00 UTC — unambiguously Jan 2 in nearly all timezones
gotInc := initialSnapshotTargetKey(inc, "/backup", "/data", util.FullPath("/data/sub/file.txt"), &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: mtime},
})
wantInc := "/backup/" + time.Unix(mtime, 0).Format("2006-01-02") + "/sub/file.txt"
if gotInc != wantInc {
t.Errorf("incremental sink: got %q, want %q", gotInc, wantInc)
}
// Trailing-slash sourcePath still produces a clean relative key.
gotTrail := initialSnapshotTargetKey(mirror, "/backup", "/data/", util.FullPath("/data/file.txt"), &filer_pb.Entry{})
if gotTrail != "/backup/file.txt" {
t.Errorf("trailing-slash sourcePath: got %q, want %q", gotTrail, "/backup/file.txt")
}
// Edge cases CodeRabbit called out: sourceKey equal to sourcePath
// (non-trailing and trailing variants). Real TraverseBfs walks never emit
// the root itself, but the helper must not panic if something else does.
if got := initialSnapshotTargetKey(mirror, "/backup", "/data", util.FullPath("/data"), &filer_pb.Entry{}); got != "/backup" {
t.Errorf("sourceKey == sourcePath (no slash): got %q, want %q", got, "/backup")
}
if got := initialSnapshotTargetKey(mirror, "/backup", "/data/", util.FullPath("/data"), &filer_pb.Entry{}); got != "/backup" {
t.Errorf("sourceKey == sourcePath (trailing slash mismatch): got %q, want %q", got, "/backup")
}
}
+1 -1
View File
@@ -553,7 +553,7 @@ func detectMimeType(f *os.File) string {
return mimeType
}
func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error) {
func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, offset int64, tsNs int64, _ uint64) (chunk *filer_pb.FileChunk, err error) {
uploader, uploaderErr := operation.NewUploader()
if uploaderErr != nil {
return nil, fmt.Errorf("upload data: %w", uploaderErr)
+31 -13
View File
@@ -653,21 +653,39 @@ func genProcessFunction(sourcePath string, targetPath string, excludePaths []str
return processEventFn
}
func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) (key string) {
if !dataSink.IsIncremental() {
key = util.Join(targetPath, string(sourceKey)[len(sourcePath):])
} else {
var mTime int64
if message.NewEntry != nil {
mTime = message.NewEntry.Attributes.Mtime
} else if message.OldEntry != nil {
mTime = message.OldEntry.Attributes.Mtime
}
dateKey := time.Unix(mTime, 0).Format("2006-01-02")
key = util.Join(targetPath, dateKey, string(sourceKey)[len(sourcePath):])
func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) string {
var mTime int64
if message.NewEntry != nil && message.NewEntry.Attributes != nil {
mTime = message.NewEntry.Attributes.Mtime
} else if message.OldEntry != nil && message.OldEntry.Attributes != nil {
mTime = message.OldEntry.Attributes.Mtime
}
return destKey(dataSink, targetPath, sourcePath, sourceKey, mTime)
}
return escapeKey(key)
// destKey derives the sink-side key for a source entry. Shared between the
// event-log path (buildKey) and the initialSnapshot walk (both paths need the
// same target layout so a walk-seeded file and an event-replayed file resolve
// to the same destination key). Normalizing to a trailing-slash base avoids
// indexing past the end of sourceKey when callers differ on trailing-slash
// conventions or when sourceKey equals sourcePath exactly.
func destKey(dataSink sink.ReplicationSink, targetPath, sourcePath string, sourceKey util.FullPath, mTime int64) string {
base := strings.TrimSuffix(sourcePath, "/") + "/"
sk := string(sourceKey)
var relative string
switch {
case strings.HasPrefix(sk, base):
relative = sk[len(base):]
case sk == strings.TrimSuffix(sourcePath, "/"):
relative = ""
default:
relative = strings.TrimPrefix(sk, "/")
}
if !dataSink.IsIncremental() {
return escapeKey(util.Join(targetPath, relative))
}
dateKey := time.Unix(mTime, 0).Format("2006-01-02")
return escapeKey(util.Join(targetPath, dateKey, relative))
}
// isEntryExcluded checks whether a single side (old or new) of an event is excluded
+6 -3
View File
@@ -74,6 +74,10 @@ type MasterOptions struct {
telemetryEnabled *bool
debug *bool
debugPort *int
// shutdownCtx, when non-nil, tells startMaster to shut down once the ctx
// is cancelled. Used by integration tests and by weed mini; nil for
// standalone weed master.
shutdownCtx context.Context
}
func init() {
@@ -336,9 +340,8 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
ms.Topo.HashicorpRaft.LeadershipTransfer()
}
})
ctx := MiniClusterCtx
if ctx != nil {
<-ctx.Done()
if masterOption.shutdownCtx != nil {
<-masterOption.shutdownCtx.Done()
ms.Shutdown()
grpcS.Stop()
} else {
+172 -21
View File
@@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -66,6 +67,123 @@ var (
MiniClusterCtx context.Context
)
// miniClientsState orchestrates graceful shutdown of admin/s3/webdav/worker on
// weed mini Ctrl+C, BEFORE filer/volume/master tear down. It is rebuilt on
// each runMini invocation so in-process test reruns see fresh state.
//
// The ctx chains from MiniClusterCtx so cancelling MiniClusterCtx (how tests
// tear down the cluster) also triggers the client-shutdown path.
//
// Shutdown has two phases:
// 1. preCancelFns run synchronously in registration order (worker disconnect,
// etc.) so downstream servers don't block on handlers that are about to
// close anyway.
// 2. ctx is cancelled and the shutdown hook waits on wg for admin/s3/webdav
// goroutines (registered via onMiniClientsShutdown / trackMiniClient) to
// drain.
type miniClientsState struct {
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
preCancelMu sync.Mutex
preCancelFns []func()
}
var miniClients *miniClientsState
// resetMiniClients installs a fresh client-shutdown state chained from
// MiniClusterCtx. Called once at the top of runMini; any goroutines from a
// prior invocation keep their old state via closure and are unaffected.
func resetMiniClients() {
parent := context.Background()
if MiniClusterCtx != nil {
parent = MiniClusterCtx
}
s := &miniClientsState{}
s.ctx, s.cancel = context.WithCancel(parent)
miniClients = s
}
// onMiniClientsShutdown runs fn when mini shutdown is triggered, and tracks
// it so the interrupt hook can wait for it to drain. No-op outside mini.
func onMiniClientsShutdown(fn func()) {
s := miniClients
if s == nil {
return
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
<-s.ctx.Done()
fn()
}()
}
// trackMiniClient registers an externally-managed goroutine (one that
// observes miniClientsCtx() itself) so the interrupt hook waits for it.
// The caller invokes the returned done func when the goroutine exits.
func trackMiniClient() (done func()) {
s := miniClients
if s == nil {
return func() {}
}
s.wg.Add(1)
return s.wg.Done
}
// beforeMiniClientsShutdown registers fn to run synchronously BEFORE the
// clients ctx is cancelled. Use for cleanup that must complete before
// downstream servers (e.g., the admin worker-gRPC) start waiting on clients.
func beforeMiniClientsShutdown(fn func()) {
s := miniClients
if s == nil {
return
}
s.preCancelMu.Lock()
defer s.preCancelMu.Unlock()
s.preCancelFns = append(s.preCancelFns, fn)
}
// miniClientsCtx returns the shutdown context for mini clients, or
// context.Background() if not running inside weed mini.
func miniClientsCtx() context.Context {
s := miniClients
if s == nil {
return context.Background()
}
return s.ctx
}
// triggerMiniClientsShutdown runs preCancel fns synchronously, cancels the
// clients ctx, and waits up to timeout for tracked goroutines to finish.
// Called from the OnInterrupt hook.
func triggerMiniClientsShutdown(timeout time.Duration) {
s := miniClients
if s == nil {
return
}
glog.V(0).Infof("Shutting down admin/s3/webdav ...")
s.preCancelMu.Lock()
fns := s.preCancelFns
s.preCancelFns = nil
s.preCancelMu.Unlock()
for _, fn := range fns {
fn()
}
s.cancel()
done := make(chan struct{})
go func() {
s.wg.Wait()
close(done)
}()
select {
case <-done:
glog.V(0).Infof("admin/s3/webdav shut down")
case <-time.After(timeout):
glog.V(0).Infof("timed out waiting for admin/s3/webdav to shut down")
}
}
func init() {
cmdMini.Run = runMini // break init cycle
}
@@ -193,6 +311,7 @@ func initMiniFilerFlags() {
miniFilerOptions.allowedOrigins = cmdMini.Flag.String("filer.allowedOrigins", "*", "comma separated list of allowed origins")
miniFilerOptions.exposeDirectoryData = cmdMini.Flag.Bool("filer.exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
miniFilerOptions.tusBasePath = cmdMini.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path")
miniFilerOptions.mountPeerRegistryEnable = cmdMini.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
}
// initMiniVolumeFlags initializes Volume server flag options
@@ -869,6 +988,21 @@ func runMini(cmd *Command, args []string) bool {
miniWhiteList := util.StringSplit(*miniWhiteListOption, ",")
// Install a fresh clients-shutdown context (chained from MiniClusterCtx)
// before any service starts.
resetMiniClients()
// Master/volume/filer observe MiniClusterCtx so tests that cancel it
// tear those services down too. On Ctrl+C they rely on their own
// OnInterrupt hooks (see grace's LIFO ordering).
miniMasterOptions.shutdownCtx = MiniClusterCtx
miniOptions.v.shutdownCtx = MiniClusterCtx
miniFilerOptions.shutdownCtx = MiniClusterCtx
// Mini is a small/dev setup with short-lived RPCs; cap the filer's
// gRPC graceful-stop at 1s so Ctrl+C returns quickly instead of sitting
// on the default 10s waiting for background subscription streams.
miniFilerOptions.gracefulStopTimeout = 1 * time.Second
// Start all services with proper dependency coordination
// This channel will be closed when all services are fully ready
allServicesReady := make(chan struct{})
@@ -877,6 +1011,13 @@ func runMini(cmd *Command, args []string) bool {
// Wait for all services to be fully running before printing welcome message
<-allServicesReady
// Register the clients-shutdown interrupt hook AFTER all services have
// registered theirs. Under grace's LIFO firing, this hook runs FIRST on
// Ctrl+C so admin/s3/webdav drain before filer/volume/master tear down.
grace.OnInterrupt(func() {
triggerMiniClientsShutdown(10 * time.Second)
})
// Print welcome message after all services are running
printWelcomeMessage()
@@ -921,17 +1062,27 @@ func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) {
// Wait for filer to be ready
waitForServiceReady("Filer", *miniFilerOptions.port, bindIp)
// Start S3 and WebDAV in parallel (both depend on filer)
// Start S3 and WebDAV in parallel (both depend on filer). Each observes
// miniClientsCtx so it shuts down first on Ctrl+C, tracked via
// trackMiniClient so runMini's interrupt hook can wait for them.
if *miniEnableS3 {
go startMiniService("S3", func() {
startS3Service()
}, *miniS3Options.port)
miniS3Options.shutdownCtx = miniClientsCtx()
done := trackMiniClient()
go func() {
defer done()
startMiniService("S3", startS3Service, *miniS3Options.port)
}()
}
if *miniEnableWebDAV {
go startMiniService("WebDAV", func() {
miniWebDavOptions.startWebDav()
}, *miniWebDavOptions.port)
miniWebDavOptions.shutdownCtx = miniClientsCtx()
done := trackMiniClient()
go func() {
defer done()
startMiniService("WebDAV", func() {
miniWebDavOptions.startWebDav()
}, *miniWebDavOptions.port)
}()
}
// Wait for services to be ready
@@ -999,12 +1150,8 @@ func startS3Service() {
func startMiniAdminWithWorker(allServicesReady chan struct{}) {
defer close(allServicesReady) // Ensure channel is always closed on all paths
var ctx context.Context
if MiniClusterCtx != nil {
ctx = MiniClusterCtx
} else {
ctx = context.Background()
}
// Admin shuts down when mini clients shutdown is triggered.
ctx := miniClientsCtx()
// Determine bind IP for health checks
bindIp := getBindIp()
@@ -1044,8 +1191,12 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
*miniAdminOptions.dataDir = filepath.Join(*miniDataFolders, "admin")
}
// Start admin server in background
// Start admin server in background. trackMiniClient lets the Ctrl+C
// handler wait for startAdminServer's graceful shutdown before filer/
// volume/master tear down.
done := trackMiniClient()
go func() {
defer done()
var icebergPort int
if miniS3Options.portIceberg != nil {
icebergPort = *miniS3Options.portIceberg
@@ -1189,13 +1340,13 @@ func startMiniWorker(workerDir string) {
// Metrics server is already started in the main init function above, so no need to start it again here
// Start the worker
if MiniClusterCtx != nil {
go func() {
<-MiniClusterCtx.Done()
workerInstance.Stop()
}()
}
// Stop the worker BEFORE the clients ctx is cancelled. Otherwise admin's
// internal worker gRPC GracefulStop (called during admin.Shutdown) would
// wait for the worker stream to close, blocking the whole mini shutdown
// by ~10s and cascading into filer's own gRPC graceful stop timeout.
beforeMiniClientsShutdown(func() {
workerInstance.Stop()
})
err = workerInstance.Start()
if err != nil {
glog.Fatalf("Failed to start worker: %v", err)
+14
View File
@@ -52,6 +52,13 @@ type MountOptions struct {
rdmaMaxConcurrent *int
rdmaTimeoutMs *int
// Peer chunk sharing options (design-weed-mount-peer-chunk-sharing.md).
peerEnabled *bool
peerListen *string
peerAdvertise *string
peerDataCenter *string
peerRack *string
dirIdleEvictSec *int
// Distributed lock for cross-mount write coordination
@@ -129,6 +136,13 @@ func init() {
mountOptions.rdmaMaxConcurrent = cmdMount.Flag.Int("rdma.maxConcurrent", 64, "max concurrent RDMA operations")
mountOptions.rdmaTimeoutMs = cmdMount.Flag.Int("rdma.timeoutMs", 5000, "RDMA operation timeout in milliseconds")
// Peer chunk sharing flags.
mountOptions.peerEnabled = cmdMount.Flag.Bool("peer.enable", false, "opt in to peer chunk sharing — mount serves its chunk cache to other mounts and fetches from peers instead of volume servers when available")
mountOptions.peerListen = cmdMount.Flag.String("peer.listen", ":18080", "bind address for peer gRPC (directory RPCs + FetchChunk streaming)")
mountOptions.peerAdvertise = cmdMount.Flag.String("peer.advertise", "", "externally-reachable host:port other mounts use to reach this one (defaults to autodetected host + -peer.listen port)")
mountOptions.peerDataCenter = cmdMount.Flag.String("peer.dataCenter", "", "optional data-center label advertised to peers; used with -peer.rack for two-level locality ranking")
mountOptions.peerRack = cmdMount.Flag.String("peer.rack", "", "optional rack label advertised to peers")
mountOptions.dirIdleEvictSec = cmdMount.Flag.Int("dirIdleEvictSec", 600, "seconds to evict idle cached directories (0 to disable)")
mountCpuProfile = cmdMount.Flag.String("cpuprofile", "", "cpu profile output file")
+13
View File
@@ -356,6 +356,12 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
EnableDistributedLock: option.distributedLock != nil && *option.distributedLock,
WritebackCache: option.writebackCache != nil && *option.writebackCache,
PosixDirNlink: option.posixDirNlink != nil && *option.posixDirNlink,
// Peer chunk sharing
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
PeerListen: peerStringOrEmpty(option.peerListen),
PeerAdvertise: peerStringOrEmpty(option.peerAdvertise),
PeerDataCenter: peerStringOrEmpty(option.peerDataCenter),
PeerRack: peerStringOrEmpty(option.peerRack),
})
// create mount root
@@ -411,3 +417,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
return true
}
func peerStringOrEmpty(p *string) string {
if p == nil {
return ""
}
return *p
}
+52 -7
View File
@@ -74,6 +74,11 @@ type S3Options struct {
externalUrl *string
defaultFileMode *string
cacheSizeMB *int64
// shutdownCtx, when non-nil, tells startS3Server/startIcebergServer to
// gracefully shut down their HTTP/gRPC servers once the ctx is cancelled.
// Used by weed mini to orchestrate an ordered shutdown; nil for standalone
// weed s3.
shutdownCtx context.Context
}
func init() {
@@ -453,10 +458,9 @@ func (s3opt *S3Options) startS3Server() bool {
}()
}
httpS := newHttpServer(router, tlsConfig)
if MiniClusterCtx != nil {
ctx := MiniClusterCtx
if s3opt.shutdownCtx != nil {
go func() {
<-ctx.Done()
<-s3opt.shutdownCtx.Done()
httpS.Shutdown(context.Background())
grpcS.Stop()
}()
@@ -495,9 +499,9 @@ func (s3opt *S3Options) startS3Server() bool {
}()
}
httpS := newHttpServer(router, nil)
if MiniClusterCtx != nil {
if s3opt.shutdownCtx != nil {
go func() {
<-MiniClusterCtx.Done()
<-s3opt.shutdownCtx.Done()
httpS.Shutdown(context.Background())
grpcS.Stop()
}()
@@ -518,6 +522,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
// Create Iceberg server using the S3ApiServer as filer client
icebergServer := iceberg.NewServer(s3ApiServer, s3ApiServer)
icebergServer.SetCredentialValidator(s3ApiServer)
icebergServer.SetS3Endpoint(s3opt.deriveS3AdvertisedEndpoint())
icebergServer.RegisterRoutes(icebergRouter)
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portIceberg)
@@ -530,9 +535,9 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
glog.V(0).Infof("Start Iceberg REST Catalog Server at http://%s", listenAddress)
httpS := newHttpServer(icebergRouter, nil)
if MiniClusterCtx != nil {
if s3opt.shutdownCtx != nil {
go func() {
<-MiniClusterCtx.Done()
<-s3opt.shutdownCtx.Done()
httpS.Shutdown(context.Background())
}()
}
@@ -548,3 +553,43 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
glog.Fatalf("Iceberg REST Catalog Server Fail to serve: %v", err)
}
}
// deriveS3AdvertisedEndpoint builds the S3 endpoint URL to advertise to
// Iceberg catalog clients as part of LoadTable FileIO config. To avoid
// hijacking correctly-configured clients (Spark/Trino/PyIceberg all bring
// their own s3.endpoint), advertising is strictly opt-in and returns ""
// whenever no reliable value is available:
// - -s3.externalUrl / S3_EXTERNAL_URL wins and supports reverse-proxy
// deployments.
// - Otherwise the bind IP is used only when it is explicit and not a
// wildcard (0.0.0.0 / ::), with the scheme picked from TLS config and
// IPv6 literals bracketed via util.JoinHostPort.
//
// See issue #9103.
func (s3opt *S3Options) deriveS3AdvertisedEndpoint() string {
if ext := strings.TrimRight(s3opt.resolveExternalUrl(), "/"); ext != "" {
return ext
}
host := ""
if s3opt.bindIp != nil {
host = *s3opt.bindIp
}
switch host {
case "", "0.0.0.0", "::", "[::]":
return ""
}
scheme := "http"
port := 0
if s3opt.port != nil {
port = *s3opt.port
}
if s3opt.tlsPrivateKey != nil && *s3opt.tlsPrivateKey != "" {
scheme = "https"
if s3opt.portHttps != nil && *s3opt.portHttps > 0 {
port = *s3opt.portHttps
}
}
return fmt.Sprintf("%s://%s", scheme, util.JoinHostPort(host, port))
}
+103
View File
@@ -0,0 +1,103 @@
package command
import (
"testing"
)
func strp(s string) *string { return &s }
func intp(i int) *int { return &i }
func TestDeriveS3AdvertisedEndpoint(t *testing.T) {
tests := []struct {
name string
opt S3Options
want string
}{
{
name: "wildcard bind IP with no externalUrl does not advertise an endpoint",
opt: S3Options{
bindIp: strp("0.0.0.0"),
port: intp(8333),
portHttps: intp(0),
tlsPrivateKey: strp(""),
externalUrl: strp(""),
},
want: "",
},
{
name: "empty bind IP with no externalUrl does not advertise an endpoint",
opt: S3Options{
bindIp: strp(""),
port: intp(8333),
portHttps: intp(0),
tlsPrivateKey: strp(""),
externalUrl: strp(""),
},
want: "",
},
{
name: "explicit bind IP is kept",
opt: S3Options{
bindIp: strp("10.0.0.5"),
port: intp(8333),
portHttps: intp(0),
tlsPrivateKey: strp(""),
externalUrl: strp(""),
},
want: "http://10.0.0.5:8333",
},
{
name: "IPv6 literals are bracketed",
opt: S3Options{
bindIp: strp("fe80::1"),
port: intp(8333),
portHttps: intp(0),
tlsPrivateKey: strp(""),
externalUrl: strp(""),
},
want: "http://[fe80::1]:8333",
},
{
name: "TLS key + https port switches scheme and port",
opt: S3Options{
bindIp: strp("10.0.0.5"),
port: intp(8333),
portHttps: intp(8443),
tlsPrivateKey: strp("/etc/seaweed/tls.key"),
externalUrl: strp(""),
},
want: "https://10.0.0.5:8443",
},
{
name: "TLS-only (no separate https port) still uses https on the HTTP port",
opt: S3Options{
bindIp: strp("10.0.0.5"),
port: intp(8333),
portHttps: intp(0),
tlsPrivateKey: strp("/etc/seaweed/tls.key"),
externalUrl: strp(""),
},
want: "https://10.0.0.5:8333",
},
{
name: "externalUrl wins and trailing slash is stripped",
opt: S3Options{
bindIp: strp("10.0.0.5"),
port: intp(8333),
portHttps: intp(0),
tlsPrivateKey: strp(""),
externalUrl: strp("https://s3.example.com/"),
},
want: "https://s3.example.com",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := tc.opt.deriveS3AdvertisedEndpoint()
if got != tc.want {
t.Fatalf("deriveS3AdvertisedEndpoint() = %q, want %q", got, tc.want)
}
})
}
}
+1
View File
@@ -130,6 +130,7 @@ func init() {
filerOptions.diskType = cmdServer.Flag.String("filer.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
filerOptions.exposeDirectoryData = cmdServer.Flag.Bool("filer.exposeDirectoryData", true, "expose directory data via filer. If false, filer UI will be innaccessible.")
filerOptions.tusBasePath = cmdServer.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
filerOptions.mountPeerRegistryEnable = cmdServer.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
serverOptions.v.port = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
serverOptions.v.portGrpc = cmdServer.Flag.Int("volume.port.grpc", 0, "volume server grpc listen port")
+7 -3
View File
@@ -1,6 +1,7 @@
package command
import (
"context"
"fmt"
"net/http"
httppprof "net/http/pprof"
@@ -75,6 +76,10 @@ type VolumeServerOptions struct {
ldbTimeout *int64
debug *bool
debugPort *int
// shutdownCtx, when non-nil, tells startVolumeServer to shut down once the
// ctx is cancelled. Used by integration tests and by weed mini; nil for
// standalone weed volume.
shutdownCtx context.Context
}
func init() {
@@ -327,11 +332,10 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
stopChan <- true
})
ctx := MiniClusterCtx
if ctx != nil {
if v.shutdownCtx != nil {
select {
case <-stopChan:
case <-ctx.Done():
case <-v.shutdownCtx.Done():
shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
}
} else {
+6 -2
View File
@@ -36,6 +36,10 @@ type WebDavOption struct {
cacheDir *string
cacheSizeMB *int64
maxMB *int
// shutdownCtx, when non-nil, tells startWebDav to gracefully shut down the
// HTTP server once the ctx is cancelled. Used by weed mini; nil for
// standalone weed webdav.
shutdownCtx context.Context
}
func init() {
@@ -137,9 +141,9 @@ func (wo *WebDavOption) startWebDav() bool {
glog.Fatalf("WebDav Server listener on %s error: %v", listenAddress, err)
}
if MiniClusterCtx != nil {
if wo.shutdownCtx != nil {
go func() {
<-MiniClusterCtx.Done()
<-wo.shutdownCtx.Done()
httpS.Shutdown(context.Background())
}()
}
+2 -2
View File
@@ -270,7 +270,7 @@ func mergeIntoManifest(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer
}
}
manifestChunk, err = saveFunc(bytes.NewReader(data), "", 0, 0)
manifestChunk, err = saveFunc(bytes.NewReader(data), "", 0, 0, uint64(len(data)))
if err != nil {
return nil, err
}
@@ -281,4 +281,4 @@ func mergeIntoManifest(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer
return
}
type SaveDataAsChunkFunctionType func(reader io.Reader, name string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error)
type SaveDataAsChunkFunctionType func(reader io.Reader, name string, offset int64, tsNs int64, expectedDataSize uint64) (chunk *filer_pb.FileChunk, err error)
+393
View File
@@ -2,10 +2,14 @@ package filer
import (
"bytes"
"context"
"fmt"
"io"
"math"
"testing"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
@@ -111,3 +115,392 @@ func mockMerge(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer_pb.File
return
}
// ---------------------------------------------------------------------------
// In-memory manifest store for round-trip tests
// ---------------------------------------------------------------------------
// testManifestStore provides in-memory save/resolve for manifest tests
// without requiring volume servers.
type testManifestStore struct {
stored map[string][]byte
nextID int
}
func newTestManifestStore() *testManifestStore {
return &testManifestStore{stored: make(map[string][]byte)}
}
func (s *testManifestStore) saveFunc() SaveDataAsChunkFunctionType {
return func(reader io.Reader, name string, offset int64, tsNs int64, _ uint64) (*filer_pb.FileChunk, error) {
data, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
s.nextID++
chunk := &filer_pb.FileChunk{
Fid: &filer_pb.FileId{VolumeId: 999, FileKey: uint64(s.nextID), Cookie: 0},
}
s.stored[chunk.GetFileIdString()] = data
return chunk, nil
}
}
// resolve expands a single manifest chunk by deserializing the stored proto.
func (s *testManifestStore) resolve(chunk *filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) {
data, ok := s.stored[chunk.GetFileIdString()]
if !ok {
return nil, fmt.Errorf("manifest %q not in store", chunk.GetFileIdString())
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal(data, m); err != nil {
return nil, err
}
filer_pb.AfterEntryDeserialization(m.Chunks)
return m.Chunks, nil
}
// resolveAll expands all manifest chunks, returns (dataChunks, manifestChunks).
func (s *testManifestStore) resolveAll(chunks []*filer_pb.FileChunk) (data, manifests []*filer_pb.FileChunk, err error) {
for _, c := range chunks {
if !c.IsChunkManifest {
data = append(data, c)
continue
}
manifests = append(manifests, c)
sub, resolveErr := s.resolve(c)
if resolveErr != nil {
return nil, nil, resolveErr
}
data = append(data, sub...)
}
return
}
func testChunk(volId uint32, key uint64, cookie uint32, offset int64, size uint64, tsNs int64) *filer_pb.FileChunk {
return &filer_pb.FileChunk{
Fid: &filer_pb.FileId{VolumeId: volId, FileKey: key, Cookie: cookie},
Offset: offset,
Size: size,
ModifiedTsNs: tsNs,
}
}
// ---------------------------------------------------------------------------
// Manifest round-trip: create -> serialize -> deserialize -> verify
// ---------------------------------------------------------------------------
func TestManifestRoundTripPreservesChunks(t *testing.T) {
store := newTestManifestStore()
chunks := []*filer_pb.FileChunk{
testChunk(1, 1, 100, 0, 1000, 10),
testChunk(1, 2, 200, 1000, 1000, 20),
testChunk(2, 3, 300, 2000, 1000, 30),
}
origIds := make([]string, len(chunks))
for i, c := range chunks {
origIds[i] = c.GetFileIdString()
}
// Use real mergeIntoManifest with batch=3 so all go into one manifest
result, err := doMaybeManifestize(store.saveFunc(), chunks, 3, mergeIntoManifest)
if err != nil {
t.Fatal(err)
}
if len(result) != 1 || !result[0].IsChunkManifest {
t.Fatalf("expected 1 manifest chunk, got %d chunks", len(result))
}
if result[0].Offset != 0 || result[0].Size != 3000 {
t.Errorf("manifest coverage: offset=%d size=%d, want 0/3000", result[0].Offset, result[0].Size)
}
resolved, err := store.resolve(result[0])
if err != nil {
t.Fatal(err)
}
if len(resolved) != 3 {
t.Fatalf("expected 3 sub-chunks, got %d", len(resolved))
}
for i, got := range resolved {
if got.GetFileIdString() != origIds[i] {
t.Errorf("chunk %d: fileId %q != %q", i, got.GetFileIdString(), origIds[i])
}
if got.Offset != chunks[i].Offset {
t.Errorf("chunk %d: offset %d != %d", i, got.Offset, chunks[i].Offset)
}
if got.Size != chunks[i].Size {
t.Errorf("chunk %d: size %d != %d", i, got.Size, chunks[i].Size)
}
if got.ModifiedTsNs != chunks[i].ModifiedTsNs {
t.Errorf("chunk %d: ts %d != %d", i, got.ModifiedTsNs, chunks[i].ModifiedTsNs)
}
}
}
// ---------------------------------------------------------------------------
// Compact resolved overlapping manifests: older sub-chunks become garbage
// ---------------------------------------------------------------------------
func TestCompactResolvedOverlappingManifests(t *testing.T) {
store := newTestManifestStore()
// Batch 1: older writes covering [0, 3000)
batch1 := []*filer_pb.FileChunk{
testChunk(1, 1, 1, 0, 1000, 1),
testChunk(1, 2, 2, 1000, 1000, 2),
testChunk(1, 3, 3, 2000, 1000, 3),
}
origBatch1Ids := make(map[string]bool)
for _, c := range batch1 {
origBatch1Ids[c.GetFileIdString()] = true
}
// Batch 2: newer writes covering [0, 3000)
batch2 := []*filer_pb.FileChunk{
testChunk(2, 1, 1, 0, 1000, 10),
testChunk(2, 2, 2, 1000, 1000, 11),
testChunk(2, 3, 3, 2000, 1000, 12),
}
origBatch2Ids := make(map[string]bool)
for _, c := range batch2 {
origBatch2Ids[c.GetFileIdString()] = true
}
// Manifestize each batch separately (simulates successive flush cycles)
save := store.saveFunc()
manifest1, err := doMaybeManifestize(save, batch1, 3, mergeIntoManifest)
if err != nil {
t.Fatal(err)
}
manifest2, err := doMaybeManifestize(save, batch2, 3, mergeIntoManifest)
if err != nil {
t.Fatal(err)
}
// Resolve all manifests into sub-chunks
allChunks := append(manifest1, manifest2...)
dataChunks, _, err := store.resolveAll(allChunks)
if err != nil {
t.Fatal(err)
}
if len(dataChunks) != 6 {
t.Fatalf("expected 6 resolved data chunks, got %d", len(dataChunks))
}
// CompactFileChunks on resolved sub-chunks (nil lookupFn is fine for non-manifest chunks)
compacted, garbage := CompactFileChunks(context.Background(), nil, dataChunks)
if len(compacted) != 3 {
t.Fatalf("expected 3 compacted chunks, got %d", len(compacted))
}
if len(garbage) != 3 {
t.Fatalf("expected 3 garbage chunks, got %d", len(garbage))
}
for _, c := range compacted {
if !origBatch2Ids[c.GetFileIdString()] {
t.Errorf("compacted chunk %q should be from newer batch", c.GetFileIdString())
}
}
for _, c := range garbage {
if !origBatch1Ids[c.GetFileIdString()] {
t.Errorf("garbage chunk %q should be from older batch", c.GetFileIdString())
}
}
}
// ---------------------------------------------------------------------------
// DoMinusChunks: old manifest sub-chunks identified as garbage vs new chunks
// ---------------------------------------------------------------------------
func TestDoMinusChunksWithResolvedManifests(t *testing.T) {
store := newTestManifestStore()
// Old entry: data packed into a manifest
oldData := []*filer_pb.FileChunk{
testChunk(1, 1, 1, 0, 1000, 1),
testChunk(1, 2, 2, 1000, 1000, 2),
testChunk(1, 3, 3, 2000, 1000, 3),
}
oldManifest, err := doMaybeManifestize(store.saveFunc(), oldData, 3, mergeIntoManifest)
if err != nil {
t.Fatal(err)
}
// Resolve old manifests into sub-chunks (what MinusChunks does internally)
oldResolved, oldMeta, err := store.resolveAll(oldManifest)
if err != nil {
t.Fatal(err)
}
// New entry: clean re-uploaded chunks (from merge) with different file IDs
newData := []*filer_pb.FileChunk{
testChunk(3, 10, 10, 0, 1500, 100),
testChunk(3, 11, 11, 1500, 1500, 101),
}
// DoMinusChunks: data sub-chunks in old but not in new
deltaData := DoMinusChunks(oldResolved, newData)
if len(deltaData) != 3 {
t.Fatalf("expected 3 old data chunks as garbage, got %d", len(deltaData))
}
// DoMinusChunks: manifest chunks in old but not in new
deltaMeta := DoMinusChunks(oldMeta, nil)
if len(deltaMeta) != 1 {
t.Fatalf("expected 1 old manifest chunk as garbage, got %d", len(deltaMeta))
}
}
// ---------------------------------------------------------------------------
// Small-batch manifestize: verify sub-chunks and remainder handling
// ---------------------------------------------------------------------------
func TestManifestizeSmallBatchWithRemainder(t *testing.T) {
store := newTestManifestStore()
// 7 chunks with batch=3: should produce 2 manifests + 1 remainder
chunks := make([]*filer_pb.FileChunk, 7)
for i := range chunks {
chunks[i] = testChunk(1, uint64(i+1), uint32(i+1), int64(i*100), 100, int64(i+1))
}
result, err := doMaybeManifestize(store.saveFunc(), chunks, 3, mergeIntoManifest)
if err != nil {
t.Fatal(err)
}
manifests := 0
regular := 0
for _, c := range result {
if c.IsChunkManifest {
manifests++
} else {
regular++
}
}
if manifests != 2 {
t.Errorf("expected 2 manifests, got %d", manifests)
}
if regular != 1 {
t.Errorf("expected 1 remainder chunk, got %d", regular)
}
// Resolve all and verify we get back 7 data chunks
data, _, err := store.resolveAll(result)
if err != nil {
t.Fatal(err)
}
if len(data) != 7 {
t.Fatalf("expected 7 data chunks after resolve, got %d", len(data))
}
}
// ---------------------------------------------------------------------------
// Multiple overlapping manifests: compaction identifies all redundant sub-chunks
// ---------------------------------------------------------------------------
func TestCompactMultipleOverlappingManifestGenerations(t *testing.T) {
store := newTestManifestStore()
save := store.saveFunc()
const fileSize int64 = 3000
const chunkSize uint64 = 1000
// Simulate 5 generations of full-file writes, each manifestized separately.
var allManifests []*filer_pb.FileChunk
for gen := 0; gen < 5; gen++ {
tsBase := int64((gen + 1) * 100)
batch := []*filer_pb.FileChunk{
testChunk(uint32(gen+1), 1, uint32(gen), 0, chunkSize, tsBase),
testChunk(uint32(gen+1), 2, uint32(gen), int64(chunkSize), chunkSize, tsBase+1),
testChunk(uint32(gen+1), 3, uint32(gen), int64(chunkSize*2), chunkSize, tsBase+2),
}
manifest, err := doMaybeManifestize(save, batch, 3, mergeIntoManifest)
if err != nil {
t.Fatal(err)
}
allManifests = append(allManifests, manifest...)
}
if len(allManifests) != 5 {
t.Fatalf("expected 5 manifest chunks, got %d", len(allManifests))
}
// Resolve all 5 manifests: 15 data chunks total
dataChunks, _, err := store.resolveAll(allManifests)
if err != nil {
t.Fatal(err)
}
if len(dataChunks) != 15 {
t.Fatalf("expected 15 resolved chunks, got %d", len(dataChunks))
}
// Compact: only generation 5 (the newest 3 chunks) should survive
compacted, garbage := CompactFileChunks(context.Background(), nil, dataChunks)
if len(compacted) != 3 {
t.Errorf("expected 3 compacted (gen 5), got %d", len(compacted))
}
if len(garbage) != 12 {
t.Errorf("expected 12 garbage (gens 1-4), got %d", len(garbage))
}
// Verify the surviving chunks are the newest (highest timestamps)
for _, c := range compacted {
if c.ModifiedTsNs < 500 {
t.Errorf("compacted chunk ts=%d should be from gen 5 (ts >= 500)", c.ModifiedTsNs)
}
}
}
// ---------------------------------------------------------------------------
// Bloat detection: manifest sizes must count toward total
// ---------------------------------------------------------------------------
func TestManifestBloatDetection(t *testing.T) {
// Simulates what shouldMergeChunks sees after multiple flush cycles.
// With the fix, manifest sizes count toward totalChunkSize, so bloat
// from accumulated manifests is detected.
const fileSize uint64 = 10000
// 1 regular chunk covering the file (from latest compaction)
regular := []*filer_pb.FileChunk{
{Offset: 0, Size: fileSize, FileId: "latest", ModifiedTsNs: 100,
Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 1}},
}
// N manifests each covering the full file (from prior flush cycles)
for n := 1; n <= 10; n++ {
var manifests []*filer_pb.FileChunk
for i := 0; i < n; i++ {
manifests = append(manifests, &filer_pb.FileChunk{
Offset: 0, Size: fileSize, IsChunkManifest: true,
Fid: &filer_pb.FileId{VolumeId: 900, FileKey: uint64(i + 1)},
})
}
allChunks := append(append([]*filer_pb.FileChunk{}, regular...), manifests...)
var totalStored uint64
for _, c := range allChunks {
totalStored += c.Size
}
totalFile := TotalSize(allChunks)
expectMerge := totalStored > 2*totalFile
t.Logf("n=%d manifests: totalStored=%d fileSize=%d ratio=%.1fx expectMerge=%v",
n, totalStored, totalFile, float64(totalStored)/float64(totalFile), expectMerge)
// With 1 regular (10000) + N manifests (N*10000):
// total = (N+1)*10000, fileSize=10000, ratio = N+1
// Merge when N+1 > 2, i.e., N >= 2
if n >= 2 && !expectMerge {
t.Errorf("n=%d: should trigger merge at ratio %.1f", n, float64(totalStored)/float64(totalFile))
}
if n < 2 && expectMerge {
t.Errorf("n=%d: should NOT trigger merge at ratio %.1f", n, float64(totalStored)/float64(totalFile))
}
}
}
+1
View File
@@ -57,6 +57,7 @@ func (f *Filer) assignAndUpload(targetFile string, data []byte) (*operation.Assi
Replication: util.Nvl(f.metaLogReplication, rule.Replication),
DiskType: rule.DiskType,
WritableVolumeCount: rule.VolumeGrowthCount,
ExpectedDataSize: uint64(len(data)),
}
assignResult, err := operation.Assign(context.Background(), f.GetMaster, f.GrpcDialOption, assignRequest)
+141
View File
@@ -0,0 +1,141 @@
package filer
import (
"sync"
"time"
)
// maxMountPeerRegistryEntries caps the number of mounts the filer will track to
// prevent a burst of buggy or malicious clients from exhausting memory. At
// ~80 B per entry (map + struct + strings) a 10k cap costs ~1 MB, which is
// ample headroom for real fleets while being well under any filer's budget.
// A full registry silently rejects new registrations until expiry frees room.
const maxMountPeerRegistryEntries = 10000
// maxMountPeerRegistryTTL caps a single heartbeat's requested TTL. Prevents a
// misconfigured or malicious client from pinning an entry indefinitely.
const maxMountPeerRegistryTTL = time.Hour
// MountPeerRegistry is the in-memory mount-server registry (tier 1 of the peer
// chunk sharing design). The filer holds a map of mount-server address ->
// metadata with TTL-bounded entries refreshed by MountRegister heartbeats.
//
// The registry is small (O(fleet_size)) and slow-changing; fid-level state
// is NOT stored here — that lives on the mount fleet itself (tier 2).
//
// See design-weed-mount-peer-chunk-sharing.md §4.2.1.
type MountPeerRegistry struct {
mu sync.RWMutex
entries map[string]*mountPeerRegistryEntry
clock func() time.Time // injectable for tests
}
type mountPeerRegistryEntry struct {
peerAddr string
dataCenter string
rack string
expiry time.Time
lastSeen time.Time
}
// MountPeerInfo is the public view of a registered mount. DataCenter and
// Rack are carried as a two-level locality hierarchy: a peer in the same
// DC but a different rack is still a much better fetch target than a peer
// in a different DC, so both are worth distinguishing for ranking.
type MountPeerInfo struct {
PeerAddr string
DataCenter string
Rack string
LastSeenNs int64
}
// NewMountPeerRegistry constructs an empty registry using the real wall clock.
func NewMountPeerRegistry() *MountPeerRegistry {
return newMountPeerRegistryWithClock(time.Now)
}
func newMountPeerRegistryWithClock(clock func() time.Time) *MountPeerRegistry {
return &MountPeerRegistry{
entries: make(map[string]*mountPeerRegistryEntry),
clock: clock,
}
}
// Register inserts or renews an entry. A zero or negative ttl is treated as
// "use a sane default" (60 s); a ttl exceeding maxMountPeerRegistryTTL is capped.
// An empty peerAddr is rejected silently. When the registry is at capacity,
// a *new* entry is rejected; renewals of existing entries always succeed.
func (r *MountPeerRegistry) Register(peerAddr, dataCenter, rack string, ttl time.Duration) {
if peerAddr == "" {
return
}
if ttl <= 0 {
ttl = 60 * time.Second
}
if ttl > maxMountPeerRegistryTTL {
ttl = maxMountPeerRegistryTTL
}
now := r.clock()
r.mu.Lock()
defer r.mu.Unlock()
entry, ok := r.entries[peerAddr]
if !ok {
if len(r.entries) >= maxMountPeerRegistryEntries {
return
}
entry = &mountPeerRegistryEntry{peerAddr: peerAddr}
r.entries[peerAddr] = entry
}
entry.dataCenter = dataCenter
entry.rack = rack
entry.lastSeen = now
entry.expiry = now.Add(ttl)
}
// List returns all entries that have not yet expired, in no particular
// order. Expired entries are filtered out of the response but NOT deleted
// here — Sweep handles that under a write lock on its own schedule. List
// is called on every mount's MountList refresh (30 s cadence per mount)
// so keeping it RLock-only lets concurrent callers proceed in parallel.
func (r *MountPeerRegistry) List() []MountPeerInfo {
now := r.clock()
r.mu.RLock()
defer r.mu.RUnlock()
result := make([]MountPeerInfo, 0, len(r.entries))
for _, entry := range r.entries {
if !entry.expiry.After(now) {
continue // Sweep will clean this up
}
result = append(result, MountPeerInfo{
PeerAddr: entry.peerAddr,
DataCenter: entry.dataCenter,
Rack: entry.rack,
LastSeenNs: entry.lastSeen.UnixNano(),
})
}
return result
}
// Len returns the current entry count (including entries that may have
// expired but not yet been swept).
func (r *MountPeerRegistry) Len() int {
r.mu.RLock()
defer r.mu.RUnlock()
return len(r.entries)
}
// Sweep removes expired entries. Safe to call periodically. Returns the
// number of entries evicted.
func (r *MountPeerRegistry) Sweep() int {
now := r.clock()
r.mu.Lock()
defer r.mu.Unlock()
evicted := 0
for addr, entry := range r.entries {
if !entry.expiry.After(now) {
delete(r.entries, addr)
evicted++
}
}
return evicted
}
+169
View File
@@ -0,0 +1,169 @@
package filer
import (
"fmt"
"sort"
"testing"
"time"
)
func testClock(t time.Time) func() time.Time {
return func() time.Time { return t }
}
func TestMountPeerRegistry_RegisterAndList(t *testing.T) {
start := time.Unix(1000, 0)
current := start
r := newMountPeerRegistryWithClock(func() time.Time { return current })
r.Register("mount-a:18080", "", "rack1", 30*time.Second)
r.Register("mount-b:18080", "", "rack2", 30*time.Second)
list := r.List()
if len(list) != 2 {
t.Fatalf("expected 2 entries, got %d", len(list))
}
sort.Slice(list, func(i, j int) bool { return list[i].PeerAddr < list[j].PeerAddr })
if list[0].PeerAddr != "mount-a:18080" || list[0].Rack != "rack1" {
t.Errorf("entry 0 unexpected: %+v", list[0])
}
if list[1].PeerAddr != "mount-b:18080" || list[1].Rack != "rack2" {
t.Errorf("entry 1 unexpected: %+v", list[1])
}
}
func TestMountPeerRegistry_RenewExtendsExpiry(t *testing.T) {
current := time.Unix(1000, 0)
r := newMountPeerRegistryWithClock(func() time.Time { return current })
r.Register("mount-a:18080", "", "rack1", 30*time.Second)
// Advance time past original expiry.
current = current.Add(25 * time.Second)
// Renew — should push expiry to now+30.
r.Register("mount-a:18080", "", "rack1-updated", 30*time.Second)
// Advance to where original expiry would have triggered eviction.
current = current.Add(10 * time.Second)
list := r.List()
if len(list) != 1 {
t.Fatalf("expected 1 entry after renew, got %d", len(list))
}
if list[0].Rack != "rack1-updated" {
t.Errorf("rack not updated on renew: %q", list[0].Rack)
}
}
func TestMountPeerRegistry_ExpirationDropsEntry(t *testing.T) {
current := time.Unix(1000, 0)
r := newMountPeerRegistryWithClock(func() time.Time { return current })
r.Register("mount-a:18080", "", "", 10*time.Second)
if n := r.Len(); n != 1 {
t.Fatalf("expected 1 entry, got %d", n)
}
current = current.Add(15 * time.Second)
list := r.List()
if len(list) != 0 {
t.Errorf("expected 0 entries after expiry, got %d", len(list))
}
// List no longer deletes — it's RLock-only so concurrent callers can
// proceed in parallel. Sweep is the sole reclamation path.
if n := r.Len(); n != 1 {
t.Errorf("List should not delete expired entries; Len=%d want 1", n)
}
if evicted := r.Sweep(); evicted != 1 {
t.Errorf("Sweep should have evicted the expired entry; got %d", evicted)
}
if n := r.Len(); n != 0 {
t.Errorf("after Sweep, Len=%d want 0", n)
}
}
func TestMountPeerRegistry_SweepCountsEvictions(t *testing.T) {
current := time.Unix(1000, 0)
r := newMountPeerRegistryWithClock(func() time.Time { return current })
r.Register("mount-a:18080", "", "", 10*time.Second)
r.Register("mount-b:18080", "", "", 60*time.Second)
current = current.Add(30 * time.Second)
got := r.Sweep()
if got != 1 {
t.Errorf("expected 1 eviction, got %d", got)
}
if n := r.Len(); n != 1 {
t.Errorf("expected 1 surviving entry, got %d", n)
}
}
func TestMountPeerRegistry_NegativeTTLFallsBackToDefault(t *testing.T) {
current := time.Unix(1000, 0)
r := newMountPeerRegistryWithClock(func() time.Time { return current })
r.Register("mount-a:18080", "", "", -5*time.Second)
if n := r.Len(); n != 1 {
t.Fatalf("expected 1 entry even with bad ttl, got %d", n)
}
// Advance past the default (60s) and confirm it expires.
current = current.Add(61 * time.Second)
list := r.List()
if len(list) != 0 {
t.Errorf("expected entry to expire after default ttl, got %d entries", len(list))
}
}
func TestMountPeerRegistry_EmptyList(t *testing.T) {
r := NewMountPeerRegistry()
list := r.List()
if len(list) != 0 {
t.Errorf("expected empty list, got %d", len(list))
}
_ = testClock // keep helper exported for future tests
}
func TestMountPeerRegistry_EmptyPeerAddrRejected(t *testing.T) {
r := NewMountPeerRegistry()
r.Register("", "", "rack", 30*time.Second)
if n := r.Len(); n != 0 {
t.Errorf("empty peer_addr should not insert; Len=%d", n)
}
}
func TestMountPeerRegistry_TTLCapped(t *testing.T) {
current := time.Unix(1000, 0)
r := newMountPeerRegistryWithClock(func() time.Time { return current })
// Request a ridiculous TTL; should be capped to maxMountPeerRegistryTTL.
r.Register("mount-a:18080", "", "", 24*time.Hour)
// Advance past the cap; entry should now be expired.
current = current.Add(maxMountPeerRegistryTTL + time.Second)
if list := r.List(); len(list) != 0 {
t.Errorf("expected entry to expire after maxMountPeerRegistryTTL, got %d", len(list))
}
}
func TestMountPeerRegistry_CapacityLimit(t *testing.T) {
r := NewMountPeerRegistry()
// Fill to capacity.
for i := 0; i < maxMountPeerRegistryEntries; i++ {
r.Register(fmt.Sprintf("mount-%d:18080", i), "", "", 60*time.Second)
}
if n := r.Len(); n != maxMountPeerRegistryEntries {
t.Fatalf("expected %d entries, got %d", maxMountPeerRegistryEntries, n)
}
// A brand-new address beyond the cap is rejected.
r.Register("new-mount:18080", "", "", 60*time.Second)
if n := r.Len(); n != maxMountPeerRegistryEntries {
t.Errorf("new entry past cap should be rejected; Len=%d", n)
}
// A renewal of an existing entry still succeeds.
r.Register("mount-0:18080", "", "rack-renewed", 60*time.Second)
if n := r.Len(); n != maxMountPeerRegistryEntries {
t.Errorf("renewal should not increase size; Len=%d", n)
}
}
+4
View File
@@ -178,6 +178,10 @@ func newSingleChunkCacher(parent *ReaderCache, fileId string, cipherKey []byte,
// startCaching downloads the chunk data in the background.
// It does NOT hold the lock during the HTTP download to allow concurrent readers
// to wait efficiently using the done channel.
//
// Concurrent downloads of the same chunk are already deduplicated by the
// ReaderCache.downloaders map (guarded by the ReaderCache mutex). Each fileId
// has at most one active SingleChunkCacher at any time.
func (s *SingleChunkCacher) startCaching() {
s.wg.Add(1)
defer s.wg.Done()
+40
View File
@@ -433,6 +433,46 @@ func TestSingleChunkCacherMultipleReadersWaitForDownload(t *testing.T) {
}
}
// TestReaderCacheDownloaderDedup tests that concurrent ReadChunkAt calls for
// the same fileId result in only one network fetch (lookup call), because
// the downloaders map deduplicates in-flight downloads.
func TestReaderCacheDownloaderDedup(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
var lookupCount int32
lookupGate := make(chan struct{})
lookupFn := func(ctx context.Context, fileId string) ([]string, error) {
atomic.AddInt32(&lookupCount, 1)
<-lookupGate
// Return an error so we don't need to mock the HTTP fetch.
return nil, fmt.Errorf("simulated lookup for %s", fileId)
}
rc := NewReaderCache(10, cache, lookupFn)
defer rc.destroy()
const numReaders = 10
var wg sync.WaitGroup
wg.Add(numReaders)
for i := 0; i < numReaders; i++ {
go func() {
defer wg.Done()
buffer := make([]byte, 100)
rc.ReadChunkAt(context.Background(), buffer, "dedup-file", nil, false, 0, 100, false)
}()
}
// Allow downloads to proceed.
close(lookupGate)
wg.Wait()
count := atomic.LoadInt32(&lookupCount)
if count != 1 {
t.Errorf("expected exactly 1 lookup call, got %d", count)
}
}
// TestSingleChunkCacherOneReaderCancelsOthersContinue tests that when one reader
// cancels, other readers waiting on the same chunk continue to wait.
func TestSingleChunkCacherOneReaderCancelsOthersContinue(t *testing.T) {
+1 -1
View File
@@ -72,7 +72,7 @@ func (pages *ChunkedDirtyPages) saveChunkedFileIntervalToStorage(reader io.Reade
fileFullPath := pages.fh.FullPath()
fileName := fileFullPath.Name()
chunk, err := pages.fh.wfs.saveDataAsChunk(fileFullPath)(reader, fileName, offset, modifiedTsNs)
chunk, err := pages.fh.wfs.saveDataAsChunk(fileFullPath)(reader, fileName, offset, modifiedTsNs, uint64(size))
if err != nil {
glog.V(0).Infof("%v saveToStorage [%d,%d): %v", fileFullPath, offset, offset+size, err)
pages.lastErr = err
+17
View File
@@ -75,6 +75,23 @@ func (fh *FileHandle) readFromChunksWithContext(ctx context.Context, buff []byte
glog.V(4).Infof("RDMA read failed for %s, falling back to HTTP: %v", fileFullPath, err)
}
// Peer chunk sharing: try a peer mount's cache before the volume tier.
// Any failure falls through transparently. See design-weed-mount-
// peer-chunk-sharing.md §4.3.
if fh.wfs.option.PeerEnabled && fh.wfs.peerGrpcServer != nil {
totalRead, ts, err := fh.tryPeerRead(ctx, fileSize, buff, offset, entry)
if err == nil {
glog.V(4).Infof("peer read successful for %s [%d,%d] %d", fileFullPath, offset, offset+int64(totalRead), totalRead)
return int64(totalRead), ts, nil
}
// Skip the "failed" log for benign skip reasons (local cache
// hit, no peer owner yet, etc.) — the cache/volume fallback is
// the expected outcome, not a failure.
if err != errPeerReadSkipped {
glog.V(4).Infof("peer read failed for %s, falling back to volume: %v", fileFullPath, err)
}
}
// Fall back to normal chunk reading
totalRead, ts, err := fh.entryChunkGroup.ReadDataAt(ctx, fileSize, buff, offset)
-181
View File
@@ -1,181 +0,0 @@
package mount
import (
"context"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
)
// FileIdEntry holds a pre-allocated file ID from the filer/master, ready for
// immediate use by an upload worker without an AssignVolume round-trip.
type FileIdEntry struct {
FileId string
Host string // volume server address (already adjusted for access mode)
Auth security.EncodedJwt
Time time.Time
}
// FileIdPool pre-allocates file IDs in batches so that chunk uploads can grab
// one instantly instead of blocking on an AssignVolume RPC per chunk.
//
// The pool is refilled in the background when it drops below a low-water mark.
// All IDs are allocated with the mount's global (replication, collection, ttl,
// diskType, dataCenter) parameters. Path-based storage rules (filer.conf) are
// NOT applied to pooled IDs since the pool allocates ahead of any specific file
// path. This is an intentional tradeoff for writeback cache performance.
type FileIdPool struct {
wfs *WFS
mu sync.Mutex
cond *sync.Cond
entries []FileIdEntry // available pre-allocated IDs
filling bool // true when a background refill is in progress
poolSize int // target pool capacity
batchSize int // how many IDs to request per Assign RPC
lowWater int // refill trigger threshold
maxAge time.Duration
}
func NewFileIdPool(wfs *WFS) *FileIdPool {
concurrency := wfs.option.ConcurrentWriters
if concurrency <= 0 {
concurrency = 128 // match default async flush worker count
}
pool := &FileIdPool{
wfs: wfs,
poolSize: concurrency * 2,
batchSize: concurrency,
lowWater: concurrency,
maxAge: 25 * time.Second, // conservative; JWT TTL is typically 30s+
}
pool.cond = sync.NewCond(&pool.mu)
return pool
}
// Get returns a pre-allocated file ID entry. If the pool is empty and a refill
// is in progress, callers wait for it to complete rather than failing. Returns
// an error only if the Assign RPC fails.
func (p *FileIdPool) Get() (FileIdEntry, error) {
p.mu.Lock()
defer p.mu.Unlock()
for {
p.evictExpired()
if len(p.entries) > 0 {
entry := p.entries[0]
p.entries = p.entries[1:]
if len(p.entries) < p.lowWater && !p.filling {
p.filling = true
go p.doRefill()
}
return entry, nil
}
// Pool empty.
if p.filling {
// Wait for the in-flight refill to complete.
p.cond.Wait()
continue
}
// No refill in progress — start one synchronously.
p.filling = true
p.mu.Unlock()
entries, err := p.assignBatch(p.batchSize)
p.mu.Lock()
p.filling = false
p.cond.Broadcast()
if err != nil {
return FileIdEntry{}, fmt.Errorf("fileIdPool: %w", err)
}
p.entries = append(p.entries, entries...)
// Loop back to pop from entries.
}
}
func (p *FileIdPool) evictExpired() {
cutoff := time.Now().Add(-p.maxAge)
i := 0
for i < len(p.entries) && p.entries[i].Time.Before(cutoff) {
i++
}
if i > 0 {
p.entries = p.entries[i:]
}
}
// doRefill runs in a background goroutine to refill the pool.
func (p *FileIdPool) doRefill() {
entries, err := p.assignBatch(p.batchSize)
if err != nil {
glog.V(1).Infof("fileIdPool refill: %v", err)
}
p.mu.Lock()
if err == nil {
p.entries = append(p.entries, entries...)
}
p.filling = false
p.cond.Broadcast()
p.mu.Unlock()
}
// assignBatch requests `count` file IDs from the filer using individual
// Count=1 RPCs over a single gRPC connection. Each response includes a
// per-fid JWT, so uploads work correctly when JWT security is enabled.
//
// We use individual requests instead of Count=N because the master generates
// one JWT for the base file ID only (master_grpc_server_assign.go:158), and
// the volume server validates that the JWT's Fid matches the upload's file ID
// exactly (volume_server_handlers.go:367). Sequential IDs derived from a
// Count=N response would fail this check.
//
// Note: the AssignVolumeRequest intentionally omits the Path field. Pooled IDs
// use the mount's global storage parameters, not per-path rules from filer.conf
// (detectStorageOption / MatchStorageRule). This is a writeback cache tradeoff.
func (p *FileIdPool) assignBatch(count int) ([]FileIdEntry, error) {
var entries []FileIdEntry
err := p.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
now := time.Now()
req := &filer_pb.AssignVolumeRequest{
Count: 1,
Replication: p.wfs.option.Replication,
Collection: p.wfs.option.Collection,
TtlSec: p.wfs.option.TtlSec,
DiskType: string(p.wfs.option.DiskType),
DataCenter: p.wfs.option.DataCenter,
ExpectedDataSize: uint64(p.wfs.option.ChunkSizeLimit),
}
for i := 0; i < count; i++ {
resp, assignErr := client.AssignVolume(context.Background(), req)
if assignErr != nil {
if len(entries) > 0 {
break // partial batch is fine
}
return assignErr
}
if resp.Error != "" {
if len(entries) > 0 {
break
}
return fmt.Errorf("assign: %s", resp.Error)
}
entries = append(entries, FileIdEntry{
FileId: resp.FileId,
Host: p.wfs.AdjustedUrl(resp.Location),
Auth: security.EncodedJwt(resp.Auth),
Time: now,
})
}
return nil
})
return entries, err
}
-280
View File
@@ -1,280 +0,0 @@
package mount
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"google.golang.org/grpc"
)
// mockFilerClient simulates AssignVolume RPCs with configurable latency.
type mockFilerClient struct {
latency time.Duration
nextVolId uint32
nextKey uint64
mu sync.Mutex
}
func (m *mockFilerClient) AssignVolume(_ context.Context, req *filer_pb.AssignVolumeRequest, _ ...grpc.CallOption) (*filer_pb.AssignVolumeResponse, error) {
if m.latency > 0 {
time.Sleep(m.latency)
}
m.mu.Lock()
defer m.mu.Unlock()
count := int(req.Count)
if count <= 0 {
count = 1
}
vid := needle.VolumeId(m.nextVolId + 1)
key := m.nextKey + 1000 // start at a non-zero key for valid hex encoding
m.nextKey += uint64(count)
m.nextVolId++
fid := needle.NewFileId(vid, key, 0x12345678)
return &filer_pb.AssignVolumeResponse{
FileId: fid.String(),
Count: int32(count),
Auth: "test-jwt-token",
Location: &filer_pb.Location{
Url: "127.0.0.1:8080",
PublicUrl: "127.0.0.1:8080",
GrpcPort: 18080,
},
}, nil
}
// TestFileIdPoolSequentialIds verifies that batch assignment generates
// correct sequential file IDs from a single AssignVolume response.
func TestFileIdPoolSequentialIds(t *testing.T) {
mock := &mockFilerClient{}
resp, err := mock.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{Count: 5})
if err != nil {
t.Fatal(err)
}
baseFid, parseErr := needle.ParseFileIdFromString(resp.FileId)
if parseErr != nil {
t.Fatal(parseErr)
}
baseKey := uint64(baseFid.Key)
for i := 0; i < int(resp.Count); i++ {
fid := needle.NewFileId(baseFid.VolumeId, baseKey+uint64(i), uint32(baseFid.Cookie))
t.Logf("ID %d: %s", i, fid.String())
parsed, err := needle.ParseFileIdFromString(fid.String())
if err != nil {
t.Fatalf("Failed to parse sequential ID %d: %v", i, err)
}
if uint64(parsed.Key) != baseKey+uint64(i) {
t.Fatalf("ID %d: expected key %d, got %d", i, baseKey+uint64(i), uint64(parsed.Key))
}
}
}
// TestFileIdPoolExpiry verifies that expired entries are evicted.
func TestFileIdPoolExpiry(t *testing.T) {
pool := &FileIdPool{
maxAge: time.Second,
}
pool.cond = sync.NewCond(&pool.mu)
now := time.Now()
pool.entries = []FileIdEntry{
{FileId: "1,old", Time: now.Add(-2 * time.Second)},
{FileId: "2,old", Time: now.Add(-2 * time.Second)},
{FileId: "3,fresh", Time: now},
}
pool.evictExpired()
if len(pool.entries) != 1 {
t.Fatalf("expected 1 entry after eviction, got %d", len(pool.entries))
}
if pool.entries[0].FileId != "3,fresh" {
t.Fatalf("expected fresh entry, got %s", pool.entries[0].FileId)
}
}
// TestFileIdPoolGetWaitsForRefill verifies that concurrent Get() calls wait
// for an in-flight refill instead of returning an error.
func TestFileIdPoolGetWaitsForRefill(t *testing.T) {
pool := &FileIdPool{
poolSize: 10,
batchSize: 5,
lowWater: 3,
maxAge: 30 * time.Second,
}
pool.cond = sync.NewCond(&pool.mu)
// Simulate a slow refill in progress.
pool.filling = true
done := make(chan struct{})
go func() {
// After a short delay, deliver entries and signal.
time.Sleep(10 * time.Millisecond)
pool.mu.Lock()
now := time.Now()
for i := 0; i < 5; i++ {
pool.entries = append(pool.entries, FileIdEntry{
FileId: fmt.Sprintf("1,%x12345678", 1000+i),
Host: "127.0.0.1:8080",
Auth: "jwt",
Time: now,
})
}
pool.filling = false
pool.cond.Broadcast()
pool.mu.Unlock()
close(done)
}()
// Get() should wait for the refill, not return an error.
entry, err := pool.Get()
if err != nil {
t.Fatalf("Get() returned error while refill in progress: %v", err)
}
if entry.FileId == "" {
t.Fatal("Get() returned empty entry")
}
<-done
}
// BenchmarkPoolGetVsDirectAssign measures the latency difference between
// getting a file ID from the pool vs a direct (simulated) AssignVolume RPC.
func BenchmarkPoolGetVsDirectAssign(b *testing.B) {
assignLatencies := []time.Duration{
0,
100 * time.Microsecond,
1 * time.Millisecond,
5 * time.Millisecond,
}
for _, latency := range assignLatencies {
name := "latency=" + latency.String()
b.Run("DirectAssign/"+name, func(b *testing.B) {
mock := &mockFilerClient{latency: latency}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := mock.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{Count: 1})
if err != nil {
b.Fatal(err)
}
}
})
b.Run("PoolGet/"+name, func(b *testing.B) {
pool := &FileIdPool{
maxAge: 30 * time.Second,
lowWater: 1000000, // disable background refill
}
pool.cond = sync.NewCond(&pool.mu)
// Pre-fill with a fixed-size pool; refill under StopTimer when depleted.
const preload = 4096
refill := func() {
now := time.Now()
for i := 0; i < preload; i++ {
pool.entries = append(pool.entries, FileIdEntry{
FileId: fmt.Sprintf("1,%x12345678", i),
Host: "127.0.0.1:8080",
Auth: security.EncodedJwt("test-jwt"),
Time: now,
})
}
}
refill()
b.ResetTimer()
for i := 0; i < b.N; i++ {
pool.mu.Lock()
if len(pool.entries) == 0 {
pool.mu.Unlock()
b.StopTimer()
refill()
b.StartTimer()
pool.mu.Lock()
}
_ = pool.entries[0]
pool.entries = pool.entries[1:]
pool.mu.Unlock()
}
})
}
}
// BenchmarkConcurrentPoolGet measures pool throughput under concurrent access.
func BenchmarkConcurrentPoolGet(b *testing.B) {
for _, workers := range []int{1, 4, 16, 64} {
b.Run(fmt.Sprintf("workers=%d", workers), func(b *testing.B) {
pool := &FileIdPool{
maxAge: 30 * time.Second,
lowWater: 1000000,
}
pool.cond = sync.NewCond(&pool.mu)
// Pre-fill
now := time.Now()
total := b.N*workers + 1000
pool.entries = make([]FileIdEntry, total)
for i := range pool.entries {
pool.entries[i] = FileIdEntry{
FileId: fmt.Sprintf("1,%x12345678", i+1000),
Host: "127.0.0.1:8080",
Auth: security.EncodedJwt("test-jwt"),
Time: now,
}
}
var ops atomic.Int64
b.ResetTimer()
var wg sync.WaitGroup
perWorker := b.N
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < perWorker; i++ {
pool.mu.Lock()
if len(pool.entries) > 0 {
_ = pool.entries[0]
pool.entries = pool.entries[1:]
ops.Add(1)
}
pool.mu.Unlock()
}
}()
}
wg.Wait()
b.ReportMetric(float64(ops.Load())/b.Elapsed().Seconds(), "ids/sec")
})
}
}
// BenchmarkBatchAssign measures the cost of batch vs individual assign RPCs.
func BenchmarkBatchAssign(b *testing.B) {
for _, batchSize := range []int{1, 8, 16, 32} {
b.Run(fmt.Sprintf("batch=%d", batchSize), func(b *testing.B) {
mock := &mockFilerClient{latency: 1 * time.Millisecond}
totalIds := 0
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err := mock.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{Count: int32(batchSize)})
if err != nil {
b.Fatal(err)
}
baseFid, _ := needle.ParseFileIdFromString(resp.FileId)
baseKey := uint64(baseFid.Key)
for j := 0; j < int(resp.Count); j++ {
_ = needle.NewFileId(baseFid.VolumeId, baseKey+uint64(j), uint32(baseFid.Cookie)).String()
totalIds++
}
}
b.ReportMetric(float64(totalIds)/b.Elapsed().Seconds(), "ids/sec")
})
}
}
@@ -2,6 +2,21 @@ package page_writer
import (
"sync"
"sync/atomic"
"time"
)
const (
// softThresholdRatio is the fraction of cap at which soft throttling begins.
// At this level, writes sleep briefly to let uploaders drain.
softThresholdRatio = 0.8
// hardThresholdRatio is the fraction of cap at which hard throttling kicks in.
// Writes sleep longer to aggressively slow intake.
hardThresholdRatio = 0.95
// softThrottleDelay is the sleep duration when usage exceeds the soft threshold.
softThrottleDelay = 10 * time.Millisecond
// hardThrottleDelay is the sleep duration when usage exceeds the hard threshold.
hardThrottleDelay = 50 * time.Millisecond
)
// WriteBufferAccountant enforces a global byte budget across all
@@ -14,16 +29,25 @@ import (
//
// A nil receiver is treated as "unlimited" for backward compatibility.
type WriteBufferAccountant struct {
mu sync.Mutex
cond *sync.Cond
cap int64 // 0 means unlimited
used int64
evictor func(needBytes int64) bool
evicting bool
mu sync.Mutex
cond *sync.Cond
cap int64 // 0 means unlimited
used int64
softThreshold int64 // pre-computed: cap * softThresholdRatio
hardThreshold int64 // pre-computed: cap * hardThresholdRatio
evictor func(needBytes int64) bool
evicting bool
softThrottleCount atomic.Int64
hardThrottleCount atomic.Int64
}
func NewWriteBufferAccountant(capBytes int64) *WriteBufferAccountant {
a := &WriteBufferAccountant{cap: capBytes}
a := &WriteBufferAccountant{
cap: capBytes,
softThreshold: int64(float64(capBytes) * softThresholdRatio),
hardThreshold: int64(float64(capBytes) * hardThresholdRatio),
}
a.cond = sync.NewCond(&a.mu)
return a
}
@@ -57,6 +81,29 @@ func (a *WriteBufferAccountant) Reserve(n int64) {
}
a.mu.Lock()
defer a.mu.Unlock()
// Graduated backpressure: slow writers before hitting the hard cap.
// Use projected usage (used + n) so that a single reservation crossing
// a threshold is throttled immediately rather than on the next call.
//
// This runs once per Reserve, not inside the blocking loop below.
// Once usage reaches the cap, the evictor + cond.Wait is the correct
// mechanism: it blocks until a sealed chunk upload frees space, which
// is strictly more efficient than repeated time-based sleeps that
// cannot free capacity on their own.
projected := a.used + n
if projected >= a.hardThreshold && a.used > 0 {
a.hardThrottleCount.Add(1)
a.mu.Unlock()
time.Sleep(hardThrottleDelay)
a.mu.Lock()
} else if projected >= a.softThreshold && a.used > 0 {
a.softThrottleCount.Add(1)
a.mu.Unlock()
time.Sleep(softThrottleDelay)
a.mu.Lock()
}
for a.used+n > a.cap && a.used > 0 {
// Before blocking, try to force-seal a writable chunk somewhere so
// its async upload path will eventually Release a slot. Single-flight
@@ -115,3 +162,19 @@ func (a *WriteBufferAccountant) Used() int64 {
defer a.mu.Unlock()
return a.used
}
// SoftThrottleCount returns the number of times soft throttling was triggered.
func (a *WriteBufferAccountant) SoftThrottleCount() int64 {
if a == nil {
return 0
}
return a.softThrottleCount.Load()
}
// HardThrottleCount returns the number of times hard throttling was triggered.
func (a *WriteBufferAccountant) HardThrottleCount() int64 {
if a == nil {
return 0
}
return a.hardThrottleCount.Load()
}
@@ -71,6 +71,116 @@ func TestWriteBufferAccountant_BlocksWhenOverCap(t *testing.T) {
}
}
func TestWriteBufferAccountant_SoftThrottle(t *testing.T) {
// Cap = 1000, soft threshold = 800. Reserve 850 (85%) then measure
// that the next Reserve is delayed by at least softThrottleDelay.
a := NewWriteBufferAccountant(1000)
a.Reserve(850)
start := time.Now()
a.Reserve(10) // should trigger soft throttle (used=850 > 800)
elapsed := time.Since(start)
if elapsed < softThrottleDelay {
t.Fatalf("expected Reserve to take >= %v (soft throttle), took %v", softThrottleDelay, elapsed)
}
}
func TestWriteBufferAccountant_HardThrottle(t *testing.T) {
// Cap = 1000, hard threshold = 950. Reserve 960 (96%) then measure
// that the next Reserve is delayed by at least hardThrottleDelay.
a := NewWriteBufferAccountant(1000)
a.Reserve(960)
start := time.Now()
a.Reserve(10) // should trigger hard throttle (used=960 > 950)
elapsed := time.Since(start)
if elapsed < hardThrottleDelay {
t.Fatalf("expected Reserve to take >= %v (hard throttle), took %v", hardThrottleDelay, elapsed)
}
}
func TestWriteBufferAccountant_NoThrottleBelowSoft(t *testing.T) {
// Cap = 1000, soft threshold = 800. Reserve 700 (70%) -- below soft
// threshold, so subsequent Reserve should return quickly.
a := NewWriteBufferAccountant(1000)
a.Reserve(700)
start := time.Now()
a.Reserve(10)
elapsed := time.Since(start)
if elapsed >= softThrottleDelay {
t.Fatalf("expected Reserve below soft threshold to avoid throttle delay (< %v), took %v", softThrottleDelay, elapsed)
}
}
func TestWriteBufferAccountant_ThrottleCounters(t *testing.T) {
a := NewWriteBufferAccountant(1000)
// Below soft -- no throttle
a.Reserve(700)
a.Reserve(10)
if a.SoftThrottleCount() != 0 || a.HardThrottleCount() != 0 {
t.Fatalf("expected no throttle counts below soft threshold, got soft=%d hard=%d",
a.SoftThrottleCount(), a.HardThrottleCount())
}
// Release back down, then fill to soft zone
a.Release(710)
a.Reserve(850) // now used=850, above soft (800)
a.Reserve(10) // triggers soft throttle
if a.SoftThrottleCount() != 1 {
t.Fatalf("expected soft throttle count 1, got %d", a.SoftThrottleCount())
}
if a.HardThrottleCount() != 0 {
t.Fatalf("expected hard throttle count 0, got %d", a.HardThrottleCount())
}
// Release and fill to hard zone
a.Release(860)
a.Reserve(960) // now used=960, above hard (950)
a.Reserve(10) // triggers hard throttle
if a.HardThrottleCount() != 1 {
t.Fatalf("expected hard throttle count 1, got %d", a.HardThrottleCount())
}
}
func TestWriteBufferAccountant_GraduatedRecovery(t *testing.T) {
// Fill to hard threshold, verify hard throttle. Release to soft zone,
// verify that throttle level decreases to soft.
a := NewWriteBufferAccountant(1000)
// Fill to hard zone (960 > 950)
a.Reserve(960)
start := time.Now()
a.Reserve(10) // hard throttle
elapsed := time.Since(start)
if elapsed < hardThrottleDelay {
t.Fatalf("expected hard throttle delay, got %v", elapsed)
}
if a.HardThrottleCount() != 1 {
t.Fatalf("expected hard throttle count 1, got %d", a.HardThrottleCount())
}
// Release down to soft zone: used = 970 - 130 = 840 (> 800 soft, < 950 hard)
a.Release(130)
start = time.Now()
a.Reserve(10) // should now be soft throttle
elapsed = time.Since(start)
if elapsed < softThrottleDelay {
t.Fatalf("expected soft throttle delay after recovery, got %v", elapsed)
}
if a.HardThrottleCount() != 1 {
t.Fatalf("expected hard throttle count to remain 1 after recovery, got %d", a.HardThrottleCount())
}
if a.SoftThrottleCount() != 1 {
t.Fatalf("expected soft throttle count 1 after recovery, got %d", a.SoftThrottleCount())
}
}
func TestWriteBufferAccountant_AllowsOversizeWhenEmpty(t *testing.T) {
// A single request larger than cap must succeed when nothing is in
// flight, otherwise a single file handle with a large chunk size would
+52
View File
@@ -0,0 +1,52 @@
package mount
import (
"fmt"
"net"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// ResolvePeerAdvertiseAddr returns the host:port this mount should
// register with the filer and announce to peers. It handles three
// common cases:
//
// 1. The operator set -peer.advertise=host:port explicitly — use it.
// 2. -peer.listen contains a specific bind host — use that host with
// the bind port (e.g. "10.0.0.5:18080").
// 3. -peer.listen is a wildcard bind (":18080", "0.0.0.0:18080", or
// "[::]:18080") — combine util.DetectedHostAddress() with the port.
//
// Returns an error if the listen string is unparseable or if case (3)
// hits and auto-detection turns up nothing. We deliberately do NOT fall
// back to "localhost": an advertised loopback gets registered with the
// filer and hands other mounts a useless address to dial (their own
// loopback). Better to fail loudly so the operator sets -peer.advertise.
func ResolvePeerAdvertiseAddr(listen, advertise string) (string, error) {
if advertise != "" {
return advertise, nil
}
if listen == "" {
return "", fmt.Errorf("peer listen address is empty")
}
host, port, err := net.SplitHostPort(listen)
if err != nil {
return "", fmt.Errorf("parse -peer.listen %q: %w", listen, err)
}
if !isWildcardHost(host) {
return net.JoinHostPort(host, port), nil
}
detected := util.DetectedHostAddress()
if detected == "" {
return "", fmt.Errorf("cannot auto-detect host for wildcard -peer.listen %q; set -peer.advertise=host:port explicitly", listen)
}
return net.JoinHostPort(detected, port), nil
}
func isWildcardHost(h string) bool {
switch h {
case "", "0.0.0.0", "::", "[::]":
return true
}
return false
}
+55
View File
@@ -0,0 +1,55 @@
package mount
import (
"strings"
"testing"
)
func TestResolvePeerAdvertiseAddr(t *testing.T) {
tests := []struct {
name string
listen string
advertise string
wantErr bool
// addr substring check — DetectedHostAddress is system-dependent so
// we don't assert an exact value for the wildcard path.
wantSuffix string
}{
{"explicit advertise wins", ":18080", "10.1.1.9:20000", false, ":20000"},
{"bind host used verbatim", "10.0.0.5:18080", "", false, "10.0.0.5:18080"},
{"wildcard ipv4 bind", "0.0.0.0:18080", "", false, ":18080"},
{"empty host bind", ":18080", "", false, ":18080"},
{"ipv6 wildcard", "[::]:18080", "", false, ":18080"},
{"unparseable listen errors", "garbage", "", true, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ResolvePeerAdvertiseAddr(tt.listen, tt.advertise)
if tt.wantErr {
if err == nil {
t.Fatalf("expected error, got addr=%q", got)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.HasSuffix(got, tt.wantSuffix) {
t.Errorf("addr=%q, expected suffix %q", got, tt.wantSuffix)
}
})
}
}
func TestIsWildcardHost(t *testing.T) {
for _, h := range []string{"", "0.0.0.0", "::", "[::]"} {
if !isWildcardHost(h) {
t.Errorf("%q should be wildcard", h)
}
}
for _, h := range []string{"10.0.0.5", "host.example", "localhost"} {
if isWildcardHost(h) {
t.Errorf("%q should NOT be wildcard", h)
}
}
}
+374
View File
@@ -0,0 +1,374 @@
package mount
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
)
// PeerAnnouncer batches and flushes ChunkAnnounce RPCs to the
// HRW-assigned owner mounts for each cached fid this mount holds.
//
// Shape:
// * EnqueueAnnounce(fid) is a non-blocking push into an in-memory set.
// * A background ticker flushes every announceInterval. Each flush
// drains the set, adds fids due for TTL renewal, groups by owner
// mount via HRW, and sends one ChunkAnnounce RPC per distinct owner.
// * A successful send records announced_at[fid]. A rejected (not-owner)
// fid is requeued so it will be retried after the seed view refreshes.
//
// See design-weed-mount-peer-chunk-sharing.md §4.4.
type PeerAnnouncer struct {
selfAddr string
selfDataCenter string
selfRack string
ownerFor func(fid string) string
dialPeer MountPeerDialer
localDir *PeerDirectory // populated directly for fids whose HRW owner == self
isCached func(fid string) bool // residency check; set nil to disable
announceInterval time.Duration
announceTTL time.Duration
mu sync.Mutex
pending map[string]struct{}
announcedAt map[string]announceRecord
stopCh chan struct{}
stopped atomic.Bool
runWg sync.WaitGroup // tracks the run goroutine so Stop can wait
// flushCancelMu guards flushCancel, which is the cancel fn for the
// currently in-flight flush (nil when idle). Stop takes the lock,
// cancels the flush to unblock its RPCs fast, then waits on runWg.
flushCancelMu sync.Mutex
flushCancel context.CancelFunc
flushes atomic.Int64
sentFids atomic.Int64
rejectedFids atomic.Int64
flushErrs atomic.Int64
clock func() time.Time
}
// MountPeerDialer opens a MountPeer gRPC client to a given peer. Tests
// inject a fake; production uses a real gRPC dial backed by a short
// connection cache.
type MountPeerDialer func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error)
// announceRecord is what we remember about a successful announce: who
// we told (the HRW owner at the time) and when. On each flush we
// recompute the HRW owner and, if it moved — typically because a new
// mount joined the seed list and the ring rebalanced — re-announce
// against the new owner. Without this, seed-view divergence during
// startup silently ages out fids on an owner that the reader never
// looks up.
type announceRecord struct {
owner string
at time.Time
}
// NewPeerAnnouncer constructs an announcer. Caller must call Start.
// selfDataCenter and selfRack are the locality labels attached to every
// ChunkAnnounce so the receiving directory records holders with DC+rack
// and the fetcher can later re-rank by locality.
//
// localDir is optional: when non-nil, any fid whose HRW owner resolves
// to self is written directly into localDir instead of sending a
// self→self RPC (which the receiver would reject anyway). This is the
// only way a fid the writer itself owns becomes visible to peers'
// ChunkLookup calls.
func NewPeerAnnouncer(selfAddr, selfDataCenter, selfRack string, ownerFor func(fid string) string, dial MountPeerDialer, localDir *PeerDirectory) *PeerAnnouncer {
return &PeerAnnouncer{
selfAddr: selfAddr,
selfDataCenter: selfDataCenter,
selfRack: selfRack,
ownerFor: ownerFor,
dialPeer: dial,
localDir: localDir,
announceInterval: 15 * time.Second,
announceTTL: 300 * time.Second,
pending: map[string]struct{}{},
announcedAt: map[string]announceRecord{},
stopCh: make(chan struct{}),
clock: time.Now,
}
}
// EnqueueAnnounce marks a fid as needing announcement. Non-blocking;
// dedupes within a flush window.
func (a *PeerAnnouncer) EnqueueAnnounce(fid string) {
a.mu.Lock()
a.pending[fid] = struct{}{}
a.mu.Unlock()
}
// SetCachePresence wires an optional residency check. When set, the
// announcer consults it right before dispatching a ChunkAnnounce RPC or
// writing a self-owned entry: if the cache no longer has the chunk
// (e.g. LRU-evicted under memory pressure between SetChunk and the
// next flush tick) we drop the announce rather than advertise bytes we
// can't serve back. nil disables the check.
func (a *PeerAnnouncer) SetCachePresence(isCached func(fid string) bool) {
a.mu.Lock()
defer a.mu.Unlock()
a.isCached = isCached
}
// Start launches the background flush loop.
func (a *PeerAnnouncer) Start() {
a.runWg.Add(1)
go func() {
defer a.runWg.Done()
a.run()
}()
}
// Stop halts the flush loop and waits for the current flush (if any) to
// finish. Safe to call multiple times. Callers that tear down shared
// dependencies (conn pool, local directory) can rely on no more
// sendTo/localDir.Announce goroutines being live after Stop returns.
func (a *PeerAnnouncer) Stop() {
if a.stopped.Swap(true) {
return
}
close(a.stopCh)
// Cancel the in-flight flush's context so its RPCs return quickly
// instead of running out the 10 s timeout.
a.flushCancelMu.Lock()
if a.flushCancel != nil {
a.flushCancel()
}
a.flushCancelMu.Unlock()
a.runWg.Wait()
}
// Stats exposes counters for observability.
func (a *PeerAnnouncer) Stats() (flushes, sentFids, rejectedFids, flushErrs int64) {
return a.flushes.Load(), a.sentFids.Load(), a.rejectedFids.Load(), a.flushErrs.Load()
}
// announceFlushTimeout caps how long a single flush cycle can run. A slow
// or unresponsive owner peer would otherwise block a flush goroutine
// indefinitely, and since flushes fan out per owner in parallel a
// pileup would bleed into subsequent ticks and grow unbounded. The
// bound is set a bit under one flush interval so the next tick's flush
// doesn't chase the previous one's tail.
const announceFlushTimeout = 10 * time.Second
func (a *PeerAnnouncer) run() {
t := time.NewTicker(a.announceInterval)
defer t.Stop()
for {
select {
case <-a.stopCh:
return
case <-t.C:
ctx, cancel := context.WithTimeout(context.Background(), announceFlushTimeout)
a.flushCancelMu.Lock()
a.flushCancel = cancel
a.flushCancelMu.Unlock()
a.flushOnce(ctx)
a.flushCancelMu.Lock()
a.flushCancel = nil
a.flushCancelMu.Unlock()
cancel()
}
}
}
// flushOnce is exported via a wrapper for tests.
func (a *PeerAnnouncer) FlushForTest(ctx context.Context) {
a.flushOnce(ctx)
}
func (a *PeerAnnouncer) flushOnce(ctx context.Context) {
a.flushes.Add(1)
now := a.clock()
a.mu.Lock()
// Swap pending in O(1) instead of copying.
toAnnounce := a.pending
a.pending = map[string]struct{}{}
// Add renewals: (1) fids we announced long enough ago that they'll
// expire on the owner side before our next flush tick; (2) fids
// whose HRW owner has changed since we last announced them —
// usually because a new mount joined the seed list and the ring
// rebalanced. Also prune announcedAt entries that are so old
// (> 2× TTL) that re-announcing them would be pointless.
renewThreshold := now.Add(-a.announceTTL + 2*a.announceInterval)
staleCutoff := now.Add(-2 * a.announceTTL)
for fid, rec := range a.announcedAt {
switch {
case rec.at.Before(staleCutoff):
delete(a.announcedAt, fid)
case rec.at.Before(renewThreshold):
toAnnounce[fid] = struct{}{}
default:
// Same fid, fresh timestamp — but owner may have moved.
// Force a re-announce if HRW says a different mount is
// the owner now.
if a.ownerFor != nil {
if cur := a.ownerFor(fid); cur != "" && cur != rec.owner {
toAnnounce[fid] = struct{}{}
}
}
}
}
a.mu.Unlock()
if len(toAnnounce) == 0 {
return
}
// Drop fids the cache no longer has. The write path hooks into
// SetChunk + EnqueueAnnounce, but the chunk can be LRU-evicted in
// the window between that and the next 15 s flush. Advertising a
// chunk we can't actually serve just sends remote fetchers to our
// FetchChunk, which then returns NOT_FOUND — a wasted round trip.
// Also drop the announcedAt record so we don't keep renewing
// evicted fids forever.
a.mu.Lock()
present := a.isCached
a.mu.Unlock()
if present != nil {
for fid := range toAnnounce {
if !present(fid) {
delete(toAnnounce, fid)
a.mu.Lock()
delete(a.announcedAt, fid)
a.mu.Unlock()
}
}
if len(toAnnounce) == 0 {
return
}
}
// Classify each fid. Three buckets:
// byOwner — HRW owner is a remote mount; send a ChunkAnnounce RPC.
// selfOwned — HRW owner is us; write directly into our local
// directory (no RPC — we ARE the directory for this
// fid). Without this, fids we wrote AND HRW-own stay
// invisible to peer ChunkLookup forever.
// deferred — HRW owner unknown (empty seed view). Re-queue for
// the next flush once listOnce has populated seeds.
byOwner := map[string][]string{}
var selfOwned []string
var deferred []string
for fid := range toAnnounce {
owner := ""
if a.ownerFor != nil {
owner = a.ownerFor(fid)
}
switch owner {
case "":
deferred = append(deferred, fid)
case a.selfAddr:
selfOwned = append(selfOwned, fid)
default:
byOwner[owner] = append(byOwner[owner], fid)
}
}
if len(selfOwned) > 0 && a.localDir != nil {
a.localDir.Announce(a.selfAddr, a.selfDataCenter, a.selfRack, selfOwned, a.announceTTL, nil)
a.mu.Lock()
for _, fid := range selfOwned {
a.announcedAt[fid] = announceRecord{owner: a.selfAddr, at: now}
a.sentFids.Add(1)
}
a.mu.Unlock()
} else if len(selfOwned) > 0 {
// No local directory wired (e.g. unit tests with nil). Re-queue
// so a future flush with a possibly-different HRW owner can
// send them.
deferred = append(deferred, selfOwned...)
}
if len(deferred) > 0 {
a.mu.Lock()
for _, fid := range deferred {
a.pending[fid] = struct{}{}
}
a.mu.Unlock()
}
// Diagnostic V(2): shape of the current flush. Helps post-mortem
// debugging when an announce pipeline silently stops making progress
// (e.g. seed view stuck at self-only, owner unreachable, etc).
if len(byOwner) > 0 || len(selfOwned) > 0 || len(deferred) > 0 {
glog.V(2).Infof("peer-announce flush: toAnnounce=%d byOwner=%d selfOwned=%d deferred=%d",
len(toAnnounce), len(byOwner), len(selfOwned), len(deferred))
}
// Fan out one RPC per owner in parallel. A slow or unreachable
// owner blocks only its own goroutine; other owners' announces
// proceed immediately.
var wg sync.WaitGroup
for owner, fids := range byOwner {
wg.Add(1)
go func(owner string, fids []string) {
defer wg.Done()
a.sendTo(ctx, owner, fids, now)
}(owner, fids)
}
wg.Wait()
}
func (a *PeerAnnouncer) sendTo(ctx context.Context, owner string, fids []string, now time.Time) {
client, closeFn, err := a.dialPeer(ctx, owner)
if err != nil {
a.flushErrs.Add(1)
// Requeue these fids: a future flush will retry.
a.requeue(fids)
glog.V(2).Infof("peer-announce dial %s: %v", owner, err)
return
}
defer closeFn()
resp, err := client.ChunkAnnounce(ctx, &mount_peer_pb.ChunkAnnounceRequest{
FileIds: fids,
PeerAddr: a.selfAddr,
DataCenter: a.selfDataCenter,
Rack: a.selfRack,
TtlSeconds: int32(a.announceTTL / time.Second),
})
if err != nil {
a.flushErrs.Add(1)
a.requeue(fids)
glog.V(2).Infof("peer-announce %s: %v", owner, err)
return
}
rejected := map[string]struct{}{}
for _, f := range resp.RejectedFileIds {
rejected[f] = struct{}{}
}
a.mu.Lock()
for _, fid := range fids {
if _, skip := rejected[fid]; skip {
// Owner has changed or doesn't yet agree; retry later.
a.pending[fid] = struct{}{}
a.rejectedFids.Add(1)
continue
}
a.announcedAt[fid] = announceRecord{owner: owner, at: now}
a.sentFids.Add(1)
}
a.mu.Unlock()
}
func (a *PeerAnnouncer) requeue(fids []string) {
a.mu.Lock()
for _, fid := range fids {
a.pending[fid] = struct{}{}
}
a.mu.Unlock()
}
+374
View File
@@ -0,0 +1,374 @@
package mount
import (
"context"
"sort"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
"google.golang.org/grpc"
)
// fakeMountPeerClient records each ChunkAnnounce call; returns rejected
// fids from a configured set.
type fakeMountPeerClient struct {
mu sync.Mutex
mount_peer_pb.MountPeerClient
announcedBy map[string][]filerAnnouncement
rejectedByClient func(fid string) bool
}
type filerAnnouncement struct {
fids []string
peerAddr string
}
func (f *fakeMountPeerClient) ChunkAnnounce(ctx context.Context, req *mount_peer_pb.ChunkAnnounceRequest, opts ...grpc.CallOption) (*mount_peer_pb.ChunkAnnounceResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
// No owner key in the request; capture keyed by peer_addr (the announcer).
f.announcedBy[req.PeerAddr] = append(f.announcedBy[req.PeerAddr], filerAnnouncement{
fids: append([]string(nil), req.FileIds...),
peerAddr: req.PeerAddr,
})
resp := &mount_peer_pb.ChunkAnnounceResponse{}
if f.rejectedByClient != nil {
for _, fid := range req.FileIds {
if f.rejectedByClient(fid) {
resp.RejectedFileIds = append(resp.RejectedFileIds, fid)
}
}
}
return resp, nil
}
// fakeDialer returns the same fakeMountPeerClient for every peer addr,
// recording which owner the announcer dialed. Close is a no-op. The
// dialed slice is protected by its own mutex because the announcer now
// fans RPCs out across goroutines — concurrent appends would race.
type dialRecorder struct {
mu sync.Mutex
dialled []string
}
func (d *dialRecorder) record(addr string) {
d.mu.Lock()
d.dialled = append(d.dialled, addr)
d.mu.Unlock()
}
func (d *dialRecorder) snapshot() []string {
d.mu.Lock()
defer d.mu.Unlock()
out := make([]string, len(d.dialled))
copy(out, d.dialled)
return out
}
func fakeDialer(fc *fakeMountPeerClient, rec *dialRecorder) MountPeerDialer {
return func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
rec.record(peerAddr)
return fc, func() {}, nil
}
}
func TestPeerAnnouncer_FlushGroupsByOwner(t *testing.T) {
fc := &fakeMountPeerClient{
announcedBy: map[string][]filerAnnouncement{},
}
rec := &dialRecorder{}
// Owner function: static assignment for test.
ownerFor := func(fid string) string {
if fid == "3,a" || fid == "3,c" {
return "owner-1:18081"
}
return "owner-2:18081"
}
a := NewPeerAnnouncer("self:18080", "", "",ownerFor, fakeDialer(fc, rec), nil)
a.EnqueueAnnounce("3,a")
a.EnqueueAnnounce("3,b")
a.EnqueueAnnounce("3,c")
a.FlushForTest(context.Background())
dialed := rec.snapshot(); sort.Strings(dialed)
if len(dialed) != 2 || dialed[0] != "owner-1:18081" || dialed[1] != "owner-2:18081" {
t.Errorf("expected both owners dialed once, got %v", dialed)
}
_, sent, _, _ := a.Stats()
if sent != 3 {
t.Errorf("expected 3 sent fids, got %d", sent)
}
}
func TestPeerAnnouncer_SkipOwnerEqualsSelf(t *testing.T) {
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
rec := &dialRecorder{}
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
return "self:18080"
}, fakeDialer(fc, rec), nil)
a.EnqueueAnnounce("3,a")
a.FlushForTest(context.Background())
if d := rec.snapshot(); len(d) != 0 {
t.Errorf("expected no dial when owner == self, dialed: %v", d)
}
// Self-owned fids stay in pending so a subsequent flush re-checks
// them against a possibly-refreshed seed view. Without this retry a
// mount whose initial MountList hadn't yet observed its peers would
// silently drop every write-path announce on the floor.
a.mu.Lock()
_, stillPending := a.pending["3,a"]
a.mu.Unlock()
if !stillPending {
t.Errorf("self-owned fid should stay pending for retry")
}
}
func TestPeerAnnouncer_RequeueOnRejection(t *testing.T) {
fc := &fakeMountPeerClient{
announcedBy: map[string][]filerAnnouncement{},
rejectedByClient: func(fid string) bool { return fid == "3,x" },
}
rec := &dialRecorder{}
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
return "owner:18081"
}, fakeDialer(fc, rec), nil)
a.EnqueueAnnounce("3,x")
a.EnqueueAnnounce("3,y")
a.FlushForTest(context.Background())
_, sent, rejected, _ := a.Stats()
if sent != 1 {
t.Errorf("expected 1 sent, got %d", sent)
}
if rejected != 1 {
t.Errorf("expected 1 rejected, got %d", rejected)
}
// The rejected fid should be back in pending.
a.mu.Lock()
_, stillPending := a.pending["3,x"]
a.mu.Unlock()
if !stillPending {
t.Errorf("3,x should have been requeued after rejection")
}
}
func TestPeerAnnouncer_TTLRenewal(t *testing.T) {
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
rec := &dialRecorder{}
now := time.Unix(1000, 0)
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
return "owner:18081"
}, fakeDialer(fc, rec), nil)
a.clock = func() time.Time { return now }
a.announceInterval = 10 * time.Second
a.announceTTL = 60 * time.Second
// Announce once.
a.EnqueueAnnounce("3,a")
a.FlushForTest(context.Background())
if _, sent, _, _ := a.Stats(); sent != 1 {
t.Fatalf("want 1 sent on initial announce, got %d", sent)
}
// Time passes to within the renewal threshold.
now = now.Add(45 * time.Second)
// No new enqueue, but renewal should fire.
a.FlushForTest(context.Background())
if _, sent, _, _ := a.Stats(); sent != 2 {
t.Errorf("want 2 sent after renewal, got %d", sent)
}
}
// TestPeerAnnouncer_ReAnnouncesOnOwnerChange guards the fix for a
// startup race where the writer's seed view reaches self-knowledge of
// its peers in two stages: first just {self,A}, then {self,A,B}. HRW
// may pick different owners across those views, so the announce from
// stage 1 is sent to a mount that will NOT be the HRW owner by the
// time a reader's seed view is the {self,A,B} version. Without
// re-announcing on owner change, the fid silently ages out on the
// wrong directory and readers get "no peer holder."
func TestPeerAnnouncer_ReAnnouncesOnOwnerChange(t *testing.T) {
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
rec := &dialRecorder{}
ownerNow := "owner-1:18081"
a := NewPeerAnnouncer("self:18080", "", "", func(fid string) string {
return ownerNow
}, fakeDialer(fc, rec), nil)
a.EnqueueAnnounce("3,x")
a.FlushForTest(context.Background())
if _, sent, _, _ := a.Stats(); sent != 1 {
t.Fatalf("initial announce: want 1 sent, got %d", sent)
}
// Seed view shifts; HRW now picks a different owner for the same
// fid. A fresh-timestamped entry in announcedAt should be treated
// as stale in owner terms and re-announced even though its age is
// well within the TTL renewal window.
ownerNow = "owner-2:18081"
a.FlushForTest(context.Background())
if _, sent, _, _ := a.Stats(); sent != 2 {
t.Errorf("after owner change: want 2 sent, got %d", sent)
}
dialed := rec.snapshot()
if len(dialed) != 2 || dialed[0] == dialed[1] {
t.Errorf("want dial to both owners, got %v", dialed)
}
}
// TestPeerAnnouncer_DropsEvictedFids guards the write→announce race:
// a chunk can be LRU-evicted between SetChunk and the next flush tick.
// Advertising an evicted fid just hands remote fetchers a NOT_FOUND
// from our FetchChunk server. With SetCachePresence wired, the
// announcer must drop evicted fids before dispatching the RPC and
// also clear them from announcedAt so they stop getting renewed.
func TestPeerAnnouncer_DropsEvictedFids(t *testing.T) {
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
rec := &dialRecorder{}
present := map[string]bool{"3,here": true, "3,gone": false}
a := NewPeerAnnouncer("self:18080", "", "", func(fid string) string {
return "owner:18081"
}, fakeDialer(fc, rec), nil)
a.SetCachePresence(func(fid string) bool { return present[fid] })
a.EnqueueAnnounce("3,here")
a.EnqueueAnnounce("3,gone")
a.FlushForTest(context.Background())
if _, sent, _, _ := a.Stats(); sent != 1 {
t.Errorf("only the still-cached fid should be announced, got sent=%d", sent)
}
fc.mu.Lock()
defer fc.mu.Unlock()
for _, an := range fc.announcedBy["self:18080"] {
for _, fid := range an.fids {
if fid == "3,gone" {
t.Errorf("evicted fid should not have been announced, saw %q", fid)
}
}
}
}
// TestPeerAnnouncer_StopWaitsForFlush guards the shutdown race: Stop
// must not return while a tick-triggered flushOnce is still dispatching
// RPCs, otherwise the owning wfs can tear down the conn pool out from
// under the in-flight sendTo goroutines.
func TestPeerAnnouncer_StopWaitsForFlush(t *testing.T) {
started := make(chan struct{})
unblock := make(chan struct{})
slowDialer := func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
close(started)
select {
case <-unblock:
case <-ctx.Done():
}
return nil, func() {}, context.DeadlineExceeded
}
a := NewPeerAnnouncer("self:18080", "", "", func(string) string {
return "owner:18081"
}, slowDialer, nil)
// Shortcut straight into a flush on a dedicated goroutine so we
// can assert Stop() blocks on it.
a.EnqueueAnnounce("3,slow")
flushDone := make(chan struct{})
go func() {
a.FlushForTest(context.Background())
close(flushDone)
}()
<-started
// Prove Stop() returns only after the flush finishes by racing
// them: Stop() normally can't cancel a FlushForTest because
// we're not going through run(); but unblocking after stop's
// goroutine starts lets us confirm flushDone happens before
// stopDone never does under the old code.
stopDone := make(chan struct{})
go func() {
a.Stop()
close(stopDone)
}()
close(unblock)
select {
case <-flushDone:
case <-time.After(3 * time.Second):
t.Fatalf("flush did not complete within deadline")
}
select {
case <-stopDone:
case <-time.After(3 * time.Second):
t.Fatalf("Stop() did not return after flush completed")
}
}
// TestPeerAnnouncer_SelfOwnedWritesToLocalDir guards the shortcut path
// for fids whose HRW owner resolves to self: no RPC should go out, but
// the local PeerDirectory must end up with a holder entry pointing at
// self — otherwise remote ChunkLookup callers would get an empty
// holder list for fids this mount owns directly.
func TestPeerAnnouncer_SelfOwnedWritesToLocalDir(t *testing.T) {
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
rec := &dialRecorder{}
dir := NewPeerDirectory()
a := NewPeerAnnouncer("self:18080", "dc1", "rackA", func(fid string) string {
return "self:18080"
}, fakeDialer(fc, rec), dir)
a.EnqueueAnnounce("3,selfowned")
a.FlushForTest(context.Background())
if d := rec.snapshot(); len(d) != 0 {
t.Errorf("self-owned fid must not trigger any dial, got %v", d)
}
holders := dir.Lookup([]string{"3,selfowned"}, nil).PeersByFid["3,selfowned"]
if len(holders) != 1 {
t.Fatalf("local dir should have 1 holder after self-owned flush, got %d", len(holders))
}
if h := holders[0]; h.PeerAddr != "self:18080" || h.DataCenter != "dc1" || h.Rack != "rackA" {
t.Errorf("local dir entry wrong: %+v", h)
}
if _, sent, _, _ := a.Stats(); sent != 1 {
t.Errorf("sent counter should increment for self-owned too; got %d", sent)
}
}
func TestPeerAnnouncer_DialerErrorRequeues(t *testing.T) {
errDialer := func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
return nil, func() {}, context.DeadlineExceeded
}
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
return "owner:18081"
}, errDialer, nil)
a.EnqueueAnnounce("3,a")
a.FlushForTest(context.Background())
_, _, _, errs := a.Stats()
if errs != 1 {
t.Errorf("expected 1 flush error, got %d", errs)
}
a.mu.Lock()
_, pending := a.pending["3,a"]
a.mu.Unlock()
if !pending {
t.Errorf("fid should be requeued after dial error")
}
}
+137
View File
@@ -0,0 +1,137 @@
package mount
import (
"context"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
)
// PeerConnPool caches one long-lived gRPC client connection per peer
// address. Both the announcer flush loop and the read-path fetcher hit
// the same handful of directory owners repeatedly; without a cache each
// call would pay TCP handshake + HTTP/2 preface cost (and on TLS, an
// additional handshake). The cache makes steady-state owner RPCs
// effectively free after the first call.
//
// Connections in terminal failure states (Shutdown) are transparently
// replaced on next access. Sizing: entries are ~1 KB + the conn itself;
// bounded at maxPeerConnPoolEntries to contain runaway growth.
type PeerConnPool struct {
dialOpts []grpc.DialOption
mu sync.Mutex
conns map[string]*grpc.ClientConn
}
// maxPeerConnPoolEntries caps live peer conns per mount. A 10k-mount
// fleet with HRW-sharded directory reaches only ~200 distinct owner
// addresses per mount in the worst case, so this is far above any real
// footprint while still bounding pathological growth.
const maxPeerConnPoolEntries = 4096
// NewPeerConnPool returns an empty pool. dialOpts should carry transport
// credentials matching the server side (production wires
// option.GrpcDialOption, which security.LoadClientTLS populates from
// security.toml). When no options are supplied we fall back to insecure
// cleartext — only safe for in-process tests.
func NewPeerConnPool(dialOpts ...grpc.DialOption) *PeerConnPool {
if len(dialOpts) == 0 {
dialOpts = []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
}
return &PeerConnPool{
dialOpts: dialOpts,
conns: map[string]*grpc.ClientConn{},
}
}
// Dialer returns a MountPeerDialer bound to this pool. The returned
// closeFn is a no-op — the pool owns the connection lifecycle. Tests
// that want per-call dials can keep using the non-pooled variant.
func (p *PeerConnPool) Dialer() MountPeerDialer {
return func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
conn, err := p.get(peerAddr)
if err != nil {
return nil, func() {}, err
}
return mount_peer_pb.NewMountPeerClient(conn), func() {}, nil
}
}
func (p *PeerConnPool) get(peerAddr string) (*grpc.ClientConn, error) {
p.mu.Lock()
defer p.mu.Unlock()
if conn, ok := p.conns[peerAddr]; ok {
if conn.GetState() != connectivity.Shutdown {
return conn, nil
}
// Pooled conn is unusable — drop it and redial below.
_ = conn.Close()
delete(p.conns, peerAddr)
}
if len(p.conns) >= maxPeerConnPoolEntries {
// Evict one arbitrary entry. Simple over LRU: the pool is small
// in practice, and the victim will be re-dialed if needed.
for k, c := range p.conns {
_ = c.Close()
delete(p.conns, k)
break
}
}
conn, err := grpc.NewClient(peerAddr, p.dialOpts...)
if err != nil {
return nil, err
}
p.conns[peerAddr] = conn
return conn, nil
}
// Close tears down every cached connection. Safe to call multiple times.
func (p *PeerConnPool) Close() {
p.mu.Lock()
defer p.mu.Unlock()
for addr, c := range p.conns {
_ = c.Close()
delete(p.conns, addr)
}
}
// Size returns the current number of cached connections — useful for
// tests and metrics exports.
func (p *PeerConnPool) Size() int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.conns)
}
// DefaultMountPeerDialer returns a per-call dialer (no pooling). Kept for
// tests and for any caller that genuinely wants a fresh connection per
// invocation. Production code should prefer PeerConnPool.Dialer().
//
// Unused options silence dial-time lints when dialOpts is nil.
func DefaultMountPeerDialer(dialOpts ...grpc.DialOption) MountPeerDialer {
opts := append([]grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}, dialOpts...)
return func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
conn, err := grpc.NewClient(peerAddr, opts...)
if err != nil {
return nil, func() {}, err
}
return mount_peer_pb.NewMountPeerClient(conn), func() { _ = conn.Close() }, nil
}
}
// peerConnMaxAge lets external callers (or future metrics) decide when a
// pool entry is "stale" for monitoring purposes. The pool itself does not
// expire on age — grpc handles reconnect internally.
var peerConnMaxAge = 10 * time.Minute
var _ = peerConnMaxAge // suppress unused-lint until a metric consumes it
+283
View File
@@ -0,0 +1,283 @@
package mount
import (
"sort"
"sync"
"sync/atomic"
"time"
)
// maxPeerDirectoryEntries caps the total (fid, holder) edges a single mount
// will hold in its shard of the chunk directory. Each edge is a
// (uint32, time.Time) map entry (~40 B with Go's map overhead), plus the
// per-peer metadata is interned — see peerMetadata below — so 500k edges
// come out to roughly 20 MB regardless of fleet size. A full directory
// rejects new announces until TTL frees room.
const maxPeerDirectoryEntries = 500000
// peerID is the interned identifier for a peer. Peer addresses and locality
// labels live once in the peers slice; the (fid -> holder) index references
// peers by this fixed-size id so we avoid paying for the ~48 B worth of
// string headers (addr, dc, rack) on every edge.
type peerID uint32
// peerMetadata is the per-peer data that used to be inlined on every
// holderEntry. Fields are updated in place on each announce so a peer
// reconfiguring its dc/rack is picked up without churn.
type peerMetadata struct {
addr string
dataCenter string
rack string
}
// PeerDirectory is the tier-2 chunk directory: an in-memory
// `fid -> set<peer>` map, holding entries only for fids for which this
// mount is the HRW-assigned owner. Populated by inbound ChunkAnnounce RPCs,
// queried by inbound ChunkLookup RPCs. Entries expire on TTL.
//
// Peer addresses are interned into peerID. That way the hot index stores
// `fid -> (peerID -> expiry)`, a map of two fixed-size values, instead of
// a full (addr, dc, rack, expiry) struct per edge. The peer slice itself
// is bounded by fleet size (typically a few hundred), so the interning
// table's memory cost is negligible next to the per-edge savings.
//
// Lookup takes only a read lock; TTL eviction is the sole responsibility of
// the Sweep goroutine, which runs on a periodic ticker. This keeps the hot
// read path concurrent even under heavy announce traffic.
//
// See design-weed-mount-peer-chunk-sharing.md §4.2.2.
type PeerDirectory struct {
mu sync.RWMutex
// Interning table. peers[id] gives the peer's metadata; peerIDByAddr
// maps an address back to its id when a new announce comes in.
peers []peerMetadata
peerIDByAddr map[string]peerID
// fid -> (peerID -> expiry). The inner map's value is a bare timestamp
// — metadata is looked up via peers[id] on demand.
index map[string]map[peerID]time.Time
// entryCount is maintained in lock-step with map mutations (under
// mu), so Stats() can report O(1) instead of scanning the index.
entryCount int
announces atomic.Int64
lookups atomic.Int64
rejected atomic.Int64
evictions atomic.Int64
clock func() time.Time
}
// NewPeerDirectory constructs a directory using the real wall clock.
func NewPeerDirectory() *PeerDirectory {
return newPeerDirectoryWithClock(time.Now)
}
func newPeerDirectoryWithClock(clock func() time.Time) *PeerDirectory {
return &PeerDirectory{
index: map[string]map[peerID]time.Time{},
peerIDByAddr: map[string]peerID{},
clock: clock,
}
}
// AnnounceResult reports how an inbound announce was handled per-fid: fids
// this receiver owns were recorded; others were rejected so the caller can
// retry the correct owner after refreshing its seed view.
type AnnounceResult struct {
Rejected []string
}
// OwnerCheck is a predicate provided by the caller (backed by HRW on the
// current seed list) that says whether self is the owner for a given fid.
type OwnerCheck func(fid string) bool
// internPeer returns the interned id for peerAddr, allocating a new slot
// if this is the first announce from that peer. Must be called under mu
// (write). dc/rack are refreshed on each call so reconfig is picked up.
func (d *PeerDirectory) internPeer(addr, dc, rack string) peerID {
if id, ok := d.peerIDByAddr[addr]; ok {
p := &d.peers[id]
p.dataCenter = dc
p.rack = rack
return id
}
id := peerID(len(d.peers))
d.peers = append(d.peers, peerMetadata{addr: addr, dataCenter: dc, rack: rack})
d.peerIDByAddr[addr] = id
return id
}
// Announce records the caller as a holder for every accepted fid. Any fid
// for which ownerCheck returns false is rejected and surfaced back. A
// directory at maxPeerDirectoryEntries silently drops *new* edges
// (renewals of existing edges continue to succeed).
func (d *PeerDirectory) Announce(peerAddr, dataCenter, rack string, fids []string, ttl time.Duration, ownerCheck OwnerCheck) AnnounceResult {
if ttl <= 0 {
ttl = 60 * time.Second
}
expiry := d.clock().Add(ttl)
d.mu.Lock()
defer d.mu.Unlock()
pid := d.internPeer(peerAddr, dataCenter, rack)
result := AnnounceResult{}
for _, fid := range fids {
if ownerCheck != nil && !ownerCheck(fid) {
result.Rejected = append(result.Rejected, fid)
d.rejected.Add(1)
continue
}
holders, ok := d.index[fid]
if !ok {
if d.entryCount >= maxPeerDirectoryEntries {
continue
}
holders = map[peerID]time.Time{}
d.index[fid] = holders
}
if _, exists := holders[pid]; !exists {
if d.entryCount >= maxPeerDirectoryEntries {
continue
}
d.entryCount++
}
holders[pid] = expiry
d.announces.Add(1)
}
return result
}
// LookupHolder is the public form of a holder entry. DataCenter and Rack
// are carried through so the fetcher can re-sort by its own locality
// before picking a peer to dial.
type LookupHolder struct {
PeerAddr string
DataCenter string
Rack string
}
// maxLookupHolders caps how many holders a single ChunkLookup response
// returns per fid. The directory stores a holder per mount caching the
// fid, which on a large hot file can reach fleet size (hundreds). The
// fetcher typically only tries the first 1-3 before succeeding, so
// returning every entry is pure wire-overhead. LRU ordering ensures the
// freshest holders are the ones kept.
const maxLookupHolders = 16
// LookupResult holds the merged lookup response. Fids for which this
// receiver is not the owner are split out so the caller can retry.
type LookupResult struct {
PeersByFid map[string][]LookupHolder
NotOwnerFids []string
}
// Lookup returns known holders for the requested fids. Expired edges are
// filtered out of the response but NOT deleted here — Sweep handles that
// under a write lock on its own schedule, so Lookup can stay read-only and
// concurrent. A fid owned by this receiver with no known holders returns
// an empty peer list.
//
// Holders are returned in LRU order (most recently announced first). Since
// each Announce stamps a fresh `now + ttl` expiry, sorting by expiry
// descending is equivalent to ordering by last-seen descending. Fetchers
// should try these in the returned order — the most recent announcer is
// the holder most likely to still have the chunk cached, given that each
// mount's chunk_cache is itself LRU.
func (d *PeerDirectory) Lookup(fids []string, ownerCheck OwnerCheck) LookupResult {
now := d.clock()
result := LookupResult{
PeersByFid: map[string][]LookupHolder{},
}
// Collect candidate holders under the read lock, including the peer
// metadata copies — Announce mutates peers[id] in place when an
// existing peer re-announces, so reading peers[pid] outside the lock
// would race with that write. Sorting happens after the unlock.
type candidate struct {
peerMetadata
expiry time.Time
}
perFid := make(map[string][]candidate, len(fids))
d.mu.RLock()
for _, fid := range fids {
d.lookups.Add(1)
if ownerCheck != nil && !ownerCheck(fid) {
result.NotOwnerFids = append(result.NotOwnerFids, fid)
continue
}
holders, ok := d.index[fid]
if !ok {
result.PeersByFid[fid] = nil
continue
}
cands := make([]candidate, 0, len(holders))
for pid, expiry := range holders {
if !expiry.After(now) {
continue // Sweep will clean this up
}
cands = append(cands, candidate{peerMetadata: d.peers[pid], expiry: expiry})
}
perFid[fid] = cands
}
d.mu.RUnlock()
for fid, cands := range perFid {
sort.Slice(cands, func(i, j int) bool {
if !cands[i].expiry.Equal(cands[j].expiry) {
return cands[i].expiry.After(cands[j].expiry) // newest first
}
return cands[i].addr < cands[j].addr // deterministic tiebreak
})
// Cap response at maxLookupHolders. The fetcher typically tries 1-3
// holders before succeeding; shipping every holder for hot fids is
// wire-overhead without hit-rate gain.
if len(cands) > maxLookupHolders {
cands = cands[:maxLookupHolders]
}
out := make([]LookupHolder, len(cands))
for i, c := range cands {
out[i] = LookupHolder{PeerAddr: c.addr, DataCenter: c.dataCenter, Rack: c.rack}
}
result.PeersByFid[fid] = out
}
return result
}
// Sweep purges expired edges. Safe to call periodically. Peer slots are
// left in place — their count is bounded by fleet size (a few hundred at
// most) and never grows faster than the fleet itself, so reclaiming them
// isn't worth the bookkeeping.
func (d *PeerDirectory) Sweep() int {
now := d.clock()
d.mu.Lock()
defer d.mu.Unlock()
n := 0
for fid, holders := range d.index {
for pid, expiry := range holders {
if !expiry.After(now) {
delete(holders, pid)
d.entryCount--
n++
}
}
if len(holders) == 0 {
delete(d.index, fid)
}
}
d.evictions.Add(int64(n))
return n
}
// Stats exposes counters for observability. O(1) — entryCount is kept in
// lock-step with map mutations.
func (d *PeerDirectory) Stats() (announces, lookups, rejected, evictions int64, entries int) {
d.mu.RLock()
defer d.mu.RUnlock()
return d.announces.Load(), d.lookups.Load(), d.rejected.Load(), d.evictions.Load(), d.entryCount
}
+217
View File
@@ -0,0 +1,217 @@
package mount
import (
"fmt"
"sort"
"testing"
"time"
)
// alwaysOwner is a trivial OwnerCheck used by tests that aren't exercising
// ownership rejection.
func alwaysOwner(string) bool { return true }
// ownerSet returns an OwnerCheck that accepts only the listed fids.
func ownerSet(fids ...string) OwnerCheck {
m := map[string]struct{}{}
for _, f := range fids {
m[f] = struct{}{}
}
return func(fid string) bool {
_, ok := m[fid]
return ok
}
}
func TestPeerDirectory_AnnounceAndLookup(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
res := d.Announce("mount-a:18080", "", "r1", []string{"3,a", "3,b"}, 60*time.Second, alwaysOwner)
if len(res.Rejected) != 0 {
t.Errorf("expected 0 rejected, got %v", res.Rejected)
}
lookup := d.Lookup([]string{"3,a", "3,b", "3,c"}, alwaysOwner)
if got := len(lookup.PeersByFid["3,a"]); got != 1 {
t.Errorf("3,a: expected 1 holder, got %d", got)
}
if got := len(lookup.PeersByFid["3,b"]); got != 1 {
t.Errorf("3,b: expected 1 holder, got %d", got)
}
if got := len(lookup.PeersByFid["3,c"]); got != 0 {
t.Errorf("3,c (unknown): expected 0 holders, got %d", got)
}
}
func TestPeerDirectory_OwnerRejection(t *testing.T) {
d := NewPeerDirectory()
res := d.Announce("mount-a:18080", "", "", []string{"3,mine", "3,yours"}, time.Minute, ownerSet("3,mine"))
if len(res.Rejected) != 1 || res.Rejected[0] != "3,yours" {
t.Errorf("expected 3,yours rejected, got %v", res.Rejected)
}
lookup := d.Lookup([]string{"3,mine", "3,yours"}, ownerSet("3,mine"))
if got := len(lookup.PeersByFid["3,mine"]); got != 1 {
t.Errorf("3,mine should have 1 holder, got %d", got)
}
if len(lookup.NotOwnerFids) != 1 || lookup.NotOwnerFids[0] != "3,yours" {
t.Errorf("expected 3,yours in not-owner list, got %v", lookup.NotOwnerFids)
}
}
func TestPeerDirectory_MultipleHolders(t *testing.T) {
d := NewPeerDirectory()
d.Announce("mount-a:18080", "", "r1", []string{"3,x"}, time.Minute, alwaysOwner)
d.Announce("mount-b:18080", "", "r2", []string{"3,x"}, time.Minute, alwaysOwner)
holders := d.Lookup([]string{"3,x"}, alwaysOwner).PeersByFid["3,x"]
if len(holders) != 2 {
t.Fatalf("expected 2 holders, got %d", len(holders))
}
sort.Slice(holders, func(i, j int) bool { return holders[i].PeerAddr < holders[j].PeerAddr })
if holders[0].PeerAddr != "mount-a:18080" || holders[1].PeerAddr != "mount-b:18080" {
t.Errorf("unexpected holder addrs: %+v", holders)
}
}
func TestPeerDirectory_RenewExtendsExpiry(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 30*time.Second, alwaysOwner)
now = now.Add(25 * time.Second)
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 30*time.Second, alwaysOwner)
now = now.Add(10 * time.Second)
lookup := d.Lookup([]string{"3,a"}, alwaysOwner)
if len(lookup.PeersByFid["3,a"]) != 1 {
t.Errorf("renew should keep entry alive, got %d holders", len(lookup.PeersByFid["3,a"]))
}
}
func TestPeerDirectory_TTLExpiry(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 10*time.Second, alwaysOwner)
now = now.Add(15 * time.Second)
holders := d.Lookup([]string{"3,a"}, alwaysOwner).PeersByFid["3,a"]
if len(holders) != 0 {
t.Errorf("expected TTL-expired holder to be gone, got %+v", holders)
}
}
func TestPeerDirectory_Sweep(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 10*time.Second, alwaysOwner)
d.Announce("mount-b:18080", "", "", []string{"3,b"}, 60*time.Second, alwaysOwner)
now = now.Add(30 * time.Second)
got := d.Sweep()
if got != 1 {
t.Errorf("expected 1 swept entry, got %d", got)
}
_, _, _, _, entries := d.Stats()
if entries != 1 {
t.Errorf("expected 1 surviving entry, got %d", entries)
}
}
// TestPeerDirectory_LookupOrdersByRecency guards the LRU contract: the
// most recently-announced holder comes first in the lookup response, so
// fetchers that try holders in order hit the holder most likely to still
// have the chunk cached locally.
func TestPeerDirectory_LookupOrdersByRecency(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
d.Announce("mount-a:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
now = now.Add(10 * time.Second)
d.Announce("mount-b:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
now = now.Add(10 * time.Second)
d.Announce("mount-c:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
got := d.Lookup([]string{"3,x"}, alwaysOwner).PeersByFid["3,x"]
if len(got) != 3 {
t.Fatalf("expected 3 holders, got %d", len(got))
}
want := []string{"mount-c:18080", "mount-b:18080", "mount-a:18080"}
for i, w := range want {
if got[i].PeerAddr != w {
t.Errorf("holder[%d] = %q, want %q (LRU order)", i, got[i].PeerAddr, w)
}
}
}
// TestPeerDirectory_LookupOrderAfterRenewal ensures renewing an older
// holder promotes it to the head — matches LRU touch-on-access semantics
// and keeps the freshest liveness signal in front.
func TestPeerDirectory_LookupOrderAfterRenewal(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
d.Announce("mount-a:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
now = now.Add(10 * time.Second)
d.Announce("mount-b:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
now = now.Add(10 * time.Second)
d.Announce("mount-a:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
got := d.Lookup([]string{"3,x"}, alwaysOwner).PeersByFid["3,x"]
if len(got) != 2 {
t.Fatalf("expected 2 holders, got %d", len(got))
}
if got[0].PeerAddr != "mount-a:18080" {
t.Errorf("after renewal, head should be mount-a; got %q", got[0].PeerAddr)
}
}
func TestPeerDirectory_StatsCountersIncrement(t *testing.T) {
d := NewPeerDirectory()
d.Announce("mount-a:18080", "", "", []string{"3,a", "3,b"}, time.Minute, alwaysOwner)
d.Lookup([]string{"3,a", "3,c"}, alwaysOwner)
d.Announce("mount-a:18080", "", "", []string{"3,nope"}, time.Minute, ownerSet("nothing"))
announces, lookups, rejected, _, _ := d.Stats()
if announces != 2 {
t.Errorf("announces counter: %d", announces)
}
if lookups != 2 {
t.Errorf("lookups counter: %d", lookups)
}
if rejected != 1 {
t.Errorf("rejected counter: %d", rejected)
}
}
// TestPeerDirectory_LookupCapsHolderList verifies that a hot fid with
// more than maxLookupHolders holders returns only the top-N LRU entries.
// The fetcher typically tries only the first 1-3 anyway, so caching
// every holder on the wire is overhead.
func TestPeerDirectory_LookupCapsHolderList(t *testing.T) {
now := time.Unix(1000, 0)
d := newPeerDirectoryWithClock(func() time.Time { return now })
// Announce 32 holders at strictly increasing timestamps so LRU order
// is well-defined and deterministic.
total := 2 * maxLookupHolders
for i := 0; i < total; i++ {
addr := fmt.Sprintf("mount-%02d:18080", i)
d.Announce(addr, "", "", []string{"3,hot"}, 60*time.Second, alwaysOwner)
now = now.Add(time.Millisecond)
}
got := d.Lookup([]string{"3,hot"}, alwaysOwner).PeersByFid["3,hot"]
if len(got) != maxLookupHolders {
t.Fatalf("expected %d holders in response, got %d", maxLookupHolders, len(got))
}
// Head should be the most recent (last announced).
want := fmt.Sprintf("mount-%02d:18080", total-1)
if got[0].PeerAddr != want {
t.Errorf("head of list: got %q want %q (LRU order)", got[0].PeerAddr, want)
}
}
+41
View File
@@ -0,0 +1,41 @@
package mount
// fakeChunkCache satisfies chunk_cache.ChunkCache with a simple in-memory
// map keyed by fid. Just enough to exercise the peer-serve handler paths.
type fakeChunkCache struct {
chunks map[string][]byte
}
func newFakeChunkCache() *fakeChunkCache {
return &fakeChunkCache{chunks: map[string][]byte{}}
}
func (f *fakeChunkCache) Put(fid string, data []byte) {
buf := make([]byte, len(data))
copy(buf, data)
f.chunks[fid] = buf
}
func (f *fakeChunkCache) ReadChunkAt(data []byte, fileId string, offset uint64) (int, error) {
b, ok := f.chunks[fileId]
if !ok {
return 0, nil
}
if int(offset) >= len(b) {
return 0, nil
}
return copy(data, b[offset:]), nil
}
func (f *fakeChunkCache) SetChunk(fileId string, data []byte) {
f.Put(fileId, data)
}
func (f *fakeChunkCache) IsInCache(fileId string, lockNeeded bool) bool {
_, ok := f.chunks[fileId]
return ok
}
func (f *fakeChunkCache) GetMaxFilePartSizeInCache() uint64 {
return 8 * 1024 * 1024
}
+324
View File
@@ -0,0 +1,324 @@
package mount
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// errPeerReadSkipped signals that the read didn't go through the peer
// path for a benign reason (local cache hit, no peer owner, etc.) rather
// than a genuine failure. Callers fall through to the volume path just
// as they would for a real error, but suppress the "peer read failed"
// log that would otherwise mislead operators into thinking peer sharing
// is broken.
var errPeerReadSkipped = fmt.Errorf("peer read skipped (not an error)")
// peerLookupTimeout bounds the ChunkLookup RPC. Short because the result
// is consumed on the read critical path.
const peerLookupTimeout = 500 * time.Millisecond
// peerFetchTimeout bounds a single FetchChunk stream; on expiry we fall
// through to the next holder or the volume server.
const peerFetchTimeout = 5 * time.Second
// maxPeerFetchChunkBytes caps how much we will accept from a single
// FetchChunk stream. gRPC per-message size is already capped by the
// server option; this is belt-and-suspenders against a runaway peer.
const maxPeerFetchChunkBytes = 64 * 1024 * 1024
// tryPeerRead attempts to satisfy a read from a peer mount's chunk cache.
// Returns (bytesRead, modifiedTsNs, nil) on success. On any failure it
// returns (0, 0, err) so the caller falls through to
// entryChunkGroup.ReadDataAt (the volume-server path).
//
// Flow:
// 1. Resolve the offset's leaf chunk (flattening manifests).
// 2. Ask the HRW owner mount for current holders via ChunkLookup.
// 3. For each holder (LRU order from PR #5), open a FetchChunk stream,
// assemble frames into a size-bounded buffer, and verify MD5
// end-to-end against FileChunk.ETag.
// 4. On success, populate chunk_cache and enqueue an announce so
// other mounts can discover us as a new holder.
func (fh *FileHandle) tryPeerRead(ctx context.Context, fileSize int64, buff []byte, offset int64, entry *LockedEntry) (int64, int64, error) {
if fh.wfs.peerRegistrar == nil || fh.wfs.peerConnPool == nil {
return 0, 0, fmt.Errorf("peer sharing not configured")
}
// Resolve offset → leaf chunk, flattening any manifest indirection.
readStop := offset + int64(len(buff))
if readStop > fileSize {
readStop = fileSize
}
dataChunks, _, err := filer.ResolveChunkManifest(ctx, fh.wfs.LookupFn(), entry.GetEntry().Chunks, offset, readStop)
if err != nil {
return 0, 0, fmt.Errorf("resolve manifest: %w", err)
}
targetChunk, chunkOffset := findChunkContaining(dataChunks, offset)
if targetChunk == nil {
return 0, 0, fmt.Errorf("no leaf chunk for offset %d", offset)
}
// Reject reads that cross a chunk boundary. We only fetch one chunk
// here, and the caller (readFromChunks) maps a short non-error
// return to "success, zero-fill the rest" — which would silently
// corrupt reads that should actually span two chunks. Bail so the
// fallback ReadDataAt path can handle the multi-chunk case
// correctly. See weedfs_file_read.go short-read semantics.
chunkEnd := targetChunk.Offset + int64(targetChunk.Size)
if readStop > chunkEnd {
return 0, 0, errPeerReadSkipped
}
// Fail fast when the chunk is already cached locally: the fallback
// ReadDataAt path will satisfy the read from chunkCache with no RPCs,
// so dialing a peer (ChunkLookup + FetchChunk) would be pure overhead.
if fh.wfs.chunkCache != nil && fh.wfs.chunkCache.IsInCache(targetChunk.FileId, true) {
return 0, 0, errPeerReadSkipped
}
selfAddr := ""
if fh.wfs.peerGrpcServer != nil {
selfAddr = fh.wfs.peerGrpcServer.SelfAddr()
}
owner := fh.wfs.peerRegistrar.OwnerFor(targetChunk.FileId)
if owner == "" || owner == selfAddr {
return 0, 0, fmt.Errorf("no peer owner for fid %s", targetChunk.FileId)
}
holders, err := peerLookupHolders(ctx, fh.wfs.peerConnPool.Dialer(), owner, targetChunk.FileId)
if err != nil {
return 0, 0, fmt.Errorf("peer lookup: %w", err)
}
if len(holders) == 0 {
return 0, 0, fmt.Errorf("no peer holder for fid %s", targetChunk.FileId)
}
// Re-rank holders by locality (same rack > same DC > elsewhere), keeping
// the server's LRU order stable within each bucket. The server caps the
// list at maxLookupHolders, so this is always a small N.
sortHoldersByLocality(holders, fh.wfs.option.PeerDataCenter, fh.wfs.option.PeerRack)
dial := fh.wfs.peerConnPool.Dialer()
for _, h := range holders {
if h.addr == selfAddr {
continue
}
data, ferr := fetchChunkFromPeer(ctx, dial, h.addr, targetChunk.FileId, targetChunk.Size, targetChunk.ETag)
if ferr != nil {
glog.V(2).Infof("peer-fetch %s from %s: %v", targetChunk.FileId, h.addr, ferr)
continue
}
if fh.wfs.chunkCache != nil {
fh.wfs.chunkCache.SetChunk(targetChunk.FileId, data)
}
if fh.wfs.peerAnnouncer != nil {
fh.wfs.peerAnnouncer.EnqueueAnnounce(targetChunk.FileId)
}
if chunkOffset >= int64(len(data)) {
return 0, 0, fmt.Errorf("peer returned short chunk")
}
// Cap the copy to whichever is smaller: the caller's buffer, or
// the remaining bytes before logical EOF (readStop already
// clamped to fileSize). FileChunk.Size can legitimately exceed
// the logical file length when the last chunk is partially
// written and the filer stored the full padded buffer, so a
// naïve copy(buff, data[chunkOffset:]) would return bytes past
// EOF. The caller treats a short non-error return as success
// and zero-fills the tail, so returning too many bytes here is
// a correctness bug, not just wasted I/O.
remaining := readStop - offset
available := int64(len(data)) - chunkOffset
maxCopy := int64(len(buff))
if remaining < maxCopy {
maxCopy = remaining
}
if available < maxCopy {
maxCopy = available
}
copied := copy(buff[:maxCopy], data[chunkOffset:chunkOffset+maxCopy])
return int64(copied), targetChunk.ModifiedTsNs, nil
}
return 0, 0, fmt.Errorf("no peer served fid %s", targetChunk.FileId)
}
func findChunkContaining(chunks []*filer_pb.FileChunk, offset int64) (*filer_pb.FileChunk, int64) {
for _, c := range chunks {
start := c.Offset
stop := c.Offset + int64(c.Size)
if offset >= start && offset < stop {
return c, offset - start
}
}
return nil, 0
}
// peerHolder is a holder entry carried through the fetcher: addr for
// dialing plus the DC/Rack labels the owner recorded at announce time, so
// the fetcher can re-rank by its own locality before dialing.
type peerHolder struct {
addr string
dc string
rack string
}
// peerLookupHolders calls ChunkLookup on the given HRW owner and returns
// the holders in the server-reported (LRU) order along with their locality
// labels. The pooled dialer is passed in from the caller.
func peerLookupHolders(ctx context.Context, dial MountPeerDialer, ownerAddr, fid string) ([]peerHolder, error) {
client, closeFn, err := dial(ctx, ownerAddr)
if err != nil {
return nil, err
}
defer closeFn()
callCtx, cancel := context.WithTimeout(ctx, peerLookupTimeout)
defer cancel()
resp, err := client.ChunkLookup(callCtx, &mount_peer_pb.ChunkLookupRequest{FileIds: []string{fid}})
if err != nil {
return nil, err
}
set, ok := resp.PeersByFid[fid]
if !ok || set == nil {
return nil, nil
}
out := make([]peerHolder, 0, len(set.Peers))
for _, p := range set.Peers {
out = append(out, peerHolder{addr: p.PeerAddr, dc: p.DataCenter, rack: p.Rack})
}
return out, nil
}
// localityBucket scores how "close" a peer is to self. Lower is better:
//
// 0 = same rack in same DC (shortest hop)
// 1 = same DC, different rack (cross-rack but still intra-DC)
// 2 = different DC, or unknown (anything else)
//
// Missing labels on either side fall to bucket 2 — we don't claim locality
// we can't prove.
func localityBucket(selfDC, selfRack, peerDC, peerRack string) int {
if selfDC == "" || peerDC == "" || selfDC != peerDC {
return 2
}
if selfRack != "" && peerRack != "" && selfRack == peerRack {
return 0
}
return 1
}
// sortHoldersByLocality stable-sorts holders so the most local peers are
// tried first. The server-returned order is LRU (freshest holder first),
// and sort.SliceStable preserves that ordering within each locality
// bucket, so among equally-local peers we still prefer the freshest.
func sortHoldersByLocality(holders []peerHolder, selfDC, selfRack string) {
if len(holders) < 2 {
return
}
sort.SliceStable(holders, func(i, j int) bool {
return localityBucket(selfDC, selfRack, holders[i].dc, holders[i].rack) <
localityBucket(selfDC, selfRack, holders[j].dc, holders[j].rack)
})
}
// fetchChunkFromPeer server-streams a chunk from the given peer and
// verifies the MD5 of the assembled bytes against expectedETag.
//
// expectedSize (when > 0) is the authoritative chunk length from the
// filer entry; we pre-allocate exactly that to avoid slice growth and
// reject streams that overshoot it. A zero expectedSize falls back to
// maxPeerFetchChunkBytes as a safety ceiling.
func fetchChunkFromPeer(ctx context.Context, dial MountPeerDialer, peerAddr, fid string, expectedSize uint64, expectedETag string) ([]byte, error) {
client, closeFn, err := dial(ctx, peerAddr)
if err != nil {
return nil, err
}
defer closeFn()
callCtx, cancel := context.WithTimeout(ctx, peerFetchTimeout)
defer cancel()
stream, err := client.FetchChunk(callCtx, &mount_peer_pb.FetchChunkRequest{
FileId: fid,
ExpectedEtag: expectedETag,
ExpectedSize: expectedSize,
})
if err != nil {
return nil, err
}
// capHint pre-sizes the assembly buffer from the filer-reported chunk
// size. When the caller didn't know the size (expectedSize == 0), we
// let append grow the buffer rather than reserve the 64 MiB ceiling —
// typical chunks are a few MiB, and the maxPeerFetchChunkBytes check
// during Recv is the real safety ceiling.
capHint := expectedSize
if capHint > maxPeerFetchChunkBytes {
capHint = maxPeerFetchChunkBytes
}
buf := make([]byte, 0, capHint)
for {
resp, rerr := stream.Recv()
if rerr == io.EOF {
break
}
if rerr != nil {
if status.Code(rerr) == codes.NotFound {
return nil, fmt.Errorf("peer not cached")
}
return nil, rerr
}
if len(buf)+len(resp.Data) > int(maxPeerFetchChunkBytes) {
return nil, fmt.Errorf("peer response exceeds max chunk size %d", maxPeerFetchChunkBytes)
}
buf = append(buf, resp.Data...)
}
if expectedSize > 0 && uint64(len(buf)) != expectedSize {
return nil, fmt.Errorf("peer returned %d bytes, expected %d", len(buf), expectedSize)
}
// Per-chunk integrity check — the peer is treated as untrusted.
// FileChunk.ETag is UploadResult.ContentMd5, which is base64 of the
// raw 16-byte MD5 (see weed/operation/upload_content.go:64 and
// filer's ETagChunks which decodes via util.Base64Md5ToBytes).
// Compare raw digests so we don't reject every valid peer response
// because of an encoding mismatch.
if expectedETag != "" {
got := md5.Sum(buf)
if !etagMatchesMD5(expectedETag, got[:]) {
return nil, fmt.Errorf("etag mismatch: peer=%s got=%x want=%s", peerAddr, got, expectedETag)
}
}
return buf, nil
}
// etagMatchesMD5 compares a stored FileChunk.ETag string to a raw 16-byte
// MD5 digest. FileChunk.ETag is produced as base64(md5) on upload, but
// some older chunks (and tests) use hex(md5). Accept either.
func etagMatchesMD5(etag string, rawMD5 []byte) bool {
if len(rawMD5) != md5.Size {
return false
}
if dec := util.Base64Md5ToBytes(etag); len(dec) == md5.Size {
return bytes.Equal(dec, rawMD5)
}
if dec, err := hex.DecodeString(etag); err == nil && len(dec) == md5.Size {
return bytes.Equal(dec, rawMD5)
}
return false
}
+180
View File
@@ -0,0 +1,180 @@
package mount
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// newTestFetchServer stands up a minimal MountPeer gRPC server that only
// serves FetchChunk out of a fakeChunkCache. Goes through the same
// PeerGrpcServer.Start path production uses (via pb.NewGrpcServer with
// the standard keepalive + msg-size options) so future default server
// options are exercised by these tests too.
func newTestFetchServer(t *testing.T, cache *fakeChunkCache) (addr string, stop func()) {
t.Helper()
dir := NewPeerDirectory()
srv := NewPeerGrpcServer(cache, dir, nil, "")
if err := srv.Start("127.0.0.1:0"); err != nil {
t.Fatalf("start: %v", err)
}
return srv.Addr(), func() { srv.Stop() }
}
func etagOf(b []byte) string {
sum := md5.Sum(b)
return hex.EncodeToString(sum[:])
}
// etagOfBase64 mirrors how the real upload path produces FileChunk.ETag:
// base64 of the raw 16-byte MD5 digest. Kept alongside the hex form so
// we can test that both encodings work end-to-end.
func etagOfBase64(b []byte) string {
sum := md5.Sum(b)
return base64.StdEncoding.EncodeToString(sum[:])
}
func TestFetchChunkFromPeer_Hit(t *testing.T) {
cache := newFakeChunkCache()
payload := []byte("hello from peer stream")
cache.Put("3,abc", payload)
addr, stop := newTestFetchServer(t, cache)
defer stop()
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
got, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,abc", uint64(len(payload)), etagOf(payload))
if err != nil {
t.Fatalf("fetch: %v", err)
}
if string(got) != string(payload) {
t.Errorf("bytes mismatch: got %q want %q", got, payload)
}
}
// TestFetchChunkFromPeer_Base64Etag mirrors the real upload path where
// FileChunk.ETag is base64(md5) rather than hex(md5). A regression
// there would reject every valid peer response in production.
func TestFetchChunkFromPeer_Base64Etag(t *testing.T) {
cache := newFakeChunkCache()
payload := []byte("base64-etag peer bytes")
cache.Put("3,b64", payload)
addr, stop := newTestFetchServer(t, cache)
defer stop()
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
got, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,b64", uint64(len(payload)), etagOfBase64(payload))
if err != nil {
t.Fatalf("fetch: %v", err)
}
if string(got) != string(payload) {
t.Errorf("bytes mismatch: got %q want %q", got, payload)
}
}
func TestFetchChunkFromPeer_EtagMismatch(t *testing.T) {
cache := newFakeChunkCache()
payload := []byte("unexpected bytes")
cache.Put("3,abc", payload)
addr, stop := newTestFetchServer(t, cache)
defer stop()
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
_, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,abc", 0, "not-the-real-etag")
if err == nil {
t.Fatalf("expected etag mismatch error, got nil")
}
}
func TestFetchChunkFromPeer_NotFound(t *testing.T) {
cache := newFakeChunkCache()
addr, stop := newTestFetchServer(t, cache)
defer stop()
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
_, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,missing", 0, "")
if err == nil {
t.Errorf("expected error for missing fid, got nil")
}
}
// TestSortHoldersByLocality verifies that same-rack peers sort ahead of
// same-DC-different-rack peers, which in turn sort ahead of cross-DC
// peers, and that LRU order is preserved within each bucket.
func TestSortHoldersByLocality(t *testing.T) {
selfDC, selfRack := "dc1", "r1"
// Input order mimics a server-side LRU list (newest first).
holders := []peerHolder{
{addr: "far-newest", dc: "dc2", rack: "r9"}, // bucket 2 (diff DC)
{addr: "mid-newer", dc: "dc1", rack: "r2"}, // bucket 1 (same DC, diff rack)
{addr: "local-newer", dc: "dc1", rack: "r1"}, // bucket 0 (same rack)
{addr: "far-older", dc: "dc2", rack: "r9"}, // bucket 2
{addr: "mid-older", dc: "dc1", rack: "r2"}, // bucket 1
{addr: "local-older", dc: "dc1", rack: "r1"}, // bucket 0
{addr: "unlabeled-older", dc: "", rack: ""}, // bucket 2 (unknown)
}
sortHoldersByLocality(holders, selfDC, selfRack)
want := []string{
"local-newer", "local-older",
"mid-newer", "mid-older",
"far-newest", "far-older", "unlabeled-older",
}
if len(holders) != len(want) {
t.Fatalf("len got %d want %d", len(holders), len(want))
}
for i, w := range want {
if holders[i].addr != w {
t.Errorf("pos %d: got %q want %q (full: %+v)", i, holders[i].addr, w, holders)
}
}
}
// TestSortHoldersByLocality_NoSelfLabels — when the caller has no DC/rack
// labels, every peer falls to bucket 2 and the server-returned LRU order
// must pass through unchanged.
func TestSortHoldersByLocality_NoSelfLabels(t *testing.T) {
holders := []peerHolder{
{addr: "a", dc: "dc1", rack: "r1"},
{addr: "b", dc: "dc2", rack: "r2"},
{addr: "c", dc: "", rack: ""},
}
sortHoldersByLocality(holders, "", "")
want := []string{"a", "b", "c"}
for i, w := range want {
if holders[i].addr != w {
t.Errorf("pos %d: got %q want %q", i, holders[i].addr, w)
}
}
}
func TestFetchChunkFromPeer_MultiFrameChunkAssembledCorrectly(t *testing.T) {
cache := newFakeChunkCache()
// Just over 2× the stream frame size so we get at least three frames.
payload := make([]byte, fetchChunkStreamSize*2+42)
for i := range payload {
payload[i] = byte((i * 7) & 0xff)
}
cache.Put("3,large", payload)
addr, stop := newTestFetchServer(t, cache)
defer stop()
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
got, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,large", uint64(len(payload)), etagOf(payload))
if err != nil {
t.Fatalf("fetch: %v", err)
}
if len(got) != len(payload) {
t.Fatalf("len got %d want %d", len(got), len(payload))
}
for i := range payload {
if got[i] != payload[i] {
t.Fatalf("mismatch at offset %d", i)
}
}
}
+258
View File
@@ -0,0 +1,258 @@
package mount
import (
"context"
"fmt"
"net"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
"github.com/seaweedfs/seaweedfs/weed/util/mem"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// fetchChunkStreamSize is the frame size used when server-streaming a chunk's
// bytes back to a peer. 1 MiB is well above gRPC's 32 KiB preferred frame but
// comfortably under the default 4 MiB message cap, so each Recv on the client
// returns quickly and the chunk is assembled with ~16 Recv calls for typical
// 16 MiB chunks.
const fetchChunkStreamSize = 1 * 1024 * 1024
// maxFetchChunkBytes caps the size of a single FetchChunk read buffer.
// The caller's expected_size is untrusted — a misbehaving peer could
// claim 1 TiB and OOM the server. 64 MiB is well above any realistic
// chunk (SeaweedFS defaults to 16 MiB, filer manifests cap at 32 MiB);
// anything larger is treated as invalid input.
const maxFetchChunkBytes = 64 * 1024 * 1024
// PeerGrpcServer is the single mount-to-mount gRPC endpoint. It serves:
// - ChunkAnnounce / ChunkLookup — the tier-2 directory RPCs, populated
// by inbound announces and queried by inbound lookups. Each handler
// is HRW-gated on the caller-side seed view.
// - FetchChunk (server stream) — serves bytes from the local
// chunk_cache to peers. Replaces the earlier HTTP-only peer-serve
// endpoint: one port, one authentication path, one connection pool.
//
// Transport credentials (TLS/mTLS) are injected via serverOpts. When the
// caller passes nothing the server runs plaintext — only appropriate on
// a trusted single-host test cluster. Production wiring passes
// security.LoadServerTLS from security.toml so cross-host traffic is
// authenticated + encrypted.
type PeerGrpcServer struct {
mount_peer_pb.UnimplementedMountPeerServer
dir *PeerDirectory
cache chunk_cache.ChunkCache
ownerFor func(fid string) string // HRW owner predicate on current seeds
selfAddr string
serverOpts []grpc.ServerOption
grpcS *grpc.Server
listener net.Listener
stopped bool
}
// NewPeerGrpcServer constructs the server. cache is the local chunk_cache
// (used to serve FetchChunk); dir is the local directory shard (used to
// answer ChunkAnnounce / ChunkLookup); ownerFor returns the HRW owner of a
// fid on the current seed view; serverOpts are forwarded to the underlying
// gRPC server (use grpc.Creds(...) for TLS/mTLS).
func NewPeerGrpcServer(cache chunk_cache.ChunkCache, dir *PeerDirectory, ownerFor func(fid string) string, selfAddr string, serverOpts ...grpc.ServerOption) *PeerGrpcServer {
return &PeerGrpcServer{
cache: cache,
dir: dir,
ownerFor: ownerFor,
selfAddr: selfAddr,
serverOpts: serverOpts,
}
}
// Start binds a TCP listener at addr and registers the MountPeer service.
func (s *PeerGrpcServer) Start(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("peer grpc listen %s: %w", addr, err)
}
s.listener = ln
s.grpcS = pb.NewGrpcServer(s.serverOpts...)
mount_peer_pb.RegisterMountPeerServer(s.grpcS, s)
go func() {
if err := s.grpcS.Serve(ln); err != nil && err != grpc.ErrServerStopped {
glog.Warningf("peer-grpc terminated: %v", err)
}
}()
glog.V(0).Infof("peer-grpc listening on %s", ln.Addr())
return nil
}
// Stop halts the gRPC server without waiting for in-flight streams.
func (s *PeerGrpcServer) Stop() {
if s.stopped {
return
}
s.stopped = true
if s.grpcS != nil {
s.grpcS.Stop()
}
}
// Addr returns the bound address (useful when the caller used ":0").
func (s *PeerGrpcServer) Addr() string {
if s.listener == nil {
return ""
}
return s.listener.Addr().String()
}
// SelfAddr returns the advertise address this server was constructed with —
// the identity the fetcher compares against to avoid dialing itself.
func (s *PeerGrpcServer) SelfAddr() string { return s.selfAddr }
// ChunkAnnounce accepts holder entries for fids this mount owns; rejects
// others so the caller can retry against the correct owner.
func (s *PeerGrpcServer) ChunkAnnounce(ctx context.Context, req *mount_peer_pb.ChunkAnnounceRequest) (*mount_peer_pb.ChunkAnnounceResponse, error) {
ttl := time.Duration(req.TtlSeconds) * time.Second
res := s.dir.Announce(req.PeerAddr, req.DataCenter, req.Rack, req.FileIds, ttl, s.ownerPredicate)
return &mount_peer_pb.ChunkAnnounceResponse{
RejectedFileIds: res.Rejected,
}, nil
}
// ChunkLookup returns known holders for each requested fid in LRU order.
func (s *PeerGrpcServer) ChunkLookup(ctx context.Context, req *mount_peer_pb.ChunkLookupRequest) (*mount_peer_pb.ChunkLookupResponse, error) {
res := s.dir.Lookup(req.FileIds, s.ownerPredicate)
resp := &mount_peer_pb.ChunkLookupResponse{
PeersByFid: make(map[string]*mount_peer_pb.PeerSet, len(res.PeersByFid)),
NotOwnerFileIds: res.NotOwnerFids,
}
for fid, holders := range res.PeersByFid {
peers := &mount_peer_pb.PeerSet{}
for _, h := range holders {
peers.Peers = append(peers.Peers, &mount_peer_pb.PeerInfo{
PeerAddr: h.PeerAddr,
DataCenter: h.DataCenter,
Rack: h.Rack,
})
}
resp.PeersByFid[fid] = peers
}
return resp, nil
}
// FetchChunk streams bytes of a cached chunk back to the caller. Missing
// fid → gRPC NOT_FOUND. Bytes are framed at fetchChunkStreamSize so gRPC's
// default 4 MiB message cap does not constrain chunk size.
func (s *PeerGrpcServer) FetchChunk(req *mount_peer_pb.FetchChunkRequest, stream mount_peer_pb.MountPeer_FetchChunkServer) error {
if s.cache == nil {
return status.Error(codes.Unavailable, "chunk cache not configured")
}
fid := req.FileId
if fid == "" {
return status.Error(codes.InvalidArgument, "missing file_id")
}
// Size the read buffer to the caller-reported chunk length. The
// TieredChunkCache.ReadChunkAt wrapper only returns success when n
// equals len(data), so a buffer larger than the actual stored chunk
// (e.g. an 8 MiB buffer for a 2 MiB chunk) makes every read look
// like a miss. Client sends expected_size from FileChunk.Size so we
// allocate exactly the right amount. Fall back to the max-part-size
// when the caller left it zero (older clients) and hope the chunk
// is that big.
//
// expected_size is untrusted — cap at maxFetchChunkBytes to prevent
// a misbehaving peer from requesting an OOM-sized allocation.
if req.ExpectedSize > maxFetchChunkBytes {
return status.Errorf(codes.InvalidArgument,
"expected_size %d exceeds max %d", req.ExpectedSize, maxFetchChunkBytes)
}
if req.Length > maxFetchChunkBytes {
return status.Errorf(codes.InvalidArgument,
"length %d exceeds max %d", req.Length, maxFetchChunkBytes)
}
readSize := int(req.ExpectedSize)
if readSize <= 0 {
max := s.cache.GetMaxFilePartSizeInCache()
if max == 0 {
max = 8 * 1024 * 1024
}
readSize = int(max)
}
// mem.Allocate rounds up to the nearest power-of-2 slot backed by a
// shared sync.Pool; avoids an allocation per FetchChunk call.
buf := mem.Allocate(readSize)
defer mem.Free(buf)
n, err := s.cache.ReadChunkAt(buf, fid, 0)
if err != nil || n <= 0 {
return status.Errorf(codes.NotFound, "fid %s not cached", fid)
}
// Apply optional offset / length range to the whole-chunk buffer.
// Default (both 0) is a full-chunk transfer starting at byte 0,
// which is what the fetcher uses today. Non-default is reserved
// for future range-read callers.
lo := int(req.Offset)
if lo < 0 || lo > n {
return status.Errorf(codes.OutOfRange, "offset %d outside chunk length %d", lo, n)
}
hi := n
if req.Length > 0 {
hi = lo + int(req.Length)
if hi > n {
hi = n
}
}
for off := lo; off < hi; off += fetchChunkStreamSize {
end := off + fetchChunkStreamSize
if end > hi {
end = hi
}
if sendErr := stream.Send(&mount_peer_pb.FetchChunkResponse{
Data: buf[off:end],
}); sendErr != nil {
return sendErr
}
}
return nil
}
func (s *PeerGrpcServer) ownerPredicate(fid string) bool {
if s.ownerFor == nil {
return true // no HRW configured → accept all (single-mount mode)
}
return s.ownerFor(fid) == s.selfAddr
}
// peerDirectorySweepInterval is how often the mount evicts expired
// directory entries. Lookup no longer deletes inline (it takes only an
// RLock), so this sweeper is the sole memory reclamation path.
const peerDirectorySweepInterval = 60 * time.Second
// runPeerDirectorySweeper runs until stopCh closes. Stopping it on
// unmount prevents the goroutine from outliving the WFS, which matters
// for tests and for any embedded use of NewSeaweedFileSystem where the
// filesystem object is recreated without a process exit.
func (wfs *WFS) runPeerDirectorySweeper(stopCh <-chan struct{}) {
ticker := time.NewTicker(peerDirectorySweepInterval)
defer ticker.Stop()
for {
select {
case <-stopCh:
return
case <-ticker.C:
dir := wfs.peerDirectory
if dir == nil {
return
}
if evicted := dir.Sweep(); evicted > 0 {
glog.V(2).Infof("peer directory: evicted %d expired entries", evicted)
}
}
}
}
+150
View File
@@ -0,0 +1,150 @@
package mount
import (
"context"
"io"
"net"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
func newTestPeerGrpc(t *testing.T, cache chunk_cache.ChunkCache, ownerFor func(fid string) string, selfAddr string) (mount_peer_pb.MountPeerClient, func()) {
t.Helper()
dir := NewPeerDirectory()
srv := NewPeerGrpcServer(cache, dir, ownerFor, selfAddr)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
srv.listener = ln
srv.grpcS = grpc.NewServer()
mount_peer_pb.RegisterMountPeerServer(srv.grpcS, srv)
go srv.grpcS.Serve(ln)
conn, err := grpc.NewClient(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("dial: %v", err)
}
client := mount_peer_pb.NewMountPeerClient(conn)
cleanup := func() {
conn.Close()
srv.Stop()
}
return client, cleanup
}
func TestPeerGrpcServer_AnnounceAndLookup(t *testing.T) {
self := "self:18080"
client, cleanup := newTestPeerGrpc(t, nil, func(fid string) string {
return self
}, self)
defer cleanup()
_, err := client.ChunkAnnounce(context.Background(), &mount_peer_pb.ChunkAnnounceRequest{
FileIds: []string{"3,a", "3,b"},
PeerAddr: "holder:18080",
TtlSeconds: 60,
})
if err != nil {
t.Fatalf("announce: %v", err)
}
resp, err := client.ChunkLookup(context.Background(), &mount_peer_pb.ChunkLookupRequest{
FileIds: []string{"3,a", "3,missing"},
})
if err != nil {
t.Fatalf("lookup: %v", err)
}
if got := len(resp.PeersByFid["3,a"].Peers); got != 1 {
t.Errorf("3,a: expected 1 holder, got %d", got)
}
if _, ok := resp.PeersByFid["3,missing"]; !ok {
t.Errorf("3,missing should have a (nil/empty) peer set entry")
}
}
func TestPeerGrpcServer_OwnerMismatch(t *testing.T) {
client, cleanup := newTestPeerGrpc(t, nil, func(fid string) string {
return "some-other:18080"
}, "self:18080")
defer cleanup()
ann, err := client.ChunkAnnounce(context.Background(), &mount_peer_pb.ChunkAnnounceRequest{
FileIds: []string{"3,x"},
PeerAddr: "holder:18080",
TtlSeconds: 60,
})
if err != nil {
t.Fatalf("announce: %v", err)
}
if len(ann.RejectedFileIds) != 1 || ann.RejectedFileIds[0] != "3,x" {
t.Errorf("expected 3,x rejected, got %v", ann.RejectedFileIds)
}
}
// TestPeerGrpcServer_FetchChunk_StreamsHit exercises the new byte-transfer
// path: a cached chunk returned as multiple gRPC frames, concatenated by
// the caller into the original payload.
func TestPeerGrpcServer_FetchChunk_StreamsHit(t *testing.T) {
cache := newFakeChunkCache()
// A payload deliberately larger than fetchChunkStreamSize to force
// multiple Send() calls.
payload := make([]byte, fetchChunkStreamSize*2+123)
for i := range payload {
payload[i] = byte(i & 0xff)
}
cache.Put("3,stream", payload)
client, cleanup := newTestPeerGrpc(t, cache, nil, "self:18080")
defer cleanup()
stream, err := client.FetchChunk(context.Background(), &mount_peer_pb.FetchChunkRequest{FileId: "3,stream"})
if err != nil {
t.Fatalf("FetchChunk: %v", err)
}
var got []byte
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("Recv: %v", err)
}
got = append(got, resp.Data...)
}
if len(got) != len(payload) {
t.Fatalf("got %d bytes, want %d", len(got), len(payload))
}
for i, b := range got {
if b != payload[i] {
t.Fatalf("byte mismatch at offset %d: got %02x want %02x", i, b, payload[i])
}
}
}
// TestPeerGrpcServer_FetchChunk_NotFound verifies that a miss returns
// gRPC NOT_FOUND so the client can distinguish miss from transport error.
func TestPeerGrpcServer_FetchChunk_NotFound(t *testing.T) {
cache := newFakeChunkCache()
client, cleanup := newTestPeerGrpc(t, cache, nil, "self:18080")
defer cleanup()
stream, err := client.FetchChunk(context.Background(), &mount_peer_pb.FetchChunkRequest{FileId: "3,missing"})
if err != nil {
t.Fatalf("FetchChunk dial: %v", err)
}
_, err = stream.Recv()
if err == nil {
t.Fatalf("expected error on missing fid, got nil")
}
if status.Code(err) != codes.NotFound {
t.Errorf("expected NotFound code, got %v", status.Code(err))
}
}
+51
View File
@@ -0,0 +1,51 @@
package mount
import (
"hash/fnv"
)
// SeedPeer is a mount server present in the filer's mount registry.
// DataCenter and Rack ride along so downstream locality-aware decisions
// (peer re-ranking in the fetcher) don't have to re-query the filer.
type SeedPeer struct {
PeerAddr string
DataCenter string
Rack string
}
// OwnerFor returns the peer_addr of the mount that is the HRW-assigned
// directory owner for fid on the given seed list.
//
// Rendezvous (highest-random-weight) hashing is deterministic for a given
// (fid, seed set): every mount computes the same owner without any
// consensus. When a mount joins or leaves the seed set, only 1/N of fids
// change owner — the rest remain on their existing mount.
//
// If seeds is empty, returns "".
//
// See design-weed-mount-peer-chunk-sharing.md §4.2.2.
func OwnerFor(fid string, seeds []SeedPeer) string {
if len(seeds) == 0 {
return ""
}
var bestScore uint64
var bestAddr string
for _, s := range seeds {
score := hrwScore(s.PeerAddr, fid)
if bestAddr == "" || score > bestScore || (score == bestScore && s.PeerAddr < bestAddr) {
bestScore = score
bestAddr = s.PeerAddr
}
}
return bestAddr
}
// hrwScore combines peer_addr and fid into a 64-bit score. Uses FNV-1a
// (cheap and fine for balancing; not a security primitive).
func hrwScore(peerAddr, fid string) uint64 {
h := fnv.New64a()
_, _ = h.Write([]byte(peerAddr))
_, _ = h.Write([]byte{0}) // separator so "ab" + "c" != "a" + "bc"
_, _ = h.Write([]byte(fid))
return h.Sum64()
}
+90
View File
@@ -0,0 +1,90 @@
package mount
import (
"fmt"
"testing"
)
func mkSeeds(addrs ...string) []SeedPeer {
out := make([]SeedPeer, len(addrs))
for i, a := range addrs {
out[i] = SeedPeer{PeerAddr: a}
}
return out
}
func TestOwnerFor_EmptySeeds(t *testing.T) {
if got := OwnerFor("3,01637037d6", nil); got != "" {
t.Errorf("expected empty owner for empty seed list, got %q", got)
}
}
func TestOwnerFor_Deterministic(t *testing.T) {
seeds := mkSeeds("a:1", "b:1", "c:1", "d:1")
fid := "3,01637037d6"
first := OwnerFor(fid, seeds)
for i := 0; i < 100; i++ {
if got := OwnerFor(fid, seeds); got != first {
t.Fatalf("non-deterministic: iter %d got %q first %q", i, got, first)
}
}
}
func TestOwnerFor_DistributesEvenly(t *testing.T) {
const N = 4
seeds := mkSeeds("a:1", "b:1", "c:1", "d:1")
counts := map[string]int{}
for i := 0; i < 10000; i++ {
fid := fmt.Sprintf("%d,%x", i, i*17)
counts[OwnerFor(fid, seeds)]++
}
// Each seed should get roughly 25% (±10% slack for a 10k sample).
for addr, c := range counts {
ratio := float64(c) / 10000.0
if ratio < 0.225 || ratio > 0.275 {
t.Errorf("HRW distribution skewed: %s got %.3f", addr, ratio)
}
}
if len(counts) != N {
t.Errorf("expected %d distinct owners, got %d", N, len(counts))
}
}
func TestOwnerFor_MinimalShuffleOnSeedChange(t *testing.T) {
// Adding one seed should move ~1/(N+1) fids to the new seed and leave
// the rest on their prior owners. Tolerance generous for a 10k sample.
const trials = 10000
before := mkSeeds("a:1", "b:1", "c:1")
after := mkSeeds("a:1", "b:1", "c:1", "d:1")
moved := 0
toNewSeed := 0
for i := 0; i < trials; i++ {
fid := fmt.Sprintf("%d,%x", i, i*31)
pre := OwnerFor(fid, before)
post := OwnerFor(fid, after)
if pre != post {
moved++
if post == "d:1" {
toNewSeed++
}
}
}
// Expected: ~1/4 = 25% of fids move, all to the new seed.
ratio := float64(moved) / float64(trials)
if ratio < 0.20 || ratio > 0.30 {
t.Errorf("expected ~25%% fids to move on seed-add, got %.3f", ratio)
}
if moved != toNewSeed {
t.Errorf("expected every moved fid to land on the new seed; moved=%d toNewSeed=%d", moved, toNewSeed)
}
}
func TestOwnerFor_TieBreakerDeterministic(t *testing.T) {
// Two seeds with equal hash score (engineered collision is unlikely in
// practice, but we guarantee determinism by lex-comparing addresses).
// This test just confirms OwnerFor runs without panicking on duplicates.
seeds := mkSeeds("a:1", "a:1", "b:1")
fid := "3,01637037d6"
_ = OwnerFor(fid, seeds)
}
+251
View File
@@ -0,0 +1,251 @@
package mount
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// PeerRegistrar maintains this mount's presence in every configured
// filer's mount registry and its local snapshot of the merged seed set.
// It runs two background tickers:
//
// - MountRegister heartbeats, fanned out to every filer in parallel so
// each filer keeps a fresh TTL entry for us. Mounts pointing at
// different filers therefore still see each other once all filers
// have been heartbeated.
// - MountList polling, fanned out identically, merged by peer_addr
// (newest LastSeenNs wins) so OwnerFor() has a view of the whole
// fleet regardless of which filer each peer happens to heartbeat
// through.
//
// An unreachable filer is tolerated: we log and continue as long as at
// least one filer succeeds. Entries cached on a permanently-gone filer
// fall out of the merged view on their own TTL.
type PeerRegistrar struct {
filerAddrs []pb.ServerAddress
dialFiler filerDialFn
selfPeerAddr string
selfDc string
selfRack string
registerInterval time.Duration
registerTTL time.Duration
listInterval time.Duration
mu sync.RWMutex
seeds []SeedPeer
// stopCtx cancels when Stop() is called. Background RPCs scope their
// deadline to this so unmount does not block on pending filer calls.
stopCtx context.Context
stopCancel context.CancelFunc
stopped atomic.Bool
}
// filerDialFn is how the registrar reaches one configured filer. The
// production wiring is pb.WithGrpcFilerClient; tests inject a fake.
type filerDialFn func(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error
// NewPeerRegistrar constructs the registrar; Start launches the background
// loops. Callers must supply the full filer set so heartbeats and list
// polls reach every filer — otherwise mounts talking to different filers
// never observe each other.
func NewPeerRegistrar(filers []pb.ServerAddress, dial filerDialFn, selfAddr, dc, rack string) *PeerRegistrar {
ctx, cancel := context.WithCancel(context.Background())
return &PeerRegistrar{
filerAddrs: filers,
dialFiler: dial,
selfPeerAddr: selfAddr,
selfRack: rack,
selfDc: dc,
registerInterval: 30 * time.Second,
registerTTL: 90 * time.Second,
listInterval: 30 * time.Second,
stopCtx: ctx,
stopCancel: cancel,
}
}
// Start does an initial register+list synchronously (so OwnerFor has a
// usable view immediately) and then kicks off the background loops.
func (r *PeerRegistrar) Start(ctx context.Context) error {
if err := r.registerOnce(ctx); err != nil {
glog.V(1).Infof("initial MountRegister: %v", err)
// Do not fail startup — the mount must still serve reads even if
// no filer yet knows about us.
}
if err := r.listOnce(ctx); err != nil {
glog.V(1).Infof("initial MountList: %v", err)
}
go r.loopRegister()
go r.loopList()
return nil
}
// Stop halts the background loops and cancels any in-flight RPCs they
// may have launched. Safe to call multiple times.
func (r *PeerRegistrar) Stop() {
if r.stopped.Swap(true) {
return
}
r.stopCancel()
}
// Seeds returns the currently-known seed set. Callers MUST NOT mutate the
// returned slice — it is shared with concurrent listOnce readers. Because
// listOnce atomically swaps to a brand-new slice on every refresh rather
// than mutating in place, returning the slice header directly is safe and
// avoids a per-call allocation on the read-hot OwnerFor path.
func (r *PeerRegistrar) Seeds() []SeedPeer {
r.mu.RLock()
defer r.mu.RUnlock()
return r.seeds
}
// OwnerFor is a convenience wrapper that runs HRW against the current
// seed snapshot.
func (r *PeerRegistrar) OwnerFor(fid string) string {
return OwnerFor(fid, r.Seeds())
}
// filerRPCTimeout bounds a single MountRegister / MountList call so a slow
// or partitioned filer can't wedge the background loops (which run on a
// 30 s cadence). 20 s gives room for TLS handshakes on cold connections
// while leaving headroom before the next tick.
const filerRPCTimeout = 20 * time.Second
// registerOnce fans a MountRegister out to every configured filer in
// parallel. Returns an error only if every filer failed; otherwise the
// best-effort semantics let the mount proceed when some filer is down.
func (r *PeerRegistrar) registerOnce(ctx context.Context) error {
if len(r.filerAddrs) == 0 {
return fmt.Errorf("no filers configured")
}
ctx, cancel := context.WithTimeout(ctx, filerRPCTimeout)
defer cancel()
req := &filer_pb.MountRegisterRequest{
PeerAddr: r.selfPeerAddr,
Rack: r.selfRack,
DataCenter: r.selfDc,
TtlSeconds: int32(r.registerTTL / time.Second),
}
var wg sync.WaitGroup
var successes atomic.Int32
for _, addr := range r.filerAddrs {
wg.Add(1)
go func(addr pb.ServerAddress) {
defer wg.Done()
err := r.dialFiler(ctx, addr, func(c filer_pb.SeaweedFilerClient) error {
_, err := c.MountRegister(ctx, req)
return err
})
if err != nil {
glog.V(2).Infof("MountRegister %s: %v", addr, err)
return
}
successes.Add(1)
}(addr)
}
wg.Wait()
if successes.Load() == 0 {
return fmt.Errorf("MountRegister failed on all %d filer(s)", len(r.filerAddrs))
}
return nil
}
// listOnce polls MountList from every filer in parallel and merges the
// responses by peer_addr (newest LastSeenNs wins). This way two mounts
// heartbeating through different filers still end up in each other's
// seed view as soon as at least one filer has been listed on each side.
func (r *PeerRegistrar) listOnce(ctx context.Context) error {
if len(r.filerAddrs) == 0 {
r.mu.Lock()
r.seeds = nil
r.mu.Unlock()
return nil
}
ctx, cancel := context.WithTimeout(ctx, filerRPCTimeout)
defer cancel()
var (
mu sync.Mutex
merged = map[string]*filer_pb.MountInfo{}
fails int
)
var wg sync.WaitGroup
for _, addr := range r.filerAddrs {
wg.Add(1)
go func(addr pb.ServerAddress) {
defer wg.Done()
err := r.dialFiler(ctx, addr, func(c filer_pb.SeaweedFilerClient) error {
resp, err := c.MountList(ctx, &filer_pb.MountListRequest{})
if err != nil {
return err
}
mu.Lock()
for _, m := range resp.Mounts {
if prev, ok := merged[m.PeerAddr]; !ok || m.LastSeenNs > prev.LastSeenNs {
merged[m.PeerAddr] = m
}
}
mu.Unlock()
return nil
})
if err != nil {
mu.Lock()
fails++
mu.Unlock()
glog.V(2).Infof("MountList %s: %v", addr, err)
}
}(addr)
}
wg.Wait()
if fails == len(r.filerAddrs) {
return fmt.Errorf("MountList failed on all %d filer(s)", len(r.filerAddrs))
}
next := make([]SeedPeer, 0, len(merged))
for _, m := range merged {
next = append(next, SeedPeer{PeerAddr: m.PeerAddr, DataCenter: m.DataCenter, Rack: m.Rack})
}
r.mu.Lock()
r.seeds = next
r.mu.Unlock()
return nil
}
func (r *PeerRegistrar) loopRegister() {
t := time.NewTicker(r.registerInterval)
defer t.Stop()
for {
select {
case <-r.stopCtx.Done():
return
case <-t.C:
if err := r.registerOnce(r.stopCtx); err != nil {
glog.V(2).Infof("MountRegister heartbeat: %v", err)
}
}
}
}
func (r *PeerRegistrar) loopList() {
t := time.NewTicker(r.listInterval)
defer t.Stop()
for {
select {
case <-r.stopCtx.Done():
return
case <-t.C:
if err := r.listOnce(r.stopCtx); err != nil {
glog.V(2).Infof("MountList refresh: %v", err)
}
}
}
}
+210
View File
@@ -0,0 +1,210 @@
package mount
import (
"context"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc"
)
// fakeFilerClient captures MountRegister/MountList calls and lets the test
// pre-seed MountList responses. Implements just enough of
// filer_pb.SeaweedFilerClient to drive the registrar.
type fakeFilerClient struct {
filer_pb.SeaweedFilerClient // embed for methods we don't need
mu sync.Mutex
registerCalls []filer_pb.MountRegisterRequest
listResponse filer_pb.MountListResponse
}
func (f *fakeFilerClient) MountRegister(ctx context.Context, req *filer_pb.MountRegisterRequest, opts ...grpc.CallOption) (*filer_pb.MountRegisterResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.registerCalls = append(f.registerCalls, *req)
return &filer_pb.MountRegisterResponse{}, nil
}
func (f *fakeFilerClient) MountList(ctx context.Context, req *filer_pb.MountListRequest, opts ...grpc.CallOption) (*filer_pb.MountListResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
resp := f.listResponse // value copy
return &resp, nil
}
// fakeFilerFleet maps each addr to its own fakeFilerClient so a test can
// simulate several filers with different registered/listed state.
type fakeFilerFleet struct {
clients map[pb.ServerAddress]*fakeFilerClient
}
func (f *fakeFilerFleet) dial(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error {
c, ok := f.clients[addr]
if !ok {
// Treat unknown filer as "reachable but empty" — lets tests omit
// pre-populating a client when they don't care.
c = &fakeFilerClient{}
f.clients[addr] = c
}
return fn(c)
}
func singleFilerFleet(c *fakeFilerClient) ([]pb.ServerAddress, filerDialFn) {
addr := pb.ServerAddress("filer-1:18888")
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{addr: c}}
return []pb.ServerAddress{addr}, fleet.dial
}
func TestPeerRegistrar_StartPopulatesSeedsFromFiler(t *testing.T) {
fc := &fakeFilerClient{
listResponse: filer_pb.MountListResponse{
Mounts: []*filer_pb.MountInfo{
{PeerAddr: "mount-a:18080", Rack: "r1"},
{PeerAddr: "mount-b:18080", Rack: "r2"},
},
},
}
filers, dial := singleFilerFleet(fc)
r := NewPeerRegistrar(filers, dial, "self:18080", "dc1", "r1")
if err := r.registerOnce(context.Background()); err != nil {
t.Fatalf("registerOnce: %v", err)
}
if err := r.listOnce(context.Background()); err != nil {
t.Fatalf("listOnce: %v", err)
}
fc.mu.Lock()
if len(fc.registerCalls) != 1 {
t.Errorf("expected 1 register call, got %d", len(fc.registerCalls))
} else if fc.registerCalls[0].PeerAddr != "self:18080" {
t.Errorf("register sent wrong peer addr: %q", fc.registerCalls[0].PeerAddr)
}
fc.mu.Unlock()
seeds := r.Seeds()
if len(seeds) != 2 {
t.Errorf("expected 2 seeds, got %d", len(seeds))
}
owner := r.OwnerFor("3,01637037d6")
if owner != "mount-a:18080" && owner != "mount-b:18080" {
t.Errorf("OwnerFor returned unexpected addr: %q", owner)
}
}
func TestPeerRegistrar_HeartbeatTTLMatchesConfig(t *testing.T) {
fc := &fakeFilerClient{}
filers, dial := singleFilerFleet(fc)
r := NewPeerRegistrar(filers, dial, "self:18080", "", "")
if err := r.registerOnce(context.Background()); err != nil {
t.Fatalf("registerOnce: %v", err)
}
fc.mu.Lock()
defer fc.mu.Unlock()
if len(fc.registerCalls) != 1 {
t.Fatalf("expected 1 register call, got %d", len(fc.registerCalls))
}
want := int32(r.registerTTL.Seconds())
if got := fc.registerCalls[0].TtlSeconds; got != want {
t.Errorf("TtlSeconds: got %d want %d", got, want)
}
}
func TestPeerRegistrar_StopIsIdempotent(t *testing.T) {
filers, dial := singleFilerFleet(&fakeFilerClient{})
r := NewPeerRegistrar(filers, dial, "self:18080", "", "")
r.Stop()
r.Stop() // second call must be a no-op (no panic)
}
// TestPeerRegistrar_RegisterBroadcastsToAllFilers guards the core
// multi-filer property: a single registerOnce must hit every configured
// filer so mounts pointing at different filers still converge.
func TestPeerRegistrar_RegisterBroadcastsToAllFilers(t *testing.T) {
fc1 := &fakeFilerClient{}
fc2 := &fakeFilerClient{}
fc3 := &fakeFilerClient{}
a1, a2, a3 := pb.ServerAddress("f1:18888"), pb.ServerAddress("f2:18888"), pb.ServerAddress("f3:18888")
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{a1: fc1, a2: fc2, a3: fc3}}
r := NewPeerRegistrar([]pb.ServerAddress{a1, a2, a3}, fleet.dial, "self:18080", "", "")
if err := r.registerOnce(context.Background()); err != nil {
t.Fatalf("registerOnce: %v", err)
}
for addr, fc := range fleet.clients {
fc.mu.Lock()
if len(fc.registerCalls) != 1 {
t.Errorf("filer %s: got %d register calls, want 1", addr, len(fc.registerCalls))
}
fc.mu.Unlock()
}
}
// TestPeerRegistrar_ListMergesAcrossFilers guards cross-filer convergence:
// mount A registered on filer-1, mount B on filer-2; a registrar that
// lists both filers must see both mounts.
func TestPeerRegistrar_ListMergesAcrossFilers(t *testing.T) {
fc1 := &fakeFilerClient{
listResponse: filer_pb.MountListResponse{
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-a:18080", Rack: "r1", LastSeenNs: 200}},
},
}
fc2 := &fakeFilerClient{
listResponse: filer_pb.MountListResponse{
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-b:18080", Rack: "r2", LastSeenNs: 200}},
},
}
a1, a2 := pb.ServerAddress("f1:18888"), pb.ServerAddress("f2:18888")
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{a1: fc1, a2: fc2}}
r := NewPeerRegistrar([]pb.ServerAddress{a1, a2}, fleet.dial, "self:18080", "", "")
if err := r.listOnce(context.Background()); err != nil {
t.Fatalf("listOnce: %v", err)
}
seeds := r.Seeds()
if len(seeds) != 2 {
t.Fatalf("want 2 merged seeds, got %d: %+v", len(seeds), seeds)
}
addrs := map[string]bool{}
for _, s := range seeds {
addrs[s.PeerAddr] = true
}
if !addrs["mount-a:18080"] || !addrs["mount-b:18080"] {
t.Errorf("merged seeds missing an entry: %+v", addrs)
}
}
// TestPeerRegistrar_ListMergeKeepsNewestLastSeen guards the dedupe rule:
// the same mount reported by two filers collapses to one entry, keeping
// the freshest LastSeenNs for liveness-ordering decisions.
func TestPeerRegistrar_ListMergeKeepsNewestLastSeen(t *testing.T) {
fc1 := &fakeFilerClient{
listResponse: filer_pb.MountListResponse{
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-a:18080", Rack: "r1", LastSeenNs: 100}},
},
}
fc2 := &fakeFilerClient{
listResponse: filer_pb.MountListResponse{
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-a:18080", Rack: "r1", LastSeenNs: 500}},
},
}
a1, a2 := pb.ServerAddress("f1:18888"), pb.ServerAddress("f2:18888")
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{a1: fc1, a2: fc2}}
r := NewPeerRegistrar([]pb.ServerAddress{a1, a2}, fleet.dial, "self:18080", "", "")
if err := r.listOnce(context.Background()); err != nil {
t.Fatalf("listOnce: %v", err)
}
seeds := r.Seeds()
if len(seeds) != 1 {
t.Fatalf("want 1 deduped seed, got %d", len(seeds))
}
}
+88 -27
View File
@@ -27,6 +27,12 @@ type inodeLocks struct {
locks []lockRange // currently held locks, sorted by Start
waiters []*lockWaiter // blocked SetLkw callers
wakeRefs int // woken waiters still retrying on this inodeLocks
// dead marks an inodeLocks that has been removed from the table's map.
// A caller holding a pointer returned by getInodeLocks/getOrCreateInodeLocks
// must recheck this flag after acquiring il.mu: if true, the pointer is
// orphaned and must be refreshed from the table so findConflict runs
// against the live state.
dead bool
}
// lockWaiter represents a blocked SetLkw caller.
@@ -48,12 +54,17 @@ func NewPosixLockTable() *PosixLockTable {
}
}
// getOrCreateInodeLocks returns the lock state for an inode, creating it if needed.
// getOrCreateInodeLocks returns the lock state for an inode, creating it if
// needed. A dead entry (which maybeCleanupInode normally evicts together
// with setting dead) is replaced transparently so callers never observe one
// via this path and the SetLk retry loop cannot spin on a stale map entry.
// The il.dead read is safe without il.mu: dead transitions only under both
// plt.mu and il.mu, so holding plt.mu here is sufficient happens-before.
func (plt *PosixLockTable) getOrCreateInodeLocks(inode uint64) *inodeLocks {
plt.mu.Lock()
defer plt.mu.Unlock()
il, ok := plt.inodes[inode]
if !ok {
if !ok || il.dead {
il = &inodeLocks{}
plt.inodes[inode] = il
}
@@ -61,14 +72,29 @@ func (plt *PosixLockTable) getOrCreateInodeLocks(inode uint64) *inodeLocks {
}
// getInodeLocks returns the lock state for an inode, or nil if none exists.
// A dead entry (which maybeCleanupInode normally evicts together with setting
// dead) is dropped so callers never observe an orphaned inodeLocks via this
// path. The il.dead read is safe without il.mu for the same reason as in
// getOrCreateInodeLocks: transitions happen under both plt.mu and il.mu.
func (plt *PosixLockTable) getInodeLocks(inode uint64) *inodeLocks {
plt.mu.Lock()
defer plt.mu.Unlock()
return plt.inodes[inode]
il, ok := plt.inodes[inode]
if !ok {
return nil
}
if il.dead {
delete(plt.inodes, inode)
return nil
}
return il
}
// maybeCleanupInode removes the inodeLocks entry if it has no locks, no waiters,
// and no woken waiters still retrying against this inodeLocks.
// and no woken waiters still retrying against this inodeLocks. The removed
// inodeLocks is marked dead so any caller that is mid-way through acquiring
// il.mu with a stale pointer will notice and refetch from the map instead of
// mutating an orphaned instance (which would be invisible to future callers).
func (plt *PosixLockTable) maybeCleanupInode(inode uint64, il *inodeLocks) {
// Caller must NOT hold il.mu. We acquire both locks in the correct order.
plt.mu.Lock()
@@ -76,7 +102,10 @@ func (plt *PosixLockTable) maybeCleanupInode(inode uint64, il *inodeLocks) {
il.mu.Lock()
defer il.mu.Unlock()
if len(il.locks) == 0 && len(il.waiters) == 0 && il.wakeRefs == 0 {
delete(plt.inodes, inode)
if plt.inodes[inode] == il {
delete(plt.inodes, inode)
}
il.dead = true
}
}
@@ -247,22 +276,32 @@ func removeWaiter(il *inodeLocks, w *lockWaiter) {
// GetLk checks for a conflicting lock. If found, it populates out with the
// conflict details. If no conflict, out.Typ is set to F_UNLCK.
func (plt *PosixLockTable) GetLk(inode uint64, proposed lockRange, out *fuse.LkOut) {
il := plt.getInodeLocks(inode)
if il == nil {
out.Lk.Typ = syscall.F_UNLCK
return
}
il.mu.Lock()
conflict, found := findConflict(il.locks, proposed)
il.mu.Unlock()
for {
il := plt.getInodeLocks(inode)
if il == nil {
out.Lk.Typ = syscall.F_UNLCK
return
}
il.mu.Lock()
if il.dead {
// Orphaned by a concurrent cleanup: the map may already hold a
// fresh inodeLocks with different state, so answering from this
// stale pointer would miss real conflicts. Refetch.
il.mu.Unlock()
continue
}
conflict, found := findConflict(il.locks, proposed)
il.mu.Unlock()
if found {
out.Lk.Start = conflict.Start
out.Lk.End = conflict.End
out.Lk.Typ = conflict.Typ
out.Lk.Pid = conflict.Pid
} else {
out.Lk.Typ = syscall.F_UNLCK
if found {
out.Lk.Start = conflict.Start
out.Lk.End = conflict.End
out.Lk.Typ = conflict.Typ
out.Lk.Pid = conflict.Pid
} else {
out.Lk.Typ = syscall.F_UNLCK
}
return
}
}
@@ -276,6 +315,13 @@ func (plt *PosixLockTable) SetLk(inode uint64, lk lockRange) fuse.Status {
return fuse.OK
}
il.mu.Lock()
if il.dead {
// Orphaned by a concurrent cleanup: any lock we may have held
// is gone with it, and there is no point waking waiters on a
// detached inodeLocks.
il.mu.Unlock()
return fuse.OK
}
removeLocks(il, func(existing lockRange) bool {
return existing.Owner == lk.Owner && existing.IsFlock == lk.IsFlock
}, lk.Start, lk.End)
@@ -285,15 +331,21 @@ func (plt *PosixLockTable) SetLk(inode uint64, lk lockRange) fuse.Status {
return fuse.OK
}
il := plt.getOrCreateInodeLocks(inode)
il.mu.Lock()
if _, found := findConflict(il.locks, lk); found {
for {
il := plt.getOrCreateInodeLocks(inode)
il.mu.Lock()
if il.dead {
il.mu.Unlock()
continue
}
if _, found := findConflict(il.locks, lk); found {
il.mu.Unlock()
return fuse.EAGAIN
}
insertAndCoalesce(il, lk)
il.mu.Unlock()
return fuse.EAGAIN
return fuse.OK
}
insertAndCoalesce(il, lk)
il.mu.Unlock()
return fuse.OK
}
// SetLkw attempts a blocking lock. It waits until the lock can be acquired
@@ -307,6 +359,15 @@ func (plt *PosixLockTable) SetLkw(inode uint64, lk lockRange, cancel <-chan stru
var waiter *lockWaiter
for {
il.mu.Lock()
if il.dead {
// The inodeLocks we were holding was orphaned by a concurrent
// cleanup. Refetch the live instance from the table and retry.
// A dead il never has waiters or wakeRefs (the cleanup condition
// requires both to be zero), so waiter is guaranteed nil here.
il.mu.Unlock()
il = plt.getOrCreateInodeLocks(inode)
continue
}
releaseWakeRef(il, waiter)
if _, found := findConflict(il.locks, lk); !found {
insertAndCoalesce(il, lk)
+207
View File
@@ -2,6 +2,9 @@ package mount
import (
"math"
"runtime"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
@@ -615,3 +618,207 @@ func TestAdjacencyNoOverflowAtMaxUint64(t *testing.T) {
t.Fatalf("expected 2 separate locks (no overflow merge), got %d", ownerLocks)
}
}
// TestSetLkRetriesPastDeadInodeLocks deterministically exercises the
// getOrCreateInodeLocks vs maybeCleanupInode race: a caller holding a
// pointer to an inodeLocks that is concurrently marked dead must refetch
// from the map instead of mutating the orphaned instance (which would be
// invisible to subsequent callers and let two exclusive flock holders
// coexist). The test bypasses scheduling by hand-installing a dead il into
// the table and asserting that the next SetLk routes around it.
func TestSetLkRetriesPastDeadInodeLocks(t *testing.T) {
plt := NewPosixLockTable()
inode := uint64(42)
// Acquire and release a lock so maybeCleanupInode marks the il dead and
// removes it from the map.
lock := lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 1, IsFlock: true}
if s := plt.SetLk(inode, lock); s != fuse.OK {
t.Fatalf("prime SetLk: got %v", s)
}
dead := plt.getInodeLocks(inode)
unlock := lock
unlock.Typ = syscall.F_UNLCK
if s := plt.SetLk(inode, unlock); s != fuse.OK {
t.Fatalf("prime unlock: got %v", s)
}
if !dead.dead {
t.Fatal("expected il to be marked dead after unlock+cleanup")
}
plt.mu.Lock()
_, stillMapped := plt.inodes[inode]
plt.mu.Unlock()
if stillMapped {
t.Fatal("expected the dead il to be removed from the map")
}
// Simulate the race: the next caller's getOrCreateInodeLocks races with
// the cleanup and ends up holding a pointer to the dead il. We force that
// state by re-publishing `dead` into the map.
plt.mu.Lock()
plt.inodes[inode] = dead
plt.mu.Unlock()
// SetLk must notice dead, refetch, and install the new lock in a fresh il.
if s := plt.SetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 2, IsFlock: true}); s != fuse.OK {
t.Fatalf("SetLk after dead: got %v", s)
}
dead.mu.Lock()
if n := len(dead.locks); n != 0 {
t.Fatalf("dead il should not have accepted the insert, found %d locks", n)
}
dead.mu.Unlock()
plt.mu.Lock()
live := plt.inodes[inode]
plt.mu.Unlock()
if live == nil || live == dead {
t.Fatalf("expected a fresh live il, got %v", live)
}
// A conflicting owner must see the new lock and be rejected.
if s := plt.SetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 3, IsFlock: true}); s != fuse.EAGAIN {
t.Fatalf("second owner should conflict with owner 2, got %v", s)
}
// GetLk must report the conflict as well: without the dead-recheck the
// GetLk path would answer F_UNLCK off the orphaned il.
var out fuse.LkOut
plt.GetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 4, IsFlock: true}, &out)
if out.Lk.Typ != syscall.F_WRLCK {
t.Fatalf("GetLk should report the live conflict, got Typ=%d", out.Lk.Typ)
}
}
// TestGetInodeLocksEvictsDeadEntry verifies that a dead inodeLocks which
// somehow ends up in the map (e.g. through a future refactor that reorders
// delete and dead=true) is dropped on read so callers never observe one.
// This is the backstop that lets GetLk's and SetLk's retry loops terminate.
func TestGetInodeLocksEvictsDeadEntry(t *testing.T) {
plt := NewPosixLockTable()
inode := uint64(42)
lock := lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 1, IsFlock: true}
if s := plt.SetLk(inode, lock); s != fuse.OK {
t.Fatalf("prime SetLk: got %v", s)
}
dead := plt.getInodeLocks(inode)
unlock := lock
unlock.Typ = syscall.F_UNLCK
if s := plt.SetLk(inode, unlock); s != fuse.OK {
t.Fatalf("prime unlock: got %v", s)
}
if !dead.dead {
t.Fatal("expected dead after cleanup")
}
// Force the broken state that production cannot reach but tests and
// future refactors might: dead entry still in the map.
plt.mu.Lock()
plt.inodes[inode] = dead
plt.mu.Unlock()
if il := plt.getInodeLocks(inode); il != nil {
t.Fatalf("getInodeLocks should drop a dead map entry, got %p", il)
}
plt.mu.Lock()
_, stillMapped := plt.inodes[inode]
plt.mu.Unlock()
if stillMapped {
t.Fatal("expected dead entry to be removed from the map")
}
// getOrCreateInodeLocks must also self-heal (replace the dead entry with
// a fresh live one) so SetLk's retry path cannot spin.
plt.mu.Lock()
plt.inodes[inode] = dead
plt.mu.Unlock()
fresh := plt.getOrCreateInodeLocks(inode)
if fresh == dead {
t.Fatal("getOrCreateInodeLocks should not return a dead entry")
}
if fresh.dead {
t.Fatal("fresh entry should not be dead")
}
}
// TestConcurrentFlockChurnPreservesMutualExclusion is a stress companion to
// the deterministic tests above. It uses a Swap+CAS detector that flags
// overlap at two points (on acquire and on release), so a second granted
// holder is caught even if it sneaks in after the first goroutine's claim
// but before its release. 16 goroutines churn whole-file exclusive flock on
// one inode; with the race the detector fires hundreds of times per run,
// with the fix it stays at zero.
func TestConcurrentFlockChurnPreservesMutualExclusion(t *testing.T) {
plt := NewPosixLockTable()
const (
inode = uint64(42)
numWorkers = 16
iterations = 500
)
var (
wg sync.WaitGroup
holder atomic.Int64 // 0 = nobody; otherwise = holder's claim token
overlapSeen atomic.Int32
)
for w := 0; w < numWorkers; w++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
owner := uint64(100 + id)
lock := lockRange{
Start: 0,
End: math.MaxUint64,
Typ: syscall.F_WRLCK,
Owner: owner,
Pid: uint32(id + 1),
IsFlock: true,
}
unlock := lock
unlock.Typ = syscall.F_UNLCK
token := int64(id + 1)
for i := 0; i < iterations; i++ {
// SetLk(WRLCK) may only return OK (granted) or EAGAIN
// (conflict); anything else indicates a bug and the test
// must fail rather than spin. Use Errorf + return because
// Fatalf is not safe from a non-test goroutine.
for {
s := plt.SetLk(inode, lock)
if s == fuse.OK {
break
}
if s != fuse.EAGAIN {
t.Errorf("worker %d iter %d: unexpected SetLk(WRLCK) status %v", id, i, s)
return
}
runtime.Gosched()
}
// Claim the slot. If Swap observes a non-zero predecessor,
// another goroutine already believes it holds the lock.
if prev := holder.Swap(token); prev != 0 {
overlapSeen.Add(1)
}
// Widen the window so a concurrently-granted peer has a
// chance to race into its own Swap before we release.
runtime.Gosched()
runtime.Gosched()
// Release the slot. If CAS fails someone else overwrote our
// claim, which only happens when two holders raced.
if !holder.CompareAndSwap(token, 0) {
overlapSeen.Add(1)
}
if s := plt.SetLk(inode, unlock); s != fuse.OK {
t.Errorf("worker %d iter %d: unexpected SetLk(UNLCK) status %v", id, i, s)
return
}
}
}(w)
}
wg.Wait()
if n := overlapSeen.Load(); n != 0 {
t.Fatalf("flock overlap detected %d times: two owners simultaneously granted the same exclusive lock", n)
}
}
+129 -6
View File
@@ -82,6 +82,16 @@ type Option struct {
RdmaMaxConcurrent int
RdmaTimeoutMs int
// Peer chunk sharing options (design-weed-mount-peer-chunk-sharing.md).
// When PeerEnabled is false (default), the mount runs exactly as today.
// One gRPC port carries everything: directory RPCs (ChunkAnnounce /
// ChunkLookup) and streaming FetchChunk byte transfers.
PeerEnabled bool
PeerListen string // host:port to bind the peer gRPC server
PeerAdvertise string // externally reachable host:port (optional; defaults to auto-detected host + PeerListen port)
PeerDataCenter string // optional data-center label advertised to peers
PeerRack string // optional rack label advertised to peers (finer than DC)
// Directory cache refresh/eviction controls
DirIdleEvictSec int
@@ -129,6 +139,12 @@ type WFS struct {
hardLinkLockTable *util.LockTable[string]
posixLocks *PosixLockTable
rdmaClient *RDMAMountClient
peerRegistrar *PeerRegistrar
peerDirectory *PeerDirectory
peerGrpcServer *PeerGrpcServer
peerAnnouncer *PeerAnnouncer
peerConnPool *PeerConnPool
peerDirectoryStop chan struct{} // closed on unmount to stop the sweeper goroutine
FilerConf *filer.FilerConf
filerClient *wdclient.FilerClient // Cached volume location client
refreshMu sync.Mutex
@@ -142,7 +158,14 @@ type WFS struct {
dirHotWindow time.Duration
dirHotThreshold int
dirIdleEvict time.Duration
fileIdPool *FileIdPool
// openMtimeCache maps inode -> [mtime_sec, mtime_ns] from the last Open.
// Used to decide whether to set FOPEN_KEEP_CACHE on subsequent opens.
// Bounded to openMtimeCacheMaxSize entries; when full a random entry is
// evicted. This trades a small amount of cache-miss overhead for
// predictable memory usage on mounts that touch many files.
openMtimeMu sync.Mutex
openMtimeCache map[uint64][2]int64
// asyncFlushWg tracks pending background flush work items for writebackCache mode.
// Must be waited on before unmount cleanup to prevent data loss.
@@ -221,6 +244,7 @@ func NewSeaweedFileSystem(option *Option) *WFS {
posixLocks: NewPosixLockTable(),
refreshingDirs: make(map[util.FullPath]struct{}),
atimeMap: make(map[uint64]time.Time, 8192),
openMtimeCache: make(map[uint64][2]int64, 8192),
dirMtimeMap: make(map[uint64]time.Time, 1024),
entryValidSec: 1,
attrValidSec: 1,
@@ -318,6 +342,26 @@ func NewSeaweedFileSystem(option *Option) *WFS {
if wfs.rdmaClient != nil {
wfs.rdmaClient.Close()
}
if wfs.peerAnnouncer != nil {
wfs.peerAnnouncer.Stop()
}
if wfs.peerConnPool != nil {
wfs.peerConnPool.Close()
}
if wfs.peerGrpcServer != nil {
wfs.peerGrpcServer.Stop()
}
if wfs.peerDirectoryStop != nil {
select {
case <-wfs.peerDirectoryStop:
// already closed
default:
close(wfs.peerDirectoryStop)
}
}
if wfs.peerRegistrar != nil {
wfs.peerRegistrar.Stop()
}
})
// Initialize RDMA client if enabled
@@ -337,6 +381,90 @@ func NewSeaweedFileSystem(option *Option) *WFS {
}
}
// Peer chunk sharing: register with every configured filer's mount
// registry + start the single gRPC server that handles ChunkAnnounce /
// ChunkLookup / FetchChunk. Broadcasting registration to the full
// filer set is what lets mounts pointing at different filers see
// each other — each filer's registry is in-memory with no
// filer-to-filer sync, so the registrar reconstructs the union
// client-side. One port, one identity — the advertise address
// resolved in PR #3 is used for everything.
if option.PeerEnabled {
selfAddr, err := ResolvePeerAdvertiseAddr(option.PeerListen, option.PeerAdvertise)
if err != nil {
// Downstream code treats PeerEnabled as "peer infrastructure
// is ready": later PRs wire the gRPC server, fetcher hook,
// and announcer from this flag. If we can't resolve a
// reachable self-address those components would nil-deref
// or advertise garbage, so disable the feature instead of
// limping along half-initialized.
glog.Warningf("peer: cannot resolve advertise addr, disabling peer sharing: %v", err)
option.PeerEnabled = false
} else {
dial := func(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error {
return pb.WithGrpcFilerClient(false, 0, addr, option.GrpcDialOption, fn)
}
wfs.peerRegistrar = NewPeerRegistrar(option.FilerAddresses, dial, selfAddr, option.PeerDataCenter, option.PeerRack)
if err := wfs.peerRegistrar.Start(context.Background()); err != nil {
glog.Warningf("peer registrar start: %v", err)
}
wfs.peerDirectory = NewPeerDirectory()
// Wire TLS/mTLS from security.toml's grpc.mount section so
// cross-host peer RPCs are authenticated + encrypted. When
// the section is empty both options come back nil and the
// server runs plaintext — intentional for dev/test.
peerTLSCreds, peerTLSVerify := security.LoadServerTLS(util.GetViper(), "grpc.mount")
var peerServerOpts []grpc.ServerOption
if peerTLSCreds != nil {
peerServerOpts = append(peerServerOpts, peerTLSCreds)
}
if peerTLSVerify != nil {
peerServerOpts = append(peerServerOpts, peerTLSVerify)
}
wfs.peerGrpcServer = NewPeerGrpcServer(
wfs.chunkCache,
wfs.peerDirectory,
wfs.peerRegistrar.OwnerFor,
selfAddr,
peerServerOpts...,
)
if err := wfs.peerGrpcServer.Start(option.PeerListen); err != nil {
glog.Warningf("peer grpc start: %v", err)
wfs.peerGrpcServer = nil
} else {
wfs.peerDirectoryStop = make(chan struct{})
go wfs.runPeerDirectorySweeper(wfs.peerDirectoryStop)
// Shared connection pool + announcer. Pool reuses one
// grpc.ClientConn per owner mount across both the
// announcer flush and the fetcher's ChunkLookup +
// FetchChunk calls. Transport credentials come from
// option.GrpcDialOption (security.LoadClientTLS), so
// peer dials match the TLS posture the server wants.
wfs.peerConnPool = NewPeerConnPool(option.GrpcDialOption)
wfs.peerAnnouncer = NewPeerAnnouncer(
selfAddr,
option.PeerDataCenter,
option.PeerRack,
wfs.peerRegistrar.OwnerFor,
wfs.peerConnPool.Dialer(),
wfs.peerDirectory,
)
// Close the write→announce race: between SetChunk and
// the flush tick (up to 15 s) the cache can LRU-evict
// the chunk. Skip announcing fids we no longer hold.
if wfs.chunkCache != nil {
cache := wfs.chunkCache
wfs.peerAnnouncer.SetCachePresence(func(fid string) bool {
return cache.IsInCache(fid, true)
})
}
wfs.peerAnnouncer.Start()
}
}
}
if wfs.option.ConcurrentWriters > 0 {
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(wfs.option.ConcurrentWriters)
wfs.concurrentCopiersSem = make(chan struct{}, wfs.option.ConcurrentWriters)
@@ -378,11 +506,6 @@ func (wfs *WFS) StartBackgroundTasks() error {
go wfs.loopEvictIdleDirCache()
go wfs.loopProactiveFlush()
if wfs.option.WritebackCache {
wfs.fileIdPool = NewFileIdPool(wfs)
glog.V(0).Infof("file ID pool enabled for writeback cache (batch=%d)", wfs.fileIdPool.batchSize)
}
return nil
}
+3
View File
@@ -74,6 +74,9 @@ func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse
if size, ok := input.GetSize(); ok {
glog.V(4).Infof("%v setattr set size=%v chunks=%d", path, size, len(entry.GetChunks()))
// Invalidate the open-mtime cache so the next Open does not set
// FOPEN_KEEP_CACHE with stale kernel page cache data.
wfs.invalidateOpenMtimeCache(input.NodeId)
if size < filer.FileSize(entry) {
// fmt.Printf("truncate %v \n", fullPath)
var chunks []*filer_pb.FileChunk
+5 -14
View File
@@ -251,7 +251,11 @@ func (wfs *WFS) applyServerSideWholeFileCopyResult(fhIn, fhOut *FileHandle, dstP
}
fhOut.dirtyMetadata = false
wfs.updateServerSideWholeFileCopyMetaCache(dstPath, entry)
wfs.invalidateCopyDestinationCache(fhOut.inode, dstPath)
// Note: we intentionally skip fuseServer.InodeNotify/EntryNotify here.
// This runs inside the CopyFileRange request handler; those notifies
// would write onto the same /dev/fuse fd the kernel is still waiting
// on for this request's reply, deadlocking the mount. The kernel will
// re-read attrs once its attr-cache TTL expires.
}
func (wfs *WFS) updateServerSideWholeFileCopyMetaCache(dstPath util.FullPath, entry *filer_pb.Entry) {
@@ -501,16 +505,3 @@ func (wfs *WFS) filerCopyJWT() security.EncodedJwt {
return security.GenJwtForFilerServer(wfs.option.FilerSigningKey, wfs.option.FilerSigningExpiresAfterSec)
}
func (wfs *WFS) invalidateCopyDestinationCache(inode uint64, fullPath util.FullPath) {
if wfs.fuseServer != nil {
if status := wfs.fuseServer.InodeNotify(inode, 0, -1); status != fuse.OK {
glog.V(4).Infof("CopyFileRange invalidate inode %d: %v", inode, status)
}
dir, name := fullPath.DirAndName()
if parentInode, found := wfs.inodeToPath.GetInode(util.FullPath(dir)); found {
if status := wfs.fuseServer.EntryNotify(parentInode, name); status != fuse.OK {
glog.V(4).Infof("CopyFileRange invalidate entry %s: %v", fullPath, status)
}
}
}
}
+39 -1
View File
@@ -64,7 +64,15 @@ func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut)
if status == fuse.OK {
out.Fh = uint64(fileHandle.fh)
out.OpenFlags = 0
// TODO https://github.com/libfuse/libfuse/blob/master/include/fuse_common.h#L64
// For read-only opens, set FOPEN_KEEP_CACHE when the file's mtime
// has not changed since the last open. This tells the kernel to
// preserve its existing page cache, avoiding redundant reads.
if in.Flags&fuse.O_ANYWRITE == 0 {
if entry := fileHandle.GetEntry(); entry != nil && entry.Attributes != nil {
wfs.applyKeepCacheFlag(in.NodeId, entry, out)
}
}
}
return status
}
@@ -94,6 +102,36 @@ func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut)
* @param ino the inode number
* @param fi file information
*/
const openMtimeCacheMaxSize = 8192
// applyKeepCacheFlag compares the entry's mtime (seconds + nanoseconds) against
// the last-seen value and sets FOPEN_KEEP_CACHE when unchanged.
func (wfs *WFS) applyKeepCacheFlag(inode uint64, entry *LockedEntry, out *fuse.OpenOut) {
currentMtime := [2]int64{entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)}
wfs.openMtimeMu.Lock()
prev, loaded := wfs.openMtimeCache[inode]
if loaded && prev == currentMtime {
out.OpenFlags |= fuse.FOPEN_KEEP_CACHE
} else {
if len(wfs.openMtimeCache) >= openMtimeCacheMaxSize {
for k := range wfs.openMtimeCache {
delete(wfs.openMtimeCache, k)
break
}
}
wfs.openMtimeCache[inode] = currentMtime
}
wfs.openMtimeMu.Unlock()
}
// invalidateOpenMtimeCache removes an inode's cached mtime so the next Open
// does not set FOPEN_KEEP_CACHE with stale kernel page cache data.
func (wfs *WFS) invalidateOpenMtimeCache(inode uint64) {
wfs.openMtimeMu.Lock()
delete(wfs.openMtimeCache, inode)
wfs.openMtimeMu.Unlock()
}
func (wfs *WFS) Release(cancel <-chan struct{}, in *fuse.ReleaseIn) {
if in.ReleaseFlags&fuse.FUSE_RELEASE_FLOCK_UNLOCK != 0 {
wfs.posixLocks.ReleaseFlockOwner(in.NodeId, in.LockOwner)
+206
View File
@@ -0,0 +1,206 @@
package mount
import (
"testing"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func newTestWFS() *WFS {
return &WFS{
openMtimeCache: make(map[uint64][2]int64, 8192),
}
}
func TestOpenKeepCache_FirstOpen(t *testing.T) {
// First open of a file should NOT set FOPEN_KEEP_CACHE because there
// is no previously cached mtime to compare against.
wfs := newTestWFS()
var out fuse.OpenOut
inode := uint64(42)
entry := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 123},
},
}
wfs.applyKeepCacheFlag(inode, entry, &out)
if out.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
t.Error("first open should not set FOPEN_KEEP_CACHE")
}
}
func TestOpenKeepCache_SecondOpenSameMtime(t *testing.T) {
// Second open with an unchanged mtime SHOULD set FOPEN_KEEP_CACHE.
wfs := newTestWFS()
inode := uint64(42)
entry := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 123},
},
}
// First open -- populate cache.
var out1 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry, &out1)
// Second open -- mtime unchanged.
var out2 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry, &out2)
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE == 0 {
t.Error("second open with same mtime should set FOPEN_KEEP_CACHE")
}
}
func TestOpenKeepCache_MtimeChanged(t *testing.T) {
// If the file's mtime changes between opens, FOPEN_KEEP_CACHE must NOT
// be set so the kernel invalidates its page cache.
wfs := newTestWFS()
inode := uint64(42)
entry1 := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
},
}
// First open.
var out1 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry1, &out1)
// File is modified externally -- mtime changes.
entry2 := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 2000, MtimeNs: 0},
},
}
var out2 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry2, &out2)
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
t.Error("open after mtime change should not set FOPEN_KEEP_CACHE")
}
}
func TestOpenKeepCache_NanosecondPrecision(t *testing.T) {
// Two modifications within the same second but different nanoseconds
// must NOT reuse cached page data.
wfs := newTestWFS()
inode := uint64(42)
entry1 := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 100},
},
}
var out1 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry1, &out1)
// Same second, different nanosecond.
entry2 := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 200},
},
}
var out2 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry2, &out2)
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
t.Error("open after nanosecond-level mtime change should not set FOPEN_KEEP_CACHE")
}
}
func TestOpenKeepCache_WriteInvalidation(t *testing.T) {
// After a write invalidates the mtime cache, the next open should NOT
// set FOPEN_KEEP_CACHE.
wfs := newTestWFS()
inode := uint64(42)
entry := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
},
}
// First open -- populate cache.
var out1 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry, &out1)
// Simulate write invalidation.
wfs.invalidateOpenMtimeCache(inode)
// Next open -- cache was invalidated.
var out2 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry, &out2)
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
t.Error("open after write invalidation should not set FOPEN_KEEP_CACHE")
}
}
func TestOpenKeepCache_WriteOpenSkipped(t *testing.T) {
// Write-mode opens should never evaluate FOPEN_KEEP_CACHE.
// The caller (WFS.Open) gates on O_ANYWRITE before calling
// applyKeepCacheFlag, so we verify the gate logic here.
wfs := newTestWFS()
inode := uint64(42)
entry := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
},
}
// Populate cache.
var out1 fuse.OpenOut
wfs.applyKeepCacheFlag(inode, entry, &out1)
// Simulate write-mode open: the caller would skip applyKeepCacheFlag.
var out2 fuse.OpenOut
flags := uint32(fuse.O_ANYWRITE)
if flags&fuse.O_ANYWRITE == 0 {
wfs.applyKeepCacheFlag(inode, entry, &out2)
}
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
t.Error("write open should not set FOPEN_KEEP_CACHE")
}
}
func TestOpenKeepCache_BoundedEviction(t *testing.T) {
// Verify the cache doesn't grow beyond openMtimeCacheMaxSize.
wfs := newTestWFS()
entry := &LockedEntry{
Entry: &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
},
}
for i := uint64(0); i < openMtimeCacheMaxSize+100; i++ {
var out fuse.OpenOut
wfs.applyKeepCacheFlag(i, entry, &out)
}
wfs.openMtimeMu.Lock()
size := len(wfs.openMtimeCache)
wfs.openMtimeMu.Unlock()
if size > openMtimeCacheMaxSize {
t.Errorf("cache size %d exceeds max %d", size, openMtimeCacheMaxSize)
}
}
+1
View File
@@ -489,6 +489,7 @@ func (wfs *WFS) truncateEntry(entryFullPath util.FullPath, entry *filer_pb.Entry
}
if inode, found := wfs.inodeToPath.GetInode(entryFullPath); found {
wfs.invalidateOpenMtimeCache(inode)
if fh, fhFound := wfs.fhMap.FindFileHandle(inode); fhFound {
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("truncateEntry", fh.fh, util.ExclusiveLock)
fh.ResetDirtyPages()
+8 -1
View File
@@ -268,6 +268,13 @@ func shouldMergeChunks(compactedChunks []*filer_pb.FileChunk, manifestChunks []*
for _, chunk := range compactedChunks {
totalChunkSize += chunk.Size
}
// Count manifest coverage toward stored total. Each manifest holds
// sub-chunks on volume servers that cover approximately Size bytes.
// Without this, overlapping manifests accumulate undetected because
// the merge condition only saw the (small) non-manifest chunk total.
for _, chunk := range manifestChunks {
totalChunkSize += chunk.Size
}
allChunks := make([]*filer_pb.FileChunk, 0, len(compactedChunks)+len(manifestChunks))
allChunks = append(allChunks, compactedChunks...)
allChunks = append(allChunks, manifestChunks...)
@@ -308,7 +315,7 @@ func (wfs *WFS) maybeMergeChunks(fileFullPath util.FullPath, compactedChunks []*
for {
n, readErr := io.ReadFull(reader, buf)
if n > 0 {
chunk, uploadErr := saveFunc(bytes.NewReader(buf[:n]), "", offset, 0)
chunk, uploadErr := saveFunc(bytes.NewReader(buf[:n]), "", offset, 0, uint64(n))
if uploadErr != nil {
return nil, uploadErr
}
+108 -7
View File
@@ -2,6 +2,7 @@ package mount
import (
"context"
"fmt"
"math"
"math/rand/v2"
"testing"
@@ -68,7 +69,8 @@ func TestShouldMergeChunks_JustOverDouble(t *testing.T) {
}
func TestShouldMergeChunks_ManifestExtendFileSize(t *testing.T) {
// Compacted chunks are small relative to file extended by manifest.
// One manifest extends the file. Total stored = 100 (regular) + 900
// (manifest) = 1000 vs 2*1000 = 2000 → no merge.
compacted := []*filer_pb.FileChunk{
{Offset: 0, Size: 100, FileId: "a", ModifiedTsNs: 1},
}
@@ -77,12 +79,13 @@ func TestShouldMergeChunks_ManifestExtendFileSize(t *testing.T) {
}
_, _, merge := shouldMergeChunks(compacted, manifest)
if merge {
t.Fatal("manifest-extended file should not merge when compacted chunks are small")
t.Fatal("single manifest extending file should not merge")
}
}
func TestShouldMergeChunks_ManifestChunksSizeIgnored(t *testing.T) {
// Only compacted chunk sizes count toward totalChunkSize.
func TestShouldMergeChunks_ManifestSizesCounted(t *testing.T) {
// Manifest sizes must count toward totalChunkSize so that overlapping
// manifests trigger merge.
compacted := []*filer_pb.FileChunk{
{Offset: 0, Size: 100, FileId: "a", ModifiedTsNs: 1},
}
@@ -90,11 +93,35 @@ func TestShouldMergeChunks_ManifestChunksSizeIgnored(t *testing.T) {
{Offset: 0, Size: 100, FileId: "m", ModifiedTsNs: 2, IsChunkManifest: true},
}
total, _, merge := shouldMergeChunks(compacted, manifest)
if total != 100 {
t.Fatalf("totalChunkSize should only count compacted, got %d", total)
if total != 200 {
t.Fatalf("totalChunkSize should count compacted + manifests, got %d", total)
}
if merge {
t.Fatal("should not merge")
t.Fatal("2x total on 100-byte file should not merge (need >2x)")
}
}
func TestShouldMergeChunks_AccumulatedManifests(t *testing.T) {
// Simulates the real bug: multiple manifests each covering the full file
// accumulate across flush cycles. Without counting manifest sizes, the
// merge condition never fires and storage bloats indefinitely.
compacted := []*filer_pb.FileChunk{
{Offset: 0, Size: 1000, FileId: "a", ModifiedTsNs: 100},
}
// 5 manifests each covering the full file — successive flush cycles
var manifests []*filer_pb.FileChunk
for i := 0; i < 5; i++ {
manifests = append(manifests, &filer_pb.FileChunk{
Offset: 0, Size: 1000, FileId: string(rune('m' + i)),
IsChunkManifest: true,
})
}
total, fileSize, merge := shouldMergeChunks(compacted, manifests)
// total = 1000 (regular) + 5*1000 (manifests) = 6000
// fileSize = 1000
// 6000 > 2*1000 → merge
if !merge {
t.Fatalf("accumulated overlapping manifests should trigger merge (total=%d fileSize=%d)", total, fileSize)
}
}
@@ -279,6 +306,80 @@ func TestRandomWritesBloatDetection(t *testing.T) {
}
}
// TestFlushCycleManifestAccumulation simulates the flushMetadataToFiler
// pipeline over multiple cycles with a small manifest batch threshold.
// Each cycle adds a full pass of random writes, compacts, and manifestizes.
// Verifies that shouldMergeChunks detects manifest bloat within a few cycles.
func TestFlushCycleManifestAccumulation(t *testing.T) {
const (
fileSize int64 = 10000
chunkSize uint64 = 1000
numSlots = int(fileSize / int64(chunkSize)) // 10 offsets
batchSize = 5 // small batch to trigger manifestize
)
var entryChunks []*filer_pb.FileChunk
nextTs := int64(1)
nextKey := uint64(1)
for cycle := 0; cycle < 20; cycle++ {
// Each cycle: new writes at every offset (simulates a full random-write pass)
for slot := 0; slot < numSlots; slot++ {
entryChunks = append(entryChunks, &filer_pb.FileChunk{
Offset: int64(slot) * int64(chunkSize), Size: chunkSize,
FileId: fmt.Sprintf("%d,%x00000000", cycle+1, nextKey),
ModifiedTsNs: nextTs,
Fid: &filer_pb.FileId{VolumeId: uint32(cycle + 1), FileKey: nextKey, Cookie: 0},
})
nextTs++
nextKey++
}
// --- flush pipeline (mirrors flushMetadataToFiler) ---
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(entryChunks)
compacted, _ := filer.CompactFileChunks(context.Background(), nil, nonManifestChunks)
_, _, merge := shouldMergeChunks(compacted, manifestChunks)
if merge {
t.Logf("cycle %d: merge correctly triggered (%d manifests, %d regular chunks)",
cycle, len(manifestChunks), len(compacted))
return
}
// Simulate MaybeManifestize with small batch:
// pack groups of batchSize regular chunks into manifest chunks.
numPacked := len(compacted) / batchSize
var newEntry []*filer_pb.FileChunk
newEntry = append(newEntry, manifestChunks...) // carry forward old manifests
for i := 0; i < numPacked; i++ {
batch := compacted[i*batchSize : (i+1)*batchSize]
var minOff int64 = math.MaxInt64
var maxEnd int64 = 0
for _, c := range batch {
if c.Offset < minOff {
minOff = c.Offset
}
if end := c.Offset + int64(c.Size); end > maxEnd {
maxEnd = end
}
}
nextKey++
newEntry = append(newEntry, &filer_pb.FileChunk{
Offset: minOff, Size: uint64(maxEnd - minOff),
FileId: fmt.Sprintf("900,%x00000000", nextKey),
IsChunkManifest: true,
Fid: &filer_pb.FileId{VolumeId: 900 + uint32(cycle), FileKey: nextKey, Cookie: 0},
})
}
// Leftover regular chunks that didn't fill a batch
remainder := compacted[numPacked*batchSize:]
newEntry = append(newEntry, remainder...)
entryChunks = newEntry
}
t.Fatal("merge never triggered after 20 flush cycles")
}
// TestVisibleContentPreservedAfterCompact verifies that CompactFileChunks
// never drops a chunk that contributes visible bytes. This is the invariant
// that maybeMergeChunks relies on: the compacted set covers the same logical
+3
View File
@@ -88,6 +88,9 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
fh.dirtyMetadata = true
// Invalidate the mtime cache so the next Open will not set FOPEN_KEEP_CACHE.
wfs.invalidateOpenMtimeCache(in.NodeId)
// POSIX: clear SUID/SGID bits on write by non-root users.
if in.Uid != 0 {
entry.Attributes.FileMode &^= 0o6000
+5 -5
View File
@@ -231,9 +231,9 @@ func (wfs *WFS) syncHardLinkSiblings(inode uint64, authoritativeEntry *filer_pb.
glog.V(4).Infof("syncHardLinkSiblings update %s: %v", p, err)
}
}
if wfs.fuseServer != nil {
if status := wfs.fuseServer.InodeNotify(inode, 0, -1); status != fuse.OK {
glog.V(4).Infof("syncHardLinkSiblings invalidate inode %d: %v", inode, status)
}
}
// Note: we deliberately do NOT call fuseServer.InodeNotify here. That
// call would be made from the FUSE Link request handler goroutine, and
// writes onto the same /dev/fuse fd that the kernel is still waiting to
// read the Link reply from — causing a self-notify deadlock. The kernel
// will re-stat siblings once its attr-cache TTL expires.
}
+35 -34
View File
@@ -8,13 +8,12 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType {
return func(reader io.Reader, filename string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error) {
return func(reader io.Reader, filename string, offset int64, tsNs int64, _ uint64) (chunk *filer_pb.FileChunk, err error) {
uploader, err := operation.NewUploader()
if err != nil {
return
@@ -35,37 +34,19 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
return fileUrl
}
var fileId string
var uploadResult *operation.UploadResult
var data []byte
if wfs.fileIdPool != nil {
// Use pre-allocated file ID from pool — avoids AssignVolume RPC.
fileId, uploadResult, err, data = uploader.UploadWithAssignFunc(
func() (string, string, security.EncodedJwt, error) {
entry, getErr := wfs.fileIdPool.Get()
if getErr != nil {
return "", "", "", getErr
}
return entry.FileId, entry.Host, entry.Auth, nil
},
uploadOption, genFileUrlFn, reader,
)
} else {
fileId, uploadResult, err, data = uploader.UploadWithRetry(
wfs,
&filer_pb.AssignVolumeRequest{
Count: 1,
Replication: wfs.option.Replication,
Collection: wfs.option.Collection,
TtlSec: wfs.option.TtlSec,
DiskType: string(wfs.option.DiskType),
DataCenter: wfs.option.DataCenter,
Path: string(fullPath),
},
uploadOption, genFileUrlFn, reader,
)
}
fileId, uploadResult, err, data := uploader.UploadWithRetry(
wfs,
&filer_pb.AssignVolumeRequest{
Count: 1,
Replication: wfs.option.Replication,
Collection: wfs.option.Collection,
TtlSec: wfs.option.TtlSec,
DiskType: string(wfs.option.DiskType),
DataCenter: wfs.option.DataCenter,
Path: string(fullPath),
},
uploadOption, genFileUrlFn, reader,
)
if err != nil {
glog.V(0).Infof("upload data %v: %v", filename, err)
@@ -76,9 +57,29 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
}
if offset == 0 {
// When peer sharing is enabled we need EVERY chunk in the
// local cache so we can actually serve it back to peers on
// FetchChunk — otherwise the directory would advertise us as
// a holder and the fetcher would get NOT_FOUND from our
// chunk cache. When peer sharing is off we preserve the
// original behavior of caching only the first chunk (small
// files) to avoid blowing the cache on large uploads. Both
// paths gate on chunkCache != nil: -cacheCapacityMB=0 disables
// the cache entirely, in which case SetChunk would panic.
shouldCache := wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil)
if shouldCache {
wfs.chunkCache.SetChunk(fileId, data)
}
// Announce every uploaded chunk so the tier-2 directory fills
// in as the file is written. Without this, the per-fetch
// announce path only bootstraps after someone else has already
// pulled a chunk via peer — which can't happen if nobody has
// told the directory who holds the chunk. Skip the announce
// when we couldn't cache (no point advertising bytes we can't
// actually serve back).
if wfs.peerAnnouncer != nil && shouldCache {
wfs.peerAnnouncer.EnqueueAnnounce(fileId)
}
chunk = uploadResult.ToPbFileChunk(fileId, offset, tsNs)
return chunk, nil
+28 -9
View File
@@ -21,6 +21,12 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
const (
brokerHealthCheckTimeout = 5 * time.Second
brokerHealthCheckAttempts = 3
brokerHealthCheckBackoff = 250 * time.Millisecond
)
// NewBrokerClientWithFilerAccessor creates a client with a shared filer accessor
func NewBrokerClientWithFilerAccessor(brokerAddress string, filerClientAccessor *filer_client.FilerClientAccessor) (*BrokerClient, error) {
ctx, cancel := context.WithCancel(context.Background())
@@ -98,17 +104,30 @@ func (bc *BrokerClient) Close() error {
// HealthCheck verifies the broker connection is working
func (bc *BrokerClient) HealthCheck() error {
// Create a timeout context for health check
ctx, cancel := context.WithTimeout(bc.ctx, 2*time.Second)
defer cancel()
// Try to list topics as a health check
_, err := bc.client.ListTopics(ctx, &mq_pb.ListTopicsRequest{})
if err != nil {
return fmt.Errorf("broker health check failed: %v", err)
if bc.client == nil {
return fmt.Errorf("broker client not connected")
}
return nil
var lastErr error
for attempt := 1; attempt <= brokerHealthCheckAttempts; attempt++ {
ctx, cancel := context.WithTimeout(bc.ctx, brokerHealthCheckTimeout)
_, err := bc.client.FindBrokerLeader(ctx, &mq_pb.FindBrokerLeaderRequest{})
cancel()
if err == nil {
return nil
}
lastErr = err
if attempt == brokerHealthCheckAttempts {
break
}
select {
case <-bc.ctx.Done():
return bc.ctx.Err()
case <-time.After(time.Duration(attempt) * brokerHealthCheckBackoff):
}
}
return fmt.Errorf("broker health check failed after %d attempts: %v", brokerHealthCheckAttempts, lastErr)
}
// GetPartitionRangeInfo gets comprehensive range information from SeaweedMQ broker's native range manager
+16 -1
View File
@@ -70,7 +70,22 @@ func Assign(ctx context.Context, masterFn GetMasterFn, grpcDialOption grpc.DialO
lastError = util.RetryWithBackoff(deadlineCtx, "assign", remaining,
func(err error) bool {
st, ok := status.FromError(err)
return ok && st.Code() == codes.Unavailable
if !ok {
return false
}
switch st.Code() {
case codes.Unavailable:
return true
case codes.Canceled, codes.DeadlineExceeded:
// A stale cached gRPC channel (e.g., master restart behind
// a k8s Service VIP) can return Canceled/DeadlineExceeded
// immediately even though the caller's context is still
// live. The first failure invalidates the cached ClientConn
// via shouldInvalidateConnection; retry so the next attempt
// dials a fresh channel.
return deadlineCtx.Err() == nil
}
return false
},
func() error {
// Per-attempt timeout to prevent a single slow RPC from consuming the entire retry budget
+30 -16
View File
@@ -52,16 +52,23 @@ type GetMasterFn func(ctx context.Context) pb.ServerAddress
func SubmitFiles(masterFn GetMasterFn, grpcDialOption grpc.DialOption, files []*FilePart, pref StoragePreference, usePublicUrl bool) ([]SubmitResult, error) {
results := make([]SubmitResult, len(files))
var totalBytes int64
for index, file := range files {
results[index].FileName = file.FileName
totalBytes += file.FileSize
}
var avgBytes uint64
if n := len(files); n > 0 {
avgBytes = uint64((totalBytes + int64(n) - 1) / int64(n))
}
ar := &VolumeAssignRequest{
Count: uint64(len(files)),
Replication: pref.Replication,
Collection: pref.Collection,
DataCenter: pref.DataCenter,
Ttl: pref.Ttl,
DiskType: pref.DiskType,
Count: uint64(len(files)),
Replication: pref.Replication,
Collection: pref.Collection,
DataCenter: pref.DataCenter,
Ttl: pref.Ttl,
DiskType: pref.DiskType,
ExpectedDataSize: avgBytes,
}
ret, err := Assign(context.Background(), masterFn, grpcDialOption, ar)
if err != nil {
@@ -150,11 +157,12 @@ func (fi *FilePart) Upload(maxMB int, masterFn GetMasterFn, usePublicUrl bool, j
var id string
if fi.Pref.DataCenter != "" {
ar := &VolumeAssignRequest{
Count: uint64(chunks),
Replication: fi.Pref.Replication,
Collection: fi.Pref.Collection,
Ttl: fi.Pref.Ttl,
DiskType: fi.Pref.DiskType,
Count: uint64(chunks),
Replication: fi.Pref.Replication,
Collection: fi.Pref.Collection,
Ttl: fi.Pref.Ttl,
DiskType: fi.Pref.DiskType,
ExpectedDataSize: uint64(chunkSize),
}
ret, err = Assign(context.Background(), masterFn, grpcDialOption, ar)
if err != nil {
@@ -163,12 +171,18 @@ func (fi *FilePart) Upload(maxMB int, masterFn GetMasterFn, usePublicUrl bool, j
}
for i := int64(0); i < chunks; i++ {
if fi.Pref.DataCenter == "" {
remaining := fi.FileSize - i*chunkSize
thisChunk := chunkSize
if remaining < thisChunk {
thisChunk = remaining
}
ar := &VolumeAssignRequest{
Count: 1,
Replication: fi.Pref.Replication,
Collection: fi.Pref.Collection,
Ttl: fi.Pref.Ttl,
DiskType: fi.Pref.DiskType,
Count: 1,
Replication: fi.Pref.Replication,
Collection: fi.Pref.Collection,
Ttl: fi.Pref.Ttl,
DiskType: fi.Pref.DiskType,
ExpectedDataSize: uint64(thisChunk),
}
ret, err = Assign(context.Background(), masterFn, grpcDialOption, ar)
if err != nil {
+4 -4
View File
@@ -36,7 +36,7 @@ type ChunkedUploadOption struct {
Jwt security.EncodedJwt
MimeType string
Cipher bool // encrypt data on volume servers
AssignFunc func(ctx context.Context, count int) (*VolumeAssignRequest, *AssignResult, error)
AssignFunc func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error)
UploadFunc func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) // Optional: for testing
}
@@ -146,7 +146,7 @@ uploadLoop:
// Upload chunk in parallel goroutine
wg.Add(1)
go func(offset int64, buf *bytes.Buffer) {
go func(offset int64, buf *bytes.Buffer, size int64) {
defer func() {
chunkBufferPool.Put(buf)
<-bytesBufferLimitChan
@@ -154,7 +154,7 @@ uploadLoop:
}()
// Assign volume for this chunk
_, assignResult, assignErr := opt.AssignFunc(ctx, 1)
_, assignResult, assignErr := opt.AssignFunc(ctx, 1, uint64(size))
if assignErr != nil {
uploadErrLock.Lock()
if uploadErr == nil {
@@ -235,7 +235,7 @@ uploadLoop:
fileChunks = append(fileChunks, chunk)
fileChunksLock.Unlock()
}(chunkOffset, bytesBuffer)
}(chunkOffset, bytesBuffer, dataSize)
// Update offset for next chunk
chunkOffset += dataSize
+4 -4
View File
@@ -20,7 +20,7 @@ func TestUploadReaderInChunksReturnsPartialResultsOnError(t *testing.T) {
uploadAttempts := 0
// Create a mock assign function that succeeds for first chunk, then fails
assignFunc := func(ctx context.Context, count int) (*VolumeAssignRequest, *AssignResult, error) {
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
uploadAttempts++
if uploadAttempts == 1 {
@@ -97,7 +97,7 @@ func TestUploadReaderInChunksSuccessPath(t *testing.T) {
reader := bytes.NewReader(testData)
// Mock assign function that always succeeds
assignFunc := func(ctx context.Context, count int) (*VolumeAssignRequest, *AssignResult, error) {
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
return nil, &AssignResult{
Fid: "test-fid,1234",
Url: "http://test-volume:8080",
@@ -187,7 +187,7 @@ func TestUploadReaderInChunksContextCancellation(t *testing.T) {
// Cancel immediately to trigger cancellation handling
cancel()
assignFunc := func(ctx context.Context, count int) (*VolumeAssignRequest, *AssignResult, error) {
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
return nil, &AssignResult{
Fid: "test-fid,1234",
Url: "http://test-volume:8080",
@@ -268,7 +268,7 @@ func TestUploadReaderInChunksReaderFailure(t *testing.T) {
failAfter: 10000, // Fail after 10KB
}
assignFunc := func(ctx context.Context, count int) (*VolumeAssignRequest, *AssignResult, error) {
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
return nil, &AssignResult{
Fid: "test-fid,1234",
Url: "http://test-volume:8080",
+6 -23
View File
@@ -172,29 +172,6 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
return
}
// AssignFunc returns a file ID, host, and auth token for uploading.
type AssignFunc func() (fileId string, host string, auth security.EncodedJwt, err error)
// UploadWithAssignFunc uploads data using a caller-provided assign function.
// This allows callers to use pre-allocated file IDs from a pool instead of
// making an AssignVolume RPC per chunk.
func (uploader *Uploader) UploadWithAssignFunc(assignFn AssignFunc, uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
bytesReader, ok := reader.(*util.BytesReader)
if ok {
data = bytesReader.Bytes
} else {
data, err = io.ReadAll(reader)
if err != nil {
glog.V(0).Infof("upload read input %s: %v", uploadOption.SourceUrl, err)
err = fmt.Errorf("read input: %w", err)
return
}
glog.V(4).Infof("upload read %d bytes from %s", len(data), uploadOption.SourceUrl)
}
fileId, uploadResult, err = uploader.uploadWithRetryData(assignFn, uploadOption, genFileUrlFn, data)
return
}
// UploadWithRetry will retry both assigning volume request and uploading content
// The option parameter does not need to specify UploadUrl and Jwt, which will come from assigning volume.
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
@@ -211,6 +188,12 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
glog.V(4).Infof("upload read %d bytes from %s", len(data), uploadOption.SourceUrl)
}
// Tell the master the real chunk size so its effectiveSize accounting
// doesn't fall back to the 1 MB DefaultNeedleSizeEstimate per fid.
if assignRequest.ExpectedDataSize == 0 {
assignRequest.ExpectedDataSize = uint64(len(data))
}
fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, err error) {
// grpc assign volume
if grpcAssignErr := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+2
View File
@@ -9,6 +9,8 @@ gen:
protoc remote.proto --go_out=./remote_pb --go-grpc_out=./remote_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc iam.proto --go_out=./iam_pb --go-grpc_out=./iam_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc mount.proto --go_out=./mount_pb --go-grpc_out=./mount_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
mkdir -p ./mount_peer_pb
protoc mount_peer.proto --go_out=./mount_peer_pb --go-grpc_out=./mount_peer_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc s3.proto --go_out=./s3_pb --go-grpc_out=./s3_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc mq_broker.proto --go_out=./mq_pb --go-grpc_out=./mq_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc mq_schema.proto --go_out=./schema_pb --go-grpc_out=./schema_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
+36
View File
@@ -86,6 +86,13 @@ service SeaweedFiler {
}
rpc ReplicateLock(ReplicateLockRequest) returns (ReplicateLockResponse) {
}
// Peer chunk sharing — tier 1: mount-server registry.
// See design-weed-mount-peer-chunk-sharing.md for details.
rpc MountRegister (MountRegisterRequest) returns (MountRegisterResponse) {
}
rpc MountList (MountListRequest) returns (MountListResponse) {
}
}
//////////////////////////////////////////////////
@@ -200,6 +207,7 @@ message FuseAttributes {
int64 ctime = 18; // unix time in seconds, inode change time
int32 mtime_ns = 19; // nanosecond component of mtime (0-999999999)
int32 ctime_ns = 20; // nanosecond component of ctime (0-999999999)
int32 crtime_ns = 21; // nanosecond component of crtime (0-999999999)
}
message CreateEntryRequest {
@@ -600,3 +608,31 @@ message StreamMutateEntryResponse {
string error = 7; // human-readable error message when the operation failed
int32 errno = 8; // POSIX errno (e.g. ENOENT=2, ENOTEMPTY=66) for direct FUSE status mapping
}
//////////////////////////////////////////////////
// Peer chunk sharing — mount-server registry
//////////////////////////////////////////////////
message MountRegisterRequest {
string peer_addr = 1; // host:port where this mount serves peer chunk requests
string rack = 2; // locality label (rack); used for peer ranking
int32 ttl_seconds = 3; // how long the filer should keep this entry without a heartbeat
string data_center = 4; // locality label (data center); coarser than rack
}
message MountRegisterResponse {
}
message MountListRequest {
}
message MountListResponse {
repeated MountInfo mounts = 1;
}
message MountInfo {
string peer_addr = 1;
string rack = 2;
int64 last_seen_ns = 3;
string data_center = 4;
}
+375 -84
View File
@@ -961,9 +961,10 @@ type FuseAttributes struct {
Md5 []byte `protobuf:"bytes,14,opt,name=md5,proto3" json:"md5,omitempty"`
Rdev uint32 `protobuf:"varint,16,opt,name=rdev,proto3" json:"rdev,omitempty"`
Inode uint64 `protobuf:"varint,17,opt,name=inode,proto3" json:"inode,omitempty"`
Ctime int64 `protobuf:"varint,18,opt,name=ctime,proto3" json:"ctime,omitempty"` // unix time in seconds, inode change time
MtimeNs int32 `protobuf:"varint,19,opt,name=mtime_ns,json=mtimeNs,proto3" json:"mtime_ns,omitempty"` // nanosecond component of mtime (0-999999999)
CtimeNs int32 `protobuf:"varint,20,opt,name=ctime_ns,json=ctimeNs,proto3" json:"ctime_ns,omitempty"` // nanosecond component of ctime (0-999999999)
Ctime int64 `protobuf:"varint,18,opt,name=ctime,proto3" json:"ctime,omitempty"` // unix time in seconds, inode change time
MtimeNs int32 `protobuf:"varint,19,opt,name=mtime_ns,json=mtimeNs,proto3" json:"mtime_ns,omitempty"` // nanosecond component of mtime (0-999999999)
CtimeNs int32 `protobuf:"varint,20,opt,name=ctime_ns,json=ctimeNs,proto3" json:"ctime_ns,omitempty"` // nanosecond component of ctime (0-999999999)
CrtimeNs int32 `protobuf:"varint,21,opt,name=crtime_ns,json=crtimeNs,proto3" json:"crtime_ns,omitempty"` // nanosecond component of crtime (0-999999999)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1117,6 +1118,13 @@ func (x *FuseAttributes) GetCtimeNs() int32 {
return 0
}
func (x *FuseAttributes) GetCrtimeNs() int32 {
if x != nil {
return x.CrtimeNs
}
return 0
}
type CreateEntryRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"`
@@ -4869,6 +4877,258 @@ func (*StreamMutateEntryResponse_DeleteResponse) isStreamMutateEntryResponse_Res
func (*StreamMutateEntryResponse_RenameResponse) isStreamMutateEntryResponse_Response() {}
type MountRegisterRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
PeerAddr string `protobuf:"bytes,1,opt,name=peer_addr,json=peerAddr,proto3" json:"peer_addr,omitempty"` // host:port where this mount serves peer chunk requests
Rack string `protobuf:"bytes,2,opt,name=rack,proto3" json:"rack,omitempty"` // locality label (rack); used for peer ranking
TtlSeconds int32 `protobuf:"varint,3,opt,name=ttl_seconds,json=ttlSeconds,proto3" json:"ttl_seconds,omitempty"` // how long the filer should keep this entry without a heartbeat
DataCenter string `protobuf:"bytes,4,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"` // locality label (data center); coarser than rack
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MountRegisterRequest) Reset() {
*x = MountRegisterRequest{}
mi := &file_filer_proto_msgTypes[71]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MountRegisterRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MountRegisterRequest) ProtoMessage() {}
func (x *MountRegisterRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[71]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MountRegisterRequest.ProtoReflect.Descriptor instead.
func (*MountRegisterRequest) Descriptor() ([]byte, []int) {
return file_filer_proto_rawDescGZIP(), []int{71}
}
func (x *MountRegisterRequest) GetPeerAddr() string {
if x != nil {
return x.PeerAddr
}
return ""
}
func (x *MountRegisterRequest) GetRack() string {
if x != nil {
return x.Rack
}
return ""
}
func (x *MountRegisterRequest) GetTtlSeconds() int32 {
if x != nil {
return x.TtlSeconds
}
return 0
}
func (x *MountRegisterRequest) GetDataCenter() string {
if x != nil {
return x.DataCenter
}
return ""
}
type MountRegisterResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MountRegisterResponse) Reset() {
*x = MountRegisterResponse{}
mi := &file_filer_proto_msgTypes[72]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MountRegisterResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MountRegisterResponse) ProtoMessage() {}
func (x *MountRegisterResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[72]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MountRegisterResponse.ProtoReflect.Descriptor instead.
func (*MountRegisterResponse) Descriptor() ([]byte, []int) {
return file_filer_proto_rawDescGZIP(), []int{72}
}
type MountListRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MountListRequest) Reset() {
*x = MountListRequest{}
mi := &file_filer_proto_msgTypes[73]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MountListRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MountListRequest) ProtoMessage() {}
func (x *MountListRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[73]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MountListRequest.ProtoReflect.Descriptor instead.
func (*MountListRequest) Descriptor() ([]byte, []int) {
return file_filer_proto_rawDescGZIP(), []int{73}
}
type MountListResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Mounts []*MountInfo `protobuf:"bytes,1,rep,name=mounts,proto3" json:"mounts,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MountListResponse) Reset() {
*x = MountListResponse{}
mi := &file_filer_proto_msgTypes[74]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MountListResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MountListResponse) ProtoMessage() {}
func (x *MountListResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[74]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MountListResponse.ProtoReflect.Descriptor instead.
func (*MountListResponse) Descriptor() ([]byte, []int) {
return file_filer_proto_rawDescGZIP(), []int{74}
}
func (x *MountListResponse) GetMounts() []*MountInfo {
if x != nil {
return x.Mounts
}
return nil
}
type MountInfo struct {
state protoimpl.MessageState `protogen:"open.v1"`
PeerAddr string `protobuf:"bytes,1,opt,name=peer_addr,json=peerAddr,proto3" json:"peer_addr,omitempty"`
Rack string `protobuf:"bytes,2,opt,name=rack,proto3" json:"rack,omitempty"`
LastSeenNs int64 `protobuf:"varint,3,opt,name=last_seen_ns,json=lastSeenNs,proto3" json:"last_seen_ns,omitempty"`
DataCenter string `protobuf:"bytes,4,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *MountInfo) Reset() {
*x = MountInfo{}
mi := &file_filer_proto_msgTypes[75]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *MountInfo) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MountInfo) ProtoMessage() {}
func (x *MountInfo) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[75]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MountInfo.ProtoReflect.Descriptor instead.
func (*MountInfo) Descriptor() ([]byte, []int) {
return file_filer_proto_rawDescGZIP(), []int{75}
}
func (x *MountInfo) GetPeerAddr() string {
if x != nil {
return x.PeerAddr
}
return ""
}
func (x *MountInfo) GetRack() string {
if x != nil {
return x.Rack
}
return ""
}
func (x *MountInfo) GetLastSeenNs() int64 {
if x != nil {
return x.LastSeenNs
}
return 0
}
func (x *MountInfo) GetDataCenter() string {
if x != nil {
return x.DataCenter
}
return ""
}
// if found, send the exact address
// if not found, send the full list of existing brokers
type LocateBrokerResponse_Resource struct {
@@ -4881,7 +5141,7 @@ type LocateBrokerResponse_Resource struct {
func (x *LocateBrokerResponse_Resource) Reset() {
*x = LocateBrokerResponse_Resource{}
mi := &file_filer_proto_msgTypes[74]
mi := &file_filer_proto_msgTypes[79]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4893,7 +5153,7 @@ func (x *LocateBrokerResponse_Resource) String() string {
func (*LocateBrokerResponse_Resource) ProtoMessage() {}
func (x *LocateBrokerResponse_Resource) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[74]
mi := &file_filer_proto_msgTypes[79]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4947,7 +5207,7 @@ type FilerConf_PathConf struct {
func (x *FilerConf_PathConf) Reset() {
*x = FilerConf_PathConf{}
mi := &file_filer_proto_msgTypes[75]
mi := &file_filer_proto_msgTypes[80]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4959,7 +5219,7 @@ func (x *FilerConf_PathConf) String() string {
func (*FilerConf_PathConf) ProtoMessage() {}
func (x *FilerConf_PathConf) ProtoReflect() protoreflect.Message {
mi := &file_filer_proto_msgTypes[75]
mi := &file_filer_proto_msgTypes[80]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -5168,7 +5428,7 @@ const file_filer_proto_rawDesc = "" +
"\x06FileId\x12\x1b\n" +
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x19\n" +
"\bfile_key\x18\x02 \x01(\x04R\afileKey\x12\x16\n" +
"\x06cookie\x18\x03 \x01(\aR\x06cookie\"\xb4\x03\n" +
"\x06cookie\x18\x03 \x01(\aR\x06cookie\"\xd1\x03\n" +
"\x0eFuseAttributes\x12\x1b\n" +
"\tfile_size\x18\x01 \x01(\x04R\bfileSize\x12\x14\n" +
"\x05mtime\x18\x02 \x01(\x03R\x05mtime\x12\x1b\n" +
@@ -5188,7 +5448,8 @@ const file_filer_proto_rawDesc = "" +
"\x05inode\x18\x11 \x01(\x04R\x05inode\x12\x14\n" +
"\x05ctime\x18\x12 \x01(\x03R\x05ctime\x12\x19\n" +
"\bmtime_ns\x18\x13 \x01(\x05R\amtimeNs\x12\x19\n" +
"\bctime_ns\x18\x14 \x01(\x05R\actimeNs\"\x82\x02\n" +
"\bctime_ns\x18\x14 \x01(\x05R\actimeNs\x12\x1b\n" +
"\tcrtime_ns\x18\x15 \x01(\x05R\bcrtimeNs\"\x82\x02\n" +
"\x12CreateEntryRequest\x12\x1c\n" +
"\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" +
"\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x12\x15\n" +
@@ -5524,7 +5785,25 @@ const file_filer_proto_rawDesc = "" +
"\x05error\x18\a \x01(\tR\x05error\x12\x14\n" +
"\x05errno\x18\b \x01(\x05R\x05errnoB\n" +
"\n" +
"\bresponse*7\n" +
"\bresponse\"\x89\x01\n" +
"\x14MountRegisterRequest\x12\x1b\n" +
"\tpeer_addr\x18\x01 \x01(\tR\bpeerAddr\x12\x12\n" +
"\x04rack\x18\x02 \x01(\tR\x04rack\x12\x1f\n" +
"\vttl_seconds\x18\x03 \x01(\x05R\n" +
"ttlSeconds\x12\x1f\n" +
"\vdata_center\x18\x04 \x01(\tR\n" +
"dataCenter\"\x17\n" +
"\x15MountRegisterResponse\"\x12\n" +
"\x10MountListRequest\"@\n" +
"\x11MountListResponse\x12+\n" +
"\x06mounts\x18\x01 \x03(\v2\x13.filer_pb.MountInfoR\x06mounts\"\x7f\n" +
"\tMountInfo\x12\x1b\n" +
"\tpeer_addr\x18\x01 \x01(\tR\bpeerAddr\x12\x12\n" +
"\x04rack\x18\x02 \x01(\tR\x04rack\x12 \n" +
"\flast_seen_ns\x18\x03 \x01(\x03R\n" +
"lastSeenNs\x12\x1f\n" +
"\vdata_center\x18\x04 \x01(\tR\n" +
"dataCenter*7\n" +
"\aSSEType\x12\b\n" +
"\x04NONE\x10\x00\x12\t\n" +
"\x05SSE_C\x10\x01\x12\v\n" +
@@ -5538,7 +5817,7 @@ const file_filer_proto_rawDesc = "" +
"\x0ePARENT_IS_FILE\x10\x02\x12\x19\n" +
"\x15EXISTING_IS_DIRECTORY\x10\x03\x12\x14\n" +
"\x10EXISTING_IS_FILE\x10\x04\x12\x18\n" +
"\x14ENTRY_ALREADY_EXISTS\x10\x052\xaf\x12\n" +
"\x14ENTRY_ALREADY_EXISTS\x10\x052\xcb\x13\n" +
"\fSeaweedFiler\x12g\n" +
"\x14LookupDirectoryEntry\x12%.filer_pb.LookupDirectoryEntryRequest\x1a&.filer_pb.LookupDirectoryEntryResponse\"\x00\x12N\n" +
"\vListEntries\x12\x1c.filer_pb.ListEntriesRequest\x1a\x1d.filer_pb.ListEntriesResponse\"\x000\x01\x12L\n" +
@@ -5567,7 +5846,9 @@ const file_filer_proto_rawDesc = "" +
"\x11DistributedUnlock\x12\x17.filer_pb.UnlockRequest\x1a\x18.filer_pb.UnlockResponse\"\x00\x12R\n" +
"\rFindLockOwner\x12\x1e.filer_pb.FindLockOwnerRequest\x1a\x1f.filer_pb.FindLockOwnerResponse\"\x00\x12R\n" +
"\rTransferLocks\x12\x1e.filer_pb.TransferLocksRequest\x1a\x1f.filer_pb.TransferLocksResponse\"\x00\x12R\n" +
"\rReplicateLock\x12\x1e.filer_pb.ReplicateLockRequest\x1a\x1f.filer_pb.ReplicateLockResponse\"\x00BO\n" +
"\rReplicateLock\x12\x1e.filer_pb.ReplicateLockRequest\x1a\x1f.filer_pb.ReplicateLockResponse\"\x00\x12R\n" +
"\rMountRegister\x12\x1e.filer_pb.MountRegisterRequest\x1a\x1f.filer_pb.MountRegisterResponse\"\x00\x12F\n" +
"\tMountList\x12\x1a.filer_pb.MountListRequest\x1a\x1b.filer_pb.MountListResponse\"\x00BO\n" +
"\x10seaweedfs.clientB\n" +
"FilerProtoZ/github.com/seaweedfs/seaweedfs/weed/pb/filer_pbb\x06proto3"
@@ -5584,7 +5865,7 @@ func file_filer_proto_rawDescGZIP() []byte {
}
var file_filer_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
var file_filer_proto_msgTypes = make([]protoimpl.MessageInfo, 76)
var file_filer_proto_msgTypes = make([]protoimpl.MessageInfo, 81)
var file_filer_proto_goTypes = []any{
(SSEType)(0), // 0: filer_pb.SSEType
(FilerError)(0), // 1: filer_pb.FilerError
@@ -5659,18 +5940,23 @@ var file_filer_proto_goTypes = []any{
(*ReplicateLockResponse)(nil), // 70: filer_pb.ReplicateLockResponse
(*StreamMutateEntryRequest)(nil), // 71: filer_pb.StreamMutateEntryRequest
(*StreamMutateEntryResponse)(nil), // 72: filer_pb.StreamMutateEntryResponse
nil, // 73: filer_pb.Entry.ExtendedEntry
nil, // 74: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
nil, // 75: filer_pb.LookupVolumeResponse.LocationsMapEntry
(*LocateBrokerResponse_Resource)(nil), // 76: filer_pb.LocateBrokerResponse.Resource
(*FilerConf_PathConf)(nil), // 77: filer_pb.FilerConf.PathConf
(*MountRegisterRequest)(nil), // 73: filer_pb.MountRegisterRequest
(*MountRegisterResponse)(nil), // 74: filer_pb.MountRegisterResponse
(*MountListRequest)(nil), // 75: filer_pb.MountListRequest
(*MountListResponse)(nil), // 76: filer_pb.MountListResponse
(*MountInfo)(nil), // 77: filer_pb.MountInfo
nil, // 78: filer_pb.Entry.ExtendedEntry
nil, // 79: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
nil, // 80: filer_pb.LookupVolumeResponse.LocationsMapEntry
(*LocateBrokerResponse_Resource)(nil), // 81: filer_pb.LocateBrokerResponse.Resource
(*FilerConf_PathConf)(nil), // 82: filer_pb.FilerConf.PathConf
}
var file_filer_proto_depIdxs = []int32{
7, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry
7, // 1: filer_pb.ListEntriesResponse.entry:type_name -> filer_pb.Entry
10, // 2: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk
13, // 3: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes
73, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry
78, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry
6, // 5: filer_pb.Entry.remote_entry:type_name -> filer_pb.RemoteEntry
7, // 6: filer_pb.FullEntry.entry:type_name -> filer_pb.Entry
7, // 7: filer_pb.EventNotification.old_entry:type_name -> filer_pb.Entry
@@ -5683,22 +5969,22 @@ var file_filer_proto_depIdxs = []int32{
44, // 14: filer_pb.CreateEntryResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
1, // 15: filer_pb.CreateEntryResponse.error_code:type_name -> filer_pb.FilerError
7, // 16: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry
74, // 17: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
79, // 17: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
44, // 18: filer_pb.UpdateEntryResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
10, // 19: filer_pb.AppendToEntryRequest.chunks:type_name -> filer_pb.FileChunk
44, // 20: filer_pb.DeleteEntryResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
9, // 21: filer_pb.StreamRenameEntryResponse.event_notification:type_name -> filer_pb.EventNotification
30, // 22: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
30, // 23: filer_pb.Locations.locations:type_name -> filer_pb.Location
75, // 24: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
80, // 24: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
32, // 25: filer_pb.CollectionListResponse.collections:type_name -> filer_pb.Collection
9, // 26: filer_pb.SubscribeMetadataResponse.event_notification:type_name -> filer_pb.EventNotification
44, // 27: filer_pb.SubscribeMetadataResponse.events:type_name -> filer_pb.SubscribeMetadataResponse
45, // 28: filer_pb.SubscribeMetadataResponse.log_file_refs:type_name -> filer_pb.LogFileChunkRef
10, // 29: filer_pb.LogFileChunkRef.chunks:type_name -> filer_pb.FileChunk
7, // 30: filer_pb.TraverseBfsMetadataResponse.entry:type_name -> filer_pb.Entry
76, // 31: filer_pb.LocateBrokerResponse.resources:type_name -> filer_pb.LocateBrokerResponse.Resource
77, // 32: filer_pb.FilerConf.locations:type_name -> filer_pb.FilerConf.PathConf
81, // 31: filer_pb.LocateBrokerResponse.resources:type_name -> filer_pb.LocateBrokerResponse.Resource
82, // 32: filer_pb.FilerConf.locations:type_name -> filer_pb.FilerConf.PathConf
7, // 33: filer_pb.CacheRemoteObjectToLocalClusterResponse.entry:type_name -> filer_pb.Entry
44, // 34: filer_pb.CacheRemoteObjectToLocalClusterResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
66, // 35: filer_pb.TransferLocksRequest.locks:type_name -> filer_pb.Lock
@@ -5710,66 +5996,71 @@ var file_filer_proto_depIdxs = []int32{
17, // 41: filer_pb.StreamMutateEntryResponse.update_response:type_name -> filer_pb.UpdateEntryResponse
21, // 42: filer_pb.StreamMutateEntryResponse.delete_response:type_name -> filer_pb.DeleteEntryResponse
25, // 43: filer_pb.StreamMutateEntryResponse.rename_response:type_name -> filer_pb.StreamRenameEntryResponse
29, // 44: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
2, // 45: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
4, // 46: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
14, // 47: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
16, // 48: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
18, // 49: filer_pb.SeaweedFiler.AppendToEntry:input_type -> filer_pb.AppendToEntryRequest
20, // 50: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
22, // 51: filer_pb.SeaweedFiler.AtomicRenameEntry:input_type -> filer_pb.AtomicRenameEntryRequest
24, // 52: filer_pb.SeaweedFiler.StreamRenameEntry:input_type -> filer_pb.StreamRenameEntryRequest
71, // 53: filer_pb.SeaweedFiler.StreamMutateEntry:input_type -> filer_pb.StreamMutateEntryRequest
26, // 54: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
28, // 55: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
33, // 56: filer_pb.SeaweedFiler.CollectionList:input_type -> filer_pb.CollectionListRequest
35, // 57: filer_pb.SeaweedFiler.DeleteCollection:input_type -> filer_pb.DeleteCollectionRequest
37, // 58: filer_pb.SeaweedFiler.Statistics:input_type -> filer_pb.StatisticsRequest
39, // 59: filer_pb.SeaweedFiler.Ping:input_type -> filer_pb.PingRequest
41, // 60: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
46, // 61: filer_pb.SeaweedFiler.TraverseBfsMetadata:input_type -> filer_pb.TraverseBfsMetadataRequest
43, // 62: filer_pb.SeaweedFiler.SubscribeMetadata:input_type -> filer_pb.SubscribeMetadataRequest
43, // 63: filer_pb.SeaweedFiler.SubscribeLocalMetadata:input_type -> filer_pb.SubscribeMetadataRequest
53, // 64: filer_pb.SeaweedFiler.KvGet:input_type -> filer_pb.KvGetRequest
55, // 65: filer_pb.SeaweedFiler.KvPut:input_type -> filer_pb.KvPutRequest
58, // 66: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:input_type -> filer_pb.CacheRemoteObjectToLocalClusterRequest
60, // 67: filer_pb.SeaweedFiler.DistributedLock:input_type -> filer_pb.LockRequest
62, // 68: filer_pb.SeaweedFiler.DistributedUnlock:input_type -> filer_pb.UnlockRequest
64, // 69: filer_pb.SeaweedFiler.FindLockOwner:input_type -> filer_pb.FindLockOwnerRequest
67, // 70: filer_pb.SeaweedFiler.TransferLocks:input_type -> filer_pb.TransferLocksRequest
69, // 71: filer_pb.SeaweedFiler.ReplicateLock:input_type -> filer_pb.ReplicateLockRequest
3, // 72: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
5, // 73: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
15, // 74: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
17, // 75: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
19, // 76: filer_pb.SeaweedFiler.AppendToEntry:output_type -> filer_pb.AppendToEntryResponse
21, // 77: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
23, // 78: filer_pb.SeaweedFiler.AtomicRenameEntry:output_type -> filer_pb.AtomicRenameEntryResponse
25, // 79: filer_pb.SeaweedFiler.StreamRenameEntry:output_type -> filer_pb.StreamRenameEntryResponse
72, // 80: filer_pb.SeaweedFiler.StreamMutateEntry:output_type -> filer_pb.StreamMutateEntryResponse
27, // 81: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
31, // 82: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
34, // 83: filer_pb.SeaweedFiler.CollectionList:output_type -> filer_pb.CollectionListResponse
36, // 84: filer_pb.SeaweedFiler.DeleteCollection:output_type -> filer_pb.DeleteCollectionResponse
38, // 85: filer_pb.SeaweedFiler.Statistics:output_type -> filer_pb.StatisticsResponse
40, // 86: filer_pb.SeaweedFiler.Ping:output_type -> filer_pb.PingResponse
42, // 87: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
47, // 88: filer_pb.SeaweedFiler.TraverseBfsMetadata:output_type -> filer_pb.TraverseBfsMetadataResponse
44, // 89: filer_pb.SeaweedFiler.SubscribeMetadata:output_type -> filer_pb.SubscribeMetadataResponse
44, // 90: filer_pb.SeaweedFiler.SubscribeLocalMetadata:output_type -> filer_pb.SubscribeMetadataResponse
54, // 91: filer_pb.SeaweedFiler.KvGet:output_type -> filer_pb.KvGetResponse
56, // 92: filer_pb.SeaweedFiler.KvPut:output_type -> filer_pb.KvPutResponse
59, // 93: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:output_type -> filer_pb.CacheRemoteObjectToLocalClusterResponse
61, // 94: filer_pb.SeaweedFiler.DistributedLock:output_type -> filer_pb.LockResponse
63, // 95: filer_pb.SeaweedFiler.DistributedUnlock:output_type -> filer_pb.UnlockResponse
65, // 96: filer_pb.SeaweedFiler.FindLockOwner:output_type -> filer_pb.FindLockOwnerResponse
68, // 97: filer_pb.SeaweedFiler.TransferLocks:output_type -> filer_pb.TransferLocksResponse
70, // 98: filer_pb.SeaweedFiler.ReplicateLock:output_type -> filer_pb.ReplicateLockResponse
72, // [72:99] is the sub-list for method output_type
45, // [45:72] is the sub-list for method input_type
45, // [45:45] is the sub-list for extension type_name
45, // [45:45] is the sub-list for extension extendee
0, // [0:45] is the sub-list for field type_name
77, // 44: filer_pb.MountListResponse.mounts:type_name -> filer_pb.MountInfo
29, // 45: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
2, // 46: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
4, // 47: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
14, // 48: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
16, // 49: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
18, // 50: filer_pb.SeaweedFiler.AppendToEntry:input_type -> filer_pb.AppendToEntryRequest
20, // 51: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
22, // 52: filer_pb.SeaweedFiler.AtomicRenameEntry:input_type -> filer_pb.AtomicRenameEntryRequest
24, // 53: filer_pb.SeaweedFiler.StreamRenameEntry:input_type -> filer_pb.StreamRenameEntryRequest
71, // 54: filer_pb.SeaweedFiler.StreamMutateEntry:input_type -> filer_pb.StreamMutateEntryRequest
26, // 55: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
28, // 56: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
33, // 57: filer_pb.SeaweedFiler.CollectionList:input_type -> filer_pb.CollectionListRequest
35, // 58: filer_pb.SeaweedFiler.DeleteCollection:input_type -> filer_pb.DeleteCollectionRequest
37, // 59: filer_pb.SeaweedFiler.Statistics:input_type -> filer_pb.StatisticsRequest
39, // 60: filer_pb.SeaweedFiler.Ping:input_type -> filer_pb.PingRequest
41, // 61: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
46, // 62: filer_pb.SeaweedFiler.TraverseBfsMetadata:input_type -> filer_pb.TraverseBfsMetadataRequest
43, // 63: filer_pb.SeaweedFiler.SubscribeMetadata:input_type -> filer_pb.SubscribeMetadataRequest
43, // 64: filer_pb.SeaweedFiler.SubscribeLocalMetadata:input_type -> filer_pb.SubscribeMetadataRequest
53, // 65: filer_pb.SeaweedFiler.KvGet:input_type -> filer_pb.KvGetRequest
55, // 66: filer_pb.SeaweedFiler.KvPut:input_type -> filer_pb.KvPutRequest
58, // 67: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:input_type -> filer_pb.CacheRemoteObjectToLocalClusterRequest
60, // 68: filer_pb.SeaweedFiler.DistributedLock:input_type -> filer_pb.LockRequest
62, // 69: filer_pb.SeaweedFiler.DistributedUnlock:input_type -> filer_pb.UnlockRequest
64, // 70: filer_pb.SeaweedFiler.FindLockOwner:input_type -> filer_pb.FindLockOwnerRequest
67, // 71: filer_pb.SeaweedFiler.TransferLocks:input_type -> filer_pb.TransferLocksRequest
69, // 72: filer_pb.SeaweedFiler.ReplicateLock:input_type -> filer_pb.ReplicateLockRequest
73, // 73: filer_pb.SeaweedFiler.MountRegister:input_type -> filer_pb.MountRegisterRequest
75, // 74: filer_pb.SeaweedFiler.MountList:input_type -> filer_pb.MountListRequest
3, // 75: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
5, // 76: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
15, // 77: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
17, // 78: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
19, // 79: filer_pb.SeaweedFiler.AppendToEntry:output_type -> filer_pb.AppendToEntryResponse
21, // 80: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
23, // 81: filer_pb.SeaweedFiler.AtomicRenameEntry:output_type -> filer_pb.AtomicRenameEntryResponse
25, // 82: filer_pb.SeaweedFiler.StreamRenameEntry:output_type -> filer_pb.StreamRenameEntryResponse
72, // 83: filer_pb.SeaweedFiler.StreamMutateEntry:output_type -> filer_pb.StreamMutateEntryResponse
27, // 84: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
31, // 85: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
34, // 86: filer_pb.SeaweedFiler.CollectionList:output_type -> filer_pb.CollectionListResponse
36, // 87: filer_pb.SeaweedFiler.DeleteCollection:output_type -> filer_pb.DeleteCollectionResponse
38, // 88: filer_pb.SeaweedFiler.Statistics:output_type -> filer_pb.StatisticsResponse
40, // 89: filer_pb.SeaweedFiler.Ping:output_type -> filer_pb.PingResponse
42, // 90: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
47, // 91: filer_pb.SeaweedFiler.TraverseBfsMetadata:output_type -> filer_pb.TraverseBfsMetadataResponse
44, // 92: filer_pb.SeaweedFiler.SubscribeMetadata:output_type -> filer_pb.SubscribeMetadataResponse
44, // 93: filer_pb.SeaweedFiler.SubscribeLocalMetadata:output_type -> filer_pb.SubscribeMetadataResponse
54, // 94: filer_pb.SeaweedFiler.KvGet:output_type -> filer_pb.KvGetResponse
56, // 95: filer_pb.SeaweedFiler.KvPut:output_type -> filer_pb.KvPutResponse
59, // 96: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:output_type -> filer_pb.CacheRemoteObjectToLocalClusterResponse
61, // 97: filer_pb.SeaweedFiler.DistributedLock:output_type -> filer_pb.LockResponse
63, // 98: filer_pb.SeaweedFiler.DistributedUnlock:output_type -> filer_pb.UnlockResponse
65, // 99: filer_pb.SeaweedFiler.FindLockOwner:output_type -> filer_pb.FindLockOwnerResponse
68, // 100: filer_pb.SeaweedFiler.TransferLocks:output_type -> filer_pb.TransferLocksResponse
70, // 101: filer_pb.SeaweedFiler.ReplicateLock:output_type -> filer_pb.ReplicateLockResponse
74, // 102: filer_pb.SeaweedFiler.MountRegister:output_type -> filer_pb.MountRegisterResponse
76, // 103: filer_pb.SeaweedFiler.MountList:output_type -> filer_pb.MountListResponse
75, // [75:104] is the sub-list for method output_type
46, // [46:75] is the sub-list for method input_type
46, // [46:46] is the sub-list for extension type_name
46, // [46:46] is the sub-list for extension extendee
0, // [0:46] is the sub-list for field type_name
}
func init() { file_filer_proto_init() }
@@ -5795,7 +6086,7 @@ func file_filer_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_filer_proto_rawDesc), len(file_filer_proto_rawDesc)),
NumEnums: 2,
NumMessages: 76,
NumMessages: 81,
NumExtensions: 0,
NumServices: 1,
},
+80
View File
@@ -46,6 +46,8 @@ const (
SeaweedFiler_FindLockOwner_FullMethodName = "/filer_pb.SeaweedFiler/FindLockOwner"
SeaweedFiler_TransferLocks_FullMethodName = "/filer_pb.SeaweedFiler/TransferLocks"
SeaweedFiler_ReplicateLock_FullMethodName = "/filer_pb.SeaweedFiler/ReplicateLock"
SeaweedFiler_MountRegister_FullMethodName = "/filer_pb.SeaweedFiler/MountRegister"
SeaweedFiler_MountList_FullMethodName = "/filer_pb.SeaweedFiler/MountList"
)
// SeaweedFilerClient is the client API for SeaweedFiler service.
@@ -80,6 +82,10 @@ type SeaweedFilerClient interface {
// distributed lock management internal use only
TransferLocks(ctx context.Context, in *TransferLocksRequest, opts ...grpc.CallOption) (*TransferLocksResponse, error)
ReplicateLock(ctx context.Context, in *ReplicateLockRequest, opts ...grpc.CallOption) (*ReplicateLockResponse, error)
// Peer chunk sharing — tier 1: mount-server registry.
// See design-weed-mount-peer-chunk-sharing.md for details.
MountRegister(ctx context.Context, in *MountRegisterRequest, opts ...grpc.CallOption) (*MountRegisterResponse, error)
MountList(ctx context.Context, in *MountListRequest, opts ...grpc.CallOption) (*MountListResponse, error)
}
type seaweedFilerClient struct {
@@ -408,6 +414,26 @@ func (c *seaweedFilerClient) ReplicateLock(ctx context.Context, in *ReplicateLoc
return out, nil
}
func (c *seaweedFilerClient) MountRegister(ctx context.Context, in *MountRegisterRequest, opts ...grpc.CallOption) (*MountRegisterResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(MountRegisterResponse)
err := c.cc.Invoke(ctx, SeaweedFiler_MountRegister_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *seaweedFilerClient) MountList(ctx context.Context, in *MountListRequest, opts ...grpc.CallOption) (*MountListResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(MountListResponse)
err := c.cc.Invoke(ctx, SeaweedFiler_MountList_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// SeaweedFilerServer is the server API for SeaweedFiler service.
// All implementations must embed UnimplementedSeaweedFilerServer
// for forward compatibility.
@@ -440,6 +466,10 @@ type SeaweedFilerServer interface {
// distributed lock management internal use only
TransferLocks(context.Context, *TransferLocksRequest) (*TransferLocksResponse, error)
ReplicateLock(context.Context, *ReplicateLockRequest) (*ReplicateLockResponse, error)
// Peer chunk sharing — tier 1: mount-server registry.
// See design-weed-mount-peer-chunk-sharing.md for details.
MountRegister(context.Context, *MountRegisterRequest) (*MountRegisterResponse, error)
MountList(context.Context, *MountListRequest) (*MountListResponse, error)
mustEmbedUnimplementedSeaweedFilerServer()
}
@@ -531,6 +561,12 @@ func (UnimplementedSeaweedFilerServer) TransferLocks(context.Context, *TransferL
func (UnimplementedSeaweedFilerServer) ReplicateLock(context.Context, *ReplicateLockRequest) (*ReplicateLockResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReplicateLock not implemented")
}
func (UnimplementedSeaweedFilerServer) MountRegister(context.Context, *MountRegisterRequest) (*MountRegisterResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method MountRegister not implemented")
}
func (UnimplementedSeaweedFilerServer) MountList(context.Context, *MountListRequest) (*MountListResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method MountList not implemented")
}
func (UnimplementedSeaweedFilerServer) mustEmbedUnimplementedSeaweedFilerServer() {}
func (UnimplementedSeaweedFilerServer) testEmbeddedByValue() {}
@@ -992,6 +1028,42 @@ func _SeaweedFiler_ReplicateLock_Handler(srv interface{}, ctx context.Context, d
return interceptor(ctx, in, info, handler)
}
func _SeaweedFiler_MountRegister_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MountRegisterRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SeaweedFilerServer).MountRegister(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SeaweedFiler_MountRegister_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SeaweedFilerServer).MountRegister(ctx, req.(*MountRegisterRequest))
}
return interceptor(ctx, in, info, handler)
}
func _SeaweedFiler_MountList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MountListRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SeaweedFilerServer).MountList(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SeaweedFiler_MountList_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SeaweedFilerServer).MountList(ctx, req.(*MountListRequest))
}
return interceptor(ctx, in, info, handler)
}
// SeaweedFiler_ServiceDesc is the grpc.ServiceDesc for SeaweedFiler service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -1083,6 +1155,14 @@ var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{
MethodName: "ReplicateLock",
Handler: _SeaweedFiler_ReplicateLock_Handler,
},
{
MethodName: "MountRegister",
Handler: _SeaweedFiler_MountRegister_Handler,
},
{
MethodName: "MountList",
Handler: _SeaweedFiler_MountList_Handler,
},
},
Streams: []grpc.StreamDesc{
{
+52 -27
View File
@@ -247,6 +247,24 @@ func requestIDUnaryInterceptor() grpc.UnaryServerInterceptor {
}
}
// InvalidateGrpcConnection drops any cached gRPC ClientConn for the given
// address. Use when a higher-level signal (for example a streaming master
// connection detecting its peer has died) indicates the cached channel is
// stale, even though gRPC itself may still believe the channel is healthy.
// Silently returns if no cached connection exists.
func InvalidateGrpcConnection(address string) {
grpcClientsLock.Lock()
vgc, ok := grpcClients[address]
if ok {
delete(grpcClients, address)
}
grpcClientsLock.Unlock()
if ok {
glog.V(1).Infof("Invalidating cached gRPC connection to %s", address)
vgc.Close()
}
}
// shouldInvalidateConnection checks if an error indicates the cached connection should be invalidated
func shouldInvalidateConnection(err error) bool {
if err == nil {
@@ -283,38 +301,45 @@ func WithGrpcClient(streamingMode bool, signature int32, fn func(*grpc.ClientCon
return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
}
executionErr := fn(vgc.ClientConn)
if executionErr != nil {
if shouldInvalidateConnection(executionErr) {
grpcClientsLock.Lock()
if t, ok := grpcClients[address]; ok {
if t.version == vgc.version {
glog.V(1).Infof("Removing cached gRPC connection to %s due to error: %v", address, executionErr)
vgc.Close()
delete(grpcClients, address)
}
}
grpcClientsLock.Unlock()
if executionErr != nil && shouldInvalidateConnection(executionErr) {
grpcClientsLock.Lock()
t, ok := grpcClients[address]
shouldClose := ok && t.version == vgc.version
if shouldClose {
delete(grpcClients, address)
}
grpcClientsLock.Unlock()
if shouldClose {
glog.V(1).Infof("Removing cached gRPC connection to %s due to error: %v", address, executionErr)
vgc.Close()
}
}
return executionErr
} else {
ctx := context.Background()
if signature != 0 {
// Optimize: Use AppendToOutgoingContext instead of creating new map
ctx = metadata.AppendToOutgoingContext(ctx, "sw-client-id", fmt.Sprintf("%d", signature))
}
grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
if err != nil {
return fmt.Errorf("fail to dial %s: %v", address, err)
}
defer grpcConnection.Close()
executionErr := fn(grpcConnection)
if executionErr != nil {
return executionErr
}
return nil
}
// Streaming mode: dedicate a fresh ClientConn to this call.
ctx := context.Background()
if signature != 0 {
// Optimize: Use AppendToOutgoingContext instead of creating new map
ctx = metadata.AppendToOutgoingContext(ctx, "sw-client-id", fmt.Sprintf("%d", signature))
}
grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
if err != nil {
return fmt.Errorf("fail to dial %s: %v", address, err)
}
defer grpcConnection.Close()
executionErr := fn(grpcConnection)
if executionErr != nil {
// The streaming channel is dedicated to this caller, but unrelated
// request-path callers share a cached non-streaming ClientConn to the
// same peer. When the stream fails, drop that cached channel so the
// next caller dials fresh: this recovers cases where a stable L4
// endpoint (k8s Service VIP, external LB) hides a peer restart from
// the transport layer, leaving the cached ClientConn healthy-looking
// but silently cancelling RPCs.
InvalidateGrpcConnection(address)
}
return executionErr
}
func hostAndPort(address string) (host string, port uint64, err error) {
+95
View File
@@ -0,0 +1,95 @@
syntax = "proto3";
package mount_peer_pb;
option go_package = "github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb";
//////////////////////////////////////////////////
// Peer chunk sharing — mount-to-mount chunk directory
//
// Each weed mount exposes this service on its -peer.listen address.
// Ownership of fid -> holders tracking is sharded across the mount fleet
// via rendezvous (HRW) hashing on the registered mount list. See
// design-weed-mount-peer-chunk-sharing.md for protocol details.
//////////////////////////////////////////////////
service MountPeer {
// ChunkAnnounce: the caller asserts it currently holds the listed fids in
// its local chunk cache and is willing to serve them to peers. The
// receiver accepts only fids for which it is the HRW-assigned owner on
// its current seed view; others are returned in rejected_file_ids.
rpc ChunkAnnounce (ChunkAnnounceRequest) returns (ChunkAnnounceResponse) {
}
// ChunkLookup: asks the receiver for known holders of each requested fid.
// The receiver responds only for fids it owns; others are listed in
// not_owner_file_ids so the caller can retry against the correct owner
// after refreshing its own seed view.
rpc ChunkLookup (ChunkLookupRequest) returns (ChunkLookupResponse) {
}
// FetchChunk: server-streams the bytes of a cached chunk to a peer.
// Streaming avoids the default gRPC 4 MiB message cap for typical
// 16 MiB chunks and lets the receiver assemble into a preallocated
// buffer. Not-cached / cache-miss returns a gRPC NOT_FOUND status.
// The fetcher re-verifies MD5 against expected_etag end-to-end after
// the stream completes.
rpc FetchChunk (FetchChunkRequest) returns (stream FetchChunkResponse) {
}
}
message ChunkAnnounceRequest {
repeated string file_ids = 1;
string peer_addr = 2;
string rack = 3;
int32 ttl_seconds = 4;
string data_center = 5;
}
message ChunkAnnounceResponse {
repeated string rejected_file_ids = 1; // receiver is not the owner of these fids
}
message ChunkLookupRequest {
repeated string file_ids = 1;
}
message ChunkLookupResponse {
map<string, PeerSet> peers_by_fid = 1;
repeated string not_owner_file_ids = 2;
}
message PeerSet {
repeated PeerInfo peers = 1;
}
message PeerInfo {
string peer_addr = 1;
string rack = 2;
string data_center = 3;
}
message FetchChunkRequest {
string file_id = 1;
string expected_etag = 2; // caller's expected MD5 over the FULL chunk.
// Only meaningful when offset=0 and length=0
// (a whole-chunk fetch); partial reads can't
// be verified against a whole-chunk MD5.
// Fetcher re-verifies end-to-end.
uint64 expected_size = 3; // filer-reported chunk byte count; server sizes
// its cache-read buffer to exactly this so a
// sub-max-part-size chunk doesn't trigger the
// cache wrapper's all-or-nothing miss path.
uint64 offset = 4; // optional: byte offset within the chunk to
// start reading from. 0 (default) means a
// whole-chunk transfer starting at byte zero.
uint64 length = 5; // optional: number of bytes to return from
// offset. 0 (default) means "until end of
// chunk". Range is capped server-side by
// maxFetchChunkBytes regardless.
}
message FetchChunkResponse {
bytes data = 1; // next frame of chunk bytes; concatenate across stream
}
+581
View File
@@ -0,0 +1,581 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v6.33.4
// source: mount_peer.proto
package mount_peer_pb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ChunkAnnounceRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
FileIds []string `protobuf:"bytes,1,rep,name=file_ids,json=fileIds,proto3" json:"file_ids,omitempty"`
PeerAddr string `protobuf:"bytes,2,opt,name=peer_addr,json=peerAddr,proto3" json:"peer_addr,omitempty"`
Rack string `protobuf:"bytes,3,opt,name=rack,proto3" json:"rack,omitempty"`
TtlSeconds int32 `protobuf:"varint,4,opt,name=ttl_seconds,json=ttlSeconds,proto3" json:"ttl_seconds,omitempty"`
DataCenter string `protobuf:"bytes,5,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChunkAnnounceRequest) Reset() {
*x = ChunkAnnounceRequest{}
mi := &file_mount_peer_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChunkAnnounceRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChunkAnnounceRequest) ProtoMessage() {}
func (x *ChunkAnnounceRequest) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ChunkAnnounceRequest.ProtoReflect.Descriptor instead.
func (*ChunkAnnounceRequest) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{0}
}
func (x *ChunkAnnounceRequest) GetFileIds() []string {
if x != nil {
return x.FileIds
}
return nil
}
func (x *ChunkAnnounceRequest) GetPeerAddr() string {
if x != nil {
return x.PeerAddr
}
return ""
}
func (x *ChunkAnnounceRequest) GetRack() string {
if x != nil {
return x.Rack
}
return ""
}
func (x *ChunkAnnounceRequest) GetTtlSeconds() int32 {
if x != nil {
return x.TtlSeconds
}
return 0
}
func (x *ChunkAnnounceRequest) GetDataCenter() string {
if x != nil {
return x.DataCenter
}
return ""
}
type ChunkAnnounceResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
RejectedFileIds []string `protobuf:"bytes,1,rep,name=rejected_file_ids,json=rejectedFileIds,proto3" json:"rejected_file_ids,omitempty"` // receiver is not the owner of these fids
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChunkAnnounceResponse) Reset() {
*x = ChunkAnnounceResponse{}
mi := &file_mount_peer_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChunkAnnounceResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChunkAnnounceResponse) ProtoMessage() {}
func (x *ChunkAnnounceResponse) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ChunkAnnounceResponse.ProtoReflect.Descriptor instead.
func (*ChunkAnnounceResponse) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{1}
}
func (x *ChunkAnnounceResponse) GetRejectedFileIds() []string {
if x != nil {
return x.RejectedFileIds
}
return nil
}
type ChunkLookupRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
FileIds []string `protobuf:"bytes,1,rep,name=file_ids,json=fileIds,proto3" json:"file_ids,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChunkLookupRequest) Reset() {
*x = ChunkLookupRequest{}
mi := &file_mount_peer_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChunkLookupRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChunkLookupRequest) ProtoMessage() {}
func (x *ChunkLookupRequest) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ChunkLookupRequest.ProtoReflect.Descriptor instead.
func (*ChunkLookupRequest) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{2}
}
func (x *ChunkLookupRequest) GetFileIds() []string {
if x != nil {
return x.FileIds
}
return nil
}
type ChunkLookupResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
PeersByFid map[string]*PeerSet `protobuf:"bytes,1,rep,name=peers_by_fid,json=peersByFid,proto3" json:"peers_by_fid,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
NotOwnerFileIds []string `protobuf:"bytes,2,rep,name=not_owner_file_ids,json=notOwnerFileIds,proto3" json:"not_owner_file_ids,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChunkLookupResponse) Reset() {
*x = ChunkLookupResponse{}
mi := &file_mount_peer_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChunkLookupResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChunkLookupResponse) ProtoMessage() {}
func (x *ChunkLookupResponse) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ChunkLookupResponse.ProtoReflect.Descriptor instead.
func (*ChunkLookupResponse) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{3}
}
func (x *ChunkLookupResponse) GetPeersByFid() map[string]*PeerSet {
if x != nil {
return x.PeersByFid
}
return nil
}
func (x *ChunkLookupResponse) GetNotOwnerFileIds() []string {
if x != nil {
return x.NotOwnerFileIds
}
return nil
}
type PeerSet struct {
state protoimpl.MessageState `protogen:"open.v1"`
Peers []*PeerInfo `protobuf:"bytes,1,rep,name=peers,proto3" json:"peers,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PeerSet) Reset() {
*x = PeerSet{}
mi := &file_mount_peer_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PeerSet) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PeerSet) ProtoMessage() {}
func (x *PeerSet) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use PeerSet.ProtoReflect.Descriptor instead.
func (*PeerSet) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{4}
}
func (x *PeerSet) GetPeers() []*PeerInfo {
if x != nil {
return x.Peers
}
return nil
}
type PeerInfo struct {
state protoimpl.MessageState `protogen:"open.v1"`
PeerAddr string `protobuf:"bytes,1,opt,name=peer_addr,json=peerAddr,proto3" json:"peer_addr,omitempty"`
Rack string `protobuf:"bytes,2,opt,name=rack,proto3" json:"rack,omitempty"`
DataCenter string `protobuf:"bytes,3,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PeerInfo) Reset() {
*x = PeerInfo{}
mi := &file_mount_peer_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PeerInfo) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PeerInfo) ProtoMessage() {}
func (x *PeerInfo) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use PeerInfo.ProtoReflect.Descriptor instead.
func (*PeerInfo) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{5}
}
func (x *PeerInfo) GetPeerAddr() string {
if x != nil {
return x.PeerAddr
}
return ""
}
func (x *PeerInfo) GetRack() string {
if x != nil {
return x.Rack
}
return ""
}
func (x *PeerInfo) GetDataCenter() string {
if x != nil {
return x.DataCenter
}
return ""
}
type FetchChunkRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
FileId string `protobuf:"bytes,1,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"`
ExpectedEtag string `protobuf:"bytes,2,opt,name=expected_etag,json=expectedEtag,proto3" json:"expected_etag,omitempty"` // caller's expected MD5 over the FULL chunk.
// Only meaningful when offset=0 and length=0
// (a whole-chunk fetch); partial reads can't
// be verified against a whole-chunk MD5.
// Fetcher re-verifies end-to-end.
ExpectedSize uint64 `protobuf:"varint,3,opt,name=expected_size,json=expectedSize,proto3" json:"expected_size,omitempty"` // filer-reported chunk byte count; server sizes
// its cache-read buffer to exactly this so a
// sub-max-part-size chunk doesn't trigger the
// cache wrapper's all-or-nothing miss path.
Offset uint64 `protobuf:"varint,4,opt,name=offset,proto3" json:"offset,omitempty"` // optional: byte offset within the chunk to
// start reading from. 0 (default) means a
// whole-chunk transfer starting at byte zero.
Length uint64 `protobuf:"varint,5,opt,name=length,proto3" json:"length,omitempty"` // optional: number of bytes to return from
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FetchChunkRequest) Reset() {
*x = FetchChunkRequest{}
mi := &file_mount_peer_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FetchChunkRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FetchChunkRequest) ProtoMessage() {}
func (x *FetchChunkRequest) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FetchChunkRequest.ProtoReflect.Descriptor instead.
func (*FetchChunkRequest) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{6}
}
func (x *FetchChunkRequest) GetFileId() string {
if x != nil {
return x.FileId
}
return ""
}
func (x *FetchChunkRequest) GetExpectedEtag() string {
if x != nil {
return x.ExpectedEtag
}
return ""
}
func (x *FetchChunkRequest) GetExpectedSize() uint64 {
if x != nil {
return x.ExpectedSize
}
return 0
}
func (x *FetchChunkRequest) GetOffset() uint64 {
if x != nil {
return x.Offset
}
return 0
}
func (x *FetchChunkRequest) GetLength() uint64 {
if x != nil {
return x.Length
}
return 0
}
type FetchChunkResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` // next frame of chunk bytes; concatenate across stream
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FetchChunkResponse) Reset() {
*x = FetchChunkResponse{}
mi := &file_mount_peer_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FetchChunkResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FetchChunkResponse) ProtoMessage() {}
func (x *FetchChunkResponse) ProtoReflect() protoreflect.Message {
mi := &file_mount_peer_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FetchChunkResponse.ProtoReflect.Descriptor instead.
func (*FetchChunkResponse) Descriptor() ([]byte, []int) {
return file_mount_peer_proto_rawDescGZIP(), []int{7}
}
func (x *FetchChunkResponse) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
var File_mount_peer_proto protoreflect.FileDescriptor
const file_mount_peer_proto_rawDesc = "" +
"\n" +
"\x10mount_peer.proto\x12\rmount_peer_pb\"\xa4\x01\n" +
"\x14ChunkAnnounceRequest\x12\x19\n" +
"\bfile_ids\x18\x01 \x03(\tR\afileIds\x12\x1b\n" +
"\tpeer_addr\x18\x02 \x01(\tR\bpeerAddr\x12\x12\n" +
"\x04rack\x18\x03 \x01(\tR\x04rack\x12\x1f\n" +
"\vttl_seconds\x18\x04 \x01(\x05R\n" +
"ttlSeconds\x12\x1f\n" +
"\vdata_center\x18\x05 \x01(\tR\n" +
"dataCenter\"C\n" +
"\x15ChunkAnnounceResponse\x12*\n" +
"\x11rejected_file_ids\x18\x01 \x03(\tR\x0frejectedFileIds\"/\n" +
"\x12ChunkLookupRequest\x12\x19\n" +
"\bfile_ids\x18\x01 \x03(\tR\afileIds\"\xef\x01\n" +
"\x13ChunkLookupResponse\x12T\n" +
"\fpeers_by_fid\x18\x01 \x03(\v22.mount_peer_pb.ChunkLookupResponse.PeersByFidEntryR\n" +
"peersByFid\x12+\n" +
"\x12not_owner_file_ids\x18\x02 \x03(\tR\x0fnotOwnerFileIds\x1aU\n" +
"\x0fPeersByFidEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12,\n" +
"\x05value\x18\x02 \x01(\v2\x16.mount_peer_pb.PeerSetR\x05value:\x028\x01\"8\n" +
"\aPeerSet\x12-\n" +
"\x05peers\x18\x01 \x03(\v2\x17.mount_peer_pb.PeerInfoR\x05peers\"\\\n" +
"\bPeerInfo\x12\x1b\n" +
"\tpeer_addr\x18\x01 \x01(\tR\bpeerAddr\x12\x12\n" +
"\x04rack\x18\x02 \x01(\tR\x04rack\x12\x1f\n" +
"\vdata_center\x18\x03 \x01(\tR\n" +
"dataCenter\"\xa6\x01\n" +
"\x11FetchChunkRequest\x12\x17\n" +
"\afile_id\x18\x01 \x01(\tR\x06fileId\x12#\n" +
"\rexpected_etag\x18\x02 \x01(\tR\fexpectedEtag\x12#\n" +
"\rexpected_size\x18\x03 \x01(\x04R\fexpectedSize\x12\x16\n" +
"\x06offset\x18\x04 \x01(\x04R\x06offset\x12\x16\n" +
"\x06length\x18\x05 \x01(\x04R\x06length\"(\n" +
"\x12FetchChunkResponse\x12\x12\n" +
"\x04data\x18\x01 \x01(\fR\x04data2\x98\x02\n" +
"\tMountPeer\x12\\\n" +
"\rChunkAnnounce\x12#.mount_peer_pb.ChunkAnnounceRequest\x1a$.mount_peer_pb.ChunkAnnounceResponse\"\x00\x12V\n" +
"\vChunkLookup\x12!.mount_peer_pb.ChunkLookupRequest\x1a\".mount_peer_pb.ChunkLookupResponse\"\x00\x12U\n" +
"\n" +
"FetchChunk\x12 .mount_peer_pb.FetchChunkRequest\x1a!.mount_peer_pb.FetchChunkResponse\"\x000\x01B6Z4github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pbb\x06proto3"
var (
file_mount_peer_proto_rawDescOnce sync.Once
file_mount_peer_proto_rawDescData []byte
)
func file_mount_peer_proto_rawDescGZIP() []byte {
file_mount_peer_proto_rawDescOnce.Do(func() {
file_mount_peer_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_mount_peer_proto_rawDesc), len(file_mount_peer_proto_rawDesc)))
})
return file_mount_peer_proto_rawDescData
}
var file_mount_peer_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
var file_mount_peer_proto_goTypes = []any{
(*ChunkAnnounceRequest)(nil), // 0: mount_peer_pb.ChunkAnnounceRequest
(*ChunkAnnounceResponse)(nil), // 1: mount_peer_pb.ChunkAnnounceResponse
(*ChunkLookupRequest)(nil), // 2: mount_peer_pb.ChunkLookupRequest
(*ChunkLookupResponse)(nil), // 3: mount_peer_pb.ChunkLookupResponse
(*PeerSet)(nil), // 4: mount_peer_pb.PeerSet
(*PeerInfo)(nil), // 5: mount_peer_pb.PeerInfo
(*FetchChunkRequest)(nil), // 6: mount_peer_pb.FetchChunkRequest
(*FetchChunkResponse)(nil), // 7: mount_peer_pb.FetchChunkResponse
nil, // 8: mount_peer_pb.ChunkLookupResponse.PeersByFidEntry
}
var file_mount_peer_proto_depIdxs = []int32{
8, // 0: mount_peer_pb.ChunkLookupResponse.peers_by_fid:type_name -> mount_peer_pb.ChunkLookupResponse.PeersByFidEntry
5, // 1: mount_peer_pb.PeerSet.peers:type_name -> mount_peer_pb.PeerInfo
4, // 2: mount_peer_pb.ChunkLookupResponse.PeersByFidEntry.value:type_name -> mount_peer_pb.PeerSet
0, // 3: mount_peer_pb.MountPeer.ChunkAnnounce:input_type -> mount_peer_pb.ChunkAnnounceRequest
2, // 4: mount_peer_pb.MountPeer.ChunkLookup:input_type -> mount_peer_pb.ChunkLookupRequest
6, // 5: mount_peer_pb.MountPeer.FetchChunk:input_type -> mount_peer_pb.FetchChunkRequest
1, // 6: mount_peer_pb.MountPeer.ChunkAnnounce:output_type -> mount_peer_pb.ChunkAnnounceResponse
3, // 7: mount_peer_pb.MountPeer.ChunkLookup:output_type -> mount_peer_pb.ChunkLookupResponse
7, // 8: mount_peer_pb.MountPeer.FetchChunk:output_type -> mount_peer_pb.FetchChunkResponse
6, // [6:9] is the sub-list for method output_type
3, // [3:6] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension type_name
3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
}
func init() { file_mount_peer_proto_init() }
func file_mount_peer_proto_init() {
if File_mount_peer_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_mount_peer_proto_rawDesc), len(file_mount_peer_proto_rawDesc)),
NumEnums: 0,
NumMessages: 9,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_mount_peer_proto_goTypes,
DependencyIndexes: file_mount_peer_proto_depIdxs,
MessageInfos: file_mount_peer_proto_msgTypes,
}.Build()
File_mount_peer_proto = out.File
file_mount_peer_proto_goTypes = nil
file_mount_peer_proto_depIdxs = nil
}
+229
View File
@@ -0,0 +1,229 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v6.33.4
// source: mount_peer.proto
package mount_peer_pb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
MountPeer_ChunkAnnounce_FullMethodName = "/mount_peer_pb.MountPeer/ChunkAnnounce"
MountPeer_ChunkLookup_FullMethodName = "/mount_peer_pb.MountPeer/ChunkLookup"
MountPeer_FetchChunk_FullMethodName = "/mount_peer_pb.MountPeer/FetchChunk"
)
// MountPeerClient is the client API for MountPeer service.
//
// 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 MountPeerClient interface {
// ChunkAnnounce: the caller asserts it currently holds the listed fids in
// its local chunk cache and is willing to serve them to peers. The
// receiver accepts only fids for which it is the HRW-assigned owner on
// its current seed view; others are returned in rejected_file_ids.
ChunkAnnounce(ctx context.Context, in *ChunkAnnounceRequest, opts ...grpc.CallOption) (*ChunkAnnounceResponse, error)
// ChunkLookup: asks the receiver for known holders of each requested fid.
// The receiver responds only for fids it owns; others are listed in
// not_owner_file_ids so the caller can retry against the correct owner
// after refreshing its own seed view.
ChunkLookup(ctx context.Context, in *ChunkLookupRequest, opts ...grpc.CallOption) (*ChunkLookupResponse, error)
// FetchChunk: server-streams the bytes of a cached chunk to a peer.
// Streaming avoids the default gRPC 4 MiB message cap for typical
// 16 MiB chunks and lets the receiver assemble into a preallocated
// buffer. Not-cached / cache-miss returns a gRPC NOT_FOUND status.
// The fetcher re-verifies MD5 against expected_etag end-to-end after
// the stream completes.
FetchChunk(ctx context.Context, in *FetchChunkRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[FetchChunkResponse], error)
}
type mountPeerClient struct {
cc grpc.ClientConnInterface
}
func NewMountPeerClient(cc grpc.ClientConnInterface) MountPeerClient {
return &mountPeerClient{cc}
}
func (c *mountPeerClient) ChunkAnnounce(ctx context.Context, in *ChunkAnnounceRequest, opts ...grpc.CallOption) (*ChunkAnnounceResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ChunkAnnounceResponse)
err := c.cc.Invoke(ctx, MountPeer_ChunkAnnounce_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *mountPeerClient) ChunkLookup(ctx context.Context, in *ChunkLookupRequest, opts ...grpc.CallOption) (*ChunkLookupResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ChunkLookupResponse)
err := c.cc.Invoke(ctx, MountPeer_ChunkLookup_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *mountPeerClient) FetchChunk(ctx context.Context, in *FetchChunkRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[FetchChunkResponse], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &MountPeer_ServiceDesc.Streams[0], MountPeer_FetchChunk_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[FetchChunkRequest, FetchChunkResponse]{ClientStream: stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type MountPeer_FetchChunkClient = grpc.ServerStreamingClient[FetchChunkResponse]
// MountPeerServer is the server API for MountPeer service.
// All implementations must embed UnimplementedMountPeerServer
// for forward compatibility.
type MountPeerServer interface {
// ChunkAnnounce: the caller asserts it currently holds the listed fids in
// its local chunk cache and is willing to serve them to peers. The
// receiver accepts only fids for which it is the HRW-assigned owner on
// its current seed view; others are returned in rejected_file_ids.
ChunkAnnounce(context.Context, *ChunkAnnounceRequest) (*ChunkAnnounceResponse, error)
// ChunkLookup: asks the receiver for known holders of each requested fid.
// The receiver responds only for fids it owns; others are listed in
// not_owner_file_ids so the caller can retry against the correct owner
// after refreshing its own seed view.
ChunkLookup(context.Context, *ChunkLookupRequest) (*ChunkLookupResponse, error)
// FetchChunk: server-streams the bytes of a cached chunk to a peer.
// Streaming avoids the default gRPC 4 MiB message cap for typical
// 16 MiB chunks and lets the receiver assemble into a preallocated
// buffer. Not-cached / cache-miss returns a gRPC NOT_FOUND status.
// The fetcher re-verifies MD5 against expected_etag end-to-end after
// the stream completes.
FetchChunk(*FetchChunkRequest, grpc.ServerStreamingServer[FetchChunkResponse]) error
mustEmbedUnimplementedMountPeerServer()
}
// UnimplementedMountPeerServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedMountPeerServer struct{}
func (UnimplementedMountPeerServer) ChunkAnnounce(context.Context, *ChunkAnnounceRequest) (*ChunkAnnounceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ChunkAnnounce not implemented")
}
func (UnimplementedMountPeerServer) ChunkLookup(context.Context, *ChunkLookupRequest) (*ChunkLookupResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ChunkLookup not implemented")
}
func (UnimplementedMountPeerServer) FetchChunk(*FetchChunkRequest, grpc.ServerStreamingServer[FetchChunkResponse]) error {
return status.Errorf(codes.Unimplemented, "method FetchChunk not implemented")
}
func (UnimplementedMountPeerServer) mustEmbedUnimplementedMountPeerServer() {}
func (UnimplementedMountPeerServer) testEmbeddedByValue() {}
// UnsafeMountPeerServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to MountPeerServer will
// result in compilation errors.
type UnsafeMountPeerServer interface {
mustEmbedUnimplementedMountPeerServer()
}
func RegisterMountPeerServer(s grpc.ServiceRegistrar, srv MountPeerServer) {
// If the following call pancis, it indicates UnimplementedMountPeerServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&MountPeer_ServiceDesc, srv)
}
func _MountPeer_ChunkAnnounce_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ChunkAnnounceRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MountPeerServer).ChunkAnnounce(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: MountPeer_ChunkAnnounce_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MountPeerServer).ChunkAnnounce(ctx, req.(*ChunkAnnounceRequest))
}
return interceptor(ctx, in, info, handler)
}
func _MountPeer_ChunkLookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ChunkLookupRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MountPeerServer).ChunkLookup(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: MountPeer_ChunkLookup_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MountPeerServer).ChunkLookup(ctx, req.(*ChunkLookupRequest))
}
return interceptor(ctx, in, info, handler)
}
func _MountPeer_FetchChunk_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(FetchChunkRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(MountPeerServer).FetchChunk(m, &grpc.GenericServerStream[FetchChunkRequest, FetchChunkResponse]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type MountPeer_FetchChunkServer = grpc.ServerStreamingServer[FetchChunkResponse]
// MountPeer_ServiceDesc is the grpc.ServiceDesc for MountPeer service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var MountPeer_ServiceDesc = grpc.ServiceDesc{
ServiceName: "mount_peer_pb.MountPeer",
HandlerType: (*MountPeerServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ChunkAnnounce",
Handler: _MountPeer_ChunkAnnounce_Handler,
},
{
MethodName: "ChunkLookup",
Handler: _MountPeer_ChunkLookup_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "FetchChunk",
Handler: _MountPeer_FetchChunk_Handler,
ServerStreams: true,
},
},
Metadata: "mount_peer.proto",
}
@@ -1156,6 +1156,12 @@ func (h *HybridMessageScanner) ReadParquetStatistics(partitionPath string) ([]*P
// extractParquetFileStats extracts column statistics from a single parquet file
func (h *HybridMessageScanner) extractParquetFileStats(entry *filer_pb.Entry, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunkCache *chunk_cache.ChunkCacheInMemory) (*ParquetFileStats, error) {
if entry == nil {
return nil, fmt.Errorf("cannot operate on nil entry")
}
if chunkCache == nil {
return nil, fmt.Errorf("cannot operate on nil chunkCache")
}
// Create reader for the parquet file
fileSize := filer.FileSize(entry)
visibleIntervals, _ := filer.NonOverlappingVisibleIntervals(context.Background(), lookupFileIdFn, entry.Chunks, 0, int64(fileSize))
+18 -56
View File
@@ -1337,11 +1337,13 @@ func (iam *IdentityAccessManagement) authenticateRequestInternal(r *http.Request
var found bool
var amzAuthType string
// SECURITY: Prevent clients from spoofing internal IAM headers
// SECURITY: Prevent clients from spoofing internal IAM headers.
// These headers are only set by the server after successful JWT authentication
// Clearing them here prevents privilege escalation via header injection
r.Header.Del("X-SeaweedFS-Principal")
r.Header.Del("X-SeaweedFS-Session-Token")
// and are trusted by downstream authorization (including S3Tables IAM checks
// reached via AuthSignatureOnly). Clearing them here — the shared entry point
// for every auth path — prevents privilege escalation via header injection.
r.Header.Del(s3_constants.SeaweedFSPrincipalHeader)
r.Header.Del(s3_constants.SeaweedFSSessionTokenHeader)
reqAuthType := getRequestAuthType(r)
@@ -1478,53 +1480,13 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
// AuthSignatureOnly performs only signature verification without any authorization checks.
// This is used for IAM API operations where authorization is handled separately based on
// the specific IAM action (e.g., self-service vs admin operations).
// the specific IAM action (e.g., self-service vs admin operations). It delegates to
// authenticateRequestInternal so the internal-IAM-header stripping and the auth-type
// dispatch stay in one place — any future fix applied there automatically covers
// S3Tables, UnifiedPostHandler, and the other AuthSignatureOnly callers.
// Returns the authenticated identity and any signature verification error.
func (iam *IdentityAccessManagement) AuthSignatureOnly(r *http.Request) (*Identity, s3err.ErrorCode) {
var identity *Identity
var s3Err s3err.ErrorCode
var authType string
switch getRequestAuthType(r) {
case authTypeUnknown:
glog.V(3).Infof("unknown auth type")
r.Header.Set(s3_constants.AmzAuthType, "Unknown")
return identity, s3err.ErrAccessDenied
case authTypePresignedV2, authTypeSignedV2:
glog.V(3).Infof("v2 auth type")
identity, s3Err = iam.isReqAuthenticatedV2(r)
authType = "SigV2"
case authTypeStreamingSigned, authTypeSigned, authTypePresigned:
glog.V(3).Infof("v4 auth type")
identity, s3Err = iam.reqSignatureV4Verify(r)
authType = "SigV4"
case authTypeStreamingUnsigned:
glog.V(3).Infof("unsigned streaming upload")
identity, s3Err = iam.reqSignatureV4Verify(r)
authType = "SigV4"
case authTypeJWT:
glog.V(3).Infof("jwt auth type detected, iamIntegration != nil? %t", iam.iamIntegration != nil)
r.Header.Set(s3_constants.AmzAuthType, "Jwt")
if iam.iamIntegration != nil {
identity, s3Err = iam.authenticateJWTWithIAM(r)
authType = "Jwt"
} else {
glog.V(2).Infof("IAM integration is nil, returning ErrNotImplemented")
return identity, s3err.ErrNotImplemented
}
case authTypeAnonymous:
if ident, found := iam.LookupAnonymous(); found {
return ident, s3err.ErrNone
}
return nil, s3err.ErrAccessDenied
default:
return identity, s3err.ErrNotImplemented
}
if len(authType) > 0 {
r.Header.Set(s3_constants.AmzAuthType, authType)
}
identity, s3Err, _ := iam.authenticateRequestInternal(r)
if s3Err != s3err.ErrNone {
return identity, s3Err
}
@@ -1631,7 +1593,7 @@ func (identity *Identity) isAdmin() bool {
func buildPrincipalARN(identity *Identity, r *http.Request) string {
// Check if principal ARN was already set by JWT authentication
if r != nil {
if principalARN := r.Header.Get("X-SeaweedFS-Principal"); principalARN != "" {
if principalARN := r.Header.Get(s3_constants.SeaweedFSPrincipalHeader); principalARN != "" {
glog.V(4).Infof("buildPrincipalARN: Using principal ARN from header: %s", principalARN)
return principalARN
}
@@ -2000,8 +1962,8 @@ func (iam *IdentityAccessManagement) authenticateJWTWithIAM(r *http.Request) (*I
}
// Store session info in request headers for later authorization
r.Header.Set("X-SeaweedFS-Session-Token", iamIdentity.SessionToken)
r.Header.Set("X-SeaweedFS-Principal", iamIdentity.Principal)
r.Header.Set(s3_constants.SeaweedFSSessionTokenHeader, iamIdentity.SessionToken)
r.Header.Set(s3_constants.SeaweedFSPrincipalHeader, iamIdentity.Principal)
return identity, s3err.ErrNone
}
@@ -2121,7 +2083,7 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide
// JWT/STS identities (no Actions or having a session token) use IAM authorization.
// IMPORTANT: We MUST prioritize IAM authorization for any request with a session token
// to ensure that session policies are correctly enforced.
hasSessionToken := r.Header.Get("X-SeaweedFS-Session-Token") != "" ||
hasSessionToken := r.Header.Get(s3_constants.SeaweedFSSessionTokenHeader) != "" ||
r.Header.Get("X-Amz-Security-Token") != "" ||
r.URL.Query().Get("X-Amz-Security-Token") != ""
iam.m.RLock()
@@ -2167,9 +2129,9 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
ctx := r.Context()
// Get session info from request headers
// First check for JWT-based authentication headers (X-SeaweedFS-Session-Token)
sessionToken := r.Header.Get("X-SeaweedFS-Session-Token")
principal := r.Header.Get("X-SeaweedFS-Principal")
// First check for JWT-based authentication headers (SeaweedFSSessionTokenHeader)
sessionToken := r.Header.Get(s3_constants.SeaweedFSSessionTokenHeader)
principal := r.Header.Get(s3_constants.SeaweedFSPrincipalHeader)
// Fallback to AWS Signature V4 STS token if JWT token not present
// This handles the case where STS AssumeRoleWithWebIdentity generates temporary credentials
+18
View File
@@ -129,6 +129,24 @@ func TestReproIssue7912(t *testing.T) {
// No Authorization header
_, errCode3 := iam.AuthSignatureOnly(r3)
assert.Equal(t, s3err.ErrAccessDenied, errCode3, "AuthSignatureOnly should be denied with unsigned streaming if no auth header")
// Verify fix: client-supplied X-SeaweedFS-Principal / X-SeaweedFS-Session-Token
// headers must be stripped, otherwise a signed low-privilege caller could
// spoof the principal that downstream IAM authorization (e.g. S3Tables
// CreateTableBucket) evaluates against.
r4 := httptest.NewRequest(http.MethodGet, "http://localhost:8333/", nil)
r4.Host = "localhost:8333"
err = signRawHTTPRequest(context.Background(), r4, "readonly_access_key", "readonly_secret_key", "us-east-1")
require.NoError(t, err)
// Attacker injects these headers after signing; they are not part of
// SignedHeaders, so SigV4 verification still passes.
r4.Header.Set(s3_constants.SeaweedFSPrincipalHeader, "arn:aws:iam::123456789012:root")
r4.Header.Set(s3_constants.SeaweedFSSessionTokenHeader, "spoofed-session-token")
_, errCode4 := iam.AuthSignatureOnly(r4)
assert.Equal(t, s3err.ErrNone, errCode4)
assert.Empty(t, r4.Header.Get(s3_constants.SeaweedFSPrincipalHeader), "client-supplied X-SeaweedFS-Principal must be stripped")
assert.Empty(t, r4.Header.Get(s3_constants.SeaweedFSSessionTokenHeader), "client-supplied X-SeaweedFS-Session-Token must be stripped")
})
t.Run("Wrong secret key", func(t *testing.T) {
+62
View File
@@ -291,6 +291,14 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
return nil, nil, "", nil, errCode
}
// 5a. Reject requests that carry x-amz-* headers outside of SignedHeaders.
// Without this check a presigned-URL holder can inject unsigned headers
// (x-amz-tagging, x-amz-acl, x-amz-meta-*, x-amz-storage-class, x-amz-object-lock-*,
// x-amz-server-side-encryption*, etc.) that downstream handlers still persist.
if errCode = verifySignedHeadersCoverage(r, authInfo.SignedHeaders, authInfo.IsPresigned); errCode != s3err.ErrNone {
return nil, nil, "", nil, errCode
}
// 6. Get the query string for the canonical request
queryStr := getCanonicalQueryString(r, authInfo.IsPresigned)
@@ -761,6 +769,60 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(formValues http.
return s3err.ErrNone
}
// sigV4PayloadHashHeader is x-amz-content-sha256. It participates in the
// canonical request via the payload-hash line regardless of whether it is
// listed in SignedHeaders, so tampering with it still breaks the signature.
// It is therefore exempted from the "all x-amz-* headers must be signed" rule
// for both header-based and presigned requests.
const sigV4PayloadHashHeader = "x-amz-content-sha256"
// presignedSigV4ProtocolHeaders lists SigV4 protocol parameters that are
// conveyed in the presigned URL's query string. Some clients and proxies echo
// them as request headers; those duplicates do not influence signature
// computation or object persistence and are exempted from the
// "all x-amz-* headers must be signed" rule for presigned requests only.
var presignedSigV4ProtocolHeaders = map[string]struct{}{
"x-amz-algorithm": {},
"x-amz-credential": {},
"x-amz-date": {},
"x-amz-expires": {},
"x-amz-signedheaders": {},
"x-amz-signature": {},
}
// verifySignedHeadersCoverage rejects requests that carry x-amz-* headers
// outside of the SignedHeaders list. AWS SigV4 requires every x-amz-* header
// present in the request to be covered by the signature; without this check a
// presigned-URL holder can add unsigned headers (ACL, tagging, storage class,
// user metadata, encryption options, object lock) that the server still
// persists to object metadata.
func verifySignedHeadersCoverage(r *http.Request, signedHeaders []string, isPresigned bool) s3err.ErrorCode {
signedSet := make(map[string]struct{}, len(signedHeaders))
for _, h := range signedHeaders {
signedSet[strings.ToLower(h)] = struct{}{}
}
for name := range r.Header {
lower := strings.ToLower(name)
if !strings.HasPrefix(lower, "x-amz-") {
continue
}
if _, ok := signedSet[lower]; ok {
continue
}
if lower == sigV4PayloadHashHeader {
continue
}
if isPresigned {
if _, exempt := presignedSigV4ProtocolHeaders[lower]; exempt {
continue
}
}
glog.V(2).Infof("reject %s %s: unsigned header %q not in SignedHeaders", r.Method, r.URL.Path, name)
return s3err.ErrSignatureDoesNotMatch
}
return s3err.ErrNone
}
// Verify if extracted signed headers are not properly signed.
func extractSignedHeaders(signedHeaders []string, r *http.Request, externalHost string) (http.Header, s3err.ErrorCode) {
reqHeaders := r.Header
@@ -0,0 +1,295 @@
package s3api
import (
"fmt"
"net/http"
"sort"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
// TestVerifySignedHeadersCoverage_Unit exercises the helper directly.
func TestVerifySignedHeadersCoverage_Unit(t *testing.T) {
tests := []struct {
name string
headers map[string]string
signedHeaders []string
isPresigned bool
want s3err.ErrorCode
}{
{
name: "no x-amz headers is fine",
headers: map[string]string{"Content-Type": "text/plain"},
signedHeaders: []string{"host"},
want: s3err.ErrNone,
},
{
name: "signed x-amz header is accepted",
headers: map[string]string{
"X-Amz-Date": "20250101T000000Z",
"X-Amz-Tagging": "a=b",
},
signedHeaders: []string{"host", "x-amz-date", "x-amz-tagging"},
want: s3err.ErrNone,
},
{
name: "unsigned x-amz-tagging is rejected (header-based)",
headers: map[string]string{
"X-Amz-Date": "20250101T000000Z",
"X-Amz-Tagging": "secret=pwn",
},
signedHeaders: []string{"host", "x-amz-date"},
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "unsigned x-amz-meta-* is rejected",
headers: map[string]string{
"X-Amz-Meta-Owner": "attacker",
},
signedHeaders: []string{"host"},
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "unsigned x-amz-acl is rejected",
headers: map[string]string{
"X-Amz-Acl": "public-read",
},
signedHeaders: []string{"host"},
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "unsigned x-amz-storage-class is rejected",
headers: map[string]string{
"X-Amz-Storage-Class": "GLACIER",
},
signedHeaders: []string{"host"},
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "unsigned x-amz-server-side-encryption is rejected",
headers: map[string]string{
"X-Amz-Server-Side-Encryption": "AES256",
},
signedHeaders: []string{"host"},
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "unsigned x-amz-object-lock-retain-until-date is rejected",
headers: map[string]string{
"X-Amz-Object-Lock-Retain-Until-Date": "2099-01-01T00:00:00Z",
},
signedHeaders: []string{"host"},
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "unsigned x-amz-security-token is rejected (even presigned)",
headers: map[string]string{
"X-Amz-Security-Token": "attacker-token",
},
signedHeaders: []string{"host"},
isPresigned: true,
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "x-amz-content-sha256 is always exempt (presigned)",
headers: map[string]string{
"X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD",
},
signedHeaders: []string{"host"},
isPresigned: true,
want: s3err.ErrNone,
},
{
name: "x-amz-content-sha256 is always exempt (header-based)",
headers: map[string]string{
"X-Amz-Content-Sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
},
signedHeaders: []string{"host"},
isPresigned: false,
want: s3err.ErrNone,
},
{
name: "presigned exempts sigv4 query params echoed as headers",
headers: map[string]string{
"X-Amz-Algorithm": "AWS4-HMAC-SHA256",
"X-Amz-Credential": "AKIA/20250101/us-east-1/s3/aws4_request",
"X-Amz-Date": "20250101T000000Z",
"X-Amz-Expires": "3600",
"X-Amz-SignedHeaders": "host",
"X-Amz-Signature": "deadbeef",
},
signedHeaders: []string{"host"},
isPresigned: true,
want: s3err.ErrNone,
},
{
name: "header-based does NOT exempt x-amz-date when unsigned",
headers: map[string]string{
"X-Amz-Date": "20250101T000000Z",
},
signedHeaders: []string{"host"},
isPresigned: false,
want: s3err.ErrSignatureDoesNotMatch,
},
{
name: "signed headers match is case-insensitive",
headers: map[string]string{
"X-Amz-Tagging": "a=b",
},
signedHeaders: []string{"HOST", "X-Amz-Tagging"},
want: s3err.ErrNone,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest(http.MethodPut, "http://example.com/bucket/key", nil)
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
for k, v := range tt.headers {
req.Header.Set(k, v)
}
got := verifySignedHeadersCoverage(req, tt.signedHeaders, tt.isPresigned)
if got != tt.want {
t.Fatalf("verifySignedHeadersCoverage = %v, want %v", got, tt.want)
}
})
}
}
// TestPresignedPutRejectsUnsignedTagging exercises the full verification path
// through reqSignatureV4Verify for a presigned URL that signs only `host` but
// whose caller attached an x-amz-tagging header after-the-fact.
func TestPresignedPutRejectsUnsignedTagging(t *testing.T) {
iam := newTestIAM()
req, err := newTestRequest(http.MethodPut, "http://127.0.0.1:9000/bucket/key", 0, nil)
if err != nil {
t.Fatalf("newTestRequest: %v", err)
}
if err := preSignV4(iam, req, "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 600); err != nil {
t.Fatalf("preSignV4: %v", err)
}
// Attacker appends an unsigned header after the URL was signed.
req.Header.Set("X-Amz-Tagging", "classification=public")
_, errCode := iam.reqSignatureV4Verify(req)
if errCode != s3err.ErrSignatureDoesNotMatch {
t.Fatalf("expected ErrSignatureDoesNotMatch for unsigned x-amz-tagging, got %v", errCode)
}
}
// TestPresignedPutAcceptsSignedTagging confirms that a presigned URL whose
// SignedHeaders list covers x-amz-tagging still validates successfully.
func TestPresignedPutAcceptsSignedTagging(t *testing.T) {
iam := newTestIAM()
req, err := newTestRequest(http.MethodPut, "http://127.0.0.1:9000/bucket/key", 0, nil)
if err != nil {
t.Fatalf("newTestRequest: %v", err)
}
req.Header.Set("X-Amz-Tagging", "classification=public")
if err := preSignV4WithHeaders(iam, req, "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 600, []string{"host", "x-amz-tagging"}); err != nil {
t.Fatalf("preSignV4WithHeaders: %v", err)
}
_, errCode := iam.reqSignatureV4Verify(req)
if errCode != s3err.ErrNone {
t.Fatalf("expected ErrNone for signed x-amz-tagging, got %v", errCode)
}
}
// preSignV4WithHeaders is a test helper that builds a presigned URL whose
// SignedHeaders list covers the specified headers (which must already be set
// on the request), then computes the signature over those headers and
// attaches X-Amz-Signature.
func preSignV4WithHeaders(_ *IdentityAccessManagement, req *http.Request, accessKey, secretKey string, expires int64, signedHeaders []string) error {
now := time.Now().UTC()
dateStr := now.Format(iso8601Format)
scope := fmt.Sprintf("%s/%s/%s/%s", now.Format(yyyymmdd), "us-east-1", "s3", "aws4_request")
credential := fmt.Sprintf("%s/%s", accessKey, scope)
normalized := make([]string, 0, len(signedHeaders))
for _, h := range signedHeaders {
normalized = append(normalized, strings.ToLower(h))
}
sort.Strings(normalized)
query := req.URL.Query()
query.Set("X-Amz-Algorithm", signV4Algorithm)
query.Set("X-Amz-Credential", credential)
query.Set("X-Amz-Date", dateStr)
query.Set("X-Amz-Expires", fmt.Sprintf("%d", expires))
query.Set("X-Amz-SignedHeaders", strings.Join(normalized, ";"))
req.URL.RawQuery = query.Encode()
hashedPayload := query.Get("X-Amz-Content-Sha256")
if hashedPayload == "" {
hashedPayload = unsignedPayload
}
extracted := make(http.Header)
for _, h := range normalized {
if h == "host" {
extracted[h] = []string{req.Host}
continue
}
if values, ok := req.Header[http.CanonicalHeaderKey(h)]; ok {
extracted[h] = values
}
}
canonicalRequest := getCanonicalRequest(extracted, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method)
stringToSign := getStringToSign(canonicalRequest, now, scope)
signingKey := getSigningKey(secretKey, now.Format(yyyymmdd), "us-east-1", "s3")
signature := getSignature(signingKey, stringToSign)
query.Set("X-Amz-Signature", signature)
req.URL.RawQuery = query.Encode()
return nil
}
// TestPresignedPutRejectsUnsignedMetadataHeaders checks a spread of
// security-relevant headers that the PUT handler persists.
func TestPresignedPutRejectsUnsignedMetadataHeaders(t *testing.T) {
dangerous := []struct {
name string
header string
value string
}{
{"acl", "X-Amz-Acl", "public-read"},
{"user-metadata", "X-Amz-Meta-Owner", "attacker"},
{"storage-class", "X-Amz-Storage-Class", "GLACIER"},
{"server-side-encryption", "X-Amz-Server-Side-Encryption", "AES256"},
{"sse-kms-key-id", "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", "kms-key"},
{"object-lock-mode", "X-Amz-Object-Lock-Mode", "GOVERNANCE"},
{"object-lock-retain-until", "X-Amz-Object-Lock-Retain-Until-Date", "2099-01-01T00:00:00Z"},
{"website-redirect-location", "X-Amz-Website-Redirect-Location", "https://attacker.example/"},
{"grant-full-control", "X-Amz-Grant-Full-Control", "id=attacker"},
}
for _, c := range dangerous {
t.Run(c.name, func(t *testing.T) {
iam := newTestIAM()
req, err := newTestRequest(http.MethodPut, "http://127.0.0.1:9000/bucket/key", 0, nil)
if err != nil {
t.Fatalf("newTestRequest: %v", err)
}
if err := preSignV4(iam, req, "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 600); err != nil {
t.Fatalf("preSignV4: %v", err)
}
req.Header.Set(c.header, c.value)
_, errCode := iam.reqSignatureV4Verify(req)
if errCode != s3err.ErrSignatureDoesNotMatch {
t.Fatalf("expected rejection for unsigned %s, got %v", c.header, errCode)
}
})
}
}
+6 -6
View File
@@ -28,8 +28,8 @@ func TestAuthorizeWithIAMSessionTokenExtraction(t *testing.T) {
}
// Extract tokens the same way authorizeWithIAM does
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
principal := req.Header.Get("X-SeaweedFS-Principal")
sessionToken := req.Header.Get(s3_constants.SeaweedFSSessionTokenHeader)
principal := req.Header.Get(s3_constants.SeaweedFSPrincipalHeader)
assert.Equal(t, "jwt-token-123", sessionToken, "Should extract JWT session token from header")
assert.Equal(t, "arn:aws:iam::user/test", principal, "Should extract principal from header")
@@ -44,8 +44,8 @@ func TestAuthorizeWithIAMSessionTokenExtraction(t *testing.T) {
}
// Extract tokens the same way authorizeWithIAM does
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
principal := req.Header.Get("X-SeaweedFS-Principal")
sessionToken := req.Header.Get(s3_constants.SeaweedFSSessionTokenHeader)
principal := req.Header.Get(s3_constants.SeaweedFSPrincipalHeader)
// If JWT token is empty, should fallback to X-Amz-Security-Token
if sessionToken == "" {
@@ -63,7 +63,7 @@ func TestAuthorizeWithIAMSessionTokenExtraction(t *testing.T) {
}
// Extract tokens the same way authorizeWithIAM does
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
sessionToken := req.Header.Get(s3_constants.SeaweedFSSessionTokenHeader)
if sessionToken == "" {
sessionToken = req.Header.Get("X-Amz-Security-Token")
if sessionToken == "" {
@@ -85,7 +85,7 @@ func TestAuthorizeWithIAMSessionTokenExtraction(t *testing.T) {
}
// Extract tokens the same way authorizeWithIAM does
sessionToken := req.Header.Get("X-SeaweedFS-Session-Token")
sessionToken := req.Header.Get(s3_constants.SeaweedFSSessionTokenHeader)
if sessionToken == "" {
sessionToken = req.Header.Get("X-Amz-Security-Token")
}
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more