Compare commits

...
46 Commits
Author SHA1 Message Date
Chris Lu eb93976166 4.35 2026-06-22 00:24:50 -07:00
Bruce Zou 7688e69146 use Leader() instead of MaybeLeader() in SendHeartbeat (#10029)
During leader election, MaybeLeader() returns empty string immediately (non-blocking),
causing master to return NotLeaderError without sending HeartbeatResponse.Leader.
Volume servers depend on HeartbeatResponse.Leader to discover the new leader address,
so they keep retrying the old leader and cannot switch.

Switching to Leader() restores the 20-second exponential backoff retry behavior,
ensuring volume servers receive the new leader address as soon as election completes.
2026-06-21 23:11:12 -07:00
Chris Lu 56d7904dc5 stats: define metric subsystems as constants (#10027) 2026-06-21 11:52:08 -07:00
e2a17a76fc feat: add Prometheus metric for volume creation operations (#10026)
* feat: add Prometheus metric for volume creation operations

Add VolumeServerVolumeCreationCounter metric to track volume creation
attempts by result (success/failure).

Changes:
- Add VolumeServerVolumeCreationCounter in weed/stats/metrics.go
- Instrument GrowByCountAndType in weed/topology/volume_growth.go
- Add unit tests in weed/stats/metrics_volume_creation_test.go
- Add Grafana dashboard panel for volume creation rate

This metric enables monitoring volume creation success/failure rates
in SeaweedFS clusters.

* fix: address CodeRabbit review - move failure counter before early return

- Move failure counter into loop else block before return statement
- Move success counter to after loop completion
- Strengthen test assertion from count < 1 to count != 2
- Add t.Cleanup() for test isolation in TestVolumeCreationCounterIncrement

* fix: count each volume create attempt and move metric to master subsystem

- topology runs on the master, so move volume_creation_total from the
  volumeServer subsystem to master (SeaweedFS_master_volume_creation_total);
  rename the var to MasterVolumeCreationCounter and group it with the other
  master metrics.
- increment the counter per findAndGrow iteration instead of once per
  GrowByCountAndType call: each logical volume is now counted, partial
  successes before a failure are credited, and a targetCount==0 call no
  longer records a spurious success.
- update the Grafana panel query and the unit tests; the registration test
  now asserts via the shared Gather registry under the fully-qualified name.

* test: drop volume_creation metric tests

They only exercised the Prometheus client library (CounterVec increment and
registry collection), not any SeaweedFS behavior, so they carried maintenance
cost without verifying anything in this codebase.

---------

Co-authored-by: Ubuntu User <ubuntu@example.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-21 10:56:03 -07:00
Chris Lu ee8742f393 install.sh: fix stale --version example (v3.93 -> 4.34) (#10025)
Release tags are MAJOR.MINOR with no v prefix; the v3.93 example 404s. Default (omit --version -> latest) is unchanged.
2026-06-21 00:54:47 -07:00
Sergey Zinchenko 395d2c80af fix(s3): verify SigV2 using percent-encoded path for Unicode object keys (#10022) 2026-06-20 08:28:40 -07:00
Chris Lu 53342c9ba6 mini: resolve admin credentials from security.toml and env vars (#10021)
* mini: resolve admin credentials from security.toml and env vars

weed mini started the admin UI without resolving admin.user/admin.password
(and the read-only pair) from security.toml [admin] or WEED_ADMIN_* env vars,
so the only way to protect the UI was the -admin.password flag. The standalone
weed admin command applies these fallbacks in runAdmin via applyViperFallback;
the mini path calls startAdminServer directly and skipped it, leaving
authRequired false and the UI unauthenticated.

* mini: load admin.toml maintenance settings

The mini admin path runs ApplyMaintenanceConfigFromToml (via startAdminServer)
against the global viper, but runMini never merged admin.toml, so file-based
maintenance task settings ([maintenance.vacuum], .balance, .erasure_coding)
were ignored under mini while the standalone weed admin honored them. Load it
alongside master/volume config.

* mini: support -admin.urlPrefix for the admin UI

Expose the reverse-proxy subdirectory prefix that the standalone weed admin
already supports, so the mini admin UI can run under e.g. /seaweedfs. The
prefix is normalized the same way and passed through to startAdminServer.
2026-06-19 13:04:04 -07:00
df1a25fd3e feat: add Prometheus metrics for replication operations (#10006)
* feat: add Prometheus metrics for replication operations

Adds 5 metrics to instrument volume server replication (write/delete):
- Operations counter with success/failure labels
- Duration histogram for latency tracking
- Targets gauge for replica fanout
- Failures counter with error reason labels
- Under-replicated volumes gauge on master

* fix: record replication duration histogram only when replicaCount > 0

* fix: update replication targets gauge for all operations including zero

* fix: ensure symmetric replication success/failure counting and proper metrics updates

* fix: change VolumeServerReplicationTargets from Gauge to Histogram

- Replace .Set() with .Observe() in store_replicate.go (2 occurrences)
- Update test to use CollectAndCount for histogram assertion
- Rename TestReplicationTargetsGauge -> TestReplicationTargetsHistogram
- Update documentation to reflect Histogram type and PromQL examples

* Add comments to replication metrics and improve test coverage

* metrics: add replication panels to grafana dashboard

Master row gets an under-replicated volumes timeseries; Volume Servers
row gets replication operations, failures-by-reason, p99 duration, and
average fan-out panels for the new replication metrics.

* metrics: name the replication duration histogram replication_seconds

Match the volumeServer convention (request_seconds, vacuuming_seconds)
rather than the admin/lifecycle _duration_seconds spelling.

* metrics: guard replication fan-out panel against divide-by-zero

clamp_min the _count rate so the avg-targets ratio reads 0 instead of
NaN when there are no replication events in the window.

---------

Co-authored-by: Ubuntu User <ubuntu@example.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-19 11:05:43 -07:00
20e4614fc6 feat(mount): attach Content-MD5 to chunk uploads (#10016)
* mount: attach Content-MD5 to chunk uploads

Mount writes never set UploadOption.Md5, so FileChunk.ETag stays empty
and filer.ETag() degenerates to md5("")-N: same-size files compare
equal regardless of content, defeating metadata-level verification
like filer.sync.verify.

Compute each chunk's MD5 and send it as Content-MD5. The volume server
verifies it on ingest (rejecting in-flight corruption) and echoes it
back, persisting FileChunk.ETag like filer/S3 writes already do.

The dirty-page flush paths already pass a *util.BytesReader whose
backing slice is the whole chunk, so the digest is taken in place with
no extra read, copy, or allocation (UploadWithRetry unwraps it the same
way downstream). Only the rarer plain-reader callers (e.g. manifest
chunks) fall back to io.ReadAll. Skipped under -cipher, where only the
ciphertext reaches the server.

The digest encoding (std-base64 of the raw md5) is the contract the
volume server verifies against, so it is factored into contentMD5Base64
and covered by a unit test.

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

* mount: compute chunk Content-MD5 in the uploader, not the caller

Move the WantMd5 hashing into UploadWithRetry, where the chunk is already
buffered for the retry path, so saveDataAsChunk stops type-switching the
reader and re-reading plain readers. One materialization point, and the
cipher exclusion lives next to the hash instead of at every call site.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-19 10:29:28 -07:00
Chris Lu bc257fe72e volume: detect phantom volumes held open as deleted FDs (#10011)
* volume: detect phantom volumes held open as deleted FDs

Add disk-file validation in heartbeat collection to prevent reporting
phantom volumes that exist in memory but are deleted from disk. This
unblocks re-replication when files are unlinked while the volume server
holds them open via file descriptors.

Cache disk checks per-volume with 30-second TTL to avoid syscall overhead.
Implement in both Go and Rust volume servers.

* volume: make last_disk_check_ns field public for heartbeat access

* volume: only check for phantom volumes when size > 0

Skip phantom volume detection for zero-size volumes (e.g., test volumes).
Phantom volumes only occur when disk files are deleted while the process
holds them open via FDs - which requires the volume to have had actual data.
Test volumes with zero size should not trigger disk file existence checks.

* volume: only check for phantom volumes when size > 0

Skip phantom volume detection for zero-size volumes (e.g., test volumes).
Phantom volumes only occur when disk files are deleted while the process
holds them open via FDs - which requires the volume to have had actual data.
Test volumes with zero size should not trigger disk file existence checks.

* volume: only check for phantom volumes if file_count > 0

Use file_count as the indicator for whether a volume held actual data,
rather than volume size. Phantom volumes only occur when a volume that
had files is deleted while the process holds open file descriptors.
Test volumes with no file count won't trigger the phantom detection check.

* volume: stat the .dat with its extension when detecting phantom volumes

DataFileName()/IndexFileName() return the extensionless base path, so os.Stat
saw every volume's files as missing and dropped it from the heartbeat, leaving
the master with no locations and breaking deletes/lookups. Stat FileName(".dat")
instead, skip remote-tiered volumes whose .dat lives in cloud storage, and
re-check a missing file every heartbeat rather than caching the negative.
2026-06-19 09:24:04 -07:00
Chris Lu 3ccd4ed85c filer: skip COLLATE "C" list fallback on CockroachDB (#10015)
* filer: skip COLLATE "C" list fallback on CockroachDB

CockroachDB string comparison is already byte-ordered, so wrapping the
list queries in COLLATE "C" can never change result order. It reports
datcollate=en_US.utf8 regardless of how the database was created, so the
collation check always misfires and forces the fallback. On 22.1 and
older COLLATE "C" is rejected as an invalid locale, turning every filer
list query into a hard failure. Detect the backend via version() and
keep the default ordering.

* filer: test CockroachDB collation detection

Cover the CockroachDB skip path and the locale-aware Postgres force path
with go-sqlmock.
2026-06-19 09:22:45 -07:00
18868e5204 fix(mount): run entry invalidations off the meta-cache apply loop (#10002)
* fix(mount): run entry invalidations off the meta-cache apply loop

The apply loop ran invalidateFunc inline, which acquires the open file
handle's lock in fhLockTable. Meanwhile flushMetadataToFiler holds that
same fh lock and then waits on the apply loop (applyLocalMetadataEvent).
When both target the same open file concurrently, the loop blocks on the
fh lock while the lock holder blocks on the loop: an ABBA deadlock that
backs up every later readdir/flush and hangs the mount.

Fix: dispatch entry invalidations to a dedicated FIFO worker goroutine so
the apply loop never blocks on locks held by goroutines waiting on it.
Adds a regression test reproducing the interleaving.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

* perf(mount): update invalidate counter once per batch

Run the batch's invalidateFunc calls without re-taking invalidateMu per
item, then bump invalidateProcessed and broadcast once after the loop.
WaitForEntryInvalidations only needs the count to reach its target and a
batch always completes together, so the per-item lock + broadcast was
wasted work.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

* mount: extract the invalidate worker into util.AsyncBatchWorker

The apply loop's off-thread entry-invalidation queue was a one-off mutex +
cond + slice + counters living inside MetaCache. Pull it out as a generic
unbounded FIFO worker so the deadlock-avoidance contract (never block the
producer, drain on shutdown, wait-for-quiesce) lives in one place.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-19 09:19:35 -07:00
msementsov 60ecdd7a2f Logs typos (#10018) 2026-06-19 09:09:01 -07:00
Minsoo Kim 638f6ff433 admin: surface user inline policies in object store user details (#10013)
GetObjectStoreUserDetails only returned identity.PolicyNames (attached
managed policies) and omitted per-user inline policies. Inline policies are
stored separately from the identity record and are authoritative at S3
enforcement time (they take precedence over the legacy Actions list), so an
operator could not see what actually governed a user's access via the admin
API/UI.

Include inline policy names (via credentialManager.ListUserInlinePolicies) in
the returned PolicyNames. Adds a unit test using the memory credential store.
2026-06-18 22:20:56 -07:00
Chris Lu 0a45c4d097 mount: cache supplementary group IDs for non-root access performance (#10008)
* mount: cache supplementary group IDs to improve non-root access performance

* mount: clear supplementary group cache between tests and add cache verification test

* mount: add docstrings and benchmarks for supplementary group cache

* mount: add performance test demonstrating cache effectiveness

* mount: add TTL-based cache expiry for supplementary group IDs (5-minute refresh)
2026-06-18 17:38:28 -07:00
Chris Lu b763a5f6bf s3: improve TTFB for large remote objects (#10010)
* s3: add streaming reader interface for remote storage

Add RemoteStorageStreamReader optional interface to support efficient
streaming of large remote objects without buffering entire file in memory.
This enables future stream-through caching where data can be served to
clients while simultaneously writing to volume servers.

Implement ReadFileAsStream() for S3, GCS, and Azure backends using their
native streaming APIs. This provides the foundation for improving TTFB
on large remote file access by serving data directly from remote storage
while background cache operation populates local chunks.

The streaming interface allows remote storage backends to return io.ReadCloser,
enabling efficient memory usage for multi-GB objects compared to the
current ReadFile() approach which buffers entire ranges in memory.

* s3: adaptive timeout for remote object caching to improve TTFB

Use size-aware cache polling timeout to balance cache-hit rate against
time-to-first-byte:

- Small files (<50MB): 10s timeout - more likely to complete caching
  before timeout, improving subsequent request performance
- Medium files (50-500MB): 5s timeout - default balance
- Large files (>500MB): 2s timeout - fail-fast to improve initial TTFB
  for very large downloads

This reduces waiting time for large remote files while maintaining
high cache-hit rate for smaller files that cache quickly.

* s3: address code review feedback for stream-through cache

- Move startBackgroundRemoteCache call after policy recheck to avoid
  cache side effects for denied requests (authorization first)
- Make startBackgroundRemoteCache version-aware by accepting versionId
  parameter and using buildVersionedRemoteObjectPath
- Add timeout (5 minutes) to background cache context to prevent
  goroutine pile-up if RPC stalls under load
- Update cacheRemoteObjectForStreamingWithShortTimeout to return both
  entry and error, allowing callers to distinguish transient errors
  (timeout/cancellation) from permanent errors (not found, denied)
- Update streamFromVolumeServers to handle permanent cache errors with
  appropriate HTTP status codes (404 for not found, 503 for transient)
2026-06-18 17:22:32 -07:00
Ruslan Bel'kov 6dac0d30ef Fix typo in SeaweedFS Filer description (#10009) 2026-06-18 10:21:23 -07:00
Chris Lu 40615e3d9d helm: reject emptyDir for volume idx, and rebuild a missing idx on restart (#10005)
* helm: reject emptyDir for volume idx

An ephemeral index on a separate volume is wiped on every pod restart
while the .dat/.vif persist on the data PVCs. The volume server then
finds data with no matching .idx and exits via glog.Fatalf, putting the
pod into CrashLoopBackOff with no automatic recovery.

emptyDir is never the right choice for idx: if the data is persistent it
is a durability mismatch, and if the data is also ephemeral the default
(idx co-located with the data) already covers it. Fail the render with a
clear message pointing at the default or a persistent volume instead, and
drop emptyDir from the documented idx options.

* helm: rebuild a missing volume idx on restart

With emptyDir rejected, a separate idx volume is always persistent
(hostPath/PVC/existingClaim) -- but it can still lose its .idx out of
band (e.g. a node-local PVC reprovisioned on reschedule, or a pre-9944
compaction crash that left a .dat without its matching .idx). The
seaweedfs-vol-move-idx init container already moves idx files next to the
data into the index dir; have it first regenerate, via weed fix, any .idx
absent from both the data dir and the index dir, then move it into place.
The rebuild only runs when an idx is genuinely missing, so a healthy
index adds no startup cost.
2026-06-18 01:30:34 -07:00
Chris Lu 443b5b1184 Merge branch 'master' of https://github.com/seaweedfs/seaweedfs 2026-06-17 13:45:47 -07:00
Chris Lu 0c343e76eb admin: don't log normal 2xx/3xx HTTP requests (incl. 304 cache hits) 2026-06-17 11:34:38 -07:00
Chris Lu b5ecfcd28c volume: validate remote S3 endpoints in FetchAndWriteNeedle (Rust) (#10001)
* volume: validate remote S3 endpoints in FetchAndWriteNeedle (Rust)

Port the Go volume server's SSRF guard to the Rust volume server. The
gRPC FetchAndWriteNeedle reads from a caller-supplied S3 endpoint, so an
unguarded server can be pointed at loopback / link-local / RFC1918 /
CGNAT / cloud-metadata hosts to read internal services. Resolve and
reject those endpoints unless -volume.allowUntrustedRemoteEndpoints is
set (default off), mirroring weed/server/volume_grpc_remote.go.

Connect-time re-validation against DNS rebinding (Go's guardedDialer) is
not yet ported: the aws-sdk-s3 client builds its own connector, so the
up-front resolve-and-check leaves a narrow TOCTOU window. Left as a
follow-up.

* volume: harden remote endpoint guard (IPv4-mapped IPv6, all S3 types)

Address SSRF review feedback:
- Normalize IPv4-mapped IPv6 (::ffff:a.b.c.d) to IPv4 before the deny
  checks, so ::ffff:127.0.0.1 / ::ffff:169.254.169.254 no longer slip
  past the IPv4 rules.
- Validate the endpoint for every S3-compatible backend, not just type
  "s3"; wasabi/backblaze/aliyun/... all dial a caller-supplied endpoint
  through the same client. Skip validation when the endpoint is empty
  (the provider default, e.g. real AWS S3, which cannot reach internal
  hosts).

* volume: set allow_untrusted_remote_endpoints in integration-test state

The tests/http_integration.rs VolumeServerState literal was missed, which
broke cargo test compilation (it builds the integration tests, unlike the
cargo test --lib used locally).
2026-06-17 00:56:13 -07:00
Chris Lu e411ff491d volume: remove ec.bitrotChecksum and ec.bitrotBlockSizeMB flags (#10000)
EC bitrot protection is now a fixed default: always on at 16 MiB block
granularity. These volume-server flags exposed needless configurability;
the package defaults in erasure_coding (BitrotProtectionEnabled,
BitrotBlockSize) are retained and still drive sidecar generation. Drop the
now-unused erasure_coding import.
2026-06-17 00:07:38 -07:00
dependabot[bot] 65484cb4bb build(deps): bump github.com/rclone/rclone from 1.74.1 to 1.74.3 in /test/kafka (#9996)
build(deps): bump github.com/rclone/rclone in /test/kafka

Bumps [github.com/rclone/rclone](https://github.com/rclone/rclone) from 1.74.1 to 1.74.3.
- [Release notes](https://github.com/rclone/rclone/releases)
- [Changelog](https://github.com/rclone/rclone/blob/master/RELEASE.md)
- [Commits](https://github.com/rclone/rclone/compare/v1.74.1...v1.74.3)

---
updated-dependencies:
- dependency-name: github.com/rclone/rclone
  dependency-version: 1.74.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-16 23:31:19 -07:00
Chris Lu 8701299baf mq(kafka): don't drop an existing topic when auto-create races (#9998)
TopicExists can return a transient false-negative for a topic that is in
fact present (a broker/filer blip under load, or a just-created topic whose
existence cache is still stale). The metadata and produce handlers then tried
to auto-create, hit "topic already exists", treated that as a failure, and
dropped the topic from the Metadata response - so the client saw a spurious
UNKNOWN_TOPIC_OR_PARTITION right after the topic was created.

Return a sentinel ErrTopicAlreadyExists from the create paths and add
ensureTopicExists, which treats it as confirmation the topic exists. It also
folds in the repeated TopicExists -> invalidate -> recheck -> create logic
shared by every metadata handler (v0-v8) and both produce paths. v2+ produce
now auto-creates too, matching the auto.create.topics.enable=true behavior the
rest of the gateway already simulates.
2026-06-16 22:24:40 -07:00
dependabot[bot] aad24f239c build(deps): bump github.com/rclone/rclone from 1.74.1 to 1.74.3 (#9997)
Bumps [github.com/rclone/rclone](https://github.com/rclone/rclone) from 1.74.1 to 1.74.3.
- [Release notes](https://github.com/rclone/rclone/releases)
- [Changelog](https://github.com/rclone/rclone/blob/master/RELEASE.md)
- [Commits](https://github.com/rclone/rclone/compare/v1.74.1...v1.74.3)

---
updated-dependencies:
- dependency-name: github.com/rclone/rclone
  dependency-version: 1.74.3
  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-06-16 19:58:31 -07:00
Chris Lu d6da0e0e13 ci: only run heavy workflows when related paths change
Add path filters to workflows that fired on every PR/push regardless
of the diff: CodeQL, go build, the e2e/EC/vacuum/TLS/plugin-worker
integration suites, the Kafka and Postgres gateways, the S3 suites
(Ceph s3tests, s3-go, s3-tables, proxy-signature, https, example,
filer-group), TUS, and the dev binary/container builds. Each scopes
to its subsystem under weed/, its test dir, go.mod/go.sum, and the
workflow file, so docs-, helm-, terraform-, rust- or java-only
changes no longer trigger a full compile-and-test fleet.
2026-06-16 18:38:28 -07:00
Chris Lu 7c32e651f7 mount: fix deadlock reading an uncached remote-mounted file (#9995)
* mount: apply cached remote entry without blocking the read

Reading an uncached remote-mounted file hung forever. The read holds the
file-handle shared lock across the on-demand download, then synchronously
waits on the metadata apply loop to apply the cached entry. The filer's
update event for that same object reaches the apply loop first and runs
invalidateFunc, which wants the file-handle exclusive lock — held in shared
mode by the still-running read. The loop blocks on the read; the read blocks
on the loop.

Enqueue the apply without waiting so the read never blocks on the apply loop
while holding the lock. The handle is already updated via SetEntry, and the
filer subscription delivers the same event regardless.

* mount: regression test for uncached remote read deadlock

Drives the real Read path through downloadRemoteEntry with a stub filer that
broadcasts the matching invalidate event before returning, reproducing the
lock-ordering deadlock. Fails (times out) without the fix.
2026-06-16 16:47:59 -07:00
Chris Lu 0a70332adf s3api: add optional request interceptor to circuit breaker (#9994)
* s3api: add optional request interceptor to circuit breaker

Add an optional Interceptor func(next http.HandlerFunc, action string) http.HandlerFunc
field on CircuitBreaker, applied at the very top of Limit() -- before upload
concurrency limiting and before the 'if !cb.Enabled' early return -- so it runs
for every route regardless of breaker state.

It is nil by default (no behavior change). An interceptor may reject a request
(write its own response and skip next) or wrap next to observe/shape it. This
provides a single per-request extension point at the existing per-route
chokepoint (cb.Limit already wraps nearly every S3 route), useful for tracing,
auditing, or request rate limiting without touching the route table.

* s3api: evaluate circuit breaker interceptor per request

Move the Interceptor nil-check into the returned handler so it is consulted
per request instead of captured at registration time. This:
- lets the interceptor be installed after registerRouter runs (handlers are
  built during construction, before request-time dependencies exist), and
- avoids dereferencing a nil CircuitBreaker at registration time, which
  panicked tests that register routes on a server with a nil cb
  (e.g. TestRouting_STSWithQueryParams).

Adds a regression test for installing the interceptor after Limit() returns.
2026-06-16 16:29:30 -07:00
7y-9andCodex bc827704d5 fix(shell): return fs.verify topology errors (#9982)
* fix(shell): return fs.verify topology errors

Problem: fs.verify can silently ignore master topology lookup failures before verifying files.

Root cause: commandFsVerify.Do returned parseErr after collectVolumeIds failed, but parseErr is nil once path parsing succeeds.

Fix: Return the actual collectVolumeIds error so VolumeList and master client failures stop the command.

Co-authored-by: Codex <noreply@openai.com>

* remove the tests

---------

Co-authored-by: Codex <noreply@openai.com>
2026-06-16 15:45:29 -07:00
Chris Lu 1826a5d222 fix(mount): pin rebuild entries by their own inode, not inodeToPath (#9993)
isLocalOnlyEntry resolved the pinned-child check through inodeToPath. A kernel
Forget drops the path→inode mapping once the lookup count reaches zero, but an
async writeback flush — and the file handle, still in fhMap during the drain —
is keyed by inode and outlives that mapping. Between Release dispatching the
async flush and the flush reaching the filer, a Forget could unpin an in-flight
create, so a concurrent directory rebuild would wipe it and the file would
ENOENT until the flush lands and the cache refreshes.

Key the check off the inode the store entry already carries (createFile stamps
it into the placeholder), so the pin no longer depends on a mapping Forget can
remove.
2026-06-16 14:59:13 -07:00
Chris Lu b888cec106 s3: bound streaming remote-cache wait so large cold GetObject returns 503, not a hang (#9988)
* s3: bound streaming remote-cache wait so large cold GetObject returns 503, not a hang

A remote-only object whose download outlasts the 30s dedup attempt fell through
to cacheRemoteObjectForStreaming, which waited on the raw request context with no
bound. For multi-GB blobs the client read timeout fires first, so the request was
canceled and surfaced as InternalError rather than the 503 + Retry-After the
handler already emits. The filer keeps caching on a detached context, so the
retry would have streamed from the cached chunks.

Bound the wait under common client read timeouts: the 503 fires while the client
is still connected, and a retry picks up the finished cache.

* s3: make the streaming remote-cache timeout atomic

The bound is a package-level var so tests can shorten it. Hold it as an
atomic int64 so a test that stores a short value can never race the request
path that loads it.

* s3: assert the streaming-cache timeout test waits on the bound

The upper-bound-only check would also pass if the RPC returned immediately on a
setup error. Add a lower bound so the test fails unless the bounded wait fired.
2026-06-16 14:02:41 -07:00
Chris Lu 93f91c96ca fix(mount): keep a deferred local create from vanishing when its dir is rebuilt (#9991)
wfs.Create defers the filer create to Flush and inserts a local-only
placeholder into the metaCache (dirtyMetadata=true), so a just-created file
exists locally before the filer has it. When the parent directory falls out of
cache (hot-dir read-through, idle evict) and is rebuilt, EnsureVisited wipes the
store and refills from a filer listing that does not yet include the un-flushed
create, then markCachedFn publishes the directory authoritatively cached without
it. lookupEntry then returns an authoritative ENOENT and ReadDir returns nothing
— the file disappears from the mount although the client created it. Under
concurrent read+write churn on one directory this is the ConcurrentReadWrite
flake.

Preserve children the mount flags as local-only (open dirty handle or pending
async flush — the signal lookupEntry already trusts) across the rebuild's wipe
instead of blind-deleting them. Unpinned stale children are still dropped so a
rebuild cannot resurrect a deleted entry.
2026-06-16 13:57:12 -07:00
Chris Lu 5e8152b81c storage: register tier backends at the binary composition root (#9989)
The s3 and rclone tiered-storage backends were registered via blank imports
in weed/storage (volume_tier.go and volume_info/volume_info.go). That forced
every library consumer of weed/storage -- weed/shell, and through it external
tools -- to link aws-sdk-go and, under the rclone build tag, the full rclone
backend set and its cloud-storage SDKs, even though those consumers never tier
volumes.

Move the registrations into a new weed/storage/backend/all aggregator and
blank-import it once from weed/command, the binary's composition root. The weed
binary still registers both backends; weed/storage and its library consumers no
longer pull the backend SDKs into their dependency graph.
2026-06-16 11:47:32 -07:00
Chris Lu b58e9ac3c4 SECURITY.md: require working repro and trust-boundary impact (#9990)
* SECURITY.md: require working repro and trust-boundary impact

Funnel reports through GitHub private vulnerability reporting, require a
reproduction against a supported version, and spell out the trust model so
internal-cluster exposure and example-config issues are out of scope.
Unvalidated scanner/AI output is handled as hardening, not as an advisory.
CVEs minted by third parties outside this process may be disputed.

* SECURITY.md: drop email channel, GitHub private reporting only
2026-06-16 11:16:48 -07:00
Chris Lu 33df4fe2c4 storage: nil-safe ReplicaPlacement.String()
Guard a nil receiver like TTL.String() already does, so formatting a
zero-value VolumeInfo can't depend on fmt's panic recovery.
2026-06-16 10:42:43 -07:00
Chris Lu 9c10d64ae9 shell: show remote storage name/key in volume.list output (#9987)
VolumeInfo.String() dropped RemoteStorageName/RemoteStorageKey, which
are useful when debugging volume tiering. Append them when the volume
is remote.
2026-06-16 10:35:06 -07:00
Chris Lu 8d388acc0e mount: tolerance-window write pattern detection for concurrent writeback (#9984)
* mount: tolerance-window write pattern detection for concurrent writeback

WriterPattern decides whether each dirty chunk is buffered in RAM
(NewMemChunk) or spilled to an on-disk swap file (NewSwapFileChunk), so a
sequential stream misclassified as random is pushed through disk-backed
swap.

The old detector compared each write's start to the previous write's
exact stop offset (atomic.Swap of lastWriteStopOffset, then
lastOffset == offset). That is brittle under concurrent FUSE writeback:
MonitorWriteAt runs before the per-handle write lock, so parallel Write
upcalls interleave the swap, and writeback flushes dirty pages slightly
out of offset order. A genuinely sequential stream then repeatedly reads
as random and spills to swap.

Replace the exact match with the same frontier + tolerance approach used
on the read side: track a never-regressing max frontier (offset+size) via
a CAS loop and treat a write whose start is within SeqTolerance (8 MiB) of
that frontier as sequential. The existing +/-ModeChangeLimit hysteresis is
kept, so a single outlier write can't flip the mode.

Adds page_writer_pattern_test.go covering sequentiality, hysteresis,
reorder tolerance, the inclusive tolerance boundary, frontier
non-regression (the CAS invariant), and recovery back to sequential mode.

* mount: read write frontier inside the CAS loop

Capture the frontier from the CAS loop's own load rather than a separate
up-front snapshot, so the sequentiality diff is judged against the freshest
pre-image even if a concurrent writeback upcall advances the frontier while
we loop. Also drops the now-redundant load. Behavior is unchanged for the
single-threaded tests; addresses review feedback on #9984.
2026-06-16 09:16:24 -07:00
Chris Lu 7e13340dcb filer: tolerance-window read pattern detection for concurrent readahead (#9983)
* filer: tolerance-window read pattern detection for concurrent readahead

ReaderPattern detected sequential access via strict contiguity (lastReadStopOffset
== offset). Under concurrent/reordered ReadAt (parallel readahead, which ReadAt
already supports via RLock + atomics), that exact match frequently misses even for
a genuinely sequential stream, drifting toward random mode and disabling prefetch.

Track a read frontier (max offset+size, advanced with a lock-free CAS loop) and
treat a read as sequential when its start is within SeqTolerance (8 MiB) of the
frontier. The window absorbs reordered/concurrent readahead while still rejecting
far random jumps; the existing ModeChangeLimit hysteresis is unchanged. API
(NewReaderPattern/MonitorReadAt/IsRandomMode) is unchanged, so reader_at is
unaffected. Adds reader_pattern_test.go.

* filer: read the read frontier inside the CAS loop

Capture the frontier from the CAS loop's own load rather than a separate
up-front snapshot, so the sequentiality diff is judged against the freshest
pre-image even if a concurrent readahead advances the frontier while we loop.
Also drops the now-redundant load. Mirrors the same fix on the write-side
ReaderPattern twin (review feedback on the companion PR).

* filer: add frontier/boundary/recovery guard tests for ReaderPattern

Mirror the regression guards added to the write-side WriterPattern: assert
the max-frontier never regresses on a backward read (the CAS invariant), pin
both sides of the inclusive SeqTolerance boundary, and verify sustained near
reads recover sequential mode out of the negative floor. Each guards an
invariant the original four tests left uncovered.
2026-06-16 09:15:44 -07:00
Chris Lu 76783f3d71 test: add FUSE database load/durability/perf benchmark (#9980)
* test: add FUSE database load/durability/perf benchmark

Runs MySQL (InnoDB) and SQLite with ~1GB datadirs on a SeaweedFS FUSE
mount. Two parts:

- durability: normal shutdown, kill -9, and crash-during-write all keep
  every fsync-committed row (verified by integrity check + row count +
  contiguous prefix + per-row CRC).
- performance: FUSE vs the same local disk. fsync/commit latency is the
  dominant cost (~0.13ms -> ~1.18ms), so small transactions run ~9-12x
  slower while bulk loads and warm reads stay close.

Harness is path-independent (runtime under $SEAWEED_BENCH_WORK) and only
touches its own processes on non-default ports.

* test/benchmark/fuse_db: portable to Linux + crash-safe progress

- export MYSQL_BIN; mysql_bench.py falls back to PATH when unset
- unmount via fusermount/fusermount3 (non-root Linux), then umount/diskutil
- atomic progress write (tmp+fsync+rename); treat empty progress file as 0
- reuse a single PRNG in the perf probe so RNG init doesn't skew timings

* test/benchmark/fuse_db: validate inputs, add subprocess timeout

- mysql_bench.py: 1800s timeout on mysql CLI calls; reject db names that
  aren't plain identifiers (interpolated into SQL)
- sqlite_gen.py / sqlite_verify.py: allowlist journal/synchronous modes and
  the verify mode so a typo can't silently weaken durability or relax checks
- run_mysql.sh: durable atomic progress write (tmp+fsync+rename), matching
  sqlite_gen.py; quote $LB in both crash-test verify calls
2026-06-15 13:25:27 -07:00
Chris Lu 9266aaa88e security.toml: document WEED_ env override for jwt signing keys (#9981)
security.toml: document WEED_ env override for the jwt signing keys

These keys are HMAC secrets; spell out the env-var mapping so they can be
injected from a secret store instead of living in the config file.
2026-06-15 13:25:06 -07:00
3bf3d29058 fix(command): preserve fuse option after writers (#9972)
* fix(command): preserve fuse option after writers

Problem: FUSE mount option parsing skipped the option immediately following concurrentWriters, so values such as concurrentReaders could be silently ignored.

Root cause: runFuse incremented the options loop index inside the concurrentWriters case in addition to the loop increment.
Co-authored-by: Codex <noreply@openai.com>

* test: save and restore mountOptions pointers, not their values

The fields are reassigned to fresh heap variables during runFuse, so
dereferencing to back up/restore mutated throwaways instead of the
flag-bound originals and could nil-panic on unset fields.

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-15 13:11:35 -07:00
dependabot[bot] 3f7105df52 build(deps): bump github.com/aws/smithy-go from 1.27.1 to 1.27.2 (#9976)
Bumps [github.com/aws/smithy-go](https://github.com/aws/smithy-go) from 1.27.1 to 1.27.2.
- [Release notes](https://github.com/aws/smithy-go/releases)
- [Changelog](https://github.com/aws/smithy-go/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws/smithy-go/compare/v1.27.1...v1.27.2)

---
updated-dependencies:
- dependency-name: github.com/aws/smithy-go
  dependency-version: 1.27.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 10:43:43 -07:00
dependabot[bot] d28cd94601 build(deps): bump cloud.google.com/go/storage from 1.62.1 to 1.62.3 (#9977)
Bumps [cloud.google.com/go/storage](https://github.com/googleapis/google-cloud-go) from 1.62.1 to 1.62.3.
- [Release notes](https://github.com/googleapis/google-cloud-go/releases)
- [Changelog](https://github.com/googleapis/google-cloud-go/blob/main/CHANGES.md)
- [Commits](https://github.com/googleapis/google-cloud-go/compare/storage/v1.62.1...storage/v1.62.3)

---
updated-dependencies:
- dependency-name: cloud.google.com/go/storage
  dependency-version: 1.62.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 10:35:41 -07:00
dependabot[bot] d793efd13a build(deps): bump go.etcd.io/etcd/client/v3 from 3.6.10 to 3.6.12 (#9979)
Bumps [go.etcd.io/etcd/client/v3](https://github.com/etcd-io/etcd) from 3.6.10 to 3.6.12.
- [Release notes](https://github.com/etcd-io/etcd/releases)
- [Commits](https://github.com/etcd-io/etcd/compare/v3.6.10...v3.6.12)

---
updated-dependencies:
- dependency-name: go.etcd.io/etcd/client/v3
  dependency-version: 3.6.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 10:35:30 -07:00
dependabot[bot] 3888e6f58a build(deps): bump github.com/a-h/templ from 0.3.1001 to 0.3.1020 (#9978)
Bumps [github.com/a-h/templ](https://github.com/a-h/templ) from 0.3.1001 to 0.3.1020.
- [Release notes](https://github.com/a-h/templ/releases)
- [Commits](https://github.com/a-h/templ/compare/v0.3.1001...v0.3.1020)

---
updated-dependencies:
- dependency-name: github.com/a-h/templ
  dependency-version: 0.3.1020
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 10:35:19 -07:00
dependabot[bot] 303b23f96a build(deps): bump github.com/aws/aws-sdk-go-v2/config from 1.32.21 to 1.32.25 (#9975)
build(deps): bump github.com/aws/aws-sdk-go-v2/config

Bumps [github.com/aws/aws-sdk-go-v2/config](https://github.com/aws/aws-sdk-go-v2) from 1.32.21 to 1.32.25.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/config/v1.32.21...config/v1.32.25)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 10:34:35 -07:00
119 changed files with 4942 additions and 1433 deletions

No files matched your search

+5
View File
@@ -3,6 +3,11 @@ name: "go: build dev binaries"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/binaries_dev.yml'
concurrency:
group: binaries-dev-${{ github.ref }}
+5
View File
@@ -2,6 +2,11 @@ name: "Code Scanning - Action"
on:
pull_request:
paths:
- '**/*.go'
- 'go.mod'
- 'go.sum'
- '.github/workflows/codeql.yml'
concurrency:
group: ${{ github.head_ref }}/codeql
+6
View File
@@ -3,6 +3,12 @@ name: "docker: build dev containers"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'docker/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/container_dev.yml'
permissions:
contents: read
+12
View File
@@ -3,8 +3,20 @@ name: "End to End"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'docker/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/e2e.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/**'
- 'docker/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/e2e.yml'
concurrency:
group: ${{ github.head_ref }}/e2e
@@ -3,8 +3,20 @@ name: "EC Integration Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/erasure_coding/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/ec-integration-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/**'
- 'test/erasure_coding/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/ec-integration-tests.yml'
permissions:
contents: read
+10
View File
@@ -3,8 +3,18 @@ name: "go: build binary"
on:
push:
branches: [ master ]
paths:
- '**/*.go'
- 'go.mod'
- 'go.sum'
- '.github/workflows/go.yml'
pull_request:
branches: [ master ]
paths:
- '**/*.go'
- 'go.mod'
- 'go.sum'
- '.github/workflows/go.yml'
concurrency:
group: ${{ github.head_ref }}/go
+16
View File
@@ -3,8 +3,24 @@ name: "Kafka Quick Test (Load Test with Schema Registry)"
on:
push:
branches: [ master ]
paths:
- 'weed/mq/**'
- 'weed/pb/mq_pb/**'
- 'weed/pb/schema_pb/**'
- 'test/kafka/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/kafka-quicktest.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/mq/**'
- 'weed/pb/mq_pb/**'
- 'weed/pb/schema_pb/**'
- 'test/kafka/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/kafka-quicktest.yml'
workflow_dispatch: # Allow manual trigger
concurrency:
+16
View File
@@ -3,8 +3,24 @@ name: "Kafka Gateway Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/mq/**'
- 'weed/pb/mq_pb/**'
- 'weed/pb/schema_pb/**'
- 'test/kafka/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/kafka-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/mq/**'
- 'weed/pb/mq_pb/**'
- 'weed/pb/schema_pb/**'
- 'test/kafka/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/kafka-tests.yml'
concurrency:
group: ${{ github.head_ref }}/kafka-tests
+12
View File
@@ -3,8 +3,20 @@ name: "Plugin Worker Integration Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/plugin_workers/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/plugin-workers.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/**'
- 'test/plugin_workers/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/plugin-workers.yml'
permissions:
contents: read
+16
View File
@@ -3,8 +3,24 @@ name: "PostgreSQL Gateway Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/server/postgres/**'
- 'weed/query/**'
- 'weed/mq/**'
- 'test/postgres/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/server/postgres/**'
- 'weed/query/**'
- 'weed/mq/**'
- 'test/postgres/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-tests.yml'
concurrency:
group: ${{ github.head_ref }}/postgres-tests
@@ -2,7 +2,16 @@ name: "S3 Authenticated Integration Tests"
on:
pull_request:
paths:
- 'weed/s3api/**'
- 'weed/iam/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/normal/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-example-integration-tests.yml'
concurrency:
group: ${{ github.head_ref }}/s3-integration-tests
cancel-in-progress: true
+9 -1
View File
@@ -2,7 +2,15 @@ name: "S3 Filer Group Tests"
on:
pull_request:
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/filer_group/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-filer-group-tests.yml'
concurrency:
group: ${{ github.head_ref }}/s3-filer-group-tests
cancel-in-progress: true
+9 -1
View File
@@ -2,7 +2,15 @@ name: "S3 Go Tests"
on:
pull_request:
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-go-tests.yml'
concurrency:
group: ${{ github.head_ref }}/s3-go-tests
cancel-in-progress: true
@@ -3,8 +3,22 @@ name: "S3 Proxy Signature Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/server/**'
- 'test/s3/proxy_signature/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-proxy-signature-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/server/**'
- 'test/s3/proxy_signature/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-proxy-signature-tests.yml'
concurrency:
group: ${{ github.head_ref || github.ref }}/s3-proxy-signature-tests
+8
View File
@@ -2,6 +2,14 @@ name: "S3 Tables Integration Tests"
on:
pull_request:
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3tables/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-tables-tests.yml'
permissions:
contents: read
+18
View File
@@ -3,8 +3,26 @@ name: "Ceph S3 tests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/iam/**'
- 'test/s3/compatibility/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/iam/**'
- 'test/s3/compatibility/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3tests.yml'
concurrency:
group: ${{ github.head_ref }}/s3tests
@@ -3,8 +3,20 @@ name: "test s3 over https using aws-cli"
on:
push:
branches: [master, test-https-s3-awscli]
paths:
- 'weed/s3api/**'
- 'weed/server/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/test-s3-over-https-using-awscli.yml'
pull_request:
branches: [master, test-https-s3-awscli]
paths:
- 'weed/s3api/**'
- 'weed/server/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/test-s3-over-https-using-awscli.yml'
env:
AWS_ACCESS_KEY_ID: some_access_key1
+12
View File
@@ -3,8 +3,20 @@ name: "TLS Rotation Integration Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/tls_rotation/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/tls-rotation-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/**'
- 'test/tls_rotation/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/tls-rotation-tests.yml'
permissions:
contents: read
+7
View File
@@ -2,6 +2,13 @@ name: "TUS Protocol Tests"
on:
pull_request:
paths:
- 'weed/server/**'
- 'weed/filer/**'
- 'test/tus/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/tus-tests.yml'
concurrency:
group: ${{ github.head_ref || github.ref }}/tus-tests
@@ -3,8 +3,20 @@ name: "Vacuum Integration Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/vacuum/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/vacuum-integration-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/**'
- 'test/vacuum/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/vacuum-integration-tests.yml'
permissions:
contents: read
+1 -1
View File
@@ -426,7 +426,7 @@ If the hot/warm data is split as 20/80, with 20 servers, you can achieve storage
## SeaweedFS Filer ##
Built on top of the blob store, SeaweedFS Filer adds directory structure to create a file system. The directory sturcture is an interface that is implemented in many key-value stores or databases.
Built on top of the blob store, SeaweedFS Filer adds directory structure to create a file system. The directory structure is an interface that is implemented in many key-value stores or databases.
The content of a file is mapped to one or many blobs, distributed to multiple volumes on multiple volume servers.
+69 -15
View File
@@ -1,24 +1,78 @@
# Security Policy
## Reporting a Vulnerability
## Supported versions
If you find a security issue in SeaweedFS, please report it privately:
Security fixes land in the latest release. Please reproduce against a recent
release or `master` before reporting; issues that only reproduce on old,
unsupported versions are not eligible for a fix or an advisory.
- Email: support@seaweedfs.com
- Do not open a public GitHub issue
## Reporting a vulnerability
Please include:
- A clear description of the issue
- Steps to reproduce (if possible)
- Affected versions
Report privately through GitHub private vulnerability reporting (the "Report a
vulnerability" button under the repository's Security tab). This keeps the
report, the fix, and any CVE in one place. Do not open a public issue.
## Response
### What a report must include
- 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
We can only act on reports that show real impact. Please include:
## Notes
- Affected version (a release tag or `master` commit you reproduced on)
- The exact deployment and configuration: which components are running
(master, volume, filer, S3, admin), which ports are reachable by the
attacker, and what authentication is enabled
- The attacker's starting position: unauthenticated, a valid S3 user, an admin,
or someone with access to the internal cluster network
- The trust boundary that is crossed (e.g. an unauthenticated client reading
another tenant's data, an S3 user escalating to admin)
- A minimal, working reproduction or proof of concept
- Expected vs. actual behavior
- Please allow time for a fix before public disclosure
- If you’re unsure whether something is a security issue, feel free to reach out
A report without a working reproduction and a clear trust boundary is a
hardening suggestion, not a vulnerability. We are glad to receive those, but
they are handled on the normal issue tracker, not as security advisories.
### Automated and AI-assisted reports
Output from static analysis, dependency scanners, fuzzers, or LLMs is welcome
only when you have manually validated it and can supply a working reproduction
against a supported version, per the requirements above. Raw tool output,
speculative findings, or generated reports without a demonstrated exploit will
be closed as hardening suggestions.
## Trust model
SeaweedFS is built to run with its cluster components (master, volume servers,
and the raw filer API) on a trusted network. Those internal APIs are not an
authentication boundary unless you explicitly enable a control (for example
volume JWT or filer authentication) and that control is bypassed. Exposing an
internal port directly to untrusted clients is a deployment mistake, not a
vulnerability in SeaweedFS.
Reports are in scope when they cross a boundary SeaweedFS is meant to enforce,
for example:
- Unauthenticated access to data or operations that require authentication
- One S3 identity reading, writing, or deleting another identity's data
- Privilege escalation from a normal S3 user to administrative capability
- Bypass of Object Lock / retention where it is configured
- Remotely triggered data corruption or loss
Reports are generally out of scope when they require:
- Direct access to an internal cluster port that is meant to be private
- Full master, filer, or volume server access (already a full compromise)
- An insecure example configuration rather than a documented secure setup
- Local-only impact on a host the attacker already controls
## CVE assignment
When a report is confirmed, we publish an advisory and request the CVE through
GitHub. CVEs assigned by third parties without coordinating with us, or for
issues that do not cross a boundary described above, may be disputed.
## Response and disclosure
- We aim to acknowledge a valid report within a few business days.
- We will investigate, work on a fix, and coordinate a disclosure timeline
with you.
- Please allow time for a fix before any public disclosure.
+22 -21
View File
@@ -5,7 +5,7 @@ go 1.25.0
require (
cloud.google.com/go v0.123.0 // indirect
cloud.google.com/go/pubsub v1.50.2
cloud.google.com/go/storage v1.62.1
cloud.google.com/go/storage v1.62.3
github.com/Shopify/sarama v1.38.1
github.com/aws/aws-sdk-go v1.55.8
github.com/beorn7/perks v1.0.1 // indirect
@@ -85,7 +85,7 @@ require (
github.com/xdg-go/scram v1.2.0
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.etcd.io/etcd/client/v3 v3.6.10
go.etcd.io/etcd/client/v3 v3.6.12
go.mongodb.org/mongo-driver v1.17.9
go.opencensus.io v0.24.0 // indirect
gocloud.dev v0.46.0
@@ -93,8 +93,8 @@ require (
gocloud.dev/pubsub/rabbitpubsub v0.46.0
golang.org/x/crypto v0.52.0
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
golang.org/x/image v0.39.0
golang.org/x/net v0.54.0
golang.org/x/image v0.41.0
golang.org/x/net v0.55.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sys v0.45.0
golang.org/x/text v0.37.0 // indirect
@@ -114,17 +114,18 @@ require (
require (
cloud.google.com/go/kms v1.31.0
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Jille/raft-grpc-transport v1.6.1
github.com/ThreeDotsLabs/watermill v1.5.1
github.com/a-h/templ v0.3.1001
github.com/a-h/templ v0.3.1020
github.com/apache/cassandra-gocql-driver/v2 v2.1.1
github.com/apache/iceberg-go v0.5.0
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/armon/go-metrics v0.4.1
github.com/aws/aws-sdk-go-v2 v1.41.12
github.com/aws/aws-sdk-go-v2/config v1.32.21
github.com/aws/aws-sdk-go-v2/credentials v1.19.20
github.com/aws/aws-sdk-go-v2 v1.42.0
github.com/aws/aws-sdk-go-v2/config v1.32.25
github.com/aws/aws-sdk-go-v2/credentials v1.19.24
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2
github.com/cognusion/imaging v1.0.3
github.com/fluent/fluent-logger-golang v1.10.1
@@ -142,7 +143,7 @@ require (
github.com/parquet-go/parquet-go v0.30.1
github.com/pkg/sftp v1.13.10
github.com/rabbitmq/amqp091-go v1.11.0
github.com/rclone/rclone v1.74.1
github.com/rclone/rclone v1.74.3
github.com/rdleal/intervalst v1.5.0
github.com/redis/go-redis/v9 v9.20.0
github.com/schollz/progressbar/v3 v3.19.0
@@ -179,7 +180,7 @@ require (
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/arrow-go/v18 v18.5.2-0.20260220015023-a886a5722b87 // indirect
github.com/apache/thrift v0.23.0 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/bazelbuild/rules_go v0.46.0 // indirect
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
@@ -321,21 +322,21 @@ require (
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0
github.com/aws/smithy-go v1.27.1
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3
github.com/aws/smithy-go v1.27.2
github.com/boltdb/bolt v1.3.1 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
@@ -482,7 +483,7 @@ require (
github.com/zeebo/blake3 v0.2.4 // indirect
github.com/zeebo/errs v1.4.0 // indirect
go.etcd.io/bbolt v1.4.3 // indirect
go.etcd.io/etcd/api/v3 v3.6.10 // indirect
go.etcd.io/etcd/api/v3 v3.6.12 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect
+43 -42
View File
@@ -485,8 +485,8 @@ cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq
cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc=
cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s=
cloud.google.com/go/storage v1.28.1/go.mod h1:Qnisd4CqDdo6BGs2AD5LLnEsmSQ80wQ5ogcBBKhU86Y=
cloud.google.com/go/storage v1.62.1 h1:Os0G3XbUbjZumkpDUf2Y0rLoXJTCF1kU2kWUujKYXD8=
cloud.google.com/go/storage v1.62.1/go.mod h1:cpYz/kRVZ+UQAF1uHeea10/9ewcRbxGoGNKsS9daSXA=
cloud.google.com/go/storage v1.62.3 h1:SZq1t23NCI+e96dH77Dg3PEfsNNEjqO8zE5AnD8gVD0=
cloud.google.com/go/storage v1.62.3/go.mod h1:cpYz/kRVZ+UQAF1uHeea10/9ewcRbxGoGNKsS9daSXA=
cloud.google.com/go/storagetransfer v1.5.0/go.mod h1:dxNzUopWy7RQevYFHewchb29POFv3/AaBgnhqzqiK0w=
cloud.google.com/go/storagetransfer v1.6.0/go.mod h1:y77xm4CQV/ZhFZH75PLEXY0ROiS7Gh6pSKrM8dJyg6I=
cloud.google.com/go/storagetransfer v1.7.0/go.mod h1:8Giuj1QNb1kfLAiWM1bN6dHzfdlDAVC9rv9abHot2W4=
@@ -648,8 +648,8 @@ github.com/ThreeDotsLabs/watermill v1.5.1 h1:t5xMivyf9tpmU3iozPqyrCZXHvoV1XQDfih
github.com/ThreeDotsLabs/watermill v1.5.1/go.mod h1:Uop10dA3VeJWsSvis9qO3vbVY892LARrKAdki6WtXS4=
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb h1:wumPkzt4zaxO4rHPBrjDK8iZMR41C1qs7njNqlacwQg=
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb/go.mod h1:QiYsIBRQEO+Z4Rz7GoI+dsHVneZNONvhczuA+llOZNM=
github.com/a-h/templ v0.3.1001 h1:yHDTgexACdJttyiyamcTHXr2QkIeVF1MukLy44EAhMY=
github.com/a-h/templ v0.3.1001/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
github.com/a-h/templ v0.3.1020 h1:ypAT/L5ySWEnZ6Zft/5yfoWXYYkhFNvEFOeeqecg4tw=
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 h1:iLDOF0rdGTrol/q8OfPIIs5kLD8XvA2q75o6Uq/tgak=
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0/go.mod h1:DrEWcQJjz7t5iF2duaiyhg4jyoF0kxOD6LtECNGkZ/Q=
github.com/aalpar/deheap v1.1.2 h1:MABHLcnjqsffb8GLkUFDigqpBBxOMz0DoKM9QfELeTw=
@@ -711,50 +711,50 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/aws/aws-sdk-go-v2 v1.41.12 h1:DIKX2c31ekm9RA2D9FBj1EWXx++9AdAqRw+e78Tq2Ck=
github.com/aws/aws-sdk-go-v2 v1.41.12/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg=
github.com/aws/aws-sdk-go-v2 v1.42.0 h1:XvXMJTkFQtpBKIWZnmr9ZEOc2InWM2yldjXEJ/bymhA=
github.com/aws/aws-sdk-go-v2 v1.42.0/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
github.com/aws/aws-sdk-go-v2/config v1.32.21 h1:1i1v5jWn6iNPl7zkH4VwIXQOb+OMqMRFNjdHQeZbFVo=
github.com/aws/aws-sdk-go-v2/config v1.32.21/go.mod h1:7NXDJjk0e4QOMv3Y3ppwALx3ifdSQHzCACFtRX5J1hI=
github.com/aws/aws-sdk-go-v2/credentials v1.19.20 h1:nIGz0+cQKwijxSsWNpggvPxjxFMtrAHNj16RYzGbu2Q=
github.com/aws/aws-sdk-go-v2/credentials v1.19.20/go.mod h1:/UQHYia3DSeilGdchXJDEVzJws15XuZSdnTlwbTBg0Q=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26 h1:a1VPHz7eG7mVNHWHXUcCyC8rQDBEr4k+o4HJYbSoYZ0=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26/go.mod h1:9G8LPblMwaodeQdS+IfDBgPqABDctJLpyZ/M6jflE6s=
github.com/aws/aws-sdk-go-v2/config v1.32.25 h1:ACCejvStYoilgwrfegSt5ZntCbPrk52qfwyNcnl3omM=
github.com/aws/aws-sdk-go-v2/config v1.32.25/go.mod h1:LJyU8sDRbXUxFn8xMJIGP+v9QYYwveNLI8a/giAOiAs=
github.com/aws/aws-sdk-go-v2/credentials v1.19.24 h1:2hQqYCV9yqyePQ9o6dCrZc/zO8U3TwPr9mIKlZnPu/I=
github.com/aws/aws-sdk-go-v2/credentials v1.19.24/go.mod h1:IDwpACtwqHLISdzfwUUNq4P9DsB/h5BLg4FwJPNfqFY=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 h1:r6qZHbT+wxgWO/e9vYNUEtg7lv5+UN3pRqKhLXvnArg=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29/go.mod h1:QRnaRcTVGKPGRy8w78HMQtKUGRYcnMZAANATkeVA6Mo=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 h1:uMC4oL6G3MNhodo358QEqSDjrgvzV3TUQ58nyQSGq2E=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13/go.mod h1:Cer86AE2686DvVUe57LPve3jUBmbujuaonSX8pNzGgw=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26 h1:dx1qc6V0exl5SK5/kwSc2IdOKCxLHoNbl/zXuYRwopw=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26/go.mod h1:iDMGb+drKqPTqRjv1kWc5meMYzT6HsvPXxJV/Axq1t0=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26 h1:ZjsIjuahUd/OxnxgfeK6OZqrReRNru1BcPfFD95IoN0=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26/go.mod h1:57VbRA0K0Xxx5XUUTUrVxZ/gm4u8Bk3LBflfufwHtKQ=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27 h1:i49S7g2smFWmlconi97Nn8dxb7jSQ0TeOFD20NX3M+o=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27/go.mod h1:qiLes3uVQAK+cpb837HUEhypYKGBz2ZCDcDl5BYQtpM=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 h1:f3vKqSo13fhTYb+JEcXwXefZQE26I1FB5eTSniU67ko=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29/go.mod h1:MzoLFUArKGpGD+ukmPiTPG1X5x4o6M2kq4v2dr1FiEc=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 h1:RdwIf/CuUsvJX3RgJagbOyotl/cxoLY4xviKuE7p2GY=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29/go.mod h1:71wt8W2EgswdZy9Mf9KNnzxZ3TiZlv4caKghPktDOkA=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 h1:VTGy885W5DKBxWRUJbym9hytNaYzsyaPkCHGRRMAOhU=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30/go.mod h1:AS0HycUvJRFvTt613AYDOgO2jzw+00cVSMny8XB3yMY=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 h1:ZD2+BSw9vFsNlKYIasSNt3uDbjqqXIBcM13UJv/Lx2k=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12/go.mod h1:Ms4zlcVBbXbiP7EVLhl+lgjvA/a7YphqQ3Ih3174EmI=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26 h1:oIRaBVJ2CxT7T61l3JkBCW/rnyh2TFZIRL71MvJTKRI=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26/go.mod h1:1gCTZPMlqAUSFoFbkl35hKtTpE96WFl7ORvDXmSLpRc=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 h1:DRebniUGZ2MqiiIVmQJ04vIXr918hubdHMnarSLEWyU=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29/go.mod h1:LfRkPCD8YHDM2E5eTkos2UpwYeZnBcVarTa8L59bJHA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2 h1:qwU4CNor4G2gRW3Na24FWOCZSEvr967IAV3D+MXxdE0=
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2/go.mod h1:vwIj2P3URYf7ZtOQkO2iVbAaR8qFhqMv05w3aPPA5XA=
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 h1:3nXpRcFwRCW8n7HgO2QGy0Dc20eQNfBuUemGQhpF8m8=
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0/go.mod h1:LxYujSTLPRlp2vTtcUO/+1ilrew8ytt6SvQyOgejzFQ=
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 h1:p8WdWDh5AwSZdp19Haa3XMyPCICi9Z375a/Nu3IIEZY=
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14/go.mod h1:NKVY7DER6VXHkt2I/ycmHakALNboi3Rqwt4eEf/1Cnk=
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 h1:JP2wjWGmUp8lTCZb13Dv0Eciyc1jbO8pd0HZVMHFlrc=
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24/go.mod h1:Ql9ziDutk8ERAN9HMaYANCW3lop451ppebkxEJMLCTM=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0 h1:cMDUWhi7vlmGFj6rldHofjnAQhLLBWwRvNRbtEoyZo4=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0/go.mod h1:VfGCm6HLUGwcouY6zjQJd81PoFsb8sfSmKd5QCg9XXc=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3 h1:/pKy3mNES+ppFHf3g/XmI95+f3vdeXnkWYObByoYGAg=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3/go.mod h1:0z2rhlVAjsYeBzV8fdT4jR23Nq+fYhoJNSJN+4SBlqM=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0 h1:HN43uYvF8D2NtaPTeE4L3HMvXgd+RtqEqrea4uUztkM=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0/go.mod h1:qzhDlfw1BRYyoNofevemNzrlRpUXa0BJamWx7klrR8w=
github.com/aws/smithy-go v1.27.1 h1:4T340VFndXtADGF52gYa1POyL7s9E4Z1OeZ1hCscIw8=
github.com/aws/smithy-go v1.27.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 h1:ey1XLTYXb9PcLt4535632o5kCGXNXEhNb620Dqwuylo=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3/go.mod h1:Lk7PlmoTYryQmyBG0EXqj5BcUbj3whXdU2s3yGI3EAc=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 h1:yLr03zQE/5Eu5l3QU0Si+xMbLMbSDF2YXsigqXngs6g=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6/go.mod h1:Q5N6icH+KJZDLh+ESNwzdv6cZ6vLFF/egy3IOxWhmz4=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3 h1:VrIhKRCSK1umelSgB9RghvA9RTUYeQffyAS5ApXehNI=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3/go.mod h1:r8wkDOuLaaMFqFiYAb8dGY2A3gJCOujMc6CFOVC4Zhc=
github.com/aws/smithy-go v1.27.2 h1:y9NPmSE6am6LjEFPfqHqG/jJk7AauQvhCJONKh7kpzk=
github.com/aws/smithy-go v1.27.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
@@ -1468,6 +1468,7 @@ github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRt
github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4=
github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
@@ -1783,8 +1784,8 @@ github.com/rclone/Proton-API-Bridge v1.0.3 h1:Bs7RC4xCFSN0BPIYVda/BNxp0qo3NV0gB2
github.com/rclone/Proton-API-Bridge v1.0.3/go.mod h1:26RAest751Ofk+F/d8xtl4UyWXrZvMQwn39U8rm/WKM=
github.com/rclone/go-proton-api v1.0.2 h1:cJtJUab0MGJ3C6q5kiEJs3pbyhSLnOKMyYOQehA0PBc=
github.com/rclone/go-proton-api v1.0.2/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
github.com/rclone/rclone v1.74.1 h1:QQI//tl4O5uooTowdKwNKcv5qCQvJ3LIBG00+TKeXw0=
github.com/rclone/rclone v1.74.1/go.mod h1:44epaKf5w/1ZQounefr76wx4+y9NZmgfMKle9T3pzj0=
github.com/rclone/rclone v1.74.3 h1:a2wln7pvEa0tS1WIZJKulEkVjxgC1DkCoyxYydkdiSY=
github.com/rclone/rclone v1.74.3/go.mod h1:t5Mh86PO49DD7xlPt0trnK/aNf2Z3M0uip4l1Jqwiv8=
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
@@ -2099,12 +2100,12 @@ go.einride.tech/aip v0.83.0 h1:TI21IdeOnLTwZEJ3BxtImIZk6bsN2Q+sd0x99SLiQ+M=
go.einride.tech/aip v0.83.0/go.mod h1:E8+wdTApA70odnpFzJgsGogHozC2JCIhFJBKPr8bVig=
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
go.etcd.io/etcd/api/v3 v3.6.10 h1:jlwjtELjA8yi2VWpOFH+0w0lGr3K6mVDyn0RDB9aaAY=
go.etcd.io/etcd/api/v3 v3.6.10/go.mod h1:pdV4VeFmvhdNjB4LWRkC8ReLyRBAxUOze3GarMhE2sk=
go.etcd.io/etcd/api/v3 v3.6.12 h1:OLOZUKEuAA36TR48F0cIaa8FdzrWygjyfrJxXg4iDgs=
go.etcd.io/etcd/api/v3 v3.6.12/go.mod h1:p14EIQXHbuOQbVvL/WEes5uqKnxP9AgKJgpjbMVvzvE=
go.etcd.io/etcd/client/pkg/v3 v3.6.12 h1:36zzB+pQOdHbhN+kH2iJz/K8bJn0ZLtLfPPO7jozTDo=
go.etcd.io/etcd/client/pkg/v3 v3.6.12/go.mod h1:hh2+ZXtfLzs3o6mn92ntgNPBrTJJOvXqICM5g3L3DMY=
go.etcd.io/etcd/client/v3 v3.6.10 h1:J598zJ+C/ZPvImypmq5waj84+bovePrlZERHklf34y0=
go.etcd.io/etcd/client/v3 v3.6.10/go.mod h1:iHhUDUcEwaKs1YFq3MgmI9U4zhTVasp/vgdVbFf1RS8=
go.etcd.io/etcd/client/v3 v3.6.12 h1:kMSP6JcPZMqSJiX+TXdUIBU/4eXEZWBAaui4VihMbIc=
go.etcd.io/etcd/client/v3 v3.6.12/go.mod h1:CMs6fJWYiZQk4ytFjd4lE1diOvvRMmtbbn/alZXd3dQ=
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
@@ -2238,8 +2239,8 @@ golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeap
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww=
golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA=
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -2342,8 +2343,8 @@ golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
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.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
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=
+1 -1
View File
@@ -6,7 +6,7 @@
# Usage:
# curl -fsSL https://raw.githubusercontent.com/seaweedfs/seaweedfs/master/install.sh | bash
# curl -fsSL ... | bash -s -- --component volume-rust --large-disk
# curl -fsSL ... | bash -s -- --version v3.93 --dir /usr/local/bin
# curl -fsSL ... | bash -s -- --version 4.34 --dir /usr/local/bin
#
# Options:
# --component COMP Which binary to install: weed, volume-rust, all (default: weed)
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.34"
appVersion: "4.35"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.34.0
version: 4.35.0
@@ -4,6 +4,10 @@
{{- $volumeName := trimSuffix "-" (printf "volume-%s" $vname) }}
{{- $volume := mergeOverwrite (deepCopy $.Values.volume) (dict "enabled" true) $volume }}
{{- if and $volume.idx (eq ($volume.idx.type | toString) "emptyDir") }}
{{- fail (printf "%s: idx.type \"emptyDir\" is not supported. An ephemeral index is wiped on every pod restart while the data persists, forcing a full index rebuild from the .dat on each start (a fatal crash on older versions). Use the default (idx: {}, kept next to the data) or a persistentVolumeClaim/hostPath/existingClaim for a separate persistent index." $volumeName) }}
{{- end }}
{{- if $volume.enabled }}
---
apiVersion: apps/v1
@@ -79,7 +83,23 @@ spec:
image: {{ template "seaweedfs.volume.image" $ }}
imagePullPolicy: {{ $.Values.global.seaweedfs.imagePullPolicy | default "IfNotPresent" }}
command: [ '/bin/sh', '-c' ]
args: [ '{{range $dir := $volume.dataDirs }}if ls /{{$dir.name}}/*.idx >/dev/null 2>&1; then mv /{{$dir.name}}/*.idx /idx/ ; fi; {{end}}' ]
args:
- |
for dir in {{ range $index, $dir := $volume.dataDirs }}{{ if ne $index 0 }} {{ end }}/{{ $dir.name }}{{ end }}; do
# Rebuild a .idx missing from both dirs (e.g. an index volume that lost files) from the .dat, else the server fatally exits on its idx check.
for dat in "$dir"/*.dat; do
[ -e "$dat" ] || continue
base=${dat##*/}; base=${base%.dat}
if [ ! -e "$dir/$base.idx" ] && [ ! -e "/idx/$base.idx" ]; then
echo "rebuilding missing idx in $dir (trigger: volume $base)"
weed fix "$dir"
break
fi
done
if ls "$dir"/*.idx >/dev/null 2>&1; then
mv "$dir"/*.idx /idx/
fi
done
volumeMounts:
- name: idx
mountPath: /idx
+8 -7
View File
@@ -385,7 +385,7 @@ volume:
enabled: true
image: alpine/k8s:1.28.4
# idx can be defined by:
# idx (the volume index) may use a separate PERSISTENT volume:
#
# idx:
# type: "hostPath"
@@ -404,13 +404,14 @@ volume:
# type: "existingClaim"
# claimName: "myClaim"
#
# or
# "emptyDir" is rejected for idx (the chart fails to render): an ephemeral
# index is wiped on every restart while the data persists, forcing a full
# rebuild each start (a fatal crash on older versions). "logs" may still use
# any of the above or emptyDir.
#
# idx:
# type: "emptyDir"
# same applies to "logs"
# Default {} keeps the index next to the data, so it persists with the data and
# needs no separate volume. Recommended unless you must split the index onto
# its own persistent storage.
idx: {}
# Resource requests, limits, etc. for the vol-move-idx initContainer. This
+576
View File
@@ -1822,6 +1822,102 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Under-replicated Volumes",
"description": "Volumes that do not have the desired replica count, by collection. 0 = healthy.",
"type": "timeseries",
"id": 210,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 53
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (collection) (SeaweedFS_master_under_replicated_volumes{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{collection}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
@@ -3786,6 +3882,486 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Replication Operations",
"description": "Rate of replica fan-out operations on volume servers by type and result",
"type": "timeseries",
"id": 211,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 102
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (operation, result) (rate(SeaweedFS_volumeServer_replication_operations_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{operation}} {{result}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Replication Failures by reason",
"description": "Rate of replication failures broken down by operation and classified reason",
"type": "timeseries",
"id": 212,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 102
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (operation, reason) (rate(SeaweedFS_volumeServer_replication_failures_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{operation}} {{reason}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Replication Duration p99",
"description": "p99 duration of replicated write/delete operations (includes local apply + replica fan-out)",
"type": "timeseries",
"id": 213,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 110
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_volumeServer_replication_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, operation))",
"range": true,
"refId": "A",
"legendFormat": "{{operation}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Replication Fan-out (avg targets)",
"description": "Average number of replica targets per replicated operation",
"type": "timeseries",
"id": 214,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 110
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum(rate(SeaweedFS_volumeServer_replication_targets_sum{cluster=~\"$cluster\"}[$__rate_interval])) / clamp_min(sum(rate(SeaweedFS_volumeServer_replication_targets_count{cluster=~\"$cluster\"}[$__rate_interval])), 1e-9)",
"range": true,
"refId": "A",
"legendFormat": "avg targets"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Volume Creation Rate",
"description": "Rate of volume creation operations by result",
"type": "timeseries",
"id": 216,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 118
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "rate(SeaweedFS_master_volume_creation_total{cluster=~\"$cluster\"}[5m])",
"range": true,
"refId": "A",
"legendFormat": "{{result}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
+10
View File
@@ -188,6 +188,12 @@ pub struct Cli {
#[arg(long = "securityFile", default_value = "")]
pub security_file: String,
/// If true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints
/// including loopback / link-local hosts. Default rejects internal /
/// metadata endpoints.
#[arg(long = "volume.allowUntrustedRemoteEndpoints", default_value_t = false)]
pub allow_untrusted_remote_endpoints: bool,
/// A file of command line options, each line in optionName=optionValue format.
#[arg(long = "options", default_value = "")]
pub options: String,
@@ -258,6 +264,9 @@ pub struct VolumeServerConfig {
pub enable_write_queue: bool,
/// Path to security.toml — stored for SIGHUP reload.
pub security_file: String,
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
/// (allows loopback / link-local / metadata hosts).
pub allow_untrusted_remote_endpoints: bool,
}
pub use crate::storage::needle_map::NeedleMapKind;
@@ -804,6 +813,7 @@ fn resolve_config(cli: Cli) -> VolumeServerConfig {
.map(|v| v == "1" || v == "true")
.unwrap_or(false),
security_file: cli.security_file,
allow_untrusted_remote_endpoints: cli.allow_untrusted_remote_endpoints,
}
}
+1
View File
@@ -327,6 +327,7 @@ async fn run(
seaweed_volume::remote_storage::s3_tier::S3TierRegistry::new(),
),
read_mode: config.read_mode,
allow_untrusted_remote_endpoints: config.allow_untrusted_remote_endpoints,
master_url,
master_urls,
seed_master_set,
@@ -0,0 +1,359 @@
//! SSRF guard for caller-supplied remote storage endpoints.
//!
//! `FetchAndWriteNeedle` accepts an S3 endpoint URL chosen by the caller and
//! dials it directly from the volume server, which typically has network
//! access to cluster-internal hosts. Without validation a caller could point
//! the server at loopback / link-local / RFC 1918 / cloud-metadata addresses
//! and read internal services (SSRF). This mirrors the Go volume server's
//! `validateRemoteEndpoint` (`weed/server/volume_grpc_remote.go`); operators
//! that legitimately fetch from private hosts opt out with
//! `-volume.allowUntrustedRemoteEndpoints`.
//!
//! NOTE: the Go server additionally pins the validated endpoint against DNS
//! rebinding with a custom dialer that re-checks the resolved IP at TCP connect
//! time (`guardedDialer`). The `aws-sdk-s3` client used here builds its own
//! connector, so that connect-time re-validation is not yet ported; the
//! up-front resolve-and-check below still blocks the common SSRF vectors. A
//! narrow TOCTOU window (a hostname that resolves to a public IP here and then
//! flips to a blocked one when the SDK dials) remains as a follow-up.
use std::net::{IpAddr, Ipv4Addr};
/// AWS/Azure/GCP IPv4 instance-metadata-service (IMDS) address. It is
/// link-local and thus already covered by [`is_link_local`], but is named
/// explicitly so the rejection reason is unambiguous in logs.
const IMDS_IPV4: IpAddr = IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254));
/// Hostnames that target cloud instance metadata services, blocked regardless
/// of how they resolve because some environments alias the IMDS address under
/// a name.
fn is_blocked_imds_host(host: &str) -> bool {
matches!(host, "metadata.google.internal" | "metadata")
}
/// Whether `ip` is in a link-local range: IPv4 169.254.0.0/16, IPv6 fe80::/10
/// (unicast) and interface-local / link-local multicast (scope 1 and 2).
fn is_link_local(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => v4.is_link_local(),
IpAddr::V6(v6) => {
let seg0 = v6.segments()[0];
if (seg0 & 0xffc0) == 0xfe80 {
return true; // fe80::/10 link-local unicast
}
if (seg0 & 0xff00) == 0xff00 {
// ffXS:: multicast; reject interface-local (scope 1) and
// link-local (scope 2) the way Go's IsInterfaceLocalMulticast /
// IsLinkLocalMulticast do.
let scope = seg0 & 0x000f;
return scope == 1 || scope == 2;
}
false
}
}
}
/// Whether `ip` is in a private range: IPv4 RFC 1918, IPv6 fc00::/7 unique-local
/// (matching Go's `net.IP.IsPrivate`).
fn is_private(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => v4.is_private(),
IpAddr::V6(v6) => (v6.segments()[0] & 0xfe00) == 0xfc00,
}
}
/// Whether `ip` is in the RFC 6598 carrier-grade NAT range (100.64.0.0/10).
/// The IPv4 private check does not cover CGNAT, so check it explicitly.
fn is_cgnat(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
let o = v4.octets();
o[0] == 100 && (o[1] & 0xc0) == 0x40 // second octet 64..=127
}
IpAddr::V6(_) => false,
}
}
/// Returns an error if `ip` is not safe to dial from a server that can reach
/// cluster-internal hosts. Mirrors Go's `checkBlockedIP`.
pub fn check_blocked_ip(endpoint: &str, ip: IpAddr) -> Result<(), String> {
// Normalize IPv4-mapped IPv6 (`::ffff:a.b.c.d`) to its IPv4 form so the
// IPv4 deny rules apply. The OS routes these to the embedded IPv4 address,
// so without this `::ffff:127.0.0.1` / `::ffff:169.254.169.254` would slip
// past the IPv6-only checks. Mirrors Go's reliance on net.IP.To4().
let ip = match ip {
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => IpAddr::V4(v4),
None => IpAddr::V6(v6),
},
other => other,
};
if ip == IMDS_IPV4 {
return Err(format!(
"remote endpoint {:?} targets instance metadata service {}",
endpoint, ip
));
}
if ip.is_loopback() {
return Err(format!(
"remote endpoint {:?} resolves to loopback address {}",
endpoint, ip
));
}
if ip.is_unspecified() {
return Err(format!(
"remote endpoint {:?} resolves to unspecified address {}",
endpoint, ip
));
}
if is_link_local(ip) {
return Err(format!(
"remote endpoint {:?} resolves to link-local address {}",
endpoint, ip
));
}
if is_private(ip) {
return Err(format!(
"remote endpoint {:?} resolves to private address {}",
endpoint, ip
));
}
if is_cgnat(ip) {
return Err(format!(
"remote endpoint {:?} resolves to CGNAT address {}",
endpoint, ip
));
}
Ok(())
}
/// Outcome of the synchronous, DNS-free portion of endpoint validation.
#[derive(Debug)]
enum HostCheck {
/// Host was a literal IP and already passed [`check_blocked_ip`].
Validated,
/// Host is a name that must be resolved and each address checked.
NeedsResolution(String),
}
/// Validate the scheme and host without touching DNS. Pure and unit-testable.
fn precheck_endpoint(endpoint: &str) -> Result<HostCheck, String> {
let trimmed = endpoint.trim();
if trimmed.is_empty() {
return Err("remote endpoint is empty".to_string());
}
let Some(scheme_end) = trimmed.find("://") else {
return Err(format!(
"remote endpoint {:?} must use http or https",
endpoint
));
};
let scheme = trimmed[..scheme_end].to_ascii_lowercase();
if scheme != "http" && scheme != "https" {
return Err(format!(
"remote endpoint {:?} must use http or https, got {:?}",
endpoint,
&trimmed[..scheme_end]
));
}
// Authority is everything up to the first '/', '?', or '#'.
let after = &trimmed[scheme_end + 3..];
let authority_end = after
.find(|c| c == '/' || c == '?' || c == '#')
.unwrap_or(after.len());
let authority = &after[..authority_end];
// Strip optional userinfo ("user:pass@").
let host_port = match authority.rfind('@') {
Some(at) => &authority[at + 1..],
None => authority,
};
// Extract the host, handling bracketed IPv6 literals and host:port.
let host = if let Some(rest) = host_port.strip_prefix('[') {
match rest.find(']') {
Some(end) => &rest[..end],
None => {
return Err(format!(
"remote endpoint {:?} has a malformed IPv6 host",
endpoint
))
}
}
} else {
match host_port.find(':') {
Some(colon) => &host_port[..colon],
None => host_port,
}
};
if host.is_empty() {
return Err(format!("remote endpoint {:?} has no host", endpoint));
}
if is_blocked_imds_host(&host.to_ascii_lowercase()) {
return Err(format!(
"remote endpoint {:?} targets instance metadata service",
endpoint
));
}
if let Ok(ip) = host.parse::<IpAddr>() {
check_blocked_ip(endpoint, ip)?;
return Ok(HostCheck::Validated);
}
Ok(HostCheck::NeedsResolution(host.to_string()))
}
/// Resolve `host` to its addresses with a short timeout, matching Go's 2s
/// resolver deadline.
async fn resolve_host(host: &str) -> Result<Vec<IpAddr>, String> {
let lookup = tokio::net::lookup_host((host, 0u16));
let addrs = tokio::time::timeout(std::time::Duration::from_secs(2), lookup)
.await
.map_err(|_| format!("resolve remote endpoint host {:?}: timed out", host))?
.map_err(|e| format!("resolve remote endpoint host {:?}: {}", host, e))?;
Ok(addrs.map(|sock| sock.ip()).collect())
}
/// Returns an error if `endpoint` is not safe to dial from a server with access
/// to cluster-internal hosts. Rejects empty / non-http(s) endpoints,
/// loopback / unspecified / link-local / RFC 1918 / CGNAT addresses, and
/// well-known IMDS hostnames. Hostnames are resolved and every returned address
/// is checked. Mirrors Go's `validateRemoteEndpoint`.
pub async fn validate_remote_endpoint(endpoint: &str) -> Result<(), String> {
match precheck_endpoint(endpoint)? {
HostCheck::Validated => Ok(()),
HostCheck::NeedsResolution(host) => {
let addrs = resolve_host(&host).await?;
if addrs.is_empty() {
return Err(format!(
"resolve remote endpoint host {:?}: no addresses",
host
));
}
for ip in addrs {
check_blocked_ip(endpoint, ip)?;
}
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn rejects_blocked_literal_endpoints() {
let cases = [
("http://127.0.0.1:8080", "loopback"),
("http://[::1]:8080", "loopback"),
("http://169.254.169.254/", "metadata"),
("http://0.0.0.0/", "unspecified"),
("http://[fe80::1]/", "link-local"),
("http://10.0.0.1/", "private"),
("http://172.16.5.5/", "private"),
("http://192.168.0.1/", "private"),
("http://100.64.0.1/", "CGNAT"),
];
for (endpoint, want) in cases {
let err = precheck_endpoint(endpoint).expect_err(endpoint);
assert!(err.contains(want), "{endpoint}: {err:?} missing {want:?}");
}
}
#[test]
fn rejects_empty_and_bad_scheme() {
assert!(precheck_endpoint("").unwrap_err().contains("empty"));
assert!(precheck_endpoint("ftp://example.com/")
.unwrap_err()
.contains("http or https"));
assert!(precheck_endpoint("example.com/")
.unwrap_err()
.contains("http or https"));
}
#[test]
fn rejects_imds_hostnames() {
assert!(precheck_endpoint("http://metadata.google.internal/")
.unwrap_err()
.contains("metadata service"));
assert!(precheck_endpoint("http://metadata/")
.unwrap_err()
.contains("metadata service"));
}
#[test]
fn accepts_public_literal_and_defers_hostname() {
assert!(matches!(
precheck_endpoint("https://52.216.10.10/"),
Ok(HostCheck::Validated)
));
match precheck_endpoint("https://s3.us-east-1.amazonaws.com/") {
Ok(HostCheck::NeedsResolution(host)) => {
assert_eq!(host, "s3.us-east-1.amazonaws.com")
}
other => panic!("expected resolution, got {other:?}"),
}
}
#[test]
fn check_blocked_ip_matches_resolved_categories() {
// Mirror Go's "host resolves to X" cases at the address level.
assert!(check_blocked_ip("e", ip("127.0.0.1"))
.unwrap_err()
.contains("loopback"));
assert!(check_blocked_ip("e", ip("169.254.10.20"))
.unwrap_err()
.contains("link-local"));
assert!(check_blocked_ip("e", ip("10.1.2.3"))
.unwrap_err()
.contains("private"));
assert!(check_blocked_ip("e", ip("172.20.0.5"))
.unwrap_err()
.contains("private"));
assert!(check_blocked_ip("e", ip("192.168.1.1"))
.unwrap_err()
.contains("private"));
assert!(check_blocked_ip("e", ip("100.64.0.42"))
.unwrap_err()
.contains("CGNAT"));
assert!(check_blocked_ip("e", ip("fc00::1"))
.unwrap_err()
.contains("private"));
assert!(check_blocked_ip("e", ip("52.216.10.10")).is_ok());
assert!(check_blocked_ip("e", ip("2606:4700:4700::1111")).is_ok());
}
#[test]
fn rejects_ipv4_mapped_ipv6() {
// IPv4-mapped IPv6 must be unmapped so the IPv4 rules catch it.
assert!(check_blocked_ip("e", ip("::ffff:127.0.0.1"))
.unwrap_err()
.contains("loopback"));
assert!(check_blocked_ip("e", ip("::ffff:169.254.169.254"))
.unwrap_err()
.contains("metadata"));
assert!(check_blocked_ip("e", ip("::ffff:10.0.0.1"))
.unwrap_err()
.contains("private"));
// A mapped public address still passes, and genuine IPv6 loopback is
// still caught by the V6 path.
assert!(check_blocked_ip("e", ip("::ffff:52.216.10.10")).is_ok());
assert!(check_blocked_ip("e", ip("::1"))
.unwrap_err()
.contains("loopback"));
// Bracketed mapped literal via the full endpoint path.
assert!(precheck_endpoint("http://[::ffff:127.0.0.1]/")
.unwrap_err()
.contains("loopback"));
}
}
+57
View File
@@ -3,9 +3,12 @@
//! Provides a trait-based abstraction over cloud storage providers (S3, GCS, Azure, etc.)
//! and a registry to create clients from protobuf RemoteConf messages.
pub mod endpoint_guard;
pub mod s3;
pub mod s3_tier;
pub use endpoint_guard::validate_remote_endpoint;
use crate::pb::remote_pb::{RemoteConf, RemoteStorageLocation};
/// Error type for remote storage operations.
@@ -86,6 +89,26 @@ pub fn make_remote_storage_client(
}
}
/// Endpoint URL that the volume server would dial directly for `conf`, or
/// `None` for non-S3-compatible backends. Every type handled here routes
/// through [`s3::S3RemoteStorageClient`] with a caller-supplied endpoint, so
/// the SSRF guard must validate each one. Keep this match in sync with
/// [`make_remote_storage_client`].
pub fn s3_compatible_endpoint(conf: &RemoteConf) -> Option<&str> {
match conf.r#type.as_str() {
"s3" => Some(&conf.s3_endpoint),
"wasabi" => Some(&conf.wasabi_endpoint),
"backblaze" => Some(&conf.backblaze_endpoint),
"aliyun" => Some(&conf.aliyun_endpoint),
"tencent" => Some(&conf.tencent_endpoint),
"baidu" => Some(&conf.baidu_endpoint),
"filebase" => Some(&conf.filebase_endpoint),
"storj" => Some(&conf.storj_endpoint),
"contabo" => Some(&conf.contabo_endpoint),
_ => None,
}
}
/// Extract S3-compatible credentials from a RemoteConf based on its type.
fn extract_s3_credentials(conf: &RemoteConf) -> (String, String, String, String) {
match conf.r#type.as_str() {
@@ -155,3 +178,37 @@ fn extract_s3_credentials(conf: &RemoteConf) -> (String, String, String, String)
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn s3_compatible_endpoint_covers_all_s3_backends() {
let s3 = RemoteConf {
r#type: "s3".to_string(),
s3_endpoint: "http://s3.internal".to_string(),
..Default::default()
};
assert_eq!(s3_compatible_endpoint(&s3), Some("http://s3.internal"));
// A non-"s3" S3-compatible type still surfaces its own endpoint, so the
// SSRF guard cannot be bypassed by picking a different alias.
let wasabi = RemoteConf {
r#type: "wasabi".to_string(),
wasabi_endpoint: "http://wasabi.internal".to_string(),
..Default::default()
};
assert_eq!(
s3_compatible_endpoint(&wasabi),
Some("http://wasabi.internal")
);
// Non-S3 backends do not dial a caller-supplied URL directly.
let gcs = RemoteConf {
r#type: "gcs".to_string(),
..Default::default()
};
assert_eq!(s3_compatible_endpoint(&gcs), None);
}
}
+1
View File
@@ -189,6 +189,7 @@ mod tests {
white_list: vec![],
fix_jpg_orientation: false,
read_mode: ReadMode::Local,
allow_untrusted_remote_endpoints: false,
cpu_profile: String::new(),
mem_profile: String::new(),
compaction_byte_per_second: 0,
+22
View File
@@ -3490,6 +3490,25 @@ impl VolumeServer for VolumeGrpcService {
.as_ref()
.ok_or_else(|| Status::invalid_argument("remote storage configuration is required"))?;
// Reject SSRF-prone endpoints unless the operator opted out. Every
// S3-compatible backend (s3, wasabi, backblaze, ...) dials a
// caller-supplied endpoint URL directly via make_remote_storage_client,
// so validate whichever endpoint applies. An empty endpoint means the
// provider default (e.g. real AWS S3) and cannot target an internal
// host, so skip it. Extends the Go volume server's validateRemoteEndpoint
// gate, which only covered type "s3".
if !self.state.allow_untrusted_remote_endpoints {
if let Some(endpoint) = crate::remote_storage::s3_compatible_endpoint(remote_conf) {
if !endpoint.trim().is_empty() {
crate::remote_storage::validate_remote_endpoint(endpoint)
.await
.map_err(|e| {
Status::invalid_argument(format!("reject remote endpoint: {}", e))
})?;
}
}
}
// Create remote storage client
let client =
crate::remote_storage::make_remote_storage_client(remote_conf).map_err(|e| {
@@ -4728,6 +4747,7 @@ mod tests {
crate::remote_storage::s3_tier::S3TierRegistry::new(),
),
read_mode: crate::config::ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: String::new(),
master_urls: Vec::new(),
seed_master_set: std::collections::HashSet::new(),
@@ -4832,6 +4852,7 @@ mod tests {
crate::remote_storage::s3_tier::S3TierRegistry::new(),
),
read_mode: crate::config::ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: String::new(),
master_urls: Vec::new(),
seed_master_set: std::collections::HashSet::new(),
@@ -4940,6 +4961,7 @@ mod tests {
crate::remote_storage::s3_tier::S3TierRegistry::new(),
),
read_mode: crate::config::ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: master_urls.first().cloned().unwrap_or_default(),
master_urls,
seed_master_set,
+24 -1
View File
@@ -4,9 +4,10 @@
//! matching Go's `server/volume_grpc_client_to_master.go`.
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::broadcast;
use tracing::{error, info, warn};
@@ -827,6 +828,27 @@ fn build_heartbeat_with_ec_status(
delete_vids.push(vol.id);
should_delete_volume = true;
} else if !vol.is_expired(volume_size, volume_size_limit) {
// Detect phantom volumes: the .dat was unlinked from disk but is still
// held open as a deleted FD, so the volume keeps serving and heartbeating
// while no disk-path operation can ever succeed. Skip remote-tiered volumes,
// whose .dat legitimately lives in cloud storage. Only a present .dat is
// cached for 30s; a missing one is re-checked every heartbeat so the volume
// stays suppressed until the file returns. See issues/10004
if vol.file_count() > 0 && !vol.has_remote_file {
const DISK_CHECK_INTERVAL_NS: i64 = 30 * 1_000_000_000;
let now_ns = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_nanos() as i64;
if now_ns - vol.last_disk_check_ns.load(Ordering::Relaxed) > DISK_CHECK_INTERVAL_NS {
if !Path::new(&vol.file_name(".dat")).exists() {
warn!("Volume {}: data file {} missing (held open as deleted FD) - not reporting to master", vol.id.0, vol.file_name(".dat"));
continue;
}
vol.last_disk_check_ns.store(now_ns, Ordering::Relaxed);
}
}
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
volumes.push(master_pb::VolumeInformationMessage {
id: vol.id.0,
@@ -1047,6 +1069,7 @@ mod tests {
write_queue: std::sync::OnceLock::new(),
s3_tier_registry: std::sync::RwLock::new(S3TierRegistry::new()),
read_mode: ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: String::new(),
master_urls: Vec::new(),
seed_master_set: std::collections::HashSet::new(),
+1
View File
@@ -131,6 +131,7 @@ mod tests {
white_list: vec![],
fix_jpg_orientation: false,
read_mode: ReadMode::Local,
allow_untrusted_remote_endpoints: false,
cpu_profile: String::new(),
mem_profile: String::new(),
compaction_byte_per_second: 0,
@@ -77,6 +77,9 @@ pub struct VolumeServerState {
pub s3_tier_registry: std::sync::RwLock<crate::remote_storage::s3_tier::S3TierRegistry>,
/// Read mode: local, proxy, or redirect for non-local volumes.
pub read_mode: ReadMode,
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation,
/// allowing arbitrary (incl. loopback / link-local / metadata) hosts.
pub allow_untrusted_remote_endpoints: bool,
/// First master address for volume lookups (e.g., "localhost:9333").
pub master_url: String,
/// Seed master addresses for UI rendering.
+1
View File
@@ -205,6 +205,7 @@ mod tests {
crate::remote_storage::s3_tier::S3TierRegistry::new(),
),
read_mode: crate::config::ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: String::new(),
master_urls: Vec::new(),
seed_master_set: std::collections::HashSet::new(),
+3
View File
@@ -503,6 +503,7 @@ pub struct Volume {
last_modified_ts_seconds: u64,
last_append_at_ns: u64,
pub last_disk_check_ns: Arc<std::sync::atomic::AtomicI64>, // for phantom volume detection cache
last_compact_index_offset: u64,
last_compact_revision: u16,
@@ -575,6 +576,7 @@ impl Volume {
location_disk_space_low: Arc::new(AtomicBool::new(false)),
last_modified_ts_seconds: 0,
last_append_at_ns: 0,
last_disk_check_ns: Arc::new(std::sync::atomic::AtomicI64::new(0)),
last_compact_index_offset: 0,
last_compact_revision: 0,
is_compacting: false,
@@ -608,6 +610,7 @@ impl Volume {
location_disk_space_low: Arc::new(AtomicBool::new(false)),
last_modified_ts_seconds: 0,
last_append_at_ns: 0,
last_disk_check_ns: Arc::new(std::sync::atomic::AtomicI64::new(0)),
last_compact_index_offset: 0,
last_compact_revision: 0,
is_compacting: false,
+1
View File
@@ -99,6 +99,7 @@ fn test_state_with_guard(
seaweed_volume::remote_storage::s3_tier::S3TierRegistry::new(),
),
read_mode: seaweed_volume::config::ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: String::new(),
master_urls: Vec::new(),
seed_master_set: std::collections::HashSet::new(),
+99
View File
@@ -0,0 +1,99 @@
# FUSE database load / durability / performance benchmark
Runs **MySQL (InnoDB)** and **SQLite** with their data files on a SeaweedFS **FUSE mount**,
with ~1 GB datasets, and answers two questions:
1. **Durability** — does any committed data get lost across normal shutdown, an unexpected
`kill -9`, or a crash during active writes?
2. **Performance** — how much slower is the FUSE mount than the local disk for the same
workload (bulk load, OLTP commits, scans, raw fsync)?
Each row carries a CRC32 of an incompressible (so ~1 GB actually hits the volumes)
deterministic payload; verification checks `integrity_check`/`CHECK TABLE`, exact row count,
contiguous-id prefix, and a per-row CRC recompute.
## Results (single node, macOS arm64 + macFUSE, weed 4.34, local NVMe, 2026-06-15)
### Durability — 6/6 PASS, no committed data lost, no corruption
| scenario | what | SQLite | MySQL |
|---|---|---|---|
| A normal shutdown | graceful DB stop, unmount, cluster stop, restart, verify | PASS | PASS |
| B unexpected (`kill -9`) | kill -9 db+mount+cluster, restart, recover, verify | PASS | PASS |
| C crash during writes | kill -9 mid-load, restart, recover, verify committed prefix | PASS | PASS |
Scenario C confirmed correct recovery: the in-flight transaction rolled back, every
fsync-committed row survived as a contiguous prefix (InnoDB redo recovery ~9 s).
### Performance — FUSE vs host (same disk, same durability settings)
Raw filesystem:
| metric | host | FUSE | FUSE slower |
|---|---|---|---|
| seq write +fsync | 2336 MB/s | 369 MB/s | 6.3x |
| seq read (warm) | 3435 MB/s | 1422 MB/s | 2.4x |
| fsync latency | 0.13 ms | 1.18 ms | 9x |
SQLite (1 GB, journal=DELETE, synchronous=FULL):
| metric | host | FUSE | FUSE slower |
|---|---|---|---|
| bulk load | 5.8 s (177 MB/s) | 11.6 s (88 MB/s) | 2.0x |
| OLTP 1-row txns | 1987 tx/s | 171 tx/s | 11.6x |
| full scan (warm) | 316 MB/s | 427 MB/s | ~equal (python-bound) |
MySQL/InnoDB (1 GB, trx_commit=1, flush_method=fsync):
| metric | host | FUSE | FUSE slower |
|---|---|---|---|
| bulk load | 24.4 s (42 MB/s) | 32.9 s (31 MB/s) | 1.35x |
| OLTP 1-row commits | 10542 tx/s | 1144 tx/s | 9.2x |
| full scan | 2419 MB/s | 430 MB/s | 5.6x |
**Takeaway:** the cost is dominated by fsync/commit latency (0.13 → 1.18 ms, ~9x) because
every durable commit uploads the chunk to the volume + persists the filer chunk-manifest over
loopback. Small fsync'd transactions are ~9-12x slower; bulk loads (commits amortized) are
1.3-2x slower; warm/sequential reads are close to host. These are single-node loopback
numbers — a real cluster (remote volumes, replication) adds network RTT + replica fsync per
commit.
## Durability caveat (test scope)
`kill -9` terminates the **processes** while the OS keeps running, so everything that reached
the OS page cache (all fsync'd data) survives — this faithfully tests process/daemon crashes
and is what passed 6/6. It does **not** simulate true **power loss** (page cache lost). The
FUSE mount uploads chunks **without** `fsync=true` (`weed/mount/weedfs_write.go` builds
`UploadOption` with no `Fsync`), so the volume does not fsync `.dat` per upload and the filer
leveldb likely does not sync per write; under a real power cut, recently-"committed" data that
only reached the page cache could be lost. A VM hard-reset / power-loss test on real hardware
is the follow-up to close that gap.
## Requirements
- `weed` on `$PATH` (or set `WEED=/path/to/weed`)
- macFUSE (macOS) or libfuse (Linux)
- `python3`, `sqlite3`
- MySQL/MariaDB install; set `MYSQL_BASE` to its prefix (default macOS Homebrew
`/opt/homebrew/opt/mysql`; must contain `bin/mysqld`, `bin/mysql`, `bin/mysqladmin`).
For `mysql_bench.py` on a non-default install, also set `MYSQL_BIN=/path/to/mysql`.
## Run
Runtime artifacts (cluster, mount, logs) go to `$SEAWEED_BENCH_WORK`
(default `/tmp/seaweedfs_fuse_db_bench`), kept out of the repo.
cd test/benchmark/fuse_db
bash bin/run_sqlite.sh > results/sqlite.log 2>&1 # SQLite durability suite
bash bin/run_mysql.sh > results/mysql.log 2>&1 # MySQL durability suite
bash bin/compare.sh > results/compare.log 2>&1 # FUSE vs host performance
The harness manages only its own processes (via pidfiles) on non-default ports
(9555/9560/9565, mysqld 3308); it never runs `pkill weed`, so other SeaweedFS instances on
the box are untouched.
## Files
bin/lib.sh cluster/mount/mysqld lifecycle helpers (start/stop/kill, clean state)
bin/run_sqlite.sh SQLite 1GB load + A/B/C crash scenarios
bin/run_mysql.sh MySQL 1GB load + A/B/C crash scenarios
bin/compare.sh FUSE-vs-host driver
bin/sqlite_gen.py deterministic incompressible SQLite loader (progress/ref files)
bin/sqlite_verify.py SQLite integrity + count + prefix + per-row CRC verifier
bin/sqlite_bench.py SQLite load/OLTP/scan timing probe
bin/mysql_bench.py MySQL load/OLTP/scan timing probe (via mysql CLI)
bin/fsbench.py raw seq-write / fsync-latency / seq-read microbenchmark
The numbers above are the reference baseline; rerun the scripts to reproduce. Run output is
written to results/*.log, which is gitignored (repo-wide *.log rule) -- not checked in.
+44
View File
@@ -0,0 +1,44 @@
#!/bin/bash
# Identical SQLite + MySQL + raw-fs workloads on HOST (local APFS) vs the SeaweedFS
# FUSE mount. Same disk underneath, same DB durability settings -> the delta is the
# SeaweedFS+FUSE stack.
BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$BIN/lib.sh"
HOSTDIR=$WORK/hostdir # local disk, NOT under the FUSE mount
ROWS=262144; SBATCH=4096; MBATCH=8192; OLTP=2000
mysqld_init_at() { rm -rf "$1"; mkdir -p "$1"; "$MYSQLD" --initialize-insecure --datadir="$1" \
--basedir="$MYSQL_BASE" --log-error="$LOGS/mysql_init_cmp.log"; }
mysqld_run() {
"$MYSQLD" --datadir="$1" --basedir="$MYSQL_BASE" --socket="$MYSQL_SOCK" --port=$MYSQL_PORT \
--bind-address=127.0.0.1 --innodb_flush_log_at_trx_commit=1 --innodb_flush_method=fsync \
--innodb_doublewrite=ON --innodb_buffer_pool_size=256M --secure-file-priv="" \
--log-error="$LOGS/mysqld_cmp.log" >> "$LOGS/mysqld_cmp.out" 2>&1 &
echo $! > "$PIDS/mysql.pid"; mysql_wait; }
echo "###### FUSE vs HOST $(date) ######"
echo "ROWS=$ROWS payload=4096B incompressible SQLite(journal=DELETE,sync=FULL) InnoDB(trx_commit=1,flush=fsync)"
# ===================== HOST (local APFS, no SeaweedFS) =====================
clean_state >/dev/null 2>&1
rm -rf "$HOSTDIR"; mkdir -p "$HOSTDIR/sqlite" "$HOSTDIR/fsb"
echo; echo "===== HOST: raw fs ====="; python3 "$BIN/fsbench.py" "$HOSTDIR/fsb"
echo; echo "===== HOST: SQLite ====="; python3 "$BIN/sqlite_bench.py" "$HOSTDIR/sqlite/b.db" $ROWS $SBATCH $OLTP
echo; echo "===== HOST: MySQL ====="
mysqld_init_at "$HOSTDIR/mysql/data"; mysqld_run "$HOSTDIR/mysql/data"
python3 "$BIN/mysql_bench.py" "$MYSQL_SOCK" cmp $ROWS $MBATCH $OLTP
mysql_stop_graceful
# ===================== FUSE (SeaweedFS mount) =====================
cluster_start || exit 1; mount_start || exit 1
mkdir -p "$MNT/sqlite" "$MNT/fsb"
echo; echo "===== FUSE: raw fs ====="; python3 "$BIN/fsbench.py" "$MNT/fsb"
echo; echo "===== FUSE: SQLite ====="; python3 "$BIN/sqlite_bench.py" "$MNT/sqlite/b.db" $ROWS $SBATCH $OLTP
echo; echo "===== FUSE: MySQL ====="
mysqld_init_at "$MNT/mysql/data"; mysqld_run "$MNT/mysql/data"
python3 "$BIN/mysql_bench.py" "$MYSQL_SOCK" cmp $ROWS $MBATCH $OLTP
mysql_stop_graceful
stop_all
rm -rf "$HOSTDIR"
echo; echo "###### compare done ######"
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
# Raw filesystem microbenchmark in one directory. Prints TSV: METRIC<TAB>value<TAB>unit
# SEQWRITE MB/s (512MB stream + final fsync)
# FSYNC ops/s (500 x: pwrite 4KB at random offset in a 64MB file, then fsync)
# SEQREAD MB/s (read the 512MB file back; warm cache)
import sys, os, time, random
d = sys.argv[1]
os.makedirs(d, exist_ok=True)
big = os.path.join(d, "fsb_big.bin")
sm = os.path.join(d, "fsb_sync.bin")
# SEQWRITE 512MB + fsync
n = 512 * 1024 * 1024
buf = os.urandom(8 * 1024 * 1024)
t = time.time(); f = open(big, "wb"); w = 0
while w < n:
f.write(buf); w += len(buf)
f.flush(); os.fsync(f.fileno()); f.close()
dt = time.time() - t
print(f"SEQWRITE\t{w/1048576/dt:.0f}\tMB/s")
# FSYNC latency: 500 x (pwrite 4KB random offset + fsync) on a 64MB file
fd = os.open(sm, os.O_RDWR | os.O_CREAT, 0o644)
os.ftruncate(fd, 64 * 1024 * 1024)
os.fsync(fd)
page = os.urandom(4096)
N = 500
rnd = random.Random(12345)
t = time.time()
for _ in range(N):
off = rnd.randrange(0, 64 * 1024 * 1024 - 4096) & ~0xfff
os.pwrite(fd, page, off)
os.fsync(fd)
dt = time.time() - t
os.close(fd)
print(f"FSYNC\t{N/dt:.0f}\tops/s")
print(f"FSYNCLAT\t{dt/N*1000:.2f}\tms")
# SEQREAD (warm)
t = time.time(); tot = 0
with open(big, "rb") as f:
while True:
b = f.read(8 * 1024 * 1024)
if not b: break
tot += len(b)
dt = time.time() - t
print(f"SEQREAD\t{tot/1048576/dt:.0f}\tMB/s")
for p in (big, sm):
try: os.remove(p)
except OSError: pass
+214
View File
@@ -0,0 +1,214 @@
# Shared config + helpers for the SeaweedFS FUSE load/durability test.
# IMPORTANT: this harness manages ONLY its own processes via pidfiles and its own
# (non-default) ports. It never runs `pkill weed`, so any other SeaweedFS instances
# on the box (e.g. default ports 9333/8888) are safe.
#
# Config via env:
# SEAWEED_BENCH_WORK runtime dir for cluster/mount/logs (default /tmp/...; kept out of the repo)
# WEED path to the weed binary (default: from $PATH)
# MYSQL_BASE MySQL install prefix (default macOS Homebrew; on Linux e.g. /usr)
set -u
WORK="${SEAWEED_BENCH_WORK:-/tmp/seaweedfs_fuse_db_bench}"
WEED="${WEED:-$(command -v weed || echo weed)}"
RUN=$WORK
CLUSTER=$RUN/cluster # weed server -dir (master+volume+filer state) -- local disk
MNT=$RUN/mnt # FUSE mount point (the SeaweedFS filesystem under test)
LOGS=$RUN/logs
LOCAL=$RUN/local # non-FUSE scratch: pidfiles, mysql socket, references
PIDS=$LOCAL/pids
RESULTS=$RUN/results
# Isolated, non-default ports (avoid colliding with any running cluster)
MASTER_PORT=9555
VOLUME_PORT=9560
FILER_PORT=9565
FILER_GRPC=19565
# MySQL (macOS Homebrew default; override MYSQL_BASE on Linux, e.g. /usr)
MYSQL_BASE="${MYSQL_BASE:-/opt/homebrew/opt/mysql}"
MYSQLD=$MYSQL_BASE/bin/mysqld
MYSQL=$MYSQL_BASE/bin/mysql
export MYSQL_BIN="${MYSQL_BIN:-$MYSQL}" # propagated to mysql_bench.py
MYSQLADMIN=$MYSQL_BASE/bin/mysqladmin
MYSQL_PORT=3308
MYSQL_SOCK=$LOCAL/mysql.sock # socket on LOCAL disk, datadir on FUSE
MYSQL_DATADIR=$MNT/mysql/data # on the FUSE mount -- the thing under test
ts() { date +%H:%M:%S; }
say() { echo "[$(ts)] $*"; }
ensure_dirs() { mkdir -p "$CLUSTER" "$MNT" "$LOGS" "$LOCAL" "$PIDS" "$RESULTS" "$LOCAL/mountcache"; }
# Portable unmount: fusermount (Linux non-root) -> umount -> diskutil (macOS).
fuse_umount() { fusermount -u "$1" 2>/dev/null || fusermount3 -u "$1" 2>/dev/null || umount "$1" 2>/dev/null || diskutil unmount "$1" 2>/dev/null; }
fuse_umount_force() { fusermount -uz "$1" 2>/dev/null || fusermount3 -uz "$1" 2>/dev/null || umount -f "$1" 2>/dev/null || diskutil unmount force "$1" 2>/dev/null; }
# My (and only my) ports. Used for the kill-by-port safety net in clean_state.
MY_PORTS="$MASTER_PORT $VOLUME_PORT $FILER_PORT 19555 19560 $FILER_GRPC $MYSQL_PORT"
port_busy() { lsof -ti TCP:"$1" >/dev/null 2>&1; }
wait_port_free() { # $1=port $2=max-halfsec
local n=${2:-40}; for i in $(seq 1 "$n"); do port_busy "$1" || return 0; sleep 0.5; done; return 1; }
# ---- cluster (master+volume+filer in one process) ----
cluster_start() {
ensure_dirs
if ! wait_port_free "$MASTER_PORT" 30; then
say "ERROR master port $MASTER_PORT still busy (pid $(lsof -ti TCP:$MASTER_PORT|tr '\n' ' ')); not starting"; return 1
fi
say "starting weed server (master:$MASTER_PORT volume:$VOLUME_PORT filer:$FILER_PORT)"
"$WEED" server -ip=127.0.0.1 -dir="$CLUSTER" \
-master.port=$MASTER_PORT -volume.port=$VOLUME_PORT \
-filer -filer.port=$FILER_PORT \
-volume.max=50 -master.volumeSizeLimitMB=1024 \
>> "$LOGS/cluster.log" 2>&1 &
echo $! > "$PIDS/cluster.pid"
cluster_wait
}
cluster_wait() {
local pid; pid=$(cat "$PIDS/cluster.pid" 2>/dev/null)
for i in $(seq 1 120); do
# the process we launched must still be alive -- guards against a foreign
# process answering on the port after ours fataled (e.g. bind conflict)
if ! kill -0 "$pid" 2>/dev/null; then
say "ERROR cluster process $pid died during startup"; tail -15 "$LOGS/cluster.log"; return 1
fi
if curl -s "http://127.0.0.1:$MASTER_PORT/cluster/status" >/dev/null 2>&1 \
&& curl -s "http://127.0.0.1:$FILER_PORT/" >/dev/null 2>&1; then
say "cluster ready (pid $pid)"; return 0
fi
sleep 0.5
done
say "ERROR cluster not ready"; tail -20 "$LOGS/cluster.log"; return 1
}
cluster_stop_graceful() {
local pid; pid=$(cat "$PIDS/cluster.pid" 2>/dev/null) || return 0
[ -n "${pid:-}" ] || return 0
say "graceful stop cluster pid $pid (SIGTERM)"
kill -TERM "$pid" 2>/dev/null
for i in $(seq 1 60); do kill -0 "$pid" 2>/dev/null || { rm -f "$PIDS/cluster.pid"; return 0; }; sleep 0.5; done
say "cluster still alive after 30s; SIGKILL"; kill -9 "$pid" 2>/dev/null; rm -f "$PIDS/cluster.pid"
}
cluster_kill_hard() {
local pid; pid=$(cat "$PIDS/cluster.pid" 2>/dev/null) || return 0
[ -n "${pid:-}" ] && { say "HARD kill -9 cluster pid $pid"; kill -9 "$pid" 2>/dev/null; }
rm -f "$PIDS/cluster.pid"
}
# ---- FUSE mount ----
mount_start() {
ensure_dirs
say "mounting FUSE at $MNT (filer 127.0.0.1:$FILER_PORT)"
"$WEED" mount -filer=127.0.0.1:$FILER_PORT -dir="$MNT" \
-dirAutoCreate -cacheDir="$LOCAL/mountcache" \
>> "$LOGS/mount.log" 2>&1 &
echo $! > "$PIDS/mount.pid"
mount_wait
}
mount_wait() {
local pid; pid=$(cat "$PIDS/mount.pid" 2>/dev/null)
for i in $(seq 1 120); do
if ! kill -0 "$pid" 2>/dev/null; then
say "ERROR mount process $pid died during startup"; tail -15 "$LOGS/mount.log"; return 1
fi
if mount | grep -q "$MNT" && ls "$MNT" >/dev/null 2>&1; then say "mount ready (pid $pid)"; return 0; fi
sleep 0.5
done
say "ERROR mount not ready"; tail -20 "$LOGS/mount.log"; return 1
}
mount_stop_graceful() {
say "graceful unmount $MNT"
fuse_umount "$MNT"
local pid; pid=$(cat "$PIDS/mount.pid" 2>/dev/null)
if [ -n "${pid:-}" ]; then
for i in $(seq 1 40); do kill -0 "$pid" 2>/dev/null || break; sleep 0.5; done
kill -0 "$pid" 2>/dev/null && { kill -TERM "$pid" 2>/dev/null; sleep 1; }
fi
rm -f "$PIDS/mount.pid"
}
mount_kill_hard() {
local pid; pid=$(cat "$PIDS/mount.pid" 2>/dev/null)
[ -n "${pid:-}" ] && { say "HARD kill -9 mount pid $pid"; kill -9 "$pid" 2>/dev/null; }
rm -f "$PIDS/mount.pid"
# clean up the stale mountpoint
fuse_umount_force "$MNT"
}
# ---- MySQL ----
mysql_init() {
ensure_dirs
rm -rf "$MNT/mysql"; mkdir -p "$MNT/mysql"
say "initializing MySQL datadir on FUSE: $MYSQL_DATADIR"
"$MYSQLD" --initialize-insecure --datadir="$MYSQL_DATADIR" --basedir="$MYSQL_BASE" \
--log-error="$LOGS/mysql-init.log"
}
mysql_start() {
say "starting mysqld (port $MYSQL_PORT, datadir on FUSE, flush_log_at_trx_commit=1, flush_method=fsync)"
"$MYSQLD" --datadir="$MYSQL_DATADIR" --basedir="$MYSQL_BASE" \
--socket="$MYSQL_SOCK" --port=$MYSQL_PORT --bind-address=127.0.0.1 \
--innodb_flush_log_at_trx_commit=1 --innodb_flush_method=fsync \
--innodb_doublewrite=ON --innodb_buffer_pool_size=256M \
--secure-file-priv="" --log-error="$LOGS/mysqld.log" \
>> "$LOGS/mysqld.out" 2>&1 &
echo $! > "$PIDS/mysql.pid"
mysql_wait
}
mysql_wait() {
for i in $(seq 1 120); do
"$MYSQLADMIN" --socket="$MYSQL_SOCK" -uroot ping >/dev/null 2>&1 && { say "mysqld ready"; return 0; }
sleep 0.5
done
say "ERROR mysqld not ready"; tail -30 "$LOGS/mysqld.log"; return 1
}
mysql_stop_graceful() {
say "graceful mysqld shutdown"
"$MYSQLADMIN" --socket="$MYSQL_SOCK" -uroot shutdown 2>/dev/null
local pid; pid=$(cat "$PIDS/mysql.pid" 2>/dev/null)
if [ -n "${pid:-}" ]; then for i in $(seq 1 60); do kill -0 "$pid" 2>/dev/null || break; sleep 0.5; done; fi
rm -f "$PIDS/mysql.pid"
}
mysql_kill() {
local pid; pid=$(cat "$PIDS/mysql.pid" 2>/dev/null)
[ -n "${pid:-}" ] && { say "HARD kill -9 mysqld pid $pid"; kill -9 "$pid" 2>/dev/null; }
rm -f "$PIDS/mysql.pid"
}
mq() { "$MYSQL" --socket="$MYSQL_SOCK" -uroot "$@"; }
# ---- whole-node unexpected shutdown (simultaneous -9) ----
hard_kill_all() {
say "=== UNEXPECTED SHUTDOWN: kill -9 db + mount + cluster ==="
mysql_kill
mount_kill_hard
cluster_kill_hard
kill_my_ports # safety net in case any pidfile was stale
}
# stop everything I started (graceful, pidfile-based)
stop_all() { mysql_stop_graceful; mount_stop_graceful; cluster_stop_graceful; }
# safety net: kill anything still bound to MY (non-default) ports
kill_my_ports() {
for p in $MY_PORTS; do
local pids; pids=$(lsof -ti TCP:"$p" 2>/dev/null)
[ -n "$pids" ] && { say "killing leftover pid(s) $pids on my port $p"; kill -9 $pids 2>/dev/null; }
done
}
# ---- clean slate (wipe all test state; never touches user data) ----
clean_state() {
say "cleaning test state"
stop_all
fuse_umount_force "$MNT"
kill_my_ports
for p in $MASTER_PORT $VOLUME_PORT $FILER_PORT; do wait_port_free "$p" 40 || say "WARN port $p still busy"; done
rm -rf "$CLUSTER" "$MNT" "$LOCAL/mountcache" "$PIDS" 2>/dev/null
ensure_dirs
}
status_report() {
echo "---- status ----"
echo "df $MNT:"; df -h "$MNT" 2>/dev/null | tail -1
echo "cluster dir size:"; du -sh "$CLUSTER" 2>/dev/null
echo "volumes:"; curl -s "http://127.0.0.1:$MASTER_PORT/dir/status" 2>/dev/null | python3 -c 'import sys,json;d=json.load(sys.stdin);print(" topology free/max:",d.get("Topology",{}).get("Free"),d.get("Topology",{}).get("Max"))' 2>/dev/null
}
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
# MySQL performance probe via the mysql CLI (no driver needed). Times each phase
# in Python. Prints TSV: METRIC<TAB>secs<TAB>rate
# LOAD : bulk-load <rows> rows (4096B incompressible AES payload), <batch>-row txns
# OLTP : <oltp> single-row autocommit INSERTs (each fsyncs redo, trx_commit=1) -> tx/s
# SCAN : SUM(CRC32(payload)) over the table (reads every payload) -> MB/s
import os, re, sys, subprocess, time
sock = sys.argv[1]
db = sys.argv[2]
rows = int(sys.argv[3])
batch = int(sys.argv[4])
oltp = int(sys.argv[5])
MYSQL = os.environ.get("MYSQL_BIN", "mysql") # lib.sh exports MYSQL_BIN; else use PATH
if not re.fullmatch(r"[A-Za-z0-9_]+", db): # db is interpolated into SQL
raise SystemExit(f"invalid database name: {db!r}")
def run(sql):
r = subprocess.run([MYSQL, "--socket", sock, "-uroot"], input=sql.encode(),
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=1800)
if r.returncode != 0:
sys.stderr.write(r.stderr.decode()[:500]); raise SystemExit("mysql failed")
run(f"DROP DATABASE IF EXISTS {db}; CREATE DATABASE {db};"
f"CREATE TABLE {db}.t(id INT PRIMARY KEY,payload BLOB,chk BIGINT) ENGINE=InnoDB;"
f"CREATE TABLE {db}.o(id INT AUTO_INCREMENT PRIMARY KEY,v INT) ENGINE=InnoDB;")
mb = rows * 4096 / 1048576
stmts = ["SET SESSION cte_max_recursion_depth=1000000;"]
o = 0
while o < rows:
b = min(batch, rows - o)
stmts.append(
f"INSERT INTO {db}.t(id,payload,chk) "
f"WITH RECURSIVE seq(n) AS (SELECT 0 UNION ALL SELECT n+1 FROM seq WHERE n<{b-1}) "
f"SELECT n+{o},AES_ENCRYPT(REPEAT('a',4080),SHA2(n+{o},256)),"
f"CRC32(AES_ENCRYPT(REPEAT('a',4080),SHA2(n+{o},256))) FROM seq;")
o += b
t = time.time(); run("\n".join(stmts)); dt = time.time() - t
print(f"LOAD\t{dt:.1f}\t{mb/dt:.0f} MB/s")
sql = "\n".join(f"INSERT INTO {db}.o(v) VALUES({i});" for i in range(oltp))
t = time.time(); run(sql); dt = time.time() - t
print(f"OLTP\t{dt:.2f}\t{oltp/dt:.0f} tx/s")
t = time.time(); run(f"SELECT SUM(CRC32(payload)) FROM {db}.t;"); dt = time.time() - t
print(f"SCAN\t{dt:.1f}\t{mb/dt:.0f} MB/s")
+120
View File
@@ -0,0 +1,120 @@
#!/bin/bash
# MySQL (InnoDB) ~1GB load test on the SeaweedFS FUSE mount + crash suite.
# Datadir lives on the FUSE mount; innodb_flush_log_at_trx_commit=1 +
# innodb_flush_method=fsync => every commit fsyncs the redo log through FUSE.
BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$BIN/lib.sh"
TOTAL=262144 # 262144 * 4096B payload = ~1GiB row data (InnoDB on-disk larger)
BATCH=8192 # 32 committed transactions
PROG=$LOCAL/mysql_progress.txt
PASS=0; FAIL=0
chk() { if [ "$1" -eq 0 ]; then echo ">>> $2: PASS"; PASS=$((PASS+1)); else echo ">>> $2: FAIL"; FAIL=$((FAIL+1)); fi; }
mysql_schema() {
mq -e "CREATE DATABASE IF NOT EXISTS loadtest;
DROP TABLE IF EXISTS loadtest.t;
CREATE TABLE loadtest.t(id INT PRIMARY KEY, payload BLOB, chk BIGINT) ENGINE=InnoDB;"
}
mysql_load() { # loads TOTAL rows in BATCH-sized committed inserts; progress -> $PROG
local O=0 B rem
: > "$PROG"
while [ $O -lt $TOTAL ]; do
B=$BATCH; rem=$((TOTAL-O)); [ $rem -lt $B ] && B=$rem
# incompressible + deterministic payload: AES-128-ECB (no IV -> deterministic)
# of a fixed 4080B plaintext, keyed per-id -> 4096B ciphertext that defeats
# gzip on the volumes. Identical expr for payload and chk, so CRC32(payload)
# recomputed at verify must equal stored chk.
mq -e "SET SESSION cte_max_recursion_depth=1000000;
INSERT INTO loadtest.t(id,payload,chk)
WITH RECURSIVE seq(n) AS (SELECT 0 UNION ALL SELECT n+1 FROM seq WHERE n < $((B-1)))
SELECT n+$O,
AES_ENCRYPT(REPEAT('a',4080), SHA2(n+$O,256)),
CRC32(AES_ENCRYPT(REPEAT('a',4080), SHA2(n+$O,256)))
FROM seq;" \
|| { echo "INSERT failed at offset $O"; return 1; }
# durable + atomic progress (matches sqlite_gen.py) so the crash-test lower
# bound is never stale or torn: write tmp, fsync, rename.
O=$((O+B)); printf '%s' "$O" > "$PROG.tmp"
python3 -c "import os,sys; fd=os.open(sys.argv[1],os.O_RDONLY); os.fsync(fd); os.close(fd)" "$PROG.tmp"
mv -f "$PROG.tmp" "$PROG"
done
}
mysql_verify() { # $1=expected $2=mode(exact|atleast) ; returns 0 on PASS
local exp=$1 mode=$2 cnt sumchk corrupt minid maxid checktbl ok=0
read -r cnt sumchk corrupt minid maxid <<EOF
$(mq -N -e "SELECT COUNT(*),COALESCE(SUM(chk),0),COALESCE(SUM(chk<>CRC32(payload)),0),COALESCE(MIN(id),-1),COALESCE(MAX(id),-1) FROM loadtest.t;")
EOF
checktbl=$(mq -N -e "CHECK TABLE loadtest.t;" | awk '{print $NF}')
echo " rows=$cnt corrupt=$corrupt minid=$minid maxid=$maxid CHECK=$checktbl (want $mode $exp)"
[ "$checktbl" = "OK" ] || { echo " -> CHECK TABLE failed"; ok=1; }
[ "$corrupt" = "0" ] || { echo " -> payload corruption in $corrupt rows"; ok=1; }
if [ "$mode" = exact ]; then
[ "$cnt" = "$exp" ] || { echo " -> row count mismatch"; ok=1; }
{ [ "$minid" = 0 ] && [ "$maxid" = "$((exp-1))" ]; } || { echo " -> not contiguous 0..$((exp-1))"; ok=1; }
else
[ "$cnt" -ge "$exp" ] 2>/dev/null || { echo " -> LOST COMMITTED DATA (cnt<$exp)"; ok=1; }
{ [ "$minid" = 0 ] && [ "$maxid" = "$((cnt-1))" ]; } || { echo " -> not contiguous prefix"; ok=1; }
fi
return $ok
}
echo "######## MySQL FUSE load test $(date) ########"
# ---------- fresh cluster + mysql + 1GB load ----------
clean_state; cluster_start || exit 1; mount_start || exit 1
mysql_init || { echo "mysql_init failed"; tail -20 "$LOGS/mysql-init.log"; exit 1; }
mysql_start || exit 1
mysql_schema
say "loading ~1GB into InnoDB"
t0=$SECONDS
mysql_load || echo "load reported an error"
say "load done in $((SECONDS-t0))s"
mq -N -e "SELECT CONCAT('innodb rows=',COUNT(*),' data_len=',ROUND(SUM(LENGTH(payload))/1048576),'MB') FROM loadtest.t;"
du -sh "$MYSQL_DATADIR"; status_report
# ---------- Scenario A: normal (graceful) shutdown + restart ----------
echo; echo "==================== SCENARIO A: NORMAL SHUTDOWN ===================="
mysql_stop_graceful
mount_stop_graceful
cluster_stop_graceful
sleep 1
cluster_start || exit 1; mount_start || exit 1; mysql_start || exit 1
mysql_verify $TOTAL exact; chk $? "A/normal-shutdown"
# ---------- Scenario B: unexpected shutdown (kill -9 everything) ----------
echo; echo "============== SCENARIO B: UNEXPECTED SHUTDOWN (kill -9) =============="
hard_kill_all
sleep 1
cluster_start || exit 1; mount_start || exit 1
say "restarting mysqld -> InnoDB crash recovery runs"
mysql_start || { echo "mysqld failed to recover"; tail -30 "$LOGS/mysqld.log"; chk 1 "B/unexpected-shutdown"; }
if mq -e "SELECT 1" >/dev/null 2>&1; then mysql_verify $TOTAL exact; chk $? "B/unexpected-shutdown"; fi
# ---------- Scenario C: crash DURING active writes ----------
echo; echo "=========== SCENARIO C: CRASH DURING ACTIVE WRITES (kill -9) ==========="
mysql_stop_graceful
clean_state; cluster_start || exit 1; mount_start || exit 1
mysql_init || exit 1; mysql_start || exit 1; mysql_schema
say "loading in background; will crash storage + mysqld mid-write"
mysql_load > "$LOGS/mysql_load_c.log" 2>&1 &
LPID=$!
while :; do
p=$(cat "$PROG" 2>/dev/null || echo 0); p=${p:-0}
[ "$p" -ge $((TOTAL/2)) ] && break
kill -0 $LPID 2>/dev/null || { say "loader exited early"; break; }
sleep 0.2
done
LB=$(cat "$PROG" 2>/dev/null); LB=${LB:-0} # empty file (killed mid-write) -> 0
say "durable committed lower-bound at crash = $LB rows; crashing now"
hard_kill_all
kill -9 $LPID 2>/dev/null; wait $LPID 2>/dev/null
sleep 1
cluster_start || exit 1; mount_start || exit 1
say "restarting mysqld -> InnoDB recovery; in-flight txn must roll back, committed must survive"
mysql_start || { echo "recovery failed"; tail -30 "$LOGS/mysqld.log"; chk 1 "C/crash-during-write"; }
if mq -e "SELECT 1" >/dev/null 2>&1; then mysql_verify "$LB" atleast; chk $? "C/crash-during-write"; fi
echo; echo "######## MySQL RESULT: PASS=$PASS FAIL=$FAIL ########"
mysql_stop_graceful; mount_stop_graceful; cluster_stop_graceful
exit $FAIL
+67
View File
@@ -0,0 +1,67 @@
#!/bin/bash
# SQLite ~1GB load test on the SeaweedFS FUSE mount + crash suite.
BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$BIN/lib.sh"
TOTAL=262144 # 262144 * 4096B payload = ~1GiB of row data
BATCH=4096 # 64 committed transactions (each fsync'd, synchronous=FULL)
DB=$MNT/sqlite/load.db
PROG=$LOCAL/sqlite_progress.txt
REF=$LOCAL/sqlite_ref.txt
PASS=0; FAIL=0
chk() { if [ "$1" -eq 0 ]; then echo ">>> $2: PASS"; PASS=$((PASS+1)); else echo ">>> $2: FAIL"; FAIL=$((FAIL+1)); fi; }
echo "######## SQLite FUSE load test $(date) ########"
# ---------- fresh cluster + 1GB load ----------
clean_state; cluster_start || exit 1; mount_start || exit 1
mkdir -p "$MNT/sqlite"
say "loading ~1GB into SQLite (journal=DELETE synchronous=FULL)"
t0=$SECONDS
python3 "$BIN/sqlite_gen.py" "$DB" $TOTAL $BATCH "$PROG" "$REF" FULL DELETE | tail -3
say "load done in $((SECONDS-t0))s; file size:"; ls -lh "$DB"; du -sh "$MNT/sqlite"
status_report
# ---------- Scenario A: normal (graceful) shutdown + restart ----------
echo; echo "==================== SCENARIO A: NORMAL SHUTDOWN ===================="
mount_stop_graceful
cluster_stop_graceful
sleep 1
cluster_start || exit 1; mount_start || exit 1
say "verifying after graceful restart"
python3 "$BIN/sqlite_verify.py" "$DB" $TOTAL exact; chk $? "A/normal-shutdown"
# ---------- Scenario B: unexpected shutdown (kill -9) + restart ----------
echo; echo "============== SCENARIO B: UNEXPECTED SHUTDOWN (kill -9) =============="
hard_kill_all
sleep 1
cluster_start || exit 1; mount_start || exit 1
say "verifying after kill -9 + restart"
python3 "$BIN/sqlite_verify.py" "$DB" $TOTAL exact; chk $? "B/unexpected-shutdown"
# ---------- Scenario C: crash DURING active writes ----------
echo; echo "=========== SCENARIO C: CRASH DURING ACTIVE WRITES (kill -9) ==========="
clean_state; cluster_start || exit 1; mount_start || exit 1
mkdir -p "$MNT/sqlite"; : > "$PROG"
say "starting loader in background; will crash storage mid-write"
python3 "$BIN/sqlite_gen.py" "$DB" $TOTAL $BATCH "$PROG" "" FULL DELETE > "$LOGS/sqlite_gen_c.log" 2>&1 &
GENPID=$!
# wait until at least half is durably committed
while :; do
p=$(cat "$PROG" 2>/dev/null || echo 0); p=${p:-0}
[ "$p" -ge $((TOTAL/2)) ] && break
kill -0 $GENPID 2>/dev/null || { say "loader exited early"; break; }
sleep 0.2
done
LB=$(cat "$PROG" 2>/dev/null); LB=${LB:-0} # empty file (killed mid-write) -> 0
say "durable committed lower-bound at crash = $LB rows; crashing storage now"
hard_kill_all # storage dies under the still-writing loader
kill -9 $GENPID 2>/dev/null; wait $GENPID 2>/dev/null
sleep 1
cluster_start || exit 1; mount_start || exit 1
say "verifying recovery (committed prefix must survive, integrity must hold)"
python3 "$BIN/sqlite_verify.py" "$DB" "$LB" atleast; chk $? "C/crash-during-write"
echo; echo "######## SQLite RESULT: PASS=$PASS FAIL=$FAIL ########"
mount_stop_graceful; cluster_stop_graceful
exit $FAIL
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
# SQLite performance probe at one db path. Prints TSV: METRIC<TAB>secs<TAB>rate
# LOAD : bulk-load <rows> rows (4096B incompressible payload) in <batch>-row txns
# OLTP : <oltp> single-row INSERTs, each its own fsync'd autocommit txn -> tx/s
# SCAN : full table scan reading every payload (warm) -> MB/s
# journal=DELETE, synchronous=FULL (durable: fsync per commit).
import sys, os, sqlite3, time, random
db = sys.argv[1]
rows = int(sys.argv[2])
batch = int(sys.argv[3])
oltp = int(sys.argv[4])
for ext in ("", "-journal", "-wal", "-shm"):
try: os.remove(db + ext)
except OSError: pass
con = sqlite3.connect(db, isolation_level=None)
con.execute("PRAGMA journal_mode=DELETE;")
con.execute("PRAGMA synchronous=FULL;")
con.execute("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB, chk INTEGER);")
# LOAD
mb = rows * 4096 / 1048576
t = time.time(); done = 0
rnd = random.Random(12345) # reuse one PRNG; this probe doesn't verify payloads
while done < rows:
end = min(done + batch, rows)
data = [(i, rnd.randbytes(4096), 0) for i in range(done, end)]
con.execute("BEGIN")
con.executemany("INSERT INTO t VALUES(?,?,?)", data)
con.execute("COMMIT")
done = end
dt = time.time() - t
print(f"LOAD\t{dt:.1f}\t{mb/dt:.0f} MB/s")
# OLTP: each INSERT autocommits (isolation_level=None) -> 1 fsync'd txn each
con.execute("CREATE TABLE o(id INTEGER PRIMARY KEY, v INTEGER);")
t = time.time()
for i in range(oltp):
con.execute("INSERT INTO o(v) VALUES(?)", (i,))
dt = time.time() - t
print(f"OLTP\t{dt:.2f}\t{oltp/dt:.0f} tx/s")
# SCAN (warm): read every payload
t = time.time(); nbytes = 0
for rid, p, c in con.execute("SELECT id,payload,chk FROM t"):
nbytes += len(p)
dt = time.time() - t
print(f"SCAN\t{dt:.1f}\t{nbytes/1048576/dt:.0f} MB/s")
con.close()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
# Deterministic ~1GB SQLite load on the FUSE mount.
# Each row: id, payload (4096 deterministic bytes derived from id), chk=crc32(payload).
# Commits in batches; after each commit, writes the committed row count to a
# progress file on LOCAL disk and fsyncs it -> a durable record of what was
# committed, used to verify "no committed data lost" after a crash.
import sys, os, sqlite3, zlib, random
db_path = sys.argv[1]
total_rows = int(sys.argv[2])
batch = int(sys.argv[3])
progress_path= sys.argv[4] # LOCAL disk
ref_path = sys.argv[5] if len(sys.argv) > 5 else None
sync_mode = sys.argv[6] if len(sys.argv) > 6 else "FULL"
journal_mode = sys.argv[7] if len(sys.argv) > 7 else "DELETE"
# Validate before interpolating into PRAGMAs: a typo must not silently weaken
# durability and invalidate the comparison / crash-survival claims.
if sync_mode.upper() not in {"OFF", "NORMAL", "FULL", "EXTRA"}:
raise SystemExit(f"invalid synchronous mode: {sync_mode!r}")
if journal_mode.upper() not in {"DELETE", "TRUNCATE", "PERSIST", "MEMORY", "WAL", "OFF"}:
raise SystemExit(f"invalid journal mode: {journal_mode!r}")
def payload(i: int) -> bytes:
# deterministic but incompressible (PRNG seeded by id) -> 4096 bytes that
# actually consume ~1GB on the volume servers (defeats gzip storage).
return random.Random(i).randbytes(4096)
con = sqlite3.connect(db_path, isolation_level=None)
con.execute(f"PRAGMA journal_mode={journal_mode};")
con.execute(f"PRAGMA synchronous={sync_mode};")
con.execute("CREATE TABLE IF NOT EXISTS t(id INTEGER PRIMARY KEY, payload BLOB, chk INTEGER);")
def write_progress(n):
# atomic: write tmp + fsync + rename, so a kill -9 mid-write can't leave an
# empty/torn progress file (the crash-test lower bound must stay trustworthy).
tmp = progress_path + ".tmp"
with open(tmp, "w") as f:
f.write(str(n)); f.flush(); os.fsync(f.fileno())
os.replace(tmp, progress_path)
done = 0
sum_chk = 0
sum_id = 0
while done < total_rows:
end = min(done + batch, total_rows)
rows = []
for i in range(done, end):
p = payload(i); c = zlib.crc32(p)
rows.append((i, p, c)); sum_chk += c; sum_id += i
con.execute("BEGIN;")
con.executemany("INSERT INTO t(id,payload,chk) VALUES(?,?,?);", rows)
con.execute("COMMIT;")
done = end
write_progress(done)
print(f"committed {done}/{total_rows}", flush=True)
if ref_path:
with open(ref_path, "w") as f:
f.write(f"{total_rows} {sum_chk} {sum_id}\n"); f.flush(); os.fsync(f.fileno())
con.close()
print("DONE", flush=True)
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
# Verify a SQLite DB after a crash/restart.
# - PRAGMA integrity_check (structural consistency of the b-tree / pages)
# - row count / sum(chk) / sum(id) vs expected
# - recompute crc32(payload) for every row vs stored chk (byte corruption)
#
# usage: sqlite_verify.py <db> <expected_rows> [mode]
# mode=exact (default): count must == expected_rows (normal/unexpected shutdown
# of a fully-loaded DB -- nothing may be lost or extra).
# mode=atleast: expected_rows is a LOWER BOUND (durable committed progress at
# crash time). count must be >= expected_rows and form a contiguous
# prefix 0..count-1 (the in-flight txn may or may not have committed,
# but no committed row may be lost and recovery must be consistent).
import sys, sqlite3, zlib, random
db_path = sys.argv[1]
expected_rows = int(sys.argv[2])
mode = sys.argv[3] if len(sys.argv) > 3 else "exact"
if mode not in ("exact", "atleast"): # a typo must not silently relax checks
raise SystemExit(f"invalid mode: {mode!r} (want exact|atleast)")
def payload(i: int) -> bytes:
return random.Random(i).randbytes(4096)
con = sqlite3.connect(db_path)
ok = True
ic = con.execute("PRAGMA integrity_check;").fetchone()[0]
print(f"integrity_check: {ic}")
if ic != "ok": ok = False
cnt = con.execute("SELECT COUNT(*) FROM t;").fetchone()[0]
minid = con.execute("SELECT MIN(id) FROM t;").fetchone()[0]
maxid = con.execute("SELECT MAX(id) FROM t;").fetchone()[0]
sum_chk= con.execute("SELECT COALESCE(SUM(chk),0) FROM t;").fetchone()[0]
sum_id = con.execute("SELECT COALESCE(SUM(id),0) FROM t;").fetchone()[0]
if mode == "exact":
target = expected_rows
if cnt != expected_rows:
print(f"rows: got={cnt} expected={expected_rows} MISMATCH"); ok = False
else:
print(f"rows: got={cnt} expected={expected_rows} OK")
else: # atleast
print(f"rows: got={cnt} committed-lower-bound={expected_rows} "
f"{'OK' if cnt >= expected_rows else 'LOST COMMITTED DATA'}")
if cnt < expected_rows: ok = False
target = cnt
# contiguous prefix 0..cnt-1 ?
if cnt > 0 and (minid != 0 or maxid != cnt - 1):
print(f"prefix: MIN={minid} MAX={maxid} expected 0..{cnt-1} NON-CONTIGUOUS"); ok = False
else:
print(f"prefix: 0..{maxid} contiguous OK")
exp_sum_chk = sum(zlib.crc32(payload(i)) for i in range(target))
exp_sum_id = target * (target - 1) // 2
print(f"sum(chk): got={sum_chk} expected={exp_sum_chk} {'OK' if sum_chk==exp_sum_chk else 'MISMATCH'}")
print(f"sum(id): got={sum_id} expected={exp_sum_id} {'OK' if sum_id==exp_sum_id else 'MISMATCH'}")
if sum_chk != exp_sum_chk or sum_id != exp_sum_id: ok = False
corrupt = 0; scanned = 0
for rid, p, c in con.execute("SELECT id,payload,chk FROM t;"):
scanned += 1
if zlib.crc32(p) != c: corrupt += 1
print(f"payload byte-check: scanned={scanned} corrupt={corrupt} {'OK' if corrupt==0 else 'CORRUPT'}")
if corrupt != 0: ok = False
con.close()
print("VERIFY: " + ("PASS" if ok else "FAIL"))
sys.exit(0 if ok else 1)
+12 -184
View File
@@ -8,207 +8,69 @@ require (
github.com/seaweedfs/seaweedfs v0.0.0-00010101000000-000000000000
github.com/segmentio/kafka-go v0.4.49
github.com/stretchr/testify v1.11.1
google.golang.org/grpc v1.80.0
google.golang.org/grpc v1.81.1
)
replace github.com/seaweedfs/seaweedfs => ../../
require (
cloud.google.com/go/auth v0.20.0 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/compute/metadata v0.9.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4 // indirect
github.com/Azure/go-ntlmssp v0.1.1 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
github.com/FilenCloudDienste/filen-sdk-go v0.0.39 // indirect
github.com/Files-com/files-sdk-go/v3 v3.3.82 // indirect
github.com/IBM/go-sdk-core/v5 v5.21.2 // indirect
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/bcrypt v0.0.0-20211005172633-e235017c1baf // indirect
github.com/ProtonMail/gluon v0.17.1-0.20230724134000-308be39be96e // indirect
github.com/ProtonMail/go-crypto v1.4.1 // indirect
github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f // indirect
github.com/ProtonMail/go-srp v0.0.7 // indirect
github.com/ProtonMail/gopenpgp/v2 v2.9.0 // indirect
github.com/PuerkitoBio/goquery v1.11.0 // indirect
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 // indirect
github.com/abbot/go-http-auth v0.4.0 // indirect
github.com/adrg/xdg v0.5.3 // indirect
github.com/anchore/go-lzo v0.1.0 // indirect
github.com/andybalholm/brotli v1.2.0 // indirect
github.com/andybalholm/cascadia v1.3.3 // indirect
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
github.com/aws/aws-sdk-go v1.55.8 // indirect
github.com/aws/aws-sdk-go-v2 v1.41.6 // 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.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.22.13 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect
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.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
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 // indirect
github.com/aws/smithy-go v1.25.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/boombuler/barcode v1.1.0 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
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
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/cloudflare/circl v1.6.3 // indirect
github.com/cloudinary/cloudinary-go/v2 v2.15.0 // indirect
github.com/cloudsoda/go-smb2 v0.0.0-20250228001242-d4c70e6251cc // indirect
github.com/cloudsoda/sddl v0.0.0-20250224235906-926454e91efc // indirect
github.com/cognusion/imaging v1.0.2 // indirect
github.com/colinmarc/hdfs/v2 v2.4.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
github.com/creasty/defaults v1.8.0 // indirect
github.com/cronokirby/saferith v0.33.1-0.20250226174546-1f11f94ce488 // indirect
github.com/cognusion/imaging v1.0.3 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/diskfs/go-diskfs v1.7.0 // indirect
github.com/dromara/dongle v1.0.1 // indirect
github.com/dropbox/dropbox-sdk-go-unofficial/v6 v6.0.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/eapache/go-resiliency v1.7.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
github.com/eapache/queue v1.1.0 // indirect
github.com/ebitengine/purego v0.10.0 // indirect
github.com/emersion/go-message v0.18.2 // indirect
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/flynn/noise v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/geoffgarside/ber v1.2.0 // indirect
github.com/go-chi/chi/v5 v5.2.5 // indirect
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
github.com/go-git/go-billy/v5 v5.9.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-openapi/errors v0.22.6 // indirect
github.com/go-openapi/strfmt v0.25.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/go-resty/resty/v2 v2.17.2 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/gorilla/schema v1.4.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/internxt/rclone-adapter v0.0.0-20260331173834-036f908d0160 // indirect
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
github.com/jcmturner/gofork v1.7.6 // indirect
github.com/jcmturner/goidentity/v6 v6.0.1 // indirect
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
github.com/jhump/protoreflect v1.18.0 // indirect
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 // indirect
github.com/jlaffaye/ftp v0.2.1-0.20251026020404-6602e981a1bb // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jtolio/noiseconn v0.0.0-20231127013910-f6d9ecbf1de7 // indirect
github.com/jzelinskie/whirlpool v0.0.0-20201016144138-0675e54bb004 // indirect
github.com/karlseguin/ccache/v2 v2.0.8 // indirect
github.com/klauspost/compress v1.18.6 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/klauspost/reedsolomon v1.14.0 // indirect
github.com/koofr/go-httpclient v0.0.0-20240520111329-e20f8f203988 // indirect
github.com/koofr/go-koofrclient v0.0.0-20221207135200-cbd7fc9ad6a6 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/lanrat/extsort v1.4.2 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lpar/date v1.0.0 // indirect
github.com/lufia/plan9stats v0.0.0-20260216142805-b3301c5f2a88 // indirect
github.com/mailru/easyjson v0.9.1 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.22 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ncw/swift/v2 v2.0.5 // indirect
github.com/oklog/ulid v1.3.1 // indirect
github.com/oracle/oci-go-sdk/v65 v65.111.0 // indirect
github.com/onsi/ginkgo v1.16.5 // indirect
github.com/onsi/gomega v1.37.0 // indirect
github.com/orcaman/concurrent-map/v2 v2.0.1 // indirect
github.com/panjf2000/ants/v2 v2.11.5 // indirect
github.com/parquet-go/bitpack v1.0.0 // indirect
github.com/parquet-go/jsonlite v1.0.0 // indirect
github.com/parquet-go/parquet-go v0.28.0 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/parquet-go/parquet-go v0.30.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
github.com/peterh/liner v1.2.2 // indirect
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
github.com/pierrec/lz4/v4 v4.1.26 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pkg/sftp v1.13.10 // indirect
github.com/pkg/xattr v0.4.12 // indirect
github.com/pierrec/lz4/v4 v4.1.27 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/pquerna/otp v1.5.0 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.5 // indirect
github.com/prometheus/procfs v0.20.1 // indirect
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
github.com/rclone/Proton-API-Bridge v1.0.3 // indirect
github.com/rclone/go-proton-api v1.0.2 // indirect
github.com/rclone/rclone v1.74.1 // indirect
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
github.com/rdleal/intervalst v1.5.0 // indirect
github.com/relvacode/iso8601 v1.7.0 // indirect
github.com/rfjakob/eme v1.2.0 // indirect
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/samber/lo v1.52.0 // indirect
github.com/seaweedfs/goexif v1.0.3 // indirect
github.com/shirou/gopsutil/v4 v4.26.3 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
github.com/smarty/assertions v1.16.0 // indirect
github.com/sony/gobreaker v1.0.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spacemonkeygo/monkit/v3 v3.0.25-0.20251022131615-eb24eb109368 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
@@ -216,60 +78,26 @@ require (
github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 // indirect
github.com/t3rm1n4l/go-mega v0.0.0-20251120131202-6845944c051c // indirect
github.com/tklauser/go-sysconf v0.3.16 // indirect
github.com/tklauser/numcpus v0.11.0 // indirect
github.com/twpayne/go-geom v1.6.1 // indirect
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/unknwon/goconfig v1.0.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/viant/ptrie v1.0.1 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
github.com/yunify/qingstor-sdk-go/v3 v3.2.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/zeebo/blake3 v0.2.4 // indirect
github.com/zeebo/errs v1.4.0 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.etcd.io/bbolt v1.4.3 // indirect
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.67.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.50.0 // indirect
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/image v0.39.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.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.278.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/image v0.41.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
google.golang.org/grpc/security/advancedtls v1.0.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/validator.v2 v2.0.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
moul.io/http2curl/v2 v2.3.0 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
storj.io/common v0.0.0-20260225132117-99155641c30a // indirect
storj.io/drpc v0.0.35-0.20250513201419-f7819ea69b55 // indirect
storj.io/eventkit v0.0.0-20250410172343-61f26d3de156 // indirect
storj.io/infectious v0.0.2 // indirect
storj.io/picobuf v0.0.4 // indirect
storj.io/uplink v1.14.0 // indirect
)
+38 -838
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,62 @@
package dash
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/credential"
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory" // register the memory credential store
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
)
// TestGetObjectStoreUserDetailsIncludesInlinePolicies verifies that inline user
// policies — which are stored separately from the identity record and are
// authoritative at S3 enforcement time (they take precedence over the legacy
// Actions list) — are surfaced in the admin user details. They were previously
// invisible in the admin API/UI, so an operator could not tell what actually
// governed a user's access.
func TestGetObjectStoreUserDetailsIncludesInlinePolicies(t *testing.T) {
cm, err := credential.NewCredentialManagerWithDefaults(credential.StoreTypeMemory)
if err != nil {
t.Fatalf("failed to init credential manager: %v", err)
}
ctx := context.Background()
const username = "svc-app"
if err := cm.CreateUser(ctx, &iam_pb.Identity{Name: username}); err != nil {
t.Fatalf("failed to create user: %v", err)
}
const inlinePolicyName = "svc-app-policy"
doc := policy_engine.PolicyDocument{
Version: "2012-10-17",
Statement: []policy_engine.PolicyStatement{
{
Effect: "Allow",
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::ml-artifacts/*"),
},
},
}
if err := cm.PutUserInlinePolicy(ctx, username, inlinePolicyName, doc); err != nil {
t.Fatalf("failed to put inline policy: %v", err)
}
s := &AdminServer{credentialManager: cm}
details, err := s.GetObjectStoreUserDetails(username)
if err != nil {
t.Fatalf("GetObjectStoreUserDetails failed: %v", err)
}
found := false
for _, p := range details.PolicyNames {
if p == inlinePolicyName {
found = true
break
}
}
if !found {
t.Errorf("expected inline policy %q in details.PolicyNames, got %v", inlinePolicyName, details.PolicyNames)
}
}
+12
View File
@@ -9,6 +9,7 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
)
@@ -190,6 +191,17 @@ func (s *AdminServer) GetObjectStoreUserDetails(username string) (*UserDetails,
PolicyNames: identity.PolicyNames,
}
// Inline user policies are stored separately from the identity record and
// are authoritative at enforcement time (they take precedence over the
// legacy Actions list). Surface their names alongside attached policies so
// the admin reflects the user's actual permissions rather than only the
// (potentially overridden) Actions.
if inlinePolicyNames, err := s.credentialManager.ListUserInlinePolicies(ctx, username); err != nil {
glog.Warningf("failed to list inline policies for user %s: %v", username, err)
} else if len(inlinePolicyNames) > 0 {
details.PolicyNames = append(details.PolicyNames, inlinePolicyNames...)
}
// Set email from account if available
if identity.Account != nil {
details.Email = identity.Account.EmailAddress
+2 -1
View File
@@ -565,7 +565,8 @@ func loggingMiddleware(next http.Handler) http.Handler {
if status == 0 {
status = http.StatusOK
}
if status >= 200 && status < 300 {
// Only log errors; 2xx/3xx (including 304 Not Modified cache hits) are normal.
if status < 400 {
return
}
+5
View File
@@ -0,0 +1,5 @@
package command
// Register the tiered-storage backends here, at the binary's composition root,
// so library consumers of weed/storage don't pull the backend SDKs.
import _ "github.com/seaweedfs/seaweedfs/weed/storage/backend/all"
-1
View File
@@ -165,7 +165,6 @@ func runFuse(cmd *Command, args []string) bool {
panic(fmt.Errorf("dirIdleEvictSec: %s", err))
}
case "concurrentWriters":
i++
if parsed, err := strconv.ParseInt(parameter.value, 0, 32); err == nil {
intValue := int(parsed)
mountOptions.concurrentWriters = &intValue
+38
View File
@@ -0,0 +1,38 @@
//go:build darwin || freebsd || linux
package command
import (
"fmt"
"strings"
"testing"
)
func TestRunFuseDoesNotSkipOptionAfterConcurrentWriters(t *testing.T) {
oldUmask := mountOptions.umaskString
oldWriters := mountOptions.concurrentWriters
oldReaders := mountOptions.concurrentReaders
oldFuseCommandPid := mountOptions.fuseCommandPid
oldDir := mountOptions.dir
defer func() {
mountOptions.umaskString = oldUmask
mountOptions.concurrentWriters = oldWriters
mountOptions.concurrentReaders = oldReaders
mountOptions.fuseCommandPid = oldFuseCommandPid
mountOptions.dir = oldDir
recovered := recover()
if recovered == nil {
t.Fatal("expected invalid concurrentReaders option to be parsed")
}
if !strings.Contains(fmt.Sprint(recovered), "concurrentReaders") {
t.Fatalf("expected concurrentReaders parse error, got %v", recovered)
}
}()
runFuse(cmdMount, []string{
"/mnt",
"-o",
"child=1,concurrentWriters=2,concurrentReaders=bad,umask=bad",
})
}
+25 -1
View File
@@ -548,6 +548,7 @@ func initMiniAdminFlags() {
miniAdminOptions.adminPassword = cmdMini.Flag.String("admin.password", "", "admin interface password (if empty, auth is disabled)")
miniAdminOptions.readOnlyUser = cmdMini.Flag.String("admin.readOnlyUser", "", "read-only user username (optional, for view-only access)")
miniAdminOptions.readOnlyPassword = cmdMini.Flag.String("admin.readOnlyPassword", "", "read-only user password (optional, for view-only access; requires admin.password to be set)")
miniAdminOptions.urlPrefix = cmdMini.Flag.String("admin.urlPrefix", "", "URL path prefix when running the admin UI behind a reverse proxy under a subdirectory (e.g. /seaweedfs)")
}
func init() {
@@ -1164,6 +1165,7 @@ func runMini(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
util.LoadConfiguration("master", false)
util.LoadConfiguration("volume", false)
util.LoadConfiguration("admin", false)
miniOptions.v.applyDiskIOProbeConfig()
ensureMiniVolumeGrowthDefaults()
@@ -1487,6 +1489,18 @@ func startS3Service() {
miniS3Options.startS3Server()
}
// applyMiniAdminCredentialFallback fills the admin credential flags from
// security.toml [admin] / WEED_ADMIN_* env vars when they were not set on the
// command line, mirroring the standalone `weed admin` command. CLI flags take
// precedence. Note the read-only viper keys (admin.readonly.*) differ from the
// mini flag names (admin.readOnly*).
func applyMiniAdminCredentialFallback(options *AdminOptions) {
applyViperFallback(cmdMini, options.adminUser, "admin.user", "admin.user")
applyViperFallback(cmdMini, options.adminPassword, "admin.password", "admin.password")
applyViperFallback(cmdMini, options.readOnlyUser, "admin.readOnlyUser", "admin.readonly.user")
applyViperFallback(cmdMini, options.readOnlyPassword, "admin.readOnlyPassword", "admin.readonly.password")
}
// startMiniAdminWithWorker starts the admin server with one worker
func startMiniAdminWithWorker(allServicesReady chan struct{}) {
defer close(allServicesReady) // Ensure channel is always closed on all paths
@@ -1503,6 +1517,10 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
// Set admin options
*miniAdminOptions.master = masterAddr
// Resolve admin credentials from security.toml [admin] / WEED_ADMIN_* env
// vars, matching the standalone `weed admin` command.
applyMiniAdminCredentialFallback(&miniAdminOptions)
// Security validation: prevent empty username when password is set
if *miniAdminOptions.adminPassword != "" && *miniAdminOptions.adminUser == "" {
glog.Fatalf("Error: -admin.user cannot be empty when -admin.password is set")
@@ -1532,6 +1550,12 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
*miniAdminOptions.dataDir = filepath.Join(*miniDataFolders, "admin")
}
// Normalize URL prefix the same way `weed admin` does.
urlPrefix := strings.TrimRight(*miniAdminOptions.urlPrefix, "/")
if urlPrefix != "" && !strings.HasPrefix(urlPrefix, "/") {
urlPrefix = "/" + urlPrefix
}
// Start admin server in background. trackMiniClient lets the Ctrl+C
// handler wait for startAdminServer's graceful shutdown before filer/
// volume/master tear down.
@@ -1546,7 +1570,7 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
if miniS3Options.portIceberg != nil {
icebergPort = *miniS3Options.portIceberg
}
if err := startAdminServer(ctx, miniAdminOptions, *miniEnableAdminUI, icebergPort, ""); err != nil {
if err := startAdminServer(ctx, miniAdminOptions, *miniEnableAdminUI, icebergPort, urlPrefix); err != nil {
glog.Errorf("Admin server error: %v", err)
}
}()
+41
View File
@@ -0,0 +1,41 @@
package command
import "testing"
// weed mini must resolve admin credentials from security.toml [admin] /
// WEED_ADMIN_* env vars the same way the standalone `weed admin` command does.
// This exercises the production fallback so the flag-name -> viper-key mapping
// stays correct, in particular the read-only keys where the mini flag
// (admin.readOnlyUser) and viper key (admin.readonly.user) differ.
func TestApplyMiniAdminCredentialFallbackFromEnv(t *testing.T) {
adminUser, adminPassword, readOnlyUser, readOnlyPassword := "admin", "", "", ""
options := &AdminOptions{
adminUser: &adminUser,
adminPassword: &adminPassword,
readOnlyUser: &readOnlyUser,
readOnlyPassword: &readOnlyPassword,
}
t.Setenv("WEED_ADMIN_USER", "env-admin")
t.Setenv("WEED_ADMIN_PASSWORD", "env-secret")
t.Setenv("WEED_ADMIN_READONLY_USER", "env-ro")
t.Setenv("WEED_ADMIN_READONLY_PASSWORD", "env-ro-secret")
applyMiniAdminCredentialFallback(options)
checks := []struct {
name string
got string
want string
}{
{"adminUser", *options.adminUser, "env-admin"},
{"adminPassword", *options.adminPassword, "env-secret"},
{"readOnlyUser", *options.readOnlyUser, "env-ro"},
{"readOnlyPassword", *options.readOnlyPassword, "env-ro-secret"},
}
for _, c := range checks {
if c.got != c.want {
t.Errorf("%s = %q, want %q", c.name, c.got, c.want)
}
}
}
+10 -1
View File
@@ -4,7 +4,16 @@
# /etc/seaweedfs/security.toml
# this file is read by master, volume server, filer, and worker
# comma separated origins allowed to make requests to the filer and s3 gateway.
# Any value below can also be supplied as an environment variable instead of
# living in this file: prefix the key with WEED_, upper-case it, and replace
# "." with "_". This is the recommended way to inject the secrets in here from
# a Kubernetes Secret (env valueFrom.secretKeyRef) rather than a ConfigMap.
# The JWT signing keys map to:
# WEED_JWT_SIGNING_KEY, WEED_JWT_SIGNING_READ_KEY (master <-> volume)
# WEED_JWT_FILER_SIGNING_KEY, WEED_JWT_FILER_SIGNING_READ_KEY (s3/clients <-> filer)
# A set env var wins over the file, so the file can stay empty (or absent).
# comma separated origins allowed to make requests to the filer and s3 gateway.
# enter in this format: https://domain.com, or http://localhost:port
[cors.allowed_origins]
values = "*"
-22
View File
@@ -23,7 +23,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/server/constants"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
@@ -248,9 +247,6 @@ var (
volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
ecBitrotChecksum = cmdVolume.Flag.Bool("ec.bitrotChecksum", true, "write a bitrot checksum sidecar (.ecsum) when generating EC shards, enabling silent-corruption detection on scrub/rebuild")
ecBitrotBlockSizeMB = cmdVolume.Flag.Int("ec.bitrotBlockSizeMB", 16, "EC bitrot checksum block granularity in MiB; must be a power of two and at least 1")
)
func runVolume(cmd *Command, args []string) bool {
@@ -285,24 +281,6 @@ func runVolume(cmd *Command, args []string) bool {
*v.mastersString = *v.mserverString
}
// Apply EC bitrot checksum settings.
erasure_coding.BitrotProtectionEnabled = *ecBitrotChecksum
// Bound-check before the multiply so a huge value cannot overflow int64 past
// the power-of-two check. Cap = shared MaxBitrotBlockSize, kept in sync with
// ValidateBitrotManifest.
const maxBitrotBlockSizeMB = erasure_coding.MaxBitrotBlockSize / (1024 * 1024)
if mb := *ecBitrotBlockSizeMB; mb >= 1 && mb <= maxBitrotBlockSizeMB {
if blockSize := int64(mb) * 1024 * 1024; blockSize&(blockSize-1) == 0 {
erasure_coding.BitrotBlockSize = blockSize
} else if mb != 16 {
glog.Warningf("ignoring invalid -ec.bitrotBlockSizeMB=%d (must be a power of two); using %d MiB",
mb, erasure_coding.BitrotBlockSize/(1024*1024))
}
} else if *ecBitrotBlockSizeMB != 16 {
glog.Warningf("ignoring out-of-range -ec.bitrotBlockSizeMB=%d (must be a power of two in [1, %d] MiB); using %d MiB",
*ecBitrotBlockSizeMB, maxBitrotBlockSizeMB, erasure_coding.BitrotBlockSize/(1024*1024))
}
minFreeSpaces := util.MustParseMinFreeSpace(*minFreeSpace, *minFreeSpacePercent)
v.masters = pb.ServerAddresses(*v.mastersString).ToAddresses()
v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, minFreeSpaces)
+16
View File
@@ -12,6 +12,11 @@ import (
// filemeta.name collation is locale-aware, so S3 ListObjectsV2 stays
// lexicographic. The fallback costs a sort, so warn the operator to fix it.
func ConfigureListOrdering(db *sql.DB, gen *SqlGenPostgres) {
if isCockroachDB(db) {
// CockroachDB string comparison is already byte-ordered, so the
// fallback is redundant; older versions also reject COLLATE "C".
return
}
collation, isBinary, err := nameColumnCollation(db)
if err != nil {
glog.V(1).Infof("postgres: skip filemeta.name collation check: %v", err)
@@ -24,6 +29,17 @@ func ConfigureListOrdering(db *sql.DB, gen *SqlGenPostgres) {
glog.Warningf(`postgres: filemeta.name collation %q is not byte-ordered, so S3 list order is not byte-lexicographic and clients that merge sorted listings may report spurious diffs. Falling back to a slower COLLATE "C" sort; declare the name column COLLATE "C" (or use a C/C.UTF-8 database collation) for correct, indexed ordering.`, collation)
}
// isCockroachDB reports whether db is a CockroachDB backend, whose version()
// string carries "CockroachDB". On any error we assume real Postgres.
func isCockroachDB(db *sql.DB) bool {
var version string
if err := db.QueryRow("SELECT version()").Scan(&version); err != nil {
glog.V(1).Infof("postgres: skip CockroachDB detection: %v", err)
return false
}
return strings.Contains(version, "CockroachDB")
}
func nameColumnCollation(db *sql.DB) (collation string, isBinary bool, err error) {
// information_schema reports NULL for a column on the database default, so
// fall back to datcollate for the effective ordering.
@@ -0,0 +1,49 @@
package postgres
import (
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
func TestConfigureListOrderingSkipsCockroachDB(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("sqlmock: %v", err)
}
defer db.Close()
mock.ExpectQuery("SELECT version\\(\\)").WillReturnRows(
sqlmock.NewRows([]string{"version"}).AddRow("CockroachDB CCL v22.1.22 (x86_64-pc-linux-gnu)"))
gen := &SqlGenPostgres{}
ConfigureListOrdering(db, gen)
if gen.ForceBinaryCollation {
t.Fatal("CockroachDB default ordering is byte-ordered; COLLATE \"C\" must not be forced")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
}
func TestConfigureListOrderingForcesBinaryOnLocalePostgres(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("sqlmock: %v", err)
}
defer db.Close()
mock.ExpectQuery("SELECT version\\(\\)").WillReturnRows(
sqlmock.NewRows([]string{"version"}).AddRow("PostgreSQL 16.2 on x86_64-pc-linux-gnu"))
mock.ExpectQuery("datcollate").WillReturnRows(
sqlmock.NewRows([]string{"collation_name", "datcollate"}).AddRow(nil, "en_US.UTF-8"))
gen := &SqlGenPostgres{}
ConfigureListOrdering(db, gen)
if !gen.ForceBinaryCollation {
t.Fatal("locale-aware Postgres collation must force byte ordering")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
}
+30 -5
View File
@@ -6,26 +6,51 @@ import (
type ReaderPattern struct {
isSequentialCounter int64
lastReadStopOffset int64
readFrontier int64 // highest (offset+size) observed across reads
}
const ModeChangeLimit = 3
// SeqTolerance: a read whose start is within this many bytes of the current read
// frontier still counts as sequential. Using a tolerance window rather than
// strict contiguity absorbs reordered/concurrent readahead (multiple ReadAt can
// be in flight at once) while still rejecting far random jumps.
const SeqTolerance = 8 << 20 // 8 MiB
// For streaming read: only cache the first chunk
// For random read: only fetch the requested range, instead of the whole chunk
func NewReaderPattern() *ReaderPattern {
return &ReaderPattern{
isSequentialCounter: 0,
lastReadStopOffset: 0,
readFrontier: 0,
}
}
func (rp *ReaderPattern) MonitorReadAt(offset int64, size int) {
lastOffset := atomic.SwapInt64(&rp.lastReadStopOffset, offset+int64(size))
counter := atomic.LoadInt64(&rp.isSequentialCounter)
// Advance the frontier to max(frontier, offset+size) and capture, in the same
// CAS loop, the pre-image this read is judged against. Reading the frontier
// inside the loop (rather than once up front) keeps `diff` below comparing
// against the freshest value even if a concurrent readahead advances the
// frontier while we loop. Lock-free, consistent with the rest of this type.
end := offset + int64(size)
var frontier int64
for {
frontier = atomic.LoadInt64(&rp.readFrontier)
if end <= frontier || atomic.CompareAndSwapInt64(&rp.readFrontier, frontier, end) {
break
}
}
if lastOffset == offset {
// near = this read starts within SeqTolerance of where reads had reached.
// Hysteresis (the ±ModeChangeLimit counter) keeps a single outlier read from
// flipping the mode.
diff := offset - frontier
if diff < 0 {
diff = -diff
}
counter := atomic.LoadInt64(&rp.isSequentialCounter)
if diff <= SeqTolerance {
if counter < ModeChangeLimit {
atomic.AddInt64(&rp.isSequentialCounter, 1)
}
+104
View File
@@ -0,0 +1,104 @@
package filer
import (
"sync/atomic"
"testing"
)
const mb = 1 << 20
func TestReaderPatternSequentialAndHysteresis(t *testing.T) {
rp := NewReaderPattern()
rp.MonitorReadAt(0, mb) // near(0 vs frontier 0) -> +1
rp.MonitorReadAt(mb, mb) // +2
rp.MonitorReadAt(2*mb, mb) // +3 (capped)
if rp.IsRandomMode() {
t.Fatal("a stream from offset 0 must not be random")
}
// a single far outlier does not flip to random (hysteresis): +3 -> +2
rp.MonitorReadAt(900*mb, mb)
if rp.IsRandomMode() {
t.Fatal("a single outlier read must not flip to random mode")
}
}
func TestReaderPatternFarFirstReadIsRandom(t *testing.T) {
rp := NewReaderPattern()
rp.MonitorReadAt(500*mb, mb) // far from frontier 0 -> -1
if !rp.IsRandomMode() {
t.Fatal("a far first read should be random")
}
}
func TestReaderPatternToleranceAbsorbsReorder(t *testing.T) {
rp := NewReaderPattern()
rp.MonitorReadAt(0, mb) // +1, frontier 1MB
rp.MonitorReadAt(6*mb, mb) // |6-1|=5MB <= 8MB tolerance -> near, +2, frontier 7MB
rp.MonitorReadAt(3*mb, mb) // |3-7|=4MB <= 8MB -> near, +3
if rp.IsRandomMode() {
t.Fatal("reordered reads within tolerance must stay sequential")
}
}
func TestReaderPatternRandomRecoveryNeedsHysteresis(t *testing.T) {
rp := NewReaderPattern()
rp.MonitorReadAt(100*mb, mb) // far -> -1
rp.MonitorReadAt(300*mb, mb) // far -> -2
rp.MonitorReadAt(500*mb, mb) // far -> -3 (capped), frontier 501MB
// a single near read must not immediately flip back to sequential: -3 -> -2
rp.MonitorReadAt(501*mb, mb)
if !rp.IsRandomMode() {
t.Fatal("one near read must not flip back from deep random mode")
}
}
// The max-frontier (vs the old atomic.Swap of the last read's stop offset) is the
// load-bearing difference of this detector: the frontier must never move backward,
// or a backward read would lower the baseline and make later far reads look near.
func TestReaderPatternFrontierNeverRegresses(t *testing.T) {
rp := NewReaderPattern()
rp.MonitorReadAt(500*mb, mb) // far first read -> -1, frontier 501MB
rp.MonitorReadAt(0, mb) // a backward read must not pull the frontier back
if got := atomic.LoadInt64(&rp.readFrontier); got != 501*mb {
t.Fatalf("frontier regressed to %d; the max-frontier must never move backward", got)
}
// Behavioral consequence: reads far below the preserved frontier stay random.
// Had the frontier regressed to ~1MB, this would wrongly read as sequential.
if !rp.IsRandomMode() {
t.Fatal("reads far below the preserved frontier must remain random")
}
}
// SeqTolerance is the central new tuning knob; pin both sides of the inclusive
// boundary so an off-by-one or a '<' vs '<=' change can't slip through silently.
func TestReaderPatternToleranceBoundary(t *testing.T) {
atBoundary := NewReaderPattern()
atBoundary.MonitorReadAt(SeqTolerance, 0) // diff == SeqTolerance -> near (inclusive), +1
if atBoundary.IsRandomMode() {
t.Fatal("a read exactly at frontier+SeqTolerance must count as sequential")
}
pastBoundary := NewReaderPattern()
pastBoundary.MonitorReadAt(SeqTolerance+1, 0) // diff == SeqTolerance+1 -> far, -1
if !pastBoundary.IsRandomMode() {
t.Fatal("a read one byte past frontier+SeqTolerance must count as random")
}
}
// The escape from random mode: sustained near reads must climb the counter back
// out of the negative floor and re-enter sequential (whole-chunk cache) mode.
func TestReaderPatternRecoversFromRandom(t *testing.T) {
rp := NewReaderPattern()
rp.MonitorReadAt(100*mb, mb) // far -> -1
rp.MonitorReadAt(300*mb, mb) // far -> -2
rp.MonitorReadAt(500*mb, mb) // far -> -3 (capped), frontier 501MB
if !rp.IsRandomMode() {
t.Fatal("three far reads must be random")
}
// contiguous near reads: -3 -> -2 -> -1 -> 0 -> +1, back out of random mode
for i := int64(0); i < 4; i++ {
rp.MonitorReadAt(501*mb+i*mb, mb)
}
if rp.IsRandomMode() {
t.Fatal("sustained near reads must recover sequential mode")
}
}
+2 -3
View File
@@ -195,13 +195,12 @@ func (fh *FileHandle) downloadRemoteEntry(entry *LockedEntry) error {
fh.SetEntry(resp.Entry)
// Async: a sync apply deadlocks against the apply loop's invalidate, which needs this read's file-handle lock.
event := resp.GetMetadataEvent()
if event == nil {
event = metadataUpdateEvent(request.Directory, resp.Entry)
}
if applyErr := fh.wfs.applyLocalMetadataEvent(context.Background(), event); applyErr != nil {
glog.Warningf("CacheRemoteObject %s: best-effort metadata apply failed: %v", fileFullPath, applyErr)
}
fh.wfs.applyLocalMetadataEventAsync(event)
return nil
})
+149
View File
@@ -0,0 +1,149 @@
package mount
import (
"context"
"net"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// cacheRemoteTestServer broadcasts the matching invalidate event before
// returning the cached entry, so the apply loop is busy invalidating the same
// file handle the read still holds when downloadRemoteEntry applies its event.
type cacheRemoteTestServer struct {
filer_pb.UnimplementedSeaweedFilerServer
wfs *WFS
dir, name string
content []byte
invalidateStarted chan struct{}
}
func (s *cacheRemoteTestServer) CacheRemoteObjectToLocalCluster(ctx context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
cached := &filer_pb.Entry{
Name: s.name,
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(s.content))},
Content: s.content,
}
go s.wfs.metaCache.ApplyMetadataResponse(context.Background(), metadataUpdateEvent(s.dir, cached), meta_cache.SubscriberMetadataResponseApplyOptions)
<-s.invalidateStarted
return &filer_pb.CacheRemoteObjectToLocalClusterResponse{
Entry: cached,
MetadataEvent: metadataUpdateEvent(s.dir, cached),
}, nil
}
// TestReadUncachedRemoteEntryDoesNotDeadlock guards the read of an uncached
// remote file against the apply-loop invalidate that needs its file-handle lock.
func TestReadUncachedRemoteEntryDoesNotDeadlock(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { _ = listener.Close() })
server := pb.NewGrpcServer()
testServer := &cacheRemoteTestServer{
dir: "/dir",
name: "file",
content: []byte("hello remote world"),
invalidateStarted: make(chan struct{}, 1),
}
filer_pb.RegisterSeaweedFilerServer(server, testServer)
go server.Serve(listener)
t.Cleanup(server.Stop)
uidGidMapper, err := meta_cache.NewUidGidMapper("", "")
if err != nil {
t.Fatalf("create uid/gid mapper: %v", err)
}
root := util.FullPath("/")
wfs := &WFS{
signature: 1,
inodeToPath: NewInodeToPath(root, 0),
fhMap: NewFileHandleToInode(),
fhLockTable: util.NewLockTable[FileHandleId](),
hardLinkLockTable: util.NewLockTable[string](),
option: &Option{
ChunkSizeLimit: 1024,
ConcurrentReaders: 1,
VolumeServerAccess: "filerProxy",
FilerAddresses: []pb.ServerAddress{
pb.NewServerAddressWithGrpcPort("127.0.0.1:1", listener.Addr().(*net.TCPAddr).Port),
},
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
testServer.wfs = wfs
wfs.metaCache = meta_cache.NewMetaCache(
filepath.Join(t.TempDir(), "meta"),
uidGidMapper,
root,
false,
func(path util.FullPath) { wfs.inodeToPath.MarkChildrenCached(path) },
func(path util.FullPath) bool { return wfs.inodeToPath.IsChildrenCached(path) },
// Mirror weedfs.go's invalidateFunc: take the file handle exclusive lock.
func(path util.FullPath, _ *filer_pb.Entry) {
inode, ok := wfs.inodeToPath.GetInode(path)
if !ok {
return
}
fh, ok := wfs.fhMap.FindFileHandle(inode)
if !ok {
return
}
select {
case testServer.invalidateStarted <- struct{}{}:
default:
}
lock := wfs.fhLockTable.AcquireLock("invalidateFunc", fh.fh, util.ExclusiveLock)
wfs.fhLockTable.ReleaseLock(fh.fh, lock)
},
nil,
)
wfs.inodeToPath.MarkChildrenCached(root)
wfs.inodeToPath.Lookup(util.FullPath("/dir"), time.Now().Unix(), true, false, 0, false)
wfs.inodeToPath.MarkChildrenCached(util.FullPath("/dir"))
t.Cleanup(func() { wfs.metaCache.Shutdown() })
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: "file",
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(testServer.content))},
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: int64(len(testServer.content))},
})
buff := make([]byte, len(testServer.content))
done := make(chan fuse.Status, 1)
go func() {
_, status := wfs.Read(make(chan struct{}), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: inode},
Fh: uint64(fh.fh),
Offset: 0,
Size: uint32(len(buff)),
}, buff)
done <- status
}()
select {
case status := <-done:
if status != fuse.OK {
t.Fatalf("Read status = %v, want OK", status)
}
if string(buff) != string(testServer.content) {
t.Fatalf("Read content = %q, want %q", buff, testServer.content)
}
case <-time.After(15 * time.Second):
t.Fatal("Read of an uncached remote entry deadlocked")
}
}
+82 -7
View File
@@ -3,6 +3,7 @@ package meta_cache
import (
"context"
"errors"
"math"
"os"
"sync"
"time"
@@ -32,7 +33,8 @@ type MetaCache struct {
isCachedFn func(fullpath util.FullPath) bool
invalidateFunc func(fullpath util.FullPath, entry *filer_pb.Entry)
onDirectoryUpdate func(dir util.FullPath)
visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path
pinnedChildFn func(*filer.Entry) bool // a child a rebuild must not drop (local-only, not yet on the filer); nil disables
visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path
applyCh chan metadataApplyRequest
applyDone chan struct{}
applyStateMu sync.Mutex
@@ -40,6 +42,12 @@ type MetaCache struct {
buildingDirs map[util.FullPath]*directoryBuildState
dedupRing dedupRingBuffer
includeSystemEntries bool
// Entry invalidations run on a worker, not inline on the apply loop:
// invalidateFunc takes the fh lock, which a flush can hold while waiting on
// the apply loop (flushMetadataToFiler -> applyLocalMetadataEvent), so inline
// invalidation deadlocks the mount.
invalidateWorker *util.AsyncBatchWorker[metadataInvalidation]
}
var errMetaCacheClosed = errors.New("metadata cache is shut down")
@@ -107,6 +115,11 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
buildingDirs: make(map[util.FullPath]*directoryBuildState),
dedupRing: newDedupRingBuffer(),
}
mc.invalidateWorker = util.NewAsyncBatchWorker(func(batch []metadataInvalidation) {
for _, invalidation := range batch {
mc.invalidateFunc(invalidation.path, invalidation.entry)
}
})
go mc.runApplyLoop()
return mc
}
@@ -226,6 +239,25 @@ func (mc *MetaCache) ApplyMetadataResponseOwned(ctx context.Context, resp *filer
return mc.applyMetadataResponseEnqueue(ctx, resp, options)
}
// ApplyMetadataResponseOwnedAsync enqueues resp without waiting, for callers holding a
// lock the apply loop's invalidateFunc also needs. Best-effort: the subscription re-delivers.
func (mc *MetaCache) ApplyMetadataResponseOwnedAsync(resp *filer_pb.SubscribeMetadataResponse, options MetadataResponseApplyOptions) {
if resp == nil || resp.EventNotification == nil {
return
}
req := metadataApplyRequest{
ctx: context.Background(),
kind: metadataApplyEvent,
resp: resp,
options: options,
done: make(chan error, 1),
}
select {
case mc.applyCh <- req:
default:
}
}
func (mc *MetaCache) applyMetadataResponseEnqueue(ctx context.Context, resp *filer_pb.SubscribeMetadataResponse, options MetadataResponseApplyOptions) error {
if ctx == nil {
ctx = context.Background()
@@ -338,6 +370,42 @@ func (mc *MetaCache) DeleteFolderChildren(ctx context.Context, fp util.FullPath)
return mc.localStore.DeleteFolderChildren(ctx, fp)
}
// SetPinnedChildFn installs a predicate reporting whether a child holds
// local-only state a rebuild must not discard. See deleteFolderChildrenForRebuild.
func (mc *MetaCache) SetPinnedChildFn(fn func(*filer.Entry) bool) {
mc.pinnedChildFn = fn
}
// deleteFolderChildrenForRebuild clears a directory's cached children ahead of a
// rebuild, but keeps any child flagged pinned by pinnedChildFn — a local-only
// create not yet flushed to the filer. A rebuild refills from a filer listing
// that does not include such a create; a blind wipe would drop it and then
// markCachedFn publishes the directory authoritatively cached without a file the
// client created, so it vanishes from the mount.
func (mc *MetaCache) deleteFolderChildrenForRebuild(ctx context.Context, dirPath util.FullPath) error {
mc.Lock()
defer mc.Unlock()
if mc.pinnedChildFn == nil {
return mc.localStore.DeleteFolderChildren(ctx, dirPath)
}
var pinned []*filer.Entry
if _, err := mc.localStore.ListDirectoryEntries(ctx, dirPath, "", true, math.MaxInt64, func(entry *filer.Entry) (bool, error) {
if mc.pinnedChildFn(entry) {
pinned = append(pinned, entry)
}
return true, nil
}); err != nil {
return err
}
if err := mc.localStore.DeleteFolderChildren(ctx, dirPath); err != nil {
return err
}
if len(pinned) > 0 {
return mc.doBatchInsertEntries(ctx, pinned)
}
return nil
}
func (mc *MetaCache) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) error {
mc.RLock()
defer mc.RUnlock()
@@ -380,6 +448,10 @@ func (mc *MetaCache) Shutdown() {
<-mc.applyDone
// The apply loop is the only dispatcher of entry invalidations; with it
// stopped, drain and stop the invalidate worker before closing the store.
mc.invalidateWorker.Shutdown()
mc.Lock()
defer mc.Unlock()
mc.localStore.Shutdown()
@@ -549,9 +621,7 @@ func (mc *MetaCache) applyMetadataSideEffects(resp *filer_pb.SubscribeMetadataRe
for _, dirPath := range sideEffects.dirsToNotify {
mc.noteDirectoryUpdate(dirPath)
}
for _, invalidation := range sideEffects.invalidations {
mc.invalidateFunc(invalidation.path, invalidation.entry)
}
mc.invalidateWorker.Enqueue(sideEffects.invalidations...)
}
// applyMetadataSideEffectsSkippingBuildingDirs is like applyMetadataSideEffects
@@ -570,9 +640,14 @@ func (mc *MetaCache) applyMetadataSideEffectsSkippingBuildingDirs(resp *filer_pb
mc.noteDirectoryUpdate(dirPath)
}
}
for _, invalidation := range sideEffects.invalidations {
mc.invalidateFunc(invalidation.path, invalidation.entry)
}
mc.invalidateWorker.Enqueue(sideEffects.invalidations...)
}
// WaitForEntryInvalidations blocks until every invalidation enqueued so far
// has been processed by the invalidate worker. Intended for tests and
// shutdown paths that need the previously-synchronous behavior.
func (mc *MetaCache) WaitForEntryInvalidations() {
mc.invalidateWorker.Drain()
}
func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *filer_pb.SubscribeMetadataResponse, _ MetadataResponseApplyOptions, allowUncachedInsert bool) (metadataResponseSideEffects, error) {
@@ -100,6 +100,7 @@ func TestApplyMetadataResponseAppliesEventsInOrder(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dir")); got != 3 {
t.Fatalf("directory notifications for /dir = %d, want 3", got)
}
mc.WaitForEntryInvalidations()
if got := countPath(invalidations.paths(), util.FullPath("/dir/file.txt")); got != 3 {
t.Fatalf("invalidations for /dir/file.txt = %d, want 3 (create + update + delete)", got)
}
@@ -170,6 +171,7 @@ func TestApplyMetadataResponseRenamesAcrossCachedDirectories(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dst")); got != 1 {
t.Fatalf("directory notifications for /dst = %d, want 1", got)
}
mc.WaitForEntryInvalidations()
if got := countPath(invalidations.paths(), util.FullPath("/src/file.tmp")); got != 1 {
t.Fatalf("invalidations for /src/file.tmp = %d, want 1", got)
}
@@ -230,6 +232,7 @@ func TestApplyMetadataResponseLocalOptionsSkipInvalidations(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dir")); got != 1 {
t.Fatalf("directory notifications for /dir = %d, want 1", got)
}
mc.WaitForEntryInvalidations()
if got := len(invalidations.paths()); got != 0 {
t.Fatalf("invalidations = %d, want 0", got)
}
@@ -292,6 +295,7 @@ func TestApplyMetadataResponseDeduplicatesRepeatedFilerEvent(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dir")); got != 1 {
t.Fatalf("directory notifications for /dir = %d, want 1", got)
}
mc.WaitForEntryInvalidations()
if got := countPath(invalidations.paths(), util.FullPath("/dir/file.txt")); got != 1 {
t.Fatalf("invalidations for /dir/file.txt = %d, want 1", got)
}
@@ -457,3 +457,103 @@ func TestBufferedRenameUpdatesOtherDirectoryBeforeBuildCompletes(t *testing.T) {
t.Fatalf("replayed new path size = %d, want 12", newEntry.FileSize)
}
}
// TestEnsureVisitedPreservesLocalOnlyEntry reproduces the residual coherence
// gap behind the FUSE ConcurrentReadWrite ENOENT flake.
//
// A FUSE create on the writeback/deferFilerCreate path inserts the entry into
// the local store directly (weedfs_file_mkrm.go createFile), off the metaCache
// apply loop, before the filer holds it. A concurrent rebuild of the parent —
// triggered when the directory falls out of cache (idle evict, hot-dir
// read-through) — wipes the store and refills it from a filer listing that does
// not yet include the un-flushed local create, then publishes the directory
// authoritatively cached (markCachedFn). The local entry vanishes although the
// client created it: lookupEntry then returns an authoritative ENOENT for it.
func TestEnsureVisitedPreservesLocalOnlyEntry(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
// The mount pins the un-flushed create (open dirty handle / pending flush),
// keyed off the inode the entry carries so a kernel Forget that dropped the
// path→inode mapping cannot unpin an in-flight create.
mc.SetPinnedChildFn(func(e *filer.Entry) bool { return e.Attr.Inode == 42 })
// A deferred local create lands before the rebuild; /dir is not yet cached.
// It carries its allocated inode, as createFile's placeholder does.
if err := mc.InsertEntry(context.Background(), &filer.Entry{
FullPath: "/dir/pending.txt",
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1, Inode: 42},
}); err != nil {
t.Fatalf("insert pending entry: %v", err)
}
// A concurrent rebuild lists the filer, whose snapshot pre-dates the
// un-flushed create, so it returns only the already-persisted sibling.
accessor := &buildFilerAccessor{client: &buildListClient{
responses: []*filer_pb.ListEntriesResponse{{
Entry: &filer_pb.Entry{
Name: "base.txt",
Attributes: &filer_pb.FuseAttributes{
Crtime: 1,
Mtime: 1,
FileMode: 0100644,
FileSize: 3,
},
},
SnapshotTsNs: 100,
}},
}}
if err := EnsureVisited(mc, accessor, util.FullPath("/dir")); err != nil {
t.Fatalf("ensure visited: %v", err)
}
if !mc.IsDirectoryCached(util.FullPath("/dir")) {
t.Fatal("/dir should be cached after build completes")
}
// base.txt from the listing is present.
if _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/base.txt")); err != nil {
t.Fatalf("listed entry missing after build: %v", err)
}
// The un-flushed local create must survive the rebuild. With /dir now
// authoritatively cached, losing it is the file-vanishes flake.
if _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/pending.txt")); err != nil {
t.Fatalf("local-only entry lost across concurrent rebuild: %v", err)
}
}
// TestEnsureVisitedDropsUnpinnedStaleEntry guards the preservation's selectivity:
// a cached child the filer listing no longer returns and that is NOT pinned must
// still be wiped, so the rebuild can't resurrect a deleted/renamed entry.
func TestEnsureVisitedDropsUnpinnedStaleEntry(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
mc.SetPinnedChildFn(func(*filer.Entry) bool { return false })
// A stale child sits in the cache; the filer no longer has it.
insertCacheEntry(t, mc, "/dir/stale.txt")
accessor := &buildFilerAccessor{client: &buildListClient{
responses: []*filer_pb.ListEntriesResponse{{
Entry: &filer_pb.Entry{
Name: "base.txt",
Attributes: &filer_pb.FuseAttributes{
Crtime: 1,
Mtime: 1,
FileMode: 0100644,
FileSize: 3,
},
},
SnapshotTsNs: 100,
}},
}}
if err := EnsureVisited(mc, accessor, util.FullPath("/dir")); err != nil {
t.Fatalf("ensure visited: %v", err)
}
if entry, err := mc.FindEntry(context.Background(), util.FullPath("/dir/stale.txt")); err != filer_pb.ErrNotFound || entry != nil {
t.Fatalf("unpinned stale entry survived rebuild = %+v, %v; want nil, %v", entry, err, filer_pb.ErrNotFound)
}
}
@@ -0,0 +1,161 @@
package meta_cache
import (
"context"
"path/filepath"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// TestApplyLoopInvalidateDoesNotDeadlockWithLockHoldingEnqueuer reproduces the
// mount hang seen in production (all readdirs stuck, FUSE waiting>0):
//
// - A FUSE flush handler (flushMetadataToFiler) holds the file handle's
// exclusive lock in wfs.fhLockTable and then enqueues a local metadata
// event, waiting for the apply loop to process it.
// - Concurrently the apply loop processes a subscriber event whose
// invalidateFunc (weedfs.go) acquires the same file handle lock.
//
// The single-goroutine apply loop blocks on the fh lock while the fh lock
// holder blocks on the apply loop: a permanent ABBA deadlock. Every later
// EnsureVisited/BeginDirectoryBuild then backs up behind the dead loop, FUSE
// handler goroutines exhaust, and the kernel queue (waiting) grows.
//
// The contract under test: the apply loop must never block on locks that can
// be held by goroutines waiting on the apply loop.
func TestApplyLoopInvalidateDoesNotDeadlockWithLockHoldingEnqueuer(t *testing.T) {
mapper, err := NewUidGidMapper("", "")
if err != nil {
t.Fatalf("uid/gid mapper: %v", err)
}
// Stand-in for wfs.fhLockTable, keyed like FileHandleId.
fhLockTable := util.NewLockTable[uint64]()
const fhKey uint64 = 42
invalidateEntered := make(chan struct{})
var enteredOnce sync.Once
var cachedMu sync.Mutex
cached := map[util.FullPath]bool{"/": true, "/dir": true}
mc := NewMetaCache(
filepath.Join(t.TempDir(), "meta"),
mapper,
util.FullPath("/"),
false,
func(path util.FullPath) {
cachedMu.Lock()
defer cachedMu.Unlock()
cached[path] = true
},
func(path util.FullPath) bool {
cachedMu.Lock()
defer cachedMu.Unlock()
return cached[path]
},
func(path util.FullPath, entry *filer_pb.Entry) {
// Mirrors the wfs invalidateFunc: it takes the open file
// handle's exclusive lock before refreshing the handle entry.
enteredOnce.Do(func() { close(invalidateEntered) })
lock := fhLockTable.AcquireLock("invalidateFunc", fhKey, util.ExclusiveLock)
fhLockTable.ReleaseLock(fhKey, lock)
},
func(dir util.FullPath) {},
)
defer func() {
// Only safe to shut down once the apply loop is unwedged.
mc.Shutdown()
}()
subscriberEvent := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
EventNotification: &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "file.txt",
Attributes: &filer_pb.FuseAttributes{
Crtime: 1,
Mtime: 1,
FileMode: 0100644,
},
},
},
}
localEvent := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
EventNotification: &filer_pb.EventNotification{
OldEntry: &filer_pb.Entry{Name: "file.txt"},
NewEntry: &filer_pb.Entry{
Name: "file.txt",
Attributes: &filer_pb.FuseAttributes{
Crtime: 1,
Mtime: 2,
FileMode: 0100644,
},
},
NewParentPath: "/dir",
},
}
// Step 1: the "flush handler" takes the fh exclusive lock
// (flushMetadataToFiler does this before talking to the filer).
flushLock := fhLockTable.AcquireLock("doFlush", fhKey, util.ExclusiveLock)
flushLockReleased := false
releaseFlushLock := func() {
if !flushLockReleased {
flushLockReleased = true
fhLockTable.ReleaseLock(fhKey, flushLock)
}
}
defer releaseFlushLock()
// Step 2: a subscriber event arrives; the apply loop will run
// invalidateFunc, which wants the fh lock held above.
subscriberDone := make(chan error, 1)
go func() {
subscriberDone <- mc.ApplyMetadataResponse(context.Background(), subscriberEvent, SubscriberMetadataResponseApplyOptions)
}()
select {
case <-invalidateEntered:
case <-time.After(5 * time.Second):
t.Fatal("invalidateFunc was never invoked for the subscriber event")
}
// Give the invalidate goroutine a moment to actually block on AcquireLock.
time.Sleep(50 * time.Millisecond)
// Step 3: still holding the fh lock, the flush handler applies its local
// metadata event and waits for the apply loop — exactly what
// flushMetadataToFiler does after streamCreateEntry succeeds.
flushApplyDone := make(chan error, 1)
go func() {
flushApplyDone <- mc.ApplyMetadataResponseOwned(context.Background(), localEvent, LocalMetadataResponseApplyOptions)
}()
select {
case err := <-flushApplyDone:
if err != nil {
t.Fatalf("local metadata apply: %v", err)
}
case <-time.After(3 * time.Second):
// Unwedge the apply loop so Shutdown in the deferred cleanup
// doesn't hang the whole test binary.
releaseFlushLock()
t.Fatal("deadlock: apply loop blocked on fh lock while fh lock holder waits on apply loop")
}
releaseFlushLock()
select {
case err := <-subscriberDone:
if err != nil {
t.Fatalf("subscriber apply: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("subscriber apply never completed")
}
}
+2 -2
View File
@@ -82,7 +82,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
return
}
cleanupDone = true
if deleteErr := mc.DeleteFolderChildren(context.Background(), path); deleteErr != nil {
if deleteErr := mc.deleteFolderChildrenForRebuild(context.Background(), path); deleteErr != nil {
glog.V(2).Infof("clear %s build %s: %v", reason, path, deleteErr)
}
if abortErr := mc.AbortDirectoryBuild(context.Background(), path); abortErr != nil {
@@ -101,7 +101,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
fetchErr := util.Retry("ReadDirAllEntries", func() error {
batch = nil // Reset batch on retry, allow GC of previous entries
if err := mc.DeleteFolderChildren(ctx, path); err != nil {
if err := mc.deleteFolderChildrenForRebuild(ctx, path); err != nil {
return fmt.Errorf("clear existing entries for %s: %w", path, err)
}
var err error
+4
View File
@@ -15,6 +15,10 @@ func (wfs *WFS) applyLocalMetadataEvent(ctx context.Context, event *filer_pb.Sub
return wfs.metaCache.ApplyMetadataResponseOwned(ctx, event, meta_cache.LocalMetadataResponseApplyOptions)
}
func (wfs *WFS) applyLocalMetadataEventAsync(event *filer_pb.SubscribeMetadataResponse) {
wfs.metaCache.ApplyMetadataResponseOwnedAsync(event, meta_cache.LocalMetadataResponseApplyOptions)
}
func metadataDeleteEvent(directory, name string, isDirectory bool) *filer_pb.SubscribeMetadataResponse {
if name == "" {
return nil
+34 -6
View File
@@ -4,27 +4,55 @@ import "sync/atomic"
type WriterPattern struct {
isSequentialCounter int64
lastWriteStopOffset int64
writeFrontier int64 // highest (offset+size) observed across writes
chunkSize int64
}
const ModeChangeLimit = 3
// For streaming write: only cache the first chunk
// For random write: fall back to temp file approach
// SeqTolerance: a write whose start is within this many bytes of the current
// write frontier still counts as sequential. Using a tolerance window rather
// than strict contiguity absorbs reordered/concurrent FUSE writeback — multiple
// Write upcalls for one handle interleave (MonitorWriteAt runs before the
// per-handle write lock) and writeback flushes dirty pages slightly out of
// offset order — while still rejecting far random seeks.
const SeqTolerance = 8 << 20 // 8 MiB
// For streaming write: keep dirty chunks in memory (NewMemChunk).
// For random write: fall back to the on-disk swap file (NewSwapFileChunk).
func NewWriterPattern(chunkSize int64) *WriterPattern {
return &WriterPattern{
isSequentialCounter: 0,
lastWriteStopOffset: 0,
writeFrontier: 0,
chunkSize: chunkSize,
}
}
func (rp *WriterPattern) MonitorWriteAt(offset int64, size int) {
lastOffset := atomic.SwapInt64(&rp.lastWriteStopOffset, offset+int64(size))
// Advance the frontier to max(frontier, offset+size) and capture, in the same
// CAS loop, the pre-image this write is judged against. Reading the frontier
// inside the loop (rather than once up front) keeps `diff` below comparing
// against the freshest value even if a concurrent writeback upcall advances
// the frontier while we loop. Lock-free, consistent with the atomic counter.
end := offset + int64(size)
var frontier int64
for {
frontier = atomic.LoadInt64(&rp.writeFrontier)
if end <= frontier || atomic.CompareAndSwapInt64(&rp.writeFrontier, frontier, end) {
break
}
}
// near = this write starts within SeqTolerance of where writes had reached.
// Hysteresis (the ±ModeChangeLimit counter) keeps a single outlier write
// from flipping the mode and spilling a sequential stream to the swap file.
diff := offset - frontier
if diff < 0 {
diff = -diff
}
counter := atomic.LoadInt64(&rp.isSequentialCounter)
if lastOffset == offset {
if diff <= SeqTolerance {
if counter < ModeChangeLimit {
atomic.AddInt64(&rp.isSequentialCounter, 1)
}
+104
View File
@@ -0,0 +1,104 @@
package mount
import (
"sync/atomic"
"testing"
)
const mb = 1 << 20
func TestWriterPatternSequentialAndHysteresis(t *testing.T) {
wp := NewWriterPattern(2 * mb)
wp.MonitorWriteAt(0, mb) // near(0 vs frontier 0) -> +1
wp.MonitorWriteAt(mb, mb) // +2
wp.MonitorWriteAt(2*mb, mb) // +3 (capped)
if !wp.IsSequentialMode() {
t.Fatal("a stream from offset 0 must be sequential")
}
// a single far outlier does not flip to random (hysteresis): +3 -> +2
wp.MonitorWriteAt(900*mb, mb)
if !wp.IsSequentialMode() {
t.Fatal("a single outlier write must not flip out of sequential mode")
}
}
func TestWriterPatternFarFirstWriteIsRandom(t *testing.T) {
wp := NewWriterPattern(2 * mb)
wp.MonitorWriteAt(500*mb, mb) // far from frontier 0 -> -1
if wp.IsSequentialMode() {
t.Fatal("a far first write should be random")
}
}
func TestWriterPatternToleranceAbsorbsReorder(t *testing.T) {
wp := NewWriterPattern(2 * mb)
wp.MonitorWriteAt(0, mb) // +1, frontier 1MB
wp.MonitorWriteAt(6*mb, mb) // |6-1|=5MB <= 8MB tolerance -> near, +2, frontier 7MB
wp.MonitorWriteAt(3*mb, mb) // |3-7|=4MB <= 8MB -> near, +3
if !wp.IsSequentialMode() {
t.Fatal("reordered writes within tolerance must stay sequential")
}
}
func TestWriterPatternRandomRecoveryNeedsHysteresis(t *testing.T) {
wp := NewWriterPattern(2 * mb)
wp.MonitorWriteAt(100*mb, mb) // far -> -1
wp.MonitorWriteAt(300*mb, mb) // far -> -2
wp.MonitorWriteAt(500*mb, mb) // far -> -3 (capped), frontier 501MB
// a single near write must not immediately flip back to sequential: -3 -> -2
wp.MonitorWriteAt(501*mb, mb)
if wp.IsSequentialMode() {
t.Fatal("one near write must not flip back from deep random mode")
}
}
// The max-frontier (vs the old atomic.Swap of the last write's stop offset) is the
// load-bearing difference of this detector: the frontier must never move backward,
// or a backward write would lower the baseline and make later far writes look near.
func TestWriterPatternFrontierNeverRegresses(t *testing.T) {
wp := NewWriterPattern(2 * mb)
wp.MonitorWriteAt(500*mb, mb) // far first write -> -1, frontier 501MB
wp.MonitorWriteAt(0, mb) // a backward write must not pull the frontier back
if got := atomic.LoadInt64(&wp.writeFrontier); got != 501*mb {
t.Fatalf("frontier regressed to %d; the max-frontier must never move backward", got)
}
// Behavioral consequence: writes far below the preserved frontier stay random.
// Had the frontier regressed to ~1MB, this would wrongly read as sequential.
if wp.IsSequentialMode() {
t.Fatal("writes far below the preserved frontier must remain random")
}
}
// SeqTolerance is the central new tuning knob; pin both sides of the inclusive
// boundary so an off-by-one or a '<' vs '<=' change can't slip through silently.
func TestWriterPatternToleranceBoundary(t *testing.T) {
atBoundary := NewWriterPattern(2 * mb)
atBoundary.MonitorWriteAt(SeqTolerance, 0) // diff == SeqTolerance -> near (inclusive), +1
if !atBoundary.IsSequentialMode() {
t.Fatal("a write exactly at frontier+SeqTolerance must count as sequential")
}
pastBoundary := NewWriterPattern(2 * mb)
pastBoundary.MonitorWriteAt(SeqTolerance+1, 0) // diff == SeqTolerance+1 -> far, -1
if pastBoundary.IsSequentialMode() {
t.Fatal("a write one byte past frontier+SeqTolerance must count as random")
}
}
// The perf-relevant escape from random (swap-file) mode: sustained near writes must
// climb the counter back out of the negative floor and re-enter sequential (RAM) mode.
func TestWriterPatternRecoversToSequential(t *testing.T) {
wp := NewWriterPattern(2 * mb)
wp.MonitorWriteAt(100*mb, mb) // far -> -1
wp.MonitorWriteAt(300*mb, mb) // far -> -2
wp.MonitorWriteAt(500*mb, mb) // far -> -3 (capped), frontier 501MB
if wp.IsSequentialMode() {
t.Fatal("three far writes must be random")
}
// contiguous near writes: -3 -> -2 -> -1 -> 0 -> +1, back into sequential mode
for i := int64(0); i < 4; i++ {
wp.MonitorWriteAt(501*mb+i*mb, mb)
}
if !wp.IsSequentialMode() {
t.Fatal("sustained near writes must recover sequential mode (escape the swap-file cliff)")
}
}
+24
View File
@@ -320,6 +320,7 @@ func NewSeaweedFileSystem(option *Option) *WFS {
wfs.markDirectoryReadThrough(dirPath)
}
})
wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry)
grace.OnInterrupt(func() {
// grace calls os.Exit(0) after all hooks, so WaitForAsyncFlush
// after server.Serve() would never execute. Drain here first.
@@ -549,6 +550,29 @@ func (wfs *WFS) maybeReadEntry(inode uint64) (path util.FullPath, fh *FileHandle
return
}
// isLocalOnlyEntry reports whether entry holds local-only state not yet on the
// filer — an open handle with dirty metadata, or a pending async flush. A
// directory rebuild refills from a filer listing that omits such an entry, so it
// must be preserved across the wipe; this is the same signal lookupEntry trusts
// over a filer ErrNotFound for deferred creates.
//
// Keyed off the inode the entry carries, not inodeToPath: a kernel Forget can
// drop the path→inode mapping while an async writeback flush is still in flight,
// and the entry must stay pinned until that flush reaches the filer.
func (wfs *WFS) isLocalOnlyEntry(entry *filer.Entry) bool {
if entry == nil || entry.Attr.Inode == 0 {
return false
}
inode := entry.Attr.Inode
if fh, fhFound := wfs.fhMap.FindFileHandle(inode); fhFound && fh.dirtyMetadata {
return true
}
wfs.pendingAsyncFlushMu.Lock()
_, pending := wfs.pendingAsyncFlush[inode]
wfs.pendingAsyncFlushMu.Unlock()
return pending
}
func (wfs *WFS) maybeLoadEntry(fullpath util.FullPath) (*filer_pb.Entry, fuse.Status) {
// glog.V(3).Infof("read entry cache miss %s", fullpath)
_, name := fullpath.DirAndName()
+57 -8
View File
@@ -3,26 +3,75 @@ package mount
import (
"os/user"
"strconv"
"sync"
"syscall"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
var lookupSupplementaryGroupIDs = func(callerUid uint32) ([]string, error) {
u, err := user.LookupId(strconv.Itoa(int(callerUid)))
type cachedGroupIDs struct {
groups []string
expiresAt time.Time
}
var (
supplementaryGroupCache = make(map[uint32]*cachedGroupIDs)
supplementaryGroupCacheMu sync.RWMutex
supplementaryGroupCacheTTL = 5 * time.Minute
lookupSupplementaryGroupIDs = func(callerUid uint32) ([]string, error) {
u, err := user.LookupId(strconv.Itoa(int(callerUid)))
if err != nil {
glog.Warningf("hasAccess: user.LookupId for uid %d failed: %v", callerUid, err)
return nil, err
}
groupIDs, err := u.GroupIds()
if err != nil {
glog.Warningf("hasAccess: u.GroupIds for uid %d failed: %v", callerUid, err)
return nil, err
}
return groupIDs, nil
}
)
// cachedLookupSupplementaryGroupIDs returns supplementary group IDs for a UID,
// caching results for 5 minutes to avoid repeated expensive system calls.
func cachedLookupSupplementaryGroupIDs(callerUid uint32) ([]string, error) {
now := time.Now()
supplementaryGroupCacheMu.RLock()
cached, ok := supplementaryGroupCache[callerUid]
supplementaryGroupCacheMu.RUnlock()
if ok && now.Before(cached.expiresAt) {
return cached.groups, nil
}
groupIDs, err := lookupSupplementaryGroupIDs(callerUid)
if err != nil {
glog.Warningf("hasAccess: user.LookupId for uid %d failed: %v", callerUid, err)
return nil, err
}
groupIDs, err := u.GroupIds()
if err != nil {
glog.Warningf("hasAccess: u.GroupIds for uid %d failed: %v", callerUid, err)
return nil, err
supplementaryGroupCacheMu.Lock()
supplementaryGroupCache[callerUid] = &cachedGroupIDs{
groups: groupIDs,
expiresAt: now.Add(supplementaryGroupCacheTTL),
}
supplementaryGroupCacheMu.Unlock()
return groupIDs, nil
}
// clearSupplementaryGroupCache wipes the UID->groups cache for test isolation.
func clearSupplementaryGroupCache() {
supplementaryGroupCacheMu.Lock()
defer supplementaryGroupCacheMu.Unlock()
for k := range supplementaryGroupCache {
delete(supplementaryGroupCache, k)
}
}
/**
* Check file access permissions
*
@@ -67,7 +116,7 @@ func hasAccess(callerUid, callerGid, fileUid, fileGid uint32, perm uint32, mask
isMember := callerGid == fileGid
if !isMember {
groupIDs, err := lookupSupplementaryGroupIDs(callerUid)
groupIDs, err := cachedLookupSupplementaryGroupIDs(callerUid)
if err != nil {
// Cannot determine supplementary group membership.
// Fall through to "other" permission check since we already
+45
View File
@@ -0,0 +1,45 @@
package mount
import (
"testing"
"github.com/seaweedfs/go-fuse/v2/fuse"
)
// BenchmarkCachedLookupSupplementaryGroupIDs measures cache hit performance.
func BenchmarkCachedLookupSupplementaryGroupIDs(b *testing.B) {
oldLookupSupplementaryGroupIDs := lookupSupplementaryGroupIDs
lookupSupplementaryGroupIDs = func(uid uint32) ([]string, error) {
return []string{"456", "789", "1011"}, nil
}
clearSupplementaryGroupCache()
defer func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
clearSupplementaryGroupCache()
}()
cachedLookupSupplementaryGroupIDs(999)
b.ResetTimer()
for i := 0; i < b.N; i++ {
cachedLookupSupplementaryGroupIDs(999)
}
}
// BenchmarkHasAccessPermissionCheck measures permission checks with the cache.
// Simulates repeated permission checks for the same user against different files.
func BenchmarkHasAccessPermissionCheck(b *testing.B) {
oldLookupSupplementaryGroupIDs := lookupSupplementaryGroupIDs
lookupSupplementaryGroupIDs = func(uid uint32) ([]string, error) {
return []string{"456", "789", "1011"}, nil
}
clearSupplementaryGroupCache()
defer func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
clearSupplementaryGroupCache()
}()
b.ResetTimer()
for i := 0; i < b.N; i++ {
hasAccess(999, 999, 123, uint32(i%10), 0o040, fuse.R_OK|fuse.W_OK)
}
}
+93
View File
@@ -0,0 +1,93 @@
package mount
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
)
// TestPermissionCheckPerformance simulates permission checks during a large copy operation.
// Shows that with caching, even 50,000 permission checks only trigger 1 system lookup.
func TestPermissionCheckPerformance(t *testing.T) {
oldLookupSupplementaryGroupIDs := lookupSupplementaryGroupIDs
lookupCount := 0
lookupSupplementaryGroupIDs = func(uid uint32) ([]string, error) {
lookupCount++
return []string{"456", "789", "1011"}, nil
}
defer func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
}()
// Simulate copying 10,000 files as non-root user.
// Each file access requires multiple permission checks.
// Without caching, this would trigger 50,000 system lookups!
fileCount := 10000
checksPerFile := 5
clearSupplementaryGroupCache()
start := time.Now()
for i := 0; i < fileCount; i++ {
for j := 0; j < checksPerFile; j++ {
gid := uint32(100 + (i % 10))
hasAccess(999, 999, 123, gid, 0o040, fuse.R_OK|fuse.W_OK)
}
}
elapsed := time.Since(start)
totalChecks := fileCount * checksPerFile
if lookupCount != 1 {
t.Fatalf("Expected 1 system lookup (cache hit for UID 999), got %d", lookupCount)
}
opsPerSecond := float64(totalChecks) / elapsed.Seconds()
fmt.Printf("\n=== Permission Check Performance Test (WITH CACHE) ===\n")
fmt.Printf("Files simulated: %d\n", fileCount)
fmt.Printf("Checks per file: %d\n", checksPerFile)
fmt.Printf("Total checks: %d\n", totalChecks)
fmt.Printf("System lookups: %d (would be %d without cache)\n", lookupCount, totalChecks)
fmt.Printf("Lookups eliminated: %d (%.1f%% reduction)\n", totalChecks-lookupCount,
(1-float64(lookupCount)/float64(totalChecks))*100)
fmt.Printf("Time elapsed: %v\n", elapsed)
fmt.Printf("Throughput: %.0f checks/sec\n", opsPerSecond)
}
// BenchmarkPermissionCheckScaling shows how performance scales with unique users.
func BenchmarkPermissionCheckScaling(b *testing.B) {
oldLookupSupplementaryGroupIDs := lookupSupplementaryGroupIDs
lookupSupplementaryGroupIDs = func(uid uint32) ([]string, error) {
return []string{"456", "789", "1011"}, nil
}
clearSupplementaryGroupCache()
defer func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
clearSupplementaryGroupCache()
}()
// Simulate repeated permission checks for the same user
// (typical single-user copy operation)
b.Run("single-user", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
hasAccess(999, 999, 123, 456, 0o040, fuse.R_OK|fuse.W_OK)
}
})
b.Run("multi-user-10", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
uid := uint32(1000 + (i % 10))
hasAccess(uid, 100, 123, 456, 0o040, fuse.R_OK|fuse.W_OK)
}
})
b.Run("multi-user-100", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
uid := uint32(1000 + (i % 100))
hasAccess(uid, 100, 123, 456, 0o040, fuse.R_OK|fuse.W_OK)
}
})
}
+58
View File
@@ -307,8 +307,10 @@ func TestAccessChecksPermissions(t *testing.T) {
lookupSupplementaryGroupIDs = func(uint32) ([]string, error) {
return nil, nil
}
clearSupplementaryGroupCache()
t.Cleanup(func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
clearSupplementaryGroupCache()
})
fullPath := util.FullPath("/visible.txt")
@@ -380,8 +382,10 @@ func TestHasAccessUsesSupplementaryGroups(t *testing.T) {
lookupSupplementaryGroupIDs = func(uint32) ([]string, error) {
return []string{"456"}, nil
}
clearSupplementaryGroupCache()
t.Cleanup(func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
clearSupplementaryGroupCache()
})
if got := hasAccess(999, 999, 123, 456, 0o060, fuse.R_OK|fuse.W_OK); !got {
@@ -389,6 +393,60 @@ func TestHasAccessUsesSupplementaryGroups(t *testing.T) {
}
}
func TestSupplementaryGroupCaching(t *testing.T) {
callCount := 0
oldLookupSupplementaryGroupIDs := lookupSupplementaryGroupIDs
lookupSupplementaryGroupIDs = func(uid uint32) ([]string, error) {
callCount++
return []string{"456"}, nil
}
clearSupplementaryGroupCache()
t.Cleanup(func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
clearSupplementaryGroupCache()
})
cachedLookupSupplementaryGroupIDs(999)
cachedLookupSupplementaryGroupIDs(999)
cachedLookupSupplementaryGroupIDs(999)
if callCount != 1 {
t.Fatalf("lookupSupplementaryGroupIDs called %d times, expected 1 (cache should prevent repeated calls)", callCount)
}
cachedLookupSupplementaryGroupIDs(1000)
if callCount != 2 {
t.Fatalf("lookupSupplementaryGroupIDs called %d times after different UID, expected 2", callCount)
}
}
func TestSupplementaryGroupCacheExpiry(t *testing.T) {
callCount := 0
oldLookupSupplementaryGroupIDs := lookupSupplementaryGroupIDs
oldTTL := supplementaryGroupCacheTTL
supplementaryGroupCacheTTL = 0
lookupSupplementaryGroupIDs = func(uid uint32) ([]string, error) {
callCount++
return []string{"456"}, nil
}
clearSupplementaryGroupCache()
t.Cleanup(func() {
lookupSupplementaryGroupIDs = oldLookupSupplementaryGroupIDs
supplementaryGroupCacheTTL = oldTTL
clearSupplementaryGroupCache()
})
cachedLookupSupplementaryGroupIDs(999)
if callCount != 1 {
t.Fatalf("Expected 1 lookup on first call, got %d", callCount)
}
cachedLookupSupplementaryGroupIDs(999)
if callCount != 2 {
t.Fatalf("Expected 2 lookups after TTL expiry, got %d", callCount)
}
}
func TestCreateExistingFileIgnoresQuotaPreflight(t *testing.T) {
wfs, _ := newCreateTestWFS(t)
wfs.option.Quota = 1
+2
View File
@@ -26,12 +26,14 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
return
}
// WantMd5 gives mount writes a real filer.ETag (server echoes Content-MD5 back).
uploadOption := &operation.UploadOption{
Filename: filename,
Cipher: wfs.option.Cipher,
IsInputCompressed: false,
MimeType: "",
PairMap: nil,
WantMd5: true,
}
genFileUrlFn := func(host, fileId string) string {
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
+2 -2
View File
@@ -62,7 +62,7 @@ func (m *mockSeaweedMQHandler) CreateTopic(topic string, partitions int32) error
m.mu.Lock()
defer m.mu.Unlock()
if _, exists := m.topics[topic]; exists {
return fmt.Errorf("topic already exists")
return fmt.Errorf("%s: %w", topic, integration.ErrTopicAlreadyExists)
}
m.topics[topic] = &integration.KafkaTopicInfo{
Name: topic,
@@ -75,7 +75,7 @@ func (m *mockSeaweedMQHandler) CreateTopicWithSchemas(name string, partitions in
m.mu.Lock()
defer m.mu.Unlock()
if _, exists := m.topics[name]; exists {
return fmt.Errorf("topic already exists")
return fmt.Errorf("%s: %w", name, integration.ErrTopicAlreadyExists)
}
m.topics[name] = &integration.KafkaTopicInfo{
Name: name,
@@ -2,6 +2,7 @@ package integration
import (
"context"
"errors"
"fmt"
"time"
@@ -15,6 +16,11 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// ErrTopicAlreadyExists is returned by the CreateTopic* methods when the topic
// already exists in the filer. Callers performing auto-creation can treat it as
// confirmation the topic exists rather than a hard failure.
var ErrTopicAlreadyExists = errors.New("topic already exists")
// CreateTopic creates a new topic in both Kafka registry and SeaweedMQ
func (h *SeaweedMQHandler) CreateTopic(name string, partitions int32) error {
return h.CreateTopicWithSchema(name, partitions, nil)
@@ -29,7 +35,7 @@ func (h *SeaweedMQHandler) CreateTopicWithSchema(name string, partitions int32,
func (h *SeaweedMQHandler) CreateTopicWithSchemas(name string, partitions int32, keyRecordType *schema_pb.RecordType, valueRecordType *schema_pb.RecordType) error {
// Check if topic already exists in filer
if h.checkTopicInFiler(name) {
return fmt.Errorf("topic %s already exists", name)
return fmt.Errorf("%s: %w", name, ErrTopicAlreadyExists)
}
// Create SeaweedMQ topic reference
@@ -90,7 +96,7 @@ func (h *SeaweedMQHandler) CreateTopicWithSchemas(name string, partitions int32,
func (h *SeaweedMQHandler) CreateTopicWithRecordType(name string, partitions int32, flatSchema *schema_pb.RecordType, keyColumns []string) error {
// Check if topic already exists in filer
if h.checkTopicInFiler(name) {
return fmt.Errorf("topic %s already exists", name)
return fmt.Errorf("%s: %w", name, ErrTopicAlreadyExists)
}
// Create SeaweedMQ topic reference
+45 -108
View File
@@ -5,6 +5,7 @@ import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"hash/fnv"
"io"
@@ -1317,28 +1318,8 @@ func (h *Handler) HandleMetadataV0(correlationID uint32, requestBody []byte) ([]
topicsToReturn = h.seaweedMQHandler.ListTopics()
} else {
for _, name := range requestedTopics {
if h.seaweedMQHandler.TopicExists(name) {
if h.ensureTopicExists(name, h.GetDefaultPartitions()) {
topicsToReturn = append(topicsToReturn, name)
} else {
// Topic doesn't exist according to current cache, check broker directly
// This handles the race condition where producers just created topics
// and consumers are requesting metadata before cache TTL expires
glog.V(3).Infof("[METADATA v0] Topic %s not in cache, checking broker directly", name)
h.seaweedMQHandler.InvalidateTopicExistsCache(name)
if h.seaweedMQHandler.TopicExists(name) {
glog.V(3).Infof("[METADATA v0] Topic %s found on broker after cache refresh", name)
topicsToReturn = append(topicsToReturn, name)
} else {
glog.V(3).Infof("[METADATA v0] Topic %s not found, auto-creating with default partitions", name)
// Auto-create topic (matches Kafka's auto.create.topics.enable=true)
if err := h.createTopicWithSchemaSupport(name, h.GetDefaultPartitions()); err != nil {
glog.V(2).Infof("[METADATA v0] Failed to auto-create topic %s: %v", name, err)
// Don't add to topicsToReturn - client will get error
} else {
glog.V(2).Infof("[METADATA v0] Successfully auto-created topic %s", name)
topicsToReturn = append(topicsToReturn, name)
}
}
}
}
}
@@ -1412,24 +1393,8 @@ func (h *Handler) HandleMetadataV1(correlationID uint32, requestBody []byte) ([]
topicsToReturn = h.seaweedMQHandler.ListTopics()
} else {
for _, name := range requestedTopics {
if h.seaweedMQHandler.TopicExists(name) {
if h.ensureTopicExists(name, h.GetDefaultPartitions()) {
topicsToReturn = append(topicsToReturn, name)
} else {
// Topic doesn't exist according to current cache, check broker directly
glog.V(3).Infof("[METADATA v1] Topic %s not in cache, checking broker directly", name)
h.seaweedMQHandler.InvalidateTopicExistsCache(name)
if h.seaweedMQHandler.TopicExists(name) {
glog.V(3).Infof("[METADATA v1] Topic %s found on broker after cache refresh", name)
topicsToReturn = append(topicsToReturn, name)
} else {
glog.V(3).Infof("[METADATA v1] Topic %s not found, auto-creating with default partitions", name)
if err := h.createTopicWithSchemaSupport(name, h.GetDefaultPartitions()); err != nil {
glog.V(2).Infof("[METADATA v1] Failed to auto-create topic %s: %v", name, err)
} else {
glog.V(2).Infof("[METADATA v1] Successfully auto-created topic %s", name)
topicsToReturn = append(topicsToReturn, name)
}
}
}
}
}
@@ -1546,24 +1511,8 @@ func (h *Handler) HandleMetadataV2(correlationID uint32, requestBody []byte) ([]
topicsToReturn = h.seaweedMQHandler.ListTopics()
} else {
for _, name := range requestedTopics {
if h.seaweedMQHandler.TopicExists(name) {
if h.ensureTopicExists(name, h.GetDefaultPartitions()) {
topicsToReturn = append(topicsToReturn, name)
} else {
// Topic doesn't exist according to current cache, check broker directly
glog.V(3).Infof("[METADATA v2] Topic %s not in cache, checking broker directly", name)
h.seaweedMQHandler.InvalidateTopicExistsCache(name)
if h.seaweedMQHandler.TopicExists(name) {
glog.V(3).Infof("[METADATA v2] Topic %s found on broker after cache refresh", name)
topicsToReturn = append(topicsToReturn, name)
} else {
glog.V(3).Infof("[METADATA v2] Topic %s not found, auto-creating with default partitions", name)
if err := h.createTopicWithSchemaSupport(name, h.GetDefaultPartitions()); err != nil {
glog.V(2).Infof("[METADATA v2] Failed to auto-create topic %s: %v", name, err)
} else {
glog.V(2).Infof("[METADATA v2] Successfully auto-created topic %s", name)
topicsToReturn = append(topicsToReturn, name)
}
}
}
}
}
@@ -1670,24 +1619,8 @@ func (h *Handler) HandleMetadataV3V4(correlationID uint32, requestBody []byte) (
topicsToReturn = h.seaweedMQHandler.ListTopics()
} else {
for _, name := range requestedTopics {
if h.seaweedMQHandler.TopicExists(name) {
if h.ensureTopicExists(name, h.GetDefaultPartitions()) {
topicsToReturn = append(topicsToReturn, name)
} else {
// Topic doesn't exist according to current cache, check broker directly
glog.V(3).Infof("[METADATA v3/v4] Topic %s not in cache, checking broker directly", name)
h.seaweedMQHandler.InvalidateTopicExistsCache(name)
if h.seaweedMQHandler.TopicExists(name) {
glog.V(3).Infof("[METADATA v3/v4] Topic %s found on broker after cache refresh", name)
topicsToReturn = append(topicsToReturn, name)
} else {
glog.V(3).Infof("[METADATA v3/v4] Topic %s not found, auto-creating with default partitions", name)
if err := h.createTopicWithSchemaSupport(name, h.GetDefaultPartitions()); err != nil {
glog.V(2).Infof("[METADATA v3/v4] Failed to auto-create topic %s: %v", name, err)
} else {
glog.V(2).Infof("[METADATA v3/v4] Successfully auto-created topic %s", name)
topicsToReturn = append(topicsToReturn, name)
}
}
}
}
}
@@ -1828,44 +1761,15 @@ func (h *Handler) handleMetadataV5ToV8(correlationID uint32, requestBody []byte,
// 4. Client will call CreateTopics for non-existent topics
// 5. Then request metadata again to see the created topics
for _, topic := range requestedTopics {
partitions := h.GetDefaultPartitions()
if isSystemTopic(topic) {
// Always try to auto-create system topics during metadata requests
glog.V(3).Infof("[METADATA v%d] Ensuring system topic %s exists during metadata request", apiVersion, topic)
if !h.seaweedMQHandler.TopicExists(topic) {
glog.V(3).Infof("[METADATA v%d] Auto-creating system topic %s during metadata request", apiVersion, topic)
if err := h.createTopicWithSchemaSupport(topic, 1); err != nil {
glog.V(0).Infof("[METADATA v%d] Failed to auto-create system topic %s: %v", apiVersion, topic, err)
// Continue without adding to topicsToReturn - client will get UNKNOWN_TOPIC_OR_PARTITION
} else {
glog.V(3).Infof("[METADATA v%d] Successfully auto-created system topic %s", apiVersion, topic)
}
} else {
glog.V(3).Infof("[METADATA v%d] System topic %s already exists", apiVersion, topic)
}
// System topics use a single partition. ensureTopicExists tolerates
// the auto-create race, so a false result means the topic genuinely
// does not exist - don't advertise it with error_code=0.
partitions = 1
}
if h.ensureTopicExists(topic, partitions) {
topicsToReturn = append(topicsToReturn, topic)
} else if h.seaweedMQHandler.TopicExists(topic) {
topicsToReturn = append(topicsToReturn, topic)
} else {
// Topic doesn't exist according to current cache, but let's check broker directly
// This handles the race condition where producers just created topics
// and consumers are requesting metadata before cache TTL expires
glog.V(3).Infof("[METADATA v%d] Topic %s not in cache, checking broker directly", apiVersion, topic)
// Force cache invalidation to do fresh broker check
h.seaweedMQHandler.InvalidateTopicExistsCache(topic)
if h.seaweedMQHandler.TopicExists(topic) {
glog.V(3).Infof("[METADATA v%d] Topic %s found on broker after cache refresh", apiVersion, topic)
topicsToReturn = append(topicsToReturn, topic)
} else {
glog.V(3).Infof("[METADATA v%d] Topic %s not found on broker, auto-creating with default partitions", apiVersion, topic)
// Auto-create non-system topics with default partitions (matches Kafka behavior)
if err := h.createTopicWithSchemaSupport(topic, h.GetDefaultPartitions()); err != nil {
glog.V(2).Infof("[METADATA v%d] Failed to auto-create topic %s: %v", apiVersion, topic, err)
// Don't add to topicsToReturn - client will get UNKNOWN_TOPIC_OR_PARTITION
} else {
glog.V(2).Infof("[METADATA v%d] Successfully auto-created topic %s", apiVersion, topic)
topicsToReturn = append(topicsToReturn, topic)
}
}
}
}
glog.V(3).Infof("[METADATA v%d] Returning topics: %v (requested: %v)", apiVersion, topicsToReturn, requestedTopics)
@@ -4067,6 +3971,39 @@ func (h *Handler) handleInitProducerId(correlationID uint32, apiVersion uint16,
return response, nil
}
// ensureTopicExists reports whether the named topic exists, auto-creating it
// when missing (matching auto.create.topics.enable=true).
//
// TopicExists can return a transient false negative for a topic that is in fact
// present: a broker/filer blip, or a just-created topic whose existence cache is
// still stale. When that happens the auto-create attempt fails with
// ErrTopicAlreadyExists - which confirms the topic exists. Treating that as
// success (rather than dropping the topic) is what keeps producers from getting
// a spurious UNKNOWN_TOPIC_OR_PARTITION right after the topic was created.
func (h *Handler) ensureTopicExists(topicName string, partitions int32) bool {
if h.seaweedMQHandler.TopicExists(topicName) {
return true
}
// Existence cache may be stale right after creation; force a fresh broker check.
h.seaweedMQHandler.InvalidateTopicExistsCache(topicName)
if h.seaweedMQHandler.TopicExists(topicName) {
return true
}
if err := h.createTopicWithSchemaSupport(topicName, partitions); err != nil {
if errors.Is(err, integration.ErrTopicAlreadyExists) {
// The topic exists; the recheck above just cached a stale negative.
// Clear it so direct TopicExists callers don't see the false negative.
h.seaweedMQHandler.InvalidateTopicExistsCache(topicName)
return true
}
glog.V(2).Infof("[METADATA] Failed to auto-create topic %s: %v", topicName, err)
return false
}
// Topic just created - clear the negative cache so callers see it immediately.
h.seaweedMQHandler.InvalidateTopicExistsCache(topicName)
return true
}
// createTopicWithSchemaSupport creates a topic with optional schema integration
// This function creates topics with schema support when schema management is enabled
func (h *Handler) createTopicWithSchemaSupport(topicName string, partitions int32) error {
+6 -21
View File
@@ -7,7 +7,6 @@ import (
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/compression"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/schema"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
@@ -78,24 +77,7 @@ func (h *Handler) handleProduceV0V1(ctx context.Context, correlationID uint32, a
offset += 4
// Check if topic exists, auto-create if it doesn't (simulates auto.create.topics.enable=true)
topicExists := h.seaweedMQHandler.TopicExists(topicName)
_ = h.seaweedMQHandler.ListTopics() // existingTopics
if !topicExists {
// Use schema-aware topic creation for auto-created topics with configurable default partitions
defaultPartitions := h.GetDefaultPartitions()
glog.V(1).Infof("[PRODUCE] Topic %s does not exist, auto-creating with %d partitions", topicName, defaultPartitions)
if err := h.createTopicWithSchemaSupport(topicName, defaultPartitions); err != nil {
glog.V(0).Infof("[PRODUCE] ERROR: Failed to auto-create topic %s: %v", topicName, err)
} else {
glog.V(1).Infof("[PRODUCE] Successfully auto-created topic %s", topicName)
// Invalidate cache immediately after creation so consumers can find it
h.seaweedMQHandler.InvalidateTopicExistsCache(topicName)
topicExists = true
}
} else {
glog.V(2).Infof("[PRODUCE] Topic %s already exists", topicName)
}
topicExists := h.ensureTopicExists(topicName, h.GetDefaultPartitions())
// Response: topic_name_size(2) + topic_name + partitions_array
response = append(response, byte(topicNameSize>>8), byte(topicNameSize))
@@ -701,8 +683,11 @@ func (h *Handler) handleProduceV2Plus(ctx context.Context, correlationID uint32,
var baseOffset int64 = 0
currentTime := time.Now().UnixNano()
// Check if topic exists; for v2+ do NOT auto-create
topicExists := h.seaweedMQHandler.TopicExists(topicName)
// Check if topic exists, auto-creating if needed. ensureTopicExists
// tolerates a transient TopicExists false-negative for a topic that
// already exists, which otherwise surfaces as a spurious
// UNKNOWN_TOPIC_OR_PARTITION right after the topic was created.
topicExists := h.ensureTopicExists(topicName, h.GetDefaultPartitions())
if !topicExists {
errorCode = 3 // UNKNOWN_TOPIC_OR_PARTITION
@@ -0,0 +1,74 @@
package protocol
import (
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/integration"
)
// autoCreateMockHandler models the flaky-existence scenario: TopicExists reports
// the topic missing (a transient broker/filer false-negative), while a create
// attempt reports the topic already exists. It reuses FastMockHandler for the
// rest of the interface and overrides only the two methods under test.
type autoCreateMockHandler struct {
*FastMockHandler
exists bool
createErr error
}
func (h *autoCreateMockHandler) TopicExists(name string) bool { return h.exists }
func (h *autoCreateMockHandler) CreateTopic(name string, partitions int32) error {
return h.createErr
}
// TestEnsureTopicExistsTreatsAlreadyExistsAsSuccess reproduces the offset-resumption
// flake: TopicExists returns a false-negative for a topic that is in fact present,
// so the auto-create attempt fails with ErrTopicAlreadyExists. The topic must still
// be reported as existing, otherwise the client sees UNKNOWN_TOPIC_OR_PARTITION.
func TestEnsureTopicExistsTreatsAlreadyExistsAsSuccess(t *testing.T) {
handler := &Handler{
seaweedMQHandler: &autoCreateMockHandler{
FastMockHandler: &FastMockHandler{},
exists: false,
createErr: fmt.Errorf("%s: %w", "offset-resumption", integration.ErrTopicAlreadyExists),
},
}
if !handler.ensureTopicExists("offset-resumption", 1) {
t.Fatal("ensureTopicExists must report true when the create attempt finds the topic already exists")
}
}
// TestEnsureTopicExistsReportsGenuineFailure confirms a real create failure (not
// "already exists") still results in the topic being treated as absent.
func TestEnsureTopicExistsReportsGenuineFailure(t *testing.T) {
handler := &Handler{
seaweedMQHandler: &autoCreateMockHandler{
FastMockHandler: &FastMockHandler{},
exists: false,
createErr: fmt.Errorf("broker unavailable"),
},
}
if handler.ensureTopicExists("missing-topic", 1) {
t.Fatal("ensureTopicExists must report false when the topic is absent and creation genuinely fails")
}
}
// TestEnsureTopicExistsWhenPresent covers the common path where the topic is
// already known to exist and no create attempt is needed.
func TestEnsureTopicExistsWhenPresent(t *testing.T) {
handler := &Handler{
seaweedMQHandler: &autoCreateMockHandler{
FastMockHandler: &FastMockHandler{},
exists: true,
createErr: fmt.Errorf("CreateTopic should not be called when the topic exists"),
},
}
if !handler.ensureTopicExists("present-topic", 1) {
t.Fatal("ensureTopicExists must report true for an existing topic")
}
}
+11
View File
@@ -3,6 +3,8 @@ package operation
import (
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
"io"
@@ -39,6 +41,7 @@ type UploadOption struct {
Jwt security.EncodedJwt
RetryForever bool
Md5 string
WantMd5 bool // compute Content-MD5 from the data when Md5 is unset and the upload is not ciphered
BytesBuffer *bytes.Buffer
SourceUrl string // optional: for logging when reading from a remote source
MaxAttempts int // <=0 uses the default
@@ -196,6 +199,14 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
assignRequest.ExpectedDataSize = uint64(len(data))
}
// Hash the buffer we already hold so the server echoes Content-MD5 back as
// the chunk ETag (std-base64 of the raw digest, the form ParseUpload
// verifies). Never under cipher: the server sees only ciphertext.
if uploadOption.WantMd5 && uploadOption.Md5 == "" && !uploadOption.Cipher {
digest := md5.Sum(data)
uploadOption.Md5 = base64.StdEncoding.EncodeToString(digest[:])
}
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 {
@@ -344,6 +344,22 @@ func (az *azureRemoteStorageClient) ReadFileWithConcurrency(loc *remote_pb.Remot
return data, nil
}
func (az *azureRemoteStorageClient) ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (reader io.ReadCloser, err error) {
key := loc.Path[1:]
blobClient := az.client.ServiceClient().NewContainerClient(loc.Bucket).NewBlockBlobClient(key)
downloadResponse, err := blobClient.DownloadStream(ctx, &blob.DownloadStreamOptions{
Range: blob.HTTPRange{
Offset: offset,
Count: size,
},
})
if err != nil {
return nil, fmt.Errorf("failed to open stream for %s%s: %v", loc.Bucket, loc.Path, err)
}
return downloadResponse.Body, nil
}
func (az *azureRemoteStorageClient) WriteDirectory(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry) (err error) {
return nil
}
@@ -212,6 +212,11 @@ func (gcs *gcsRemoteStorageClient) ReadFile(loc *remote_pb.RemoteStorageLocation
return
}
func (gcs *gcsRemoteStorageClient) ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (reader io.ReadCloser, err error) {
key := loc.Path[1:]
return gcs.client.Bucket(loc.Bucket).Object(key).NewRangeReader(ctx, offset, size)
}
func (gcs *gcsRemoteStorageClient) WriteDirectory(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry) (err error) {
return nil
}
+6
View File
@@ -95,6 +95,12 @@ type RemoteStorageConcurrentReader interface {
ReadFileWithConcurrency(loc *remote_pb.RemoteStorageLocation, offset int64, size int64, concurrency int) (data []byte, err error)
}
// RemoteStorageStreamReader is an optional interface for remote storage clients
// that support streaming reads with io.Reader for efficient memory usage.
type RemoteStorageStreamReader interface {
ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (reader io.ReadCloser, err error)
}
type RemoteStorageClientMaker interface {
Make(remoteConf *remote_pb.RemoteConf) (RemoteStorageClient, error)
HasBucket() bool
@@ -261,6 +261,21 @@ func (s *s3RemoteStorageClient) ReadFileWithConcurrency(loc *remote_pb.RemoteSto
return writerAt.Bytes(), nil
}
func (s *s3RemoteStorageClient) ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (reader io.ReadCloser, err error) {
output, err := s.conn.GetObjectWithContext(ctx, &s3.GetObjectInput{
Bucket: aws.String(loc.Bucket),
Key: aws.String(loc.Path[1:]),
Range: aws.String(fmt.Sprintf("bytes=%d-%d", offset, offset+size-1)),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchKey {
return nil, remote_storage.ErrRemoteObjectNotFound
}
return nil, fmt.Errorf("failed to open stream for %s%s: %v", loc.Bucket, loc.Path, err)
}
return output.Body, nil
}
func (s *s3RemoteStorageClient) WriteDirectory(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry) (err error) {
return nil
}
+2 -2
View File
@@ -147,7 +147,7 @@ func (iam *IdentityAccessManagement) doesSignV2Match(r *http.Request) (*Identity
return nil, s3err.ErrAccessDenied
}
expectedAuth := signatureV2(cred, r.Method, r.URL.Path, r.URL.Query().Encode(), r.Header)
expectedAuth := signatureV2(cred, r.Method, r.URL.EscapedPath(), r.URL.Query().Encode(), r.Header)
// Extract signatures from both auth headers
v2Signature := ""
@@ -224,7 +224,7 @@ func (iam *IdentityAccessManagement) doesPresignV2SignatureMatch(r *http.Request
return nil, s3err.ErrAccessDenied
}
expectedSignature := preSignatureV2(cred, r.Method, r.URL.Path, r.URL.Query().Encode(), r.Header, expires)
expectedSignature := preSignatureV2(cred, r.Method, r.URL.EscapedPath(), r.URL.Query().Encode(), r.Header, expires)
if !compareSignatureV2(signature, expectedSignature) {
return nil, s3err.ErrSignatureDoesNotMatch
}
+78
View File
@@ -2,7 +2,9 @@ package s3api
import (
"net/http"
"strconv"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
@@ -287,3 +289,79 @@ func TestDoesSignV2Match(t *testing.T) {
})
}
}
func TestDoesSignV2MatchUnicodePath(t *testing.T) {
iam := setupTestIAMForV2Auth()
cred := &Credential{
AccessKey: "AKIAIOSFODNN7EXAMPLE",
SecretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
}
tests := []struct {
name string
path string
}{
{
name: "CJK conversation key from ai-dial-core",
path: "/dialcore/core/Users/test-user/conversations/qwen3.5-35b-a3b__%E5%A4%9A%E7%9D%87%E3%80%82",
},
{
name: "Japanese filename from issue 8598",
path: "/voyage-dev1/public/1773200112088-998898991/%E3%81%9F%E3%81%82%E3%81%84%E3%81%BEd%C2%B7.jpg",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "http://example.com"+tt.path, nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("Date", "Mon, 09 Sep 2011 23:36:00 GMT")
// Clients (jclouds, AWS SDK) sign percent-encoded paths, not decoded Path.
authHeader := signatureV2(cred, req.Method, tt.path, req.URL.Query().Encode(), req.Header)
req.Header.Set("Authorization", authHeader)
identity, errCode := iam.doesSignV2Match(req)
if errCode != s3err.ErrNone {
t.Fatalf("doesSignV2Match() error = %v, want %v; path=%q escaped=%q",
errCode, s3err.ErrNone, req.URL.Path, req.URL.EscapedPath())
}
if identity == nil {
t.Fatal("Expected non-nil identity")
}
})
}
}
func TestDoesPresignV2MatchUnicodePath(t *testing.T) {
iam := setupTestIAMForV2Auth()
cred := &Credential{
AccessKey: "AKIAIOSFODNN7EXAMPLE",
SecretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
}
path := "/dialcore/core/Users/test-user/conversations/qwen3.5-35b-a3b__%E5%A4%9A%E7%9D%87%E3%80%82"
expires := strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)
req, err := http.NewRequest(http.MethodGet, "http://example.com"+path, nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
query := req.URL.Query()
query.Set("AWSAccessKeyId", cred.AccessKey)
query.Set("Expires", expires)
query.Set("Signature", preSignatureV2(cred, req.Method, path, query.Encode(), req.Header, expires))
req.URL.RawQuery = query.Encode()
identity, errCode := iam.doesPresignV2SignatureMatch(req)
if errCode != s3err.ErrNone {
t.Fatalf("doesPresignV2SignatureMatch() error = %v, want %v; path=%q escaped=%q",
errCode, s3err.ErrNone, req.URL.Path, req.URL.EscapedPath())
}
if identity == nil {
t.Fatal("Expected non-nil identity")
}
}
+23 -1
View File
@@ -25,6 +25,14 @@ type CircuitBreaker struct {
counters map[string]*int64
limitations map[string]int64
s3a *S3ApiServer
// Interceptor, if set, wraps the per-route handler ahead of ALL
// circuit-breaker logic (upload limiting and the breaker checks) and runs
// even when the breaker is disabled. It is a general per-request
// interceptor seam: an implementation may reject the request (write its own
// response and not call next) or wrap next to observe/shape it. Nil by
// default, so it is a no-op unless explicitly set.
Interceptor func(next http.HandlerFunc, action string) http.HandlerFunc
}
func NewCircuitBreaker(option *S3ApiServerOption) *CircuitBreaker {
@@ -92,7 +100,7 @@ func (cb *CircuitBreaker) loadCircuitBreakerConfig(cfg *s3_pb.S3CircuitBreakerCo
}
func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request), action string) (http.HandlerFunc, Action) {
return func(w http.ResponseWriter, r *http.Request) {
inner := func(w http.ResponseWriter, r *http.Request) {
// Apply upload limiting for write actions if configured
if cb.s3a != nil && (action == s3_constants.ACTION_WRITE) &&
(cb.s3a.option.ConcurrentUploadLimit != 0 || cb.s3a.option.ConcurrentFileUploadLimit != 0) {
@@ -161,6 +169,20 @@ func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request),
return
}
s3err.WriteErrorResponse(w, r, errCode)
}
// The interceptor is consulted per request rather than captured here, so it
// can be installed after the routes are registered (e.g. once the server and
// its dependencies are constructed) and so a nil CircuitBreaker is never
// dereferenced at registration time. When unset this is just a nil check.
// It runs outermost: before upload limiting and the breaker checks, and
// regardless of cb.Enabled.
return func(w http.ResponseWriter, r *http.Request) {
if cb.Interceptor != nil {
cb.Interceptor(inner, action)(w, r)
return
}
inner(w, r)
}, Action(action)
}
+97
View File
@@ -2,6 +2,7 @@ package s3api
import (
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
@@ -106,3 +107,99 @@ func doLimit(circuitBreaker *CircuitBreaker, routineCount int, r *http.Request,
}
return successCounter
}
// TestLimitInterceptor verifies the optional request interceptor: it is a no-op
// when nil, runs ahead of the (disabled) breaker logic, and can either reject a
// request or pass it through to the wrapped handler.
func TestLimitInterceptor(t *testing.T) {
readAction := s3_constants.ACTION_READ
newCB := func() *CircuitBreaker {
// Enabled defaults to false and s3a is nil, so without an interceptor
// Limit's handler falls straight through to the wrapped handler.
return &CircuitBreaker{counters: make(map[string]*int64), limitations: make(map[string]int64)}
}
// 1. nil interceptor must not change behavior: the handler still runs.
t.Run("nil interceptor is a no-op", func(t *testing.T) {
cb := newCB()
called := false
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { called = true }, readAction)
h(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if !called {
t.Fatal("handler should run when no interceptor is set")
}
})
// 2. a rejecting interceptor runs first and prevents the handler, even
// though the breaker itself is disabled.
t.Run("interceptor can reject", func(t *testing.T) {
cb := newCB()
var order []string
cb.Interceptor = func(next http.HandlerFunc, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
order = append(order, "interceptor")
s3err.WriteErrorResponse(w, r, s3err.ErrTooManyRequest) // reject; do not call next
}
}
handlerRan := false
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
handlerRan = true
order = append(order, "handler")
}, readAction)
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if handlerRan {
t.Fatal("a rejecting interceptor must prevent the handler from running")
}
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503 from ErrTooManyRequest, got %d", rec.Code)
}
if len(order) != 1 || order[0] != "interceptor" {
t.Fatalf("interceptor should run alone, got %v", order)
}
})
// 3. a pass-through interceptor runs before the handler and sees the action.
t.Run("interceptor can pass through", func(t *testing.T) {
cb := newCB()
var order []string
var seenAction string
cb.Interceptor = func(next http.HandlerFunc, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
seenAction = action
order = append(order, "interceptor")
next(w, r)
}
}
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
order = append(order, "handler")
}, readAction)
h(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if seenAction != readAction {
t.Fatalf("interceptor should receive the route action, got %q", seenAction)
}
if len(order) != 2 || order[0] != "interceptor" || order[1] != "handler" {
t.Fatalf("interceptor must run before the handler, got %v", order)
}
})
// 4. installed AFTER Limit() returns: still takes effect, because the
// interceptor is consulted per request rather than captured at
// registration time (the handlers are built during router registration,
// before dependencies that need the running server exist).
t.Run("interceptor installed after registration takes effect", func(t *testing.T) {
cb := newCB()
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {}, readAction) // built while nil
ran := false
cb.Interceptor = func(next http.HandlerFunc, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ran = true
next(w, r)
}
}
h(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if !ran {
t.Fatal("interceptor set after Limit() must still run (request-time evaluation)")
}
})
}
+127 -26
View File
@@ -16,6 +16,7 @@ import (
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
@@ -775,19 +776,24 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
return
}
// Handle remote storage objects: cache to local cluster if object is remote-only
// This uses singleflight to deduplicate concurrent caching requests for the same object
// On cache error, gracefully falls back to streaming from remote
if objectEntryForSSE.IsInRemoteOnly() {
objectEntryForSSE = s3a.cacheRemoteObjectWithDedup(r.Context(), bucket, object, objectEntryForSSE)
}
// Re-check bucket policy with object entry for tag-based conditions (e.g., s3:ExistingObjectTag)
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, string(s3_constants.ACTION_READ), objectEntryForSSE.Extended, "GetObjectHandler"); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
// Handle remote storage objects: initiate background caching without blocking
// This implements stream-through caching: serve first byte immediately while
// caching happens in the background, improving TTFB for large files
if objectEntryForSSE.IsInRemoteOnly() {
// Start background cache without waiting (non-blocking)
// Only after authorization passes to avoid cache side effects for denied requests
versionId := r.URL.Query().Get("versionId")
cacheVersionId := resolvedSourceVersionId(versionId, objectEntryForSSE)
s3a.startBackgroundRemoteCache(bucket, object, cacheVersionId, objectEntryForSSE)
// Continue with streaming immediately - will serve from remote or cached chunks
}
// Check if PartNumber query parameter is present (for multipart GET requests)
partNumberStr := r.URL.Query().Get("partNumber")
if partNumberStr == "" {
@@ -977,28 +983,31 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
len(chunks), totalSize, isRangeRequest, offset, size)
if len(chunks) == 0 {
// Check if this is a remote-only entry that needs caching
// This handles the case where initial caching attempt timed out or failed
// Check if this is a remote-only entry
if entry.IsInRemoteOnly() {
glog.V(1).Infof("streamFromVolumeServers: entry is remote-only, attempting to cache before streaming")
// Latest-version reads carry an empty query versionId even when the
// entry lives at .versions/v_<id>; resolve from the entry itself.
glog.V(1).Infof("streamFromVolumeServers: entry is remote-only, attempting stream-through cache")
cacheVersionId := resolvedSourceVersionId(versionId, entry)
cachedEntry := s3a.cacheRemoteObjectForStreaming(r, entry, bucket, object, cacheVersionId)
if cachedEntry != nil && len(cachedEntry.GetChunks()) > 0 {
cachedEntry, cacheErr := s3a.cacheRemoteObjectForStreamingWithShortTimeout(r, entry, bucket, object, cacheVersionId)
if cacheErr == nil && cachedEntry != nil && len(cachedEntry.GetChunks()) > 0 {
// Cache completed, use cached chunks
chunks = cachedEntry.GetChunks()
entry = cachedEntry
glog.V(1).Infof("streamFromVolumeServers: successfully cached remote object, got %d chunks", len(chunks))
} else {
// Client disconnected: report cancellation, not 503.
if ctxErr := r.Context().Err(); ctxErr != nil {
return ctxErr
} else if cacheErr != nil && !errors.Is(cacheErr, context.DeadlineExceeded) && !errors.Is(cacheErr, context.Canceled) && status.Code(cacheErr) != codes.DeadlineExceeded && status.Code(cacheErr) != codes.Canceled {
// Permanent error (e.g. not found, permission denied) - return final status
glog.Errorf("streamFromVolumeServers: permanent cache error for %s/%s: %v", bucket, object, cacheErr)
if status.Code(cacheErr) == codes.NotFound {
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
} else {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
}
// Cache still filling: 503 + Retry-After so SDKs back off and retry.
return newStreamErrorWithResponse(cacheErr)
} else {
// Cache not ready yet; return 503 with Retry-After for client backoff
glog.V(1).Infof("streamFromVolumeServers: remote object %s/%s not cached yet, returning 503 for retry", bucket, object)
w.Header().Set("Retry-After", "5")
w.Header().Set("Retry-After", "2")
s3err.WriteErrorResponse(w, r, s3err.ErrServiceUnavailable)
return newStreamErrorWithResponse(fmt.Errorf("remote object not cached yet"))
return newStreamErrorWithResponse(fmt.Errorf("remote object not cached yet, will be available on retry"))
}
} else if totalSize > 0 && len(entry.Content) == 0 {
// Not a remote entry but has size without content - this is a data integrity issue
@@ -3105,18 +3114,82 @@ func cachedEntryHasLocalData(entry *filer_pb.Entry) bool {
return entry != nil && (len(entry.GetChunks()) > 0 || len(entry.Content) > 0)
}
// remoteCacheStreamingTimeoutNS bounds (nanoseconds) how long the streaming read
// path waits for the filer to finish caching a remote-only object. Without a
// bound a multi-GB download outlasts the client's read timeout, so the request
// is canceled before the caller can emit 503 + Retry-After. Kept under common S3
// client read timeouts (~60s) given the 30s dedup attempt that precedes it.
// Atomic so tests can shorten it without racing the read path.
var remoteCacheStreamingTimeoutNS = int64(20 * time.Second)
// cacheRemoteObjectForStreamingWithShortTimeout polls for cache completion with an adaptive timeout.
// Timeout is based on file size: small files wait longer to maximize cache hits, large files
// fail-fast to improve TTFB. Returns the cached entry and error to allow callers to distinguish
// between transient errors (timeout) and permanent errors (not found, permission denied).
// The filer continues caching on detached context, so retry finds cached chunks.
func (s3a *S3ApiServer) cacheRemoteObjectForStreamingWithShortTimeout(r *http.Request, entry *filer_pb.Entry, bucket, object, versionId string) (*filer_pb.Entry, error) {
// Adaptive timeout: smaller files can afford to wait longer since cache completes faster
pollTimeout := 5 * time.Second
if entry.RemoteEntry != nil && entry.RemoteEntry.RemoteSize > 0 {
// For very large files (>500MB), use shorter timeout to improve TTFB
// For smaller files, allow longer to increase cache hit rate
remoteSize := entry.RemoteEntry.RemoteSize
if remoteSize > 500*1024*1024 {
pollTimeout = 2 * time.Second
} else if remoteSize < 50*1024*1024 {
pollTimeout = 10 * time.Second
}
}
cacheCtx, cancel := context.WithTimeout(r.Context(), pollTimeout)
defer cancel()
dir, name := s3a.buildVersionedRemoteObjectPath(bucket, object, versionId)
glog.V(2).Infof("cacheRemoteObjectForStreamingWithShortTimeout: polling cache status for %s/%s (timeout=%v)", dir, name, pollTimeout)
cachedEntry, err := s3a.doCacheRemoteObject(cacheCtx, dir, name)
if err != nil {
// Distinguish transient errors (timeout/cancellation) from permanent errors
if cacheCtx.Err() != nil {
glog.V(2).Infof("cacheRemoteObjectForStreamingWithShortTimeout: %s/%s not cached within %v", dir, name, pollTimeout)
return nil, cacheCtx.Err()
}
glog.V(2).Infof("cacheRemoteObjectForStreamingWithShortTimeout: cache error for %s/%s: %v", dir, name, err)
return nil, err
}
if cachedEntry != nil && len(cachedEntry.GetChunks()) > 0 {
glog.V(1).Infof("cacheRemoteObjectForStreamingWithShortTimeout: successfully cached %s/%s (%d chunks)", dir, name, len(cachedEntry.GetChunks()))
return cachedEntry, nil
}
return nil, nil
}
// cacheRemoteObjectForStreaming caches a remote-only object to the local cluster for streaming.
// Uses the request context (no artificial timeout) so the caching can complete.
// Returns the cached entry only when chunks are present; the streaming caller
// is not wired to read inline Content from a cache result here.
// Bounded so a slow large-file download returns to the caller (which emits 503 +
// Retry-After) before the client gives up; the filer keeps caching on a detached
// context, so a retry streams from the cached chunks. Returns the cached entry
// only when chunks are present; the caller cannot read inline Content here.
func (s3a *S3ApiServer) cacheRemoteObjectForStreaming(r *http.Request, entry *filer_pb.Entry, bucket, object, versionId string) *filer_pb.Entry {
timeout := time.Duration(atomic.LoadInt64(&remoteCacheStreamingTimeoutNS))
cacheCtx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
dir, name := s3a.buildVersionedRemoteObjectPath(bucket, object, versionId)
glog.V(1).Infof("cacheRemoteObjectForStreaming: caching %s/%s (remote size: %d, versionId: %s)", dir, name, entry.RemoteEntry.RemoteSize, versionId)
cachedEntry, err := s3a.doCacheRemoteObject(r.Context(), dir, name)
cachedEntry, err := s3a.doCacheRemoteObject(cacheCtx, dir, name)
if err != nil {
glog.Errorf("cacheRemoteObjectForStreaming: failed to cache %s/%s: %v", dir, name, err)
// A bounded-wait timeout (or client disconnect) is not a cache failure:
// the filer keeps downloading and the caller maps a nil return to 503.
if cacheCtx.Err() != nil {
glog.V(1).Infof("cacheRemoteObjectForStreaming: %s/%s not ready within %v (will retry)", dir, name, timeout)
} else {
glog.Errorf("cacheRemoteObjectForStreaming: failed to cache %s/%s: %v", dir, name, err)
}
return nil
}
@@ -3159,6 +3232,34 @@ func (s3a *S3ApiServer) cacheRemoteObjectForCopy(ctx context.Context, bucket, ob
return nil
}
// startBackgroundRemoteCache initiates caching without blocking the request.
// This enables fast TTFB: the client's request returns immediately (via 503 if not
// cached), while a background task fills the cache. Subsequent requests will find
// cached chunks via singleflight deduplication in the filer's CacheRemoteObjectToLocalCluster.
// Uses detached context with reasonable timeout to prevent goroutine pile-up.
func (s3a *S3ApiServer) startBackgroundRemoteCache(bucket, object, versionId string, entry *filer_pb.Entry) {
if !entry.IsInRemoteOnly() {
return
}
dir, name := s3a.buildVersionedRemoteObjectPath(bucket, object, versionId)
// Start background cache without blocking. The filer's CacheRemoteObjectToLocalCluster
// uses singleflight internally, so concurrent requests will all benefit from the same
// cache operation.
go func() {
// Use timeout to bound goroutine and prevent pile-up if RPC stalls under load
bgCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
_, err := s3a.doCacheRemoteObject(bgCtx, dir, name)
if err != nil {
glog.V(2).Infof("startBackgroundRemoteCache: cache failed for %s/%s: %v", bucket, object, err)
} else {
glog.V(2).Infof("startBackgroundRemoteCache: cached %s/%s in background", bucket, object)
}
}()
}
// resolvedSourceVersionId falls back to the version recorded on the entry
// when the request didn't carry one — necessary for latest-version reads
// in versioning-enabled buckets, where the entry lives at .versions/v_<id>.
+101
View File
@@ -1,13 +1,24 @@
package s3api
import (
"context"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// TestIsInRemoteOnly tests the IsInRemoteOnly method on filer_pb.Entry
@@ -484,3 +495,93 @@ func TestCopyObjectRemoteOnlySourceDetection(t *testing.T) {
})
}
}
// fakeCacheFiler is a minimal SeaweedFiler gRPC server whose
// CacheRemoteObjectToLocalCluster behavior is driven by a callback, so tests can
// model a slow (still-caching) filer or one that returns cached chunks.
type fakeCacheFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
cache func(context.Context, *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error)
}
func (f *fakeCacheFiler) CacheRemoteObjectToLocalCluster(ctx context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
return f.cache(ctx, req)
}
// startFakeCacheFiler serves impl on a random localhost port and returns the
// S3-style filer address whose ToGrpcAddress resolves back to that port.
func startFakeCacheFiler(t *testing.T, impl *fakeCacheFiler) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
srv := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(srv, impl)
go srv.Serve(lis)
t.Cleanup(srv.Stop)
port := lis.Addr().(*net.TCPAddr).Port
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", port))
}
func newRemoteCacheTestServer(filerAddr pb.ServerAddress) *S3ApiServer {
return &S3ApiServer{
option: &S3ApiServerOption{
Filers: []pb.ServerAddress{filerAddr},
BucketsPath: "/buckets",
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
}
func remoteOnlyEntry(name string, size int64) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: size}}
}
// TestCacheRemoteObjectForStreamingTimeout pins the fix for large-file cold
// GetObject: when the filer is still caching, the streaming path returns nil
// within its bound (so the handler emits 503 + Retry-After) instead of blocking
// on the raw request context until the client gives up.
func TestCacheRemoteObjectForStreamingTimeout(t *testing.T) {
filerAddr := startFakeCacheFiler(t, &fakeCacheFiler{
cache: func(ctx context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
<-ctx.Done() // never finishes within the bound
return nil, ctx.Err()
},
})
s3a := newRemoteCacheTestServer(filerAddr)
const shortTimeout = 200 * time.Millisecond
defer func(prev int64) { atomic.StoreInt64(&remoteCacheStreamingTimeoutNS, prev) }(atomic.LoadInt64(&remoteCacheStreamingTimeoutNS))
atomic.StoreInt64(&remoteCacheStreamingTimeoutNS, int64(shortTimeout))
r := httptest.NewRequest(http.MethodGet, "/mybucket/large.bin", nil)
start := time.Now()
got := s3a.cacheRemoteObjectForStreaming(r, remoteOnlyEntry("large.bin", 1<<30), "mybucket", "large.bin", "")
elapsed := time.Since(start)
assert.Nil(t, got, "uncached object must return nil so the caller maps to 503")
assert.GreaterOrEqual(t, elapsed, shortTimeout/2, "must wait on the bounded timeout, not return early on a setup error")
assert.Less(t, elapsed, 5*time.Second, "must not block on the full download")
assert.NoError(t, r.Context().Err(), "request context stays alive so the caller chooses 503, not cancellation")
}
// TestCacheRemoteObjectForStreamingCached confirms that once the filer reports
// local chunks, the streaming path returns the cached entry to stream from.
func TestCacheRemoteObjectForStreamingCached(t *testing.T) {
filerAddr := startFakeCacheFiler(t, &fakeCacheFiler{
cache: func(ctx context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
return &filer_pb.CacheRemoteObjectToLocalClusterResponse{
Entry: &filer_pb.Entry{
Name: req.Name,
Chunks: []*filer_pb.FileChunk{{FileId: "1,abc", Size: 100, Offset: 0}},
},
}, nil
},
})
s3a := newRemoteCacheTestServer(filerAddr)
r := httptest.NewRequest(http.MethodGet, "/mybucket/obj.bin", nil)
got := s3a.cacheRemoteObjectForStreaming(r, remoteOnlyEntry("obj.bin", 100), "mybucket", "obj.bin", "")
require.NotNil(t, got)
assert.Len(t, got.GetChunks(), 1)
}
+3 -3
View File
@@ -120,9 +120,9 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
if !ms.Topo.IsLeader() {
// tell the volume servers about the leader
newLeader, err := ms.Topo.MaybeLeader()
if err != nil || newLeader == "" {
glog.Warningf("SendHeartbeat find leader: %v, %v", newLeader, err)
newLeader, err := ms.Topo.Leader()
if err != nil {
glog.Warningf("SendHeartbeat find leader: %v", err)
return raft.NotLeaderError
}
if err := stream.Send(&master_pb.HeartbeatResponse{
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more