Compare commits

..
Author SHA1 Message Date
Chris Lu 1fe294fd44 fix(fuse-tests): drop glog globals from TestWriteBufferCap mount options
-logtostderr and -v are glog globals parsed before the subcommand; weed
mount's flag set rejects them, so the mount process exited with a usage
error and the test silently ran against the local disk (masked until
waitForMount started verifying a real mount). glog already writes to
stderr here by default, so the options were also redundant.
2026-07-02 15:47:41 -07:00
Chris Lu 57246c345b fix(fuse-tests): don't declare the FUSE mount ready before it is mounted
waitForMount probed the mount point with stat+ReadDir, which a bare local
directory also passes, so Setup could return before the weed mount process
finished mounting. Tests then wrote to the local disk underneath the mount
point; when the mount activated it shadowed those files, producing the
intermittent TestConcurrentFileOperations/ConcurrentReadWrite ENOENT with
an empty ReadDir. Require the mount point's device ID to differ from its
parent's before reporting ready.
2026-07-02 13:27:07 -07:00
Chris Lu 77694d3a93 s3: surface transient store errors during multipart resume/copy instead of masking them (#10207)
* s3: surface multipart-list store errors instead of masking them

listMultipartUploads masked a filer/metadata-store list error as an empty
200 response, and listObjectParts masked it as NoSuchUpload. A client
resuming a multipart upload (the Docker Registry S3 driver resolves an
in-progress upload via ListMultipartUploads, then ListParts) reads either
as "upload gone" and fails the upload permanently with a non-retryable
error. Return ErrInternalError so a transient store error stays retryable,
keeping ErrNotFound as an empty list / NoSuchUpload respectively.

* s3: return retryable error for transient CopyObject source lookups

Resolving the copy source is reported as InvalidArgument ("Copy Source must
mention the source bucket and key") whenever the lookup returns any error,
including a transient store error. Clients don't retry a 400, so a resumable
blob commit fails permanently. Keep the client error for a missing, invalid,
directory, or delete-marker source; map a transient store error to
ErrInternalError.

* s3: mark versioned lookup miss with the not-found sentinel

recoverLatestVersionWithoutPointer's terminal miss (a .versions directory
with no pointer, no versions, and no null object) returned a plain error,
so errors.Is-based callers could not tell this designed NoSuchKey state
from a store failure and reported it as an internal error.

* s3: reject a delete-marker copy source with NoSuchKey

getLatestObjectVersion returns the delete-marker entry when the latest
version is a delete marker, and the copy handlers copied its empty stub
into the destination. Every other handler detects ExtDeleteMarkerKey and
answers NoSuchKey; do the same for CopyObject and UploadPartCopy.

* s3: align copy-source not-found detection with the grpc status idiom

The lookup path canonicalizes text-form not-found into the sentinel in
filer_pb.LookupEntry and wraps with %w after that, so matching sentinel
text here was unreachable -- and risky, since a store error whose message
merely mentions the sentinel would be downgraded to a terminal 400.
Match the raw grpc NotFound code instead, like the other version-lookup
sites, and give transient filer errors the 503 that the upload-entry
lookup in this file already returns.

* s3: keep source-bucket versioning lookup errors retryable in copy

CopyObject and UploadPartCopy mapped any source-bucket versioning-state
lookup error to a terminal InvalidCopySource, including transient store
errors; getVersioningState signals a missing bucket with the not-found
sentinel, so split on that and let real store errors surface as 500, the
same mapping the destination-bucket lookup already uses.

* s3: match grpc-transported not-found in multipart list error paths

The list client path returns raw grpc status errors without the sentinel
reconstruction that lookups get in filer_pb.LookupEntry, so errors.Is on
the not-found sentinel never matched a store-reported missing directory;
match the sentinel text as well via a shared helper. The common missing-
directory case still lists as empty with no error and is unaffected.

* s3: complete and abort multipart surface store errors

prepareMultipartCompletionState mapped any upload-directory list or
lookup error to NoSuchUpload, so a transient store error at completion
time made the client discard a fully-uploaded object as gone. Split on
not-found like the sibling listing paths. abortMultipartUpload did the
same on s3a.exists, whose errors are never not-found (filer_pb.Exists
reports that as false with no error) -- a store failure there answered
NoSuchUpload and silently leaked the uploaded parts.

* s3: reject part numbers below 1 in UploadPartCopy

Only the upper bound was checked, unlike PutObjectPart; partNumber=0
passed the route regex and validation and wrote an out-of-range
0000_copy.part into the upload directory.
2026-07-02 13:25:04 -07:00
Chris Lu 9b1ff91949 filer: stream offloaded metadata-log entries to fix concurrent-write OOM (#10203)
* filer: stream offloaded metadata-log entries instead of buffering whole files

The client metadata-chunks read path (ReadLogFileRefs, used by the meta
aggregator to consume peer filers and by mounts) decoded every entry of a
log file into a slice before handing it to the consumer, and prefetched the
next whole file the same way. Peak memory scaled with log-file size: under
heavy concurrent writes the per-event chunk lists grow and minute-files reach
hundreds of MB to GBs, so a filer aggregating a few peers held many GBs of
decoded entries at once (heap dominated by readLogFileEntries ->
consumeBytesNoZero) and OOMed.

Stream entries through a bounded channel: a producer decodes one entry at a
time and the next file's read overlaps processing via the channel buffer, so
peak memory is bounded by the channel depth rather than O(file size). In a
synthetic replay peak live heap dropped from ~1.3x the file size to a flat
few MB regardless of file size.

* filer: tighten offload replay tests

Share one ordered-replay assertion between the merge-order and single-filer
tests, assert the callback's own error is what propagates, and drop atomic
counters from callbacks that run on a single goroutine.

* filer: abort offloaded log replay promptly instead of joining wedged readers

Collapse the single-filer fast path into the merged reader: it was a second
copy of the producer/stop lifecycle with its own subtler synchronization, and
a one-stream merge does the same job.

On abort (processing error or a fatal read error from one filer), the
consumer used to drain channels and join every producer. A producer blocked
in an uncancellable chunk read cannot observe stop until that read returns,
so an abort could stall the caller's retry loop behind a dead volume-server
connection. Closing stop is now the only cleanup: producers check it at every
send and file boundary and exit on their own, and the merge loop's blocking
receives also escape on stop. Producers also check stop before opening each
file, so an aborted replay no longer keeps reading remaining files whose
entries never reach the channel.

A mid-file chunk-not-found still skips to the next file, but the log line now
reports how many entries were delivered first instead of pretending the whole
file was skipped; the redundant error log before setFatal is gone since the
error propagates to callers that already log it.

* filer: cap offloaded log entry allocation against corrupt size prefix

A garbage 4-byte size prefix (torn chunk or stream desync) drove
make([]byte, size) up to 4GiB per entry. Reject sizes above the same 1GiB
bound the filer-side log readers enforce.
2026-07-02 12:34:03 -07:00
Chris LuandMorezMartin b0d1786c28 feat(k8s): filer HTTP + gRPC ingress for the Helm chart (#10205)
* feat(k8s): add HTTP + gRPC Ingress templates for filer

Add HTTP and gRPC Ingress templates for the filer component in both
standalone and all-in-one modes. The HTTP ingress handles REST API
traffic, the gRPC ingress exposes the gRPC endpoint with proper
annotations for nginx and Traefik.

Additionally add Traefik IngressRouteTCP for mTLS filer gRPC passthrough.
When the filer has mTLS enabled, the standard HTTP Ingress terminates TLS
at the ingress level which conflicts with the filer's mutual-TLS requirement.
IngressRouteTCP forwards raw TCP with tls.passthrough: true so the TLS
negotiation happens directly between client and filer.

Refs: PR #10035 (original fix-grpc-filer)

Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf)

* feat(k8s): restructure filer ingress into ingresses.{http,grpc}

Split the single filer ingress value into http and grpc sub-structures
so the HTTP Ingress and gRPC Ingress templates each have their own
configuration.

* k8s: document nginx ssl-passthrough for end-to-end mTLS gRPC

The filer's mTLS gRPC needs the TLS stream to reach the filer intact,
which an L7 Ingress can't do when it terminates TLS. Document the
ingress-nginx ssl-passthrough annotation on the gRPC ingress so the
whole chart stays on the standard Ingress kind, no controller-specific
CRD required.

* k8s: align filer ingress with the volume/admin ingress pattern

Only render ingressClassName when a class is set (an empty value opts out
of the cluster's default IngressClass), fall back to the
kubernetes.io/ingress.class annotation on k8s <1.18, version-gate
pathType, and quote the host so wildcard hosts stay valid YAML.

* k8s: route the filer gRPC ingress at / with Prefix

gRPC methods are called at /<package>.<Service>/<Method>; the HTTP UI
regex path never matches them, so gRPC requests would 404.

---------

Co-authored-by: MorezMartin <martin.morez@morez.org>
2026-07-02 12:01:37 -07:00
Chris Lu 01406e661a weed shell: add ec.shard.unmount command (#10204)
Unmount, and optionally delete, EC volume shards from the shell, so broken
or over-replicated shards can be handled without stopping volume servers and
deleting files by hand.

Default action is unmount; --delete also removes the shard files. Targets
resolve against the live topology, with shardId:host:port to disambiguate
co-located or over-replicated shards. Dry-run by default; pass --apply.
2026-07-02 11:58:08 -07:00
292abfae33 [filer] applyStorageDefaultsToEntry before CreateEntry (#10196)
* applyStorageDefaultsToEntry befor CreateEntry

* Update weed/server/filer_grpc_server.go

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* Update weed/server/filer_grpc_server.go

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* add tests

* fix: tests

* enforce read-only storage rule regardless of explicit TTL, match CreateEntry remote handling

* CreateEntry shares applyStorageDefaultsToEntry

* routed PUT enforces the path rule's max file name length

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Konstantin Lebedev <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-02 11:56:49 -07:00
0ead130bfc feat(k8s): add certificates.dnsNames to inject custom SANs in cert-manager certs (#10198)
* feat(k8s): add certificates.dnsNames to inject custom SANs in cert-manager certs

Add certificates.dnsNames configuration option that allows users to
inject custom Subject Alternative Names (SANs) into all cert-manager
Certificate resources. This enables exposing SeaweedFS components
under custom hostnames/CN that aren't covered by the default
wildcard patterns (e.g., '*.filer.default.svc').

The dnsNames list is iterated over in all 6 cert templates
(admin, client, filer, master, volume, worker) and appended to
the spec.x509.subject.names list.

Refs: PR #10035 (original fix-grpc-filer)

Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf)

* k8s: quote certificates.dnsNames entries so wildcard SANs render valid YAML

---------

Co-authored-by: MorezMartin <martin.morez@morez.org>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-02 10:05:20 -07:00
Chris Lu c46526822b s3: embedded IAM inline policy honors prefix-scoped resources (#10192)
* s3: embedded IAM inline policy honors prefix-scoped resources

getActions stripped the trailing wildcard from a resource like
arn:aws:s3:::bucket/prefix/*, producing a non-wildcard action
(Write:bucket/prefix) that CanDo only ever matched at bucket level, so
PutObject under the prefix was denied. Preserve the object path with its
wildcard (Write:bucket/prefix/*) to match objects under the prefix,
matching the standalone iamapi behavior.

* s3: prune bucket-confined wildcard actions on bucket delete

actionScopedToBucket treated any wildcard as multi-bucket, so a
prefix-scoped action like Write:bucket/prefix/* survived deletion of its
own bucket and could re-grant access if the bucket was recreated. Scope
the wildcard check to the bucket segment only: a wildcard in the object
path stays scoped to its bucket, while one in the bucket segment does
not.
2026-07-02 09:14:54 -07:00
cc4043c9d2 fix(volume [rust]): compare live compaction_revision instead of stale last_compact_revision (#10189)
* fix(volume [rust]): compare live compaction_revision instead of stale last_compact_revision

* fix(volume [rust]): compare live compaction_revision instead of stale last_compact_revision - unit tests

* s3: invalidate stale reader cache locations on chunk read failure (#10156)

* s3: invalidate stale reader cache locations on chunk read failure

* filer: share the chunk-read self-heal across reader cache and streaming paths

The reader cache retry added a third copy of the invalidate-relookup-compare-retry
dance already inlined in PrepareStreamContentWithThrottler and duplicated in
retryWithCacheInvalidation. Extract retryFetchWithFreshLocations and route all
three through it, parameterized by the refetch primitive.

* filer: drop redundant completedTimeNew store in reader cache success path

startCaching already stamps completedTimeNew unconditionally before the
fetchErr branch; the second store inside the success branch is dead.

* filer: make NewReaderCache cache invalidator an explicit parameter

The variadic ...CacheInvalidator only ever read the first element, so a caller
could pass two and silently get one. Take a single explicit argument and have
the non-S3 callers pass nil.

* filer: inject reader cache chunk fetch as a struct field

Replace the process-global readerCacheFetchChunkData test seam with a
per-instance fetchChunkDataFn field defaulted in NewReaderCache, matching how
lookupFileIdFn is already wired. Tests set the field on the cache instead of
swapping a shared global.

* filer: log the location count, not full URLs, on self-heal retry

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>

* fix(shell): honor explicit fs.mergeVolumes from/to direction (#10159)

* fix(shell): honor explicit fs.mergeVolumes from/to direction

mergeVolumes only ever merged a smaller volume into a larger one. When the
user named both -fromVolumeId and -toVolumeId with the source larger than the
target, the planner produced an empty plan and the command printed just
"max volume size: N MB" and moved nothing.

Build the requested pair directly when both ids are given, instead of routing
through the size-descending heuristic. Read-only, empty, and wrong-collection
endpoints are rejected with a clear error rather than a silent no-op.

* fix(shell): allow fs.mergeVolumes into an empty target volume

Merging chunks into an empty volume is valid, e.g. consolidating data into a
freshly created or recently vacuumed volume. Only reject an empty source, which
has nothing to move.

* fix(shell): reject self-map in directed mergeVolumes planner

createMergePlan with from == to returned a {vid: vid} self-merge when called
directly. Guard it in the planner so it is correct independent of the Do
entrypoint.

* fix(volume [rust]): compare compaction_revision in u32, not truncated u16

`req.compaction_revision as u16` truncates any request value above 65535, so a
stale revision of 65537 aliases to a live revision of 1 and the "is compacted"
guard wrongly passes. Widen the volume's revision to u32 and compare there,
matching Go's uint32(v.CompactionRevision) != req.CompactionRevision.

---------

Co-authored-by: adri <adri@digitalunited.net>
Co-authored-by: Aleksey <48918167+MilanFun@users.noreply.github.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-07-01 21:36:44 -07:00
Chris Lu ece4f42ecd fix(filer): avoid ReaderCache WaitGroup reuse race between reads and destroy (#10190)
filer: count reader on cacher waitgroup under the map lock

The read's wg.Add(1) ran after ReadChunkAt released the ReaderCache lock, so a
concurrent destroy() (error eviction, LRU, or UnCache) could start wg.Wait() on
a zero counter and then race the Add - a WaitGroup reuse that trips -race and
can panic. Move the Add under the lock, before the cacher can leave the
downloaders map, so a destroy is always ordered against a counted read.
2026-07-01 21:17:46 -07:00
Chris Lu 155140bed8 s3: return IncompleteBody instead of 500 for truncated PUT bodies (#10186)
* s3: add IncompleteBody error code

* operation: tag a truncated source read as ErrTruncatedBody

The chunked uploader wraps both source-read failures and volume-upload failures,
and a mid-write volume server drop also carries io.ErrUnexpectedEOF. Tag only the
source read so callers can tell a truncated input apart from a server-side fault.

* s3: return IncompleteBody for a truncated PUT body

A client abort or reverse-proxy timeout truncates the request body mid-upload.
putToFiler mapped every streaming-upload failure to InternalError (500), which a
reverse proxy relays as a 502. Classify a source-read truncation as IncompleteBody
(400) so the response matches AWS and passes through. All S3 write paths share
putToFiler, so they all benefit.
2026-07-01 18:45:17 -07:00
Chris Lu cf64cafc3b volume: drop stale volume-location cache on under-replication (#10185)
* volume: drop stale volume-location cache on under-replication

A replicated write looks up the volume's locations and caches them for 10
minutes. When the master briefly reports fewer replicas than the copy count
(e.g. a stale heartbeat drops a just-added volume), that under-replicated
result got cached, so every write failed with "replicating operations is less
than replication copy count" until the entry expired -- long after the master
re-registered the replica.

Invalidate the cached entry when the location count is below the copy count, so
the next write re-queries the master and recovers as soon as it heals.

* volume: mirror the replication copy-count guard in seaweed-volume

do_replicated_request accepted a write even when the master reported fewer
locations than the volume's copy count, silently under-replicating. Reject it,
matching Go's GetWritableRemoteReplications. lookup_volume is uncached, so the
next write recovers as soon as the missing replica re-registers.
2026-07-01 13:51:59 -07:00
Chris Lu f6032cf23d fix(ec): read chunk-manifest chunks stored on EC volumes (rust volume server) (#10187)
* fix(ec): read chunk-manifest chunks stored on EC volumes

Chunk-manifest expansion read every chunk through store.read_volume_needle,
which only resolves a local regular volume. Once a chunk's volume is
EC-encoded, that lookup returns NotFound and the GET fails 500 with
"read chunk ...: not found", so a chunked object over an EC tier is
unreadable even though its parity is intact and reconstructable.

Resolve each chunk to wherever it lives — a local regular volume, a
local EC volume (reconstruct-on-read from the surviving shards), or a
peer via master lookup — matching Go's ChunkedFileReader, which never
assumes chunks are local regular needles.

* fix(ec): validate the chunk cookie on local manifest chunk reads

A chunk fetched from a peer is cookie-checked by that peer's GET handler,
but the local regular and EC reads returned data without comparing the
needle's cookie to the one in the chunk fid. Check it, matching the main
GET paths, so a stale or guessed id can't serve another needle's bytes.

* fix(ec): clamp manifest chunk copy to its declared size

Expansion writes each chunk into result[offset..] by offset, so a chunk
whose bytes exceed its declared size could overwrite the next chunk's
window. Clamp the copy to chunk.size (and reject a negative size) so an
over-long or malformed chunk stays within its own range.
2026-07-01 13:38:34 -07:00
Chris Lu 746ed82662 remote.meta.sync: sync directories and remove files deleted from remote (#10184)
* remote.meta.sync: materialize directory entries, including empty ones

Pull metadata by walking the remote tree one directory level at a time
with a delimiter, so subdirectories, including empty ones, are listed as
their own entries and created locally. The previous flat listing only
returned files, so empty remote directories never appeared locally and
non-empty ones only existed as filer-synthesized parents.

* remote.meta.sync: remove local metadata for entries deleted from remote

After reconciling each directory, drop local entries whose remote source
is gone: files are deleted outright, and a directory removed from the
remote is descended into so its remote-backed children are cleaned while
local-only entries are kept. remote.meta.sync exposes -delete (default
on) and remote.mount.buckets reconciles the same way; a plain
remote.mount stays additive.

* remote.meta.sync: reconcile type swaps and prune emptied directories

- when the remote swaps an entry's type (file <-> directory), drop the
  stale local entry and recreate it with the right type; local-only
  entries are left alone
- mark synced directories remote-backed and clean a directory removed
  from the remote locally, deleting it once it holds no local-only
  entries, instead of re-listing the missing remote path
- treat a differing remote size or mtime, not only a newer mtime, as a
  change worth pulling
2026-07-01 12:14:19 -07:00
Kwak Byoung MinandChris Lu 9d75048594 admin: respect filerGroup for cluster discovery (#10170)
* Respect filerGroup in admin discovery

Admin discovery previously queried master cluster nodes with an empty filer group, so filers registered under a non-default group could not appear in the admin UI. Add an admin filerGroup flag and carry it through cluster-node discovery requests while preserving the empty default behavior.

Constraint: SeaweedFS master ListClusterNodes filters by exact filer_group.

Rejected: Discover all groups implicitly | no existing admin or shell behavior exposes cross-group discovery.

Confidence: high

Scope-risk: narrow

Directive: Keep admin cluster discovery scoped to the configured filerGroup unless an explicit all-groups API is added.

Tested: docker run --rm -v "$PWD:/src" -w /src golang:1.25 go test ./weed/admin/dash -run TestListClusterNodesRequest -count=1

Tested: docker run --rm -v "$PWD:/src" -w /src golang:1.25 go test ./weed/command -run '^$' -count=1

Not-tested: full repository test suite

* mini: pass filer group to admin cluster discovery

miniAdminOptions.filerGroup was never initialized, so startAdminServer
dereferenced a nil *string. Share the filer.filerGroup flag pointer so the
co-located admin queries the same group the filer registers under.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-01 10:56:58 -07:00
Jaehoon KimandChris Lu ebeab4b6ec feat(filer.sync.verify): reclassify chunk-slice-order ETag diffs as CHUNK_REORDER (#10177)
* feat(filer.sync.verify): reclassify chunk-slice-order ETag diffs as CHUNK_REORDER

filer.ETagChunks concatenates per-chunk MD5s in stored slice order without
normalising by offset, so byte-identical content written by two different paths
(S3 multipart part-completion order on the source vs filer.backup replication
arrival order on the destination) yields different file ETags. filer.sync.verify
reported these as ETAG_MISMATCH even though the files are equal.

Add a second-pass check on every ETAG_MISMATCH: when both sides derive their ETag
from chunks (no attr.Md5) and hold a manifest-free, non-overlapping chunk set
that, once sorted by offset, matches element-wise on (offset, size, ETag),
classify the file as CHUNK_REORDER. Such files are content-equal, so they are
not counted as errors and do not affect the exit code; they are listed only at
higher verbosity (weed -v=1), while the summary always shows their count.

The check stays conservative: a stored attr.Md5 (order-independent content
hash), a differing chunk count, an overlapping/duplicate offset (whose visible
bytes are resolved by timestamp), or a manifest chunk all remain ETAG_MISMATCH.

* filer.sync.verify: decline chunk-reorder fast path on empty per-chunk ETag

An empty or undecodable per-chunk ETag is not a content fingerprint, so
element-wise (offset, size, ETag) equality can't prove the bytes match.
Treating "" == "" as content-equal could reclassify a genuine divergence as
CHUNK_REORDER and drop it from the error count. Decline such chunk sets so they
stay ETAG_MISMATCH.

* filer.sync.verify: emit CHUNK_REORDER in JSON output regardless of -v

The -v=1 gate belongs to the human text report only. Applying it before the
jsonOutput branch dropped the per-file CHUNK_REORDER records from NDJSON while
the summary still counted them, so a machine consumer saw a non-zero count with
no records to reconcile it. Gate the text path only; JSON always emits.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-01 10:38:21 -07:00
Chris Lu e6441d84e0 deps: update x/image and thrift for high-severity advisories (#10179)
deps: bump x/image to v0.43.0, repin thrift to CVE-fixed 32-bit-safe commit

x/image v0.41.0 -> v0.43.0 clears CVE-2026-33813/-46601/-46602/-46604.

thrift's only Go-affecting advisory, CVE-2026-41602 (HIGH), is fixed in
v0.23.0, but that release compares an int against untyped math.MaxUint32 in
framed_transport.go and fails to compile on 32-bit (linux/386, arm/v7).
Upstream fixed the range check post-release without tagging it, so replace
now points at that commit: it carries the CVE fix and builds on 32-bit.
Revert to a plain require once thrift tags a release past v0.23.0.
2026-07-01 10:28:02 -07:00
Chris Lu 05b4b5bf56 ec: expose force_deleted_needles_check in ScrubEcVolume RPC and shell (#10176)
* ec: expose force_deleted_needles_check in ScrubEcVolume RPC and shell

FULL EC scrubs can opt into strict deleted-needle verification via the
-forceDeletedNeedlesCheck shell flag, off by default since it can report
false positives when EC indexes disagree. Rejected for non-FULL modes.

The Rust volume server parses the new field and ignores it: its FULL
scrub verifies shards via RS parity, not per-needle reads.

* volume: require admin auth for ScrubEcVolume

ScrubEcVolume ran unauthenticated while its sibling ScrubVolume, and the
rest of the mutating volume handlers, gate on checkGrpcAdminAuth. Close
the gap so an EC scrub can't be triggered anonymously.

* shell: reject ec.scrub -forceDeletedNeedlesCheck outside full mode

Fail in the client before fanning out to every volume server, instead of
erroring halfway through once the servers reject the request.
2026-06-30 23:20:50 -07:00
Chris Lu b872d5e683 balance: extract the bytes-aware density metric to a shared package (#10174)
* balance: extract the bytes-aware density metric to weed/topology/balancer

The shell's volume.balance ranks servers by a bytes-aware density (used volume
equivalents over free capacity). Move that math into the shared balancer package
(VolumeDensity / DensityRatio / DensityNextRatio) so the maintenance worker can
adopt the same metric next. Shell behavior is unchanged.

* balance: rank a server with no free capacity as the fullest

DensityRatio/DensityNextRatio divided by capacity, so a server past its slot
limit (negative capacity) returned a negative ratio and sorted as the emptiest
under ascending consumers — the opposite of reality. Treat any non-positive
capacity (full, or overfull mid-run after receiving volumes) as the fullest
(+Inf) so it is a move source, never a target. Covered by negative-capacity and
ordering tests.
2026-06-30 21:26:57 -07:00
Chris Lu 430d4b5394 kms: cache decrypted data keys so cache_enabled/cache_ttl take effect (#10173)
* kms: cache decrypted data keys so cache_enabled/cache_ttl take effect

cache_enabled/cache_ttl were parsed into KMSConfig but never consulted,
so every SSE-KMS read repeated a KMS Decrypt round-trip. Add a
CachedKMSProvider decorator keyed on (ciphertext, encryption context)
and wrap providers with it wherever one is created. Decrypt is
deterministic for that pair; GenerateDataKey/DescribeKey/GetKeyID pass
through untouched.

Cache hits and stores return private copies so the read path's
ClearSensitiveData can't wipe the cached key. TTL and max_cache_size
bound the cache.

* kms: zero superseded data keys and pool cache-key hash states

Wipe the old plaintext when a cache entry is overwritten so a key
material buffer left behind by two readers racing on the same miss does
not linger in memory. Reuse sha256 states via a sync.Pool so the read
hot path stops allocating a fresh hash on every Decrypt.

* kms: drop cache writes after Close

An in-flight Decrypt miss can call set after Close scrubbed the map,
repopulating it with a data key that would then never be cleared. Guard
set with a closed flag so post-Close stores wipe their copy and no-op.
2026-06-30 21:23:53 -07:00
Chris Lu 36e51e5542 admin: fix 'send on closed channel' panic in worker gRPC server (#10175)
* admin: never close the worker outgoing channel while senders are live

conn.outgoing has multiple concurrent senders (heartbeat, task assignment,
log request, registration handlers). Closing it on connection teardown raced
a sender and paniced with "send on closed channel" — reliably reproduced when
a laptop goes idle: heartbeats stall past the 2-minute stale cutoff, the
cleanup routine closes the channel, and the resumed worker's heartbeat is
received and handled at the same moment.

The connection context is already the sole teardown signal, so stop closing
the channel entirely. handleOutgoingMessages exits on conn.ctx.Done(), and the
buffered channel is GC'd once the connection drops. Route sends through a
sendToWorker helper that also selects on conn.ctx.Done() so they bail on
teardown instead of blocking for the full timeout.

* admin: bail on ctx.Done() while waiting for a worker log response
2026-06-30 21:22:28 -07:00
bdcc3154ed refactor: centralize genUploadUrl in UploadOption (#10164)
* refactor: centralize genUploadUrl in UploadOption

Replace inline genFileUrlFn closures with operation.GenUploadUrl field:

- Add GenUploadUrl func(host, fileId) string to UploadOption struct
- Add GenUploadUrlProxy(filerAddress string) utility function
- Remove genFileUrlFn parameter from UploadWithRetry signature
- Update all callers: mount, gateway, mq, filer_copy, filer_sync

This matches the weed mount -filerProxy pattern exactly,
factorizing the URL generation logic across all consumers.

Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf)

* docker release: run all platform jobs in one wave, cache rocksdb compile

Drop max-parallel so the 13 per-platform builds run together instead of two
waves of 8 (rocksdb was queuing behind the cap and starting ~8 min late).

Keep cache-to mode=max for rocksdb: its RocksDB static_lib compile is
sha-independent, so it caches across releases and stops being the ~16-min
long-pole that gates the merge fan-in. go-build variants stay mode=min.

Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf)

* refactor: centralize genUploadUrl in UploadOption

Replace inline genFileUrlFn closures with operation.GenUploadUrl field:

- Add GenUploadUrl func(host, fileId) string to UploadOption struct
- Add GenUploadUrlProxy(filerAddress string) utility function
- Remove genFileUrlFn parameter from UploadWithRetry signature
- Update all callers: mount, gateway, mq, filer_copy, filer_sync

This matches the weed mount -filerProxy pattern exactly,
factorizing the URL generation logic across all consumers.

Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf)

* Remove accidental ROCmFPX submodule reference

* gofmt chunk upload option block

* Preserve broker cipher and re-read proxy filer per upload attempt

Chunk uploads must keep the configured Cipher, and both the mount and broker current filer can change on failover, so build the proxy upload URL inside the closure instead of capturing the address once.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-30 20:45:43 -07:00
Chris Lu ce3ba31bcd fix(ec): reject oversized bitrot payload before narrowing to u32 (#10172)
save_bitrot_sidecar writes payload.len() into the header as a u32; guard against
a payload > 1 GiB (which would silently truncate the length field), mirroring
Go's SaveBitrotSidecar maxBitrotPayloadSize check. The check uses encoded_len()
before serializing, so an oversized manifest never allocates a large buffer.
Never triggers for a real sidecar (a few KB).

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 20:43:11 -07:00
Chris Lu b4a99b996d feat(ec): EC bitrot CHECKSUM scrub on the Rust volume server (#10154)
* proto: add EC bitrot checksum messages + CHECKSUM scrub mode

Mirror weed/pb/volume_server.proto byte-for-byte (field numbers + types) so the
.ecsum sidecar payload is wire-identical across the Go and Rust binaries:
EcBitrotProtection / EcShardChecksums / ChecksumAlgorithm, VolumeScrubMode.CHECKSUM=4,
and VolumeEcShardsCopyRequest.copy_ecsum_file. No code uses them yet — the .ecsum
format, producer, mount-load, copy, and scrub land in following commits.

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

* feat(ec): port the .ecsum bitrot checksum module

ec_bitrot.rs mirrors weed/storage/erasure_coding/ec_bitrot.go: the .ecsum sidecar
format (14-byte big-endian ECSU header + CRC32C over a prost-serialized
EcBitrotProtection payload), the per-shard per-block CRC32C producer
(ShardChecksumBuilder), save/load with payload self-integrity, manifest
validation, status resolution, and verify_shard_file_blocks for the CHECKSUM
scrub. A byte-exact test pins the serialized bytes against the Go reference's
identical constant so a format drift in either binary fails loudly.

Producer wiring (encode/vacuum), mount-load, copy, and the mode-4 dispatch land
in following commits.

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

* test(ec): pin .ecsum sidecar bytes for cross-binary interop

Deterministic EcBitrotProtection -> exact on-disk bytes, asserted against a
canonical constant on BOTH sides (this test and ec_bitrot.rs), so a format drift
in either binary fails its own suite rather than silently desyncing a Go-written
.ecsum from a Rust-written one.

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

* feat(ec): write the .ecsum bitrot sidecar during EC encode

write_ec_files now feeds each shard's bytes through a per-shard
ShardChecksumBuilder as it writes them, then persists the generation-0 sidecar
(<base>.ecsum) alongside the shards — mirroring weed's WriteEcFiles +
SaveBitrotSidecar. Best-effort: a failed sidecar write leaves the generation
unprotected rather than failing the encode. A test confirms the produced sidecar
validates and its per-block CRCs match every on-disk shard.

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

* feat(ec): load the .ecsum at mount + EcVolume::checksum_scrub

EcVolume now loads and validates its generation-0 .ecsum sidecar at mount,
caching the parsed protection + BitrotStatus (Off/On/Invalid), and exposes
bitrot_protection() mirroring Go's EcVolume.BitrotProtection(). checksum_scrub()
verifies every locally-held shard's raw bytes against the sidecar block CRCs —
the only path that exercises cold parity shards — reporting mismatched shards
without mutating anything; a wholesale mismatch beyond parity is flagged as a
suspect sidecar rather than mass shard corruption. Mirrors Go's ChecksumScrub.

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

* feat(scrub): dispatch EC CHECKSUM (mode 4) to checksum_scrub

Accept VolumeScrubMode.CHECKSUM=4 and route it to EcVolume::checksum_scrub,
accumulating blocks scanned + mismatched shards into the scrub response, plus the
CHECKSUM scrub-mode metric label. Read-only bitrot verification over local shards.

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

* feat(ec): copy the .ecsum sidecar during VolumeEcShardsCopy

Honor copy_ecsum_file: when set, copy the generation-0 .ecsum alongside the
shards so protection travels with them, mirroring Go's non-2PC copy path.
Tolerant of a missing source (empty stream) — the 0-byte file is dropped so
mount sees no sidecar (protection off) rather than a truncated/invalid one.

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

* feat(ec): remove the .ecsum sidecars when destroying an EC volume

remove_ec_volume_files now clears <base>.ecsum (and any versioned .ecsum.v<N>)
from the data and idx dirs, so a vid reuse can't load a stale sidecar. Mirrors
Go's removeBitrotSidecars.

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

* style(ec): align bitrot comments and test setup for merge-cleanliness

Match the shared bitrot code (write_ec_files, encode_one_batch, checksum_scrub,
the encode sidecar test) to the canonical wording/layout so the volume-server
Rust port stays line-aligned across trees, keeping periodic merges conflict-free.
No behavior change.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 20:09:31 -07:00
Chris Lu 9550b830d0 worker: project the moved volume when gating on disk fullness (#10171)
The disk-fullness gate only rejected destinations already at/above the mark, so a
server just under it could take a large volume and overshoot. Project the selected
volume's bytes onto the candidate: if the move would cross the mark, drop that
destination for the rest of the cycle and re-pick instead of overshooting. Also
note the per-location capacity-summing assumption on the Rust heartbeat side, to
match the Go store.go comment.
2026-06-30 20:08:19 -07:00
Chris Lu d02ee6d5df balance: share replica-placement logic between shell and worker (#10169)
The replica-placement rule (data-center/rack/same-node limits plus host
anti-affinity) existed three times: the shell's satisfyReplicaPlacement/isGoodMove
used by volume.balance, fix.replication, and tier.move, and a line-for-line port
in the maintenance balance worker. Move the canonical logic into
weed/topology/balancer on a shared Location type; the shell and worker keep thin
adapters that convert their own location representation and call it. Behavior is
unchanged (the shared IsGoodMove keeps the shell's reject-move-to-self guard, and
all four replica test suites pass).
2026-06-30 20:02:23 -07:00
Chris Lu bea1357d38 ec: skip physically near-full disks when placing EC shards (#10167)
EC placement scored destinations purely by free EC shard slots (derived from
maxVolumeCount) and shard counts, blind to real disk fullness — the same defect
as volume balancing. A disk that is physically full but still shows free EC slots
kept being chosen, and EC shard bytes are captured by statfs free space yet not
by any slot accounting, so the slot math is exactly the metric that can't see EC
fullness.

Treat a disk at/above 90% physical usage as having zero free EC slots at
snapshot-build time, so every existing freeSlots>0 placement predicate excludes
it. Applied in all three snapshot builders (shell countFreeShardSlots, the shared
ecbalancer FromActiveTopology, and the worker ec_balance buildBalancerTopology)
via the shared balancer.DiskTooFullAfter gate. Servers not reporting disk bytes
fall back to slot-only behavior. ec.rebuild recovery is left ungated so shard
recovery can still complete onto fuller disks.
2026-06-30 20:01:55 -07:00
Chris Lu 77bf2a3ab0 volume.balance: gate on real physical disk usage (fixes #10160) (#10162)
* shell: add volume.balance -byDiskUsage to balance by actual data

The default balancer ranks servers by slot density, dividing used volumes by
MaxVolumeCount. When MaxVolumeCount is configured higher than the disk can hold,
a physically near-full server looks nearly empty and gets picked as the move
target, so balancing drains less-full servers onto an already-full one.

-byDiskUsage ranks servers by the actual data they hold (sum of volume sizes)
instead, so the fullest-by-data server is treated as full and balancing drains
it. It assumes comparable disk sizes per disk type and still respects each
server's free volume slots. Default behavior is unchanged.

* plumb physical disk usage into topology, gate volume.balance on it

Volume servers now report each disk's filesystem total/free bytes in the
heartbeat, and the master stores them in DiskInfo. volume.balance uses them to
skip any move target whose disk is already near full (-maxDiskUsagePercent,
default 90), so an over-configured maxVolumeCount can no longer make a
physically full server look empty and get drained onto. The gate judges each
server against its own disk, so heterogeneous disk sizes are fine; servers that
do not report bytes fall back to slot-only behavior.

Rust seaweed-volume mirrors the heartbeat reporting.

* admin: report real physical disk capacity when volume servers provide it

The dashboard estimated server capacity as maxVolumeCount * volumeSizeLimit,
which overstates it when maxVolumeCount is set higher than the disk holds.
Prefer the filesystem capacity now reported per disk, falling back to the
estimate for servers that do not report it.

* worker: gate automatic balance on physical disk fullness too

The maintenance balance worker selects the least slot-utilized server as the
move destination, so an over-configured maxVolumeCount makes a physically full
server look empty and get drained onto — the same defect as the shell command.
Now that DiskInfo carries real disk bytes, skip any destination whose disk is
at/above 90% used (per server, against its own disk); a full server can still be
a source. When every candidate destination is full, create no tasks. Servers
that do not report disk bytes are not gated.

* balance: share the physical-disk-fullness gate between shell and worker

The shell volume.balance command and the maintenance balance worker each grew
their own copy of the disk-fullness gate (targetDiskTooFull / destinationDiskTooFull)
and a maxDiskUsagePercent=90 constant. Pull both into weed/topology/balancer
(DiskTooFullAfter + DefaultMaxDiskUsagePercent) so the policy has one home and the
two balancers can't drift.

* balance: harden the physical-disk gate

Guard against a nil DiskInfo in the byte/slot lookups. Let a zero disk-capacity
report clear previously stored bytes (0 means "not reported" for bytes, unlike
maxVolumeCount), so a server that stops reporting falls back to slot-only instead
of trusting stale capacity. In the worker, charge each planned move's bytes to
its destination within a detection cycle so the gate sees a target fill up rather
than only its heartbeat-time free space. Note the per-location capacity summing
assumes one location per filesystem (the used ratio the gate relies on stays
correct regardless; absolute capacity can over-report).
2026-06-30 19:31:12 -07:00
Chris Lu 41d6c821ba feat(topology): report empty disks (per-disk type + capacity in heartbeat) (#10166)
* fix(topology): keep physical disk 0 distinct in SplitByPhysicalDisk

DiskId 0 doubles as the first physical disk (Locations[0]) and the
protobuf "unset" default. SplitByPhysicalDisk folded every DiskId-0
record onto the aggregate DiskId whenever that was non-zero, so on a
multi-disk node the first disk's volumes merged into whichever disk
held volumes[0]: the node reported one fewer disk, the sibling showed
~2x volumes, and per-disk max was smeared across the survivors. This
surfaced as cluster.status and volume.list undercounting disks.

Only treat 0 as unset when no record carries a non-zero DiskId; with a
mix, 0 is a real disk and keeps its own entry.

* fix(admin): resolve physical disk 0 in active-topology indexes

rebuildIndexes re-derived each volume/EC record's physical disk id with
the same "DiskId 0 means unset" heuristic SplitByPhysicalDisk used, so
the two agreed only by sharing the bug. Now that SplitByPhysicalDisk
keeps disk 0 distinct, the duplicated heuristic would fold disk-0 records
onto a sibling while at.disks kept them on disk 0; GetVolumeLocations and
GetECShardLocations then matched no record and silently dropped every
volume and EC shard on the first disk, starving balance and EC tasks.

Build the indexes from the same SplitByPhysicalDisk reconstruction that
builds at.disks, so the keys always resolve. One source of truth instead
of a parallel normalize.

* fix(ec): allow physical disk 0 as preferred EC shard target

pickBestDiskOnNode gated its result on bestDiskId != 0, but 0 is both a
valid physical disk and the uint32 zero value, so a best-scoring disk 0
was discarded and the non-matching fallback returned instead. Gate on
bestScore.

* test(admin): cover EC-shard index resolution for physical disk 0

rebuildIndexes builds ecShardIndex the same way as volumeIndex; pin the EC
path too so a shard on disk 0 keeps resolving via GetECShardLocations.

* proto: per-disk type/capacity in DiskTag, DiskInfo.physical_disks

DiskTag gains type + max_volume_count so the heartbeat can describe every
physical disk, including ones holding no volumes or EC shards. DiskInfo
gains physical_disks so the master can hand the full per-type disk set to
per-physical-disk consumers.

* feat(volume): report each physical disk's type and capacity

CollectHeartbeat fills DiskTag.type and the per-disk effective max for
every location, so the master can account for disks that hold no volumes
or EC shards yet. Rust heartbeat mirrors it.

* feat(master): surface empty disks in the per-physical-disk view

The master records each disk's type and max from DiskTags and lists them
on DiskInfo.physical_disks per type, including disks with no volumes or
EC shards. SplitByPhysicalDisk enumerates that full set and gives each
disk its exact max, so cluster.status, volume.list and the admin
topology count and can target empty disks. Without physical_disks the
even-split fallback is unchanged.

* fix(master): clamp per-disk free at zero for over-allocated disks

In the exact-max path FreeVolumeCount could go negative when a disk holds
more volumes than its max; a negative would reduce the node's summed free
and block placement on healthy disks. Clamp at 0.

* fix(master): rebuild disk tags fresh each heartbeat

DiskTags is the full authoritative per-disk list every heartbeat, so
rebuild dn.diskTags from scratch like dn.diskBackends; merging left stale
entries for removed disks.

* fix(master): keep zero-capacity disks in physical_disks

A disk reporting max 0 (an unavailable disk) is a valid physical disk,
not a signal to drop it. List every disk of the type, but only emit
physical_disks when the node reports real per-disk capacity, so an older
server sending all zeros still falls back to the aggregate split.

* test(volume): cover disk-space-low per-disk max in heartbeat

Assert DiskTag.max_volume_count follows the used-slots override when a
location is low on space, matching the per-type max_volume_counts.

* chore: trim comments on the empty-disk change

Drop narration; keep only the non-obvious why (disk-0 sentinel, exact-max
free clamp, EC slots not subtracted, all-zeros fallback).

* refactor(master): merge per-disk tags and capacity into one map

diskTags and diskBackends were parallel maps keyed by the same DiskId and
filled together from DiskTags. Fold them into one diskMetas map of
{tags, type, max}.

* refactor(proto): per-disk max as a map keyed by disk id

physical_disks was a repeated {disk_id, max_volume_count} whose fields
duplicated DiskInfo's own disk_id/max_volume_count. A map<uint32,int64>
keyed by disk id expresses "max per disk" directly, drops the extra
PhysicalDiskInfo message, and the consumer reads it as the disk set.

* docs(proto): note DiskInfo.disk_id's two meanings

Identity on a per-physical-disk DiskInfo (from SplitByPhysicalDisk),
representative fallback on the type-keyed aggregate.
2026-06-30 18:45:44 -07:00
Chris Lu a9c0ed91b5 fix(topology): keep physical disk 0 distinct in SplitByPhysicalDisk (#10161)
* fix(topology): keep physical disk 0 distinct in SplitByPhysicalDisk

DiskId 0 doubles as the first physical disk (Locations[0]) and the
protobuf "unset" default. SplitByPhysicalDisk folded every DiskId-0
record onto the aggregate DiskId whenever that was non-zero, so on a
multi-disk node the first disk's volumes merged into whichever disk
held volumes[0]: the node reported one fewer disk, the sibling showed
~2x volumes, and per-disk max was smeared across the survivors. This
surfaced as cluster.status and volume.list undercounting disks.

Only treat 0 as unset when no record carries a non-zero DiskId; with a
mix, 0 is a real disk and keeps its own entry.

* fix(admin): resolve physical disk 0 in active-topology indexes

rebuildIndexes re-derived each volume/EC record's physical disk id with
the same "DiskId 0 means unset" heuristic SplitByPhysicalDisk used, so
the two agreed only by sharing the bug. Now that SplitByPhysicalDisk
keeps disk 0 distinct, the duplicated heuristic would fold disk-0 records
onto a sibling while at.disks kept them on disk 0; GetVolumeLocations and
GetECShardLocations then matched no record and silently dropped every
volume and EC shard on the first disk, starving balance and EC tasks.

Build the indexes from the same SplitByPhysicalDisk reconstruction that
builds at.disks, so the keys always resolve. One source of truth instead
of a parallel normalize.

* fix(ec): allow physical disk 0 as preferred EC shard target

pickBestDiskOnNode gated its result on bestDiskId != 0, but 0 is both a
valid physical disk and the uint32 zero value, so a best-scoring disk 0
was discarded and the non-matching fallback returned instead. Gate on
bestScore.

* test(admin): cover EC-shard index resolution for physical disk 0

rebuildIndexes builds ecShardIndex the same way as volumeIndex; pin the EC
path too so a shard on disk 0 keeps resolving via GetECShardLocations.
2026-06-30 15:35:27 -07:00
Chris Lu a653a7f72a fix(shell): honor explicit fs.mergeVolumes from/to direction (#10159)
* fix(shell): honor explicit fs.mergeVolumes from/to direction

mergeVolumes only ever merged a smaller volume into a larger one. When the
user named both -fromVolumeId and -toVolumeId with the source larger than the
target, the planner produced an empty plan and the command printed just
"max volume size: N MB" and moved nothing.

Build the requested pair directly when both ids are given, instead of routing
through the size-descending heuristic. Read-only, empty, and wrong-collection
endpoints are rejected with a clear error rather than a silent no-op.

* fix(shell): allow fs.mergeVolumes into an empty target volume

Merging chunks into an empty volume is valid, e.g. consolidating data into a
freshly created or recently vacuumed volume. Only reject an empty source, which
has nothing to move.

* fix(shell): reject self-map in directed mergeVolumes planner

createMergePlan with from == to returned a {vid: vid} self-merge when called
directly. Guard it in the planner so it is correct independent of the Do
entrypoint.
2026-06-30 13:28:53 -07:00
AlekseyandChris Lu 424cd164e9 s3: invalidate stale reader cache locations on chunk read failure (#10156)
* s3: invalidate stale reader cache locations on chunk read failure

* filer: share the chunk-read self-heal across reader cache and streaming paths

The reader cache retry added a third copy of the invalidate-relookup-compare-retry
dance already inlined in PrepareStreamContentWithThrottler and duplicated in
retryWithCacheInvalidation. Extract retryFetchWithFreshLocations and route all
three through it, parameterized by the refetch primitive.

* filer: drop redundant completedTimeNew store in reader cache success path

startCaching already stamps completedTimeNew unconditionally before the
fetchErr branch; the second store inside the success branch is dead.

* filer: make NewReaderCache cache invalidator an explicit parameter

The variadic ...CacheInvalidator only ever read the first element, so a caller
could pass two and silently get one. Take a single explicit argument and have
the non-S3 callers pass nil.

* filer: inject reader cache chunk fetch as a struct field

Replace the process-global readerCacheFetchChunkData test seam with a
per-instance fetchChunkDataFn field defaulted in NewReaderCache, matching how
lookupFileIdFn is already wired. Tests set the field on the cache instead of
swapping a shared global.

* filer: log the location count, not full URLs, on self-heal retry

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-30 13:27:49 -07:00
Chris Lu 803c5a8dca fix(filer): use DROP TABLE IF EXISTS in SQL stores (#10158)
Concurrent bucket deletion across multiple filer replicas races on the
per-bucket DROP TABLE. The first replica drops the table; the rest hit
an undefined-table error (postgres 42P01, mysql 1051) which propagates
out of DeleteFolderChildren and panics the filer. On restart the same
pending DROP re-runs and the filer crash-loops.

Make the drop idempotent. Same defect class in all SQL backends, so fix
postgres, postgres2, mysql, mysql2, and sqlite together.
2026-06-30 10:38:51 -07:00
Chris Lu 8f2a2abae4 fix(ec): correct EC FULL scrub for deleted needles, shard-location cache, and parity coverage (#10152)
* fix(ec): correct EC FULL scrub for deleted needles + shard-location cache

Addresses review findings on the EC FULL distributed scrub:
- Remote EC reads now thread Go's (bytes, is_deleted) contract. A runtime EC
  delete keeps the .ecx size positive (the delete lives in .ecj/memory), so the
  raw-index walk verifies the needle, and its header interval is usually remote;
  the peer answers is_deleted with no payload. The scrub zero-fills that interval
  (so the needle reaches read_bytes -> SizeMismatch{0} -> the delete-state
  suppression), the serving direct read short-circuits to not-found, and
  reconstruction EXCLUDES the shard instead of feeding zeros into Reed-Solomon.
- The walk skips size.is_deleted() (not just is_tombstone), so a -originalSize
  .ecx entry (pre-encode delete) can't yield empty intervals or panic parse_header.
- Restore Go's < data_shards completeness guard (per-volume, custom-ratio aware)
  and per-shard merge in the location cache instead of clobber-with-partial.
- Abort the scrub with an error on mid-scan unmount instead of a false-CLEAN.
- Hoist the refreshed location map once instead of cloning it per needle.

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

* feat(scrub): keep RS parity check in EC FULL until CHECKSUM lands

The per-needle FULL walk only reads live data-shard intervals, so it can't catch
bitrot in a parity shard or an unwalked cold region. Run verify_ec_shards
alongside the walk, gated on all-shards-local (single-node EC), via spawn_blocking.
A deliberate temporary divergence from Go FULL; moves to mode 4 (CHECKSUM) once
the .ecsum subsystem lands.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 10:18:31 -07:00
Kwak Byoung Min a85318111c admin: restore cluster volume page CSV export (#10155) 2026-06-30 08:31:37 -07:00
Peter Dodd bb5e6e40df fix(remote/gcs): tolerate already-deleted object in DeleteFile (#10151) 2026-06-30 07:52:25 -07:00
132 changed files with 6103 additions and 1279 deletions

No files matched your search

+8 -6
View File
@@ -93,11 +93,11 @@ 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.41.0
golang.org/x/image v0.43.0
golang.org/x/net v0.55.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sys v0.46.0
golang.org/x/text v0.37.0 // indirect
golang.org/x/text v0.38.0 // indirect
golang.org/x/tools v0.45.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.278.0
@@ -513,10 +513,12 @@ require (
// replace github.com/seaweedfs/raft => /Users/chrislu/go/src/github.com/seaweedfs/raft
// apache/thrift v0.23.0 uses math.MaxUint32 as an untyped int constant in
// lib/go/thrift/framed_transport.go, which overflows int on 32-bit GOARCHes
// (e.g. openbsd/arm, linux/arm). Pin to v0.22.0 until upstream fixes it.
replace github.com/apache/thrift => github.com/apache/thrift v0.22.0
// apache/thrift v0.23.0 fixes CVE-2026-41602 but compares int against the
// untyped math.MaxUint32 in lib/go/thrift/framed_transport.go, which overflows
// int on 32-bit GOARCHes (e.g. openbsd/arm, linux/arm) and fails to compile.
// Upstream fixed the range check post-release; pin to that commit until the
// next tagged release carries both the CVE fix and the 32-bit fix.
replace github.com/apache/thrift => github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58
// tyler-smith/go-bip39 was deleted from GitHub, so `go mod download` fails for
// anyone resolving it directly (GOPROXY=direct). It only reaches us transitively
+6 -6
View File
@@ -694,8 +694,8 @@ github.com/apache/cassandra-gocql-driver/v2 v2.1.2 h1:lu/p0Db2av18enHJvWJQoChLss
github.com/apache/cassandra-gocql-driver/v2 v2.1.2/go.mod h1:QH/asJjB3mHvY6Dot6ZKMMpTcOrWJ8i9GhsvG1g0PK4=
github.com/apache/iceberg-go v0.6.0 h1:tOVhC5BhBOEgPTowo5AVrPnAgsDo00qEbUPprFcLd4s=
github.com/apache/iceberg-go v0.6.0/go.mod h1:kESfDlyaW/6hK0WW6TzA4EWps+0NMhhrDYE4qajVjlo=
github.com/apache/thrift v0.22.0 h1:r7mTJdj51TMDe6RtcmNdQxgn9XcyfGDOzegMDRg47uc=
github.com/apache/thrift v0.22.0/go.mod h1:1e7J/O1Ae6ZQMTYdy9xa3w9k+XHWPfRvdPyJeynQ+/g=
github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58 h1:rDLE+tSW60VzRD7v5I+DU22Mjhmm+mfLc5Xl5dHkx6w=
github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58/go.mod h1:zPt6WxgvTOM6hF92y8C+MkEM5LMxZuk4JcQOiU4Esvs=
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3 h1:WZaTKNHCfcw7fWSR6/RKnCldVzvYZC+Y20Su4lffEIg=
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U=
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er+LKDHDUfU5tRvFwxH0LjPpZN8OoG8Ll+liGU=
@@ -2211,8 +2211,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.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
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=
@@ -2514,8 +2514,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -29,6 +29,11 @@ spec:
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
@@ -23,6 +23,11 @@ spec:
- '*.{{ .Release.Namespace }}'
- '*.{{ .Release.Namespace }}.svc'
- '*.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
- '*.{{ include "seaweedfs.fullname" . }}-master'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
@@ -28,6 +28,11 @@ spec:
- '*.{{ .Release.Namespace }}'
- '*.{{ .Release.Namespace }}.svc'
- '*.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
- '*.{{ include "seaweedfs.fullname" . }}-master'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
@@ -28,6 +28,11 @@ spec:
- '*.{{ .Release.Namespace }}'
- '*.{{ .Release.Namespace }}.svc'
- '*.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
- '*.{{ include "seaweedfs.fullname" . }}-master'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
@@ -28,6 +28,11 @@ spec:
- '*.{{ .Release.Namespace }}'
- '*.{{ .Release.Namespace }}.svc'
- '*.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
- '*.{{ include "seaweedfs.fullname" . }}-master'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
@@ -29,6 +29,11 @@ spec:
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}'
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}.svc'
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
@@ -1,6 +1,8 @@
{{- /* Filer ingress works for both normal mode (filer.enabled) and all-in-one mode (allInOne.enabled) */}}
{{- /* Filer ingresses work for both normal mode (filer.enabled) and all-in-one mode (allInOne.enabled) */}}
{{- $filerEnabled := or .Values.filer.enabled .Values.allInOne.enabled }}
{{- if and $filerEnabled .Values.filer.ingress.enabled }}
{{- /* HTTP Ingress */}}
{{- if and $filerEnabled .Values.filer.ingresses.http.enabled }}
{{- /* Determine service name based on deployment mode */}}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
@@ -12,10 +14,13 @@ apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
name: ingress-{{ include "seaweedfs.fullname" . }}-filer
name: ingress-{{ include "seaweedfs.fullname" . }}-filer-http
namespace: {{ .Release.Namespace }}
{{- with .Values.filer.ingress.annotations }}
annotations:
{{- if and (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) .Values.filer.ingresses.http.className }}
kubernetes.io/ingress.class: {{ .Values.filer.ingresses.http.className }}
{{- end }}
{{- with .Values.filer.ingresses.http.annotations }}
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
@@ -25,14 +30,21 @@ metadata:
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: filer
spec:
ingressClassName: {{ .Values.filer.ingress.className | quote }}
{{- if and (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) .Values.filer.ingresses.http.className }}
ingressClassName: {{ .Values.filer.ingresses.http.className | quote }}
{{- end }}
tls:
{{ .Values.filer.ingress.tls | default list | toYaml | nindent 6}}
{{ .Values.filer.ingresses.http.tls | default list | toYaml | nindent 6}}
rules:
- http:
- {{- if .Values.filer.ingresses.http.host }}
host: {{ .Values.filer.ingresses.http.host | quote }}
{{- end }}
http:
paths:
- path: {{ .Values.filer.ingress.path | quote }}
pathType: {{ .Values.filer.ingress.pathType | quote }}
- path: {{ .Values.filer.ingresses.http.path | quote }}
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
pathType: {{ .Values.filer.ingresses.http.pathType | quote }}
{{- end }}
backend:
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
service:
@@ -43,7 +55,62 @@ spec:
serviceName: {{ $serviceName }}
servicePort: {{ .Values.filer.port }}
{{- end }}
{{- if .Values.filer.ingress.host }}
host: {{ .Values.filer.ingress.host }}
{{- end }}
---
{{- /* gRPC Ingress */}}
{{- if and $filerEnabled .Values.filer.ingresses.grpc.enabled }}
{{- /* Determine service name based on deployment mode */}}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: networking.k8s.io/v1beta1
{{- else }}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
name: ingress-{{ include "seaweedfs.fullname" . }}-filer-grpc
namespace: {{ .Release.Namespace }}
annotations:
{{- if and (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) .Values.filer.ingresses.grpc.className }}
kubernetes.io/ingress.class: {{ .Values.filer.ingresses.grpc.className }}
{{- end }}
{{- with .Values.filer.ingresses.grpc.annotations }}
{{- toYaml . | nindent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: filer
spec:
{{- if and (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) .Values.filer.ingresses.grpc.className }}
ingressClassName: {{ .Values.filer.ingresses.grpc.className | quote }}
{{- end }}
tls:
{{ .Values.filer.ingresses.grpc.tls | default list | toYaml | nindent 6}}
rules:
- {{- if .Values.filer.ingresses.grpc.host }}
host: {{ .Values.filer.ingresses.grpc.host | quote }}
{{- end }}
http:
paths:
- path: {{ .Values.filer.ingresses.grpc.path | quote }}
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
pathType: {{ .Values.filer.ingresses.grpc.pathType | quote }}
{{- end }}
backend:
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
service:
name: {{ $serviceName }}
port:
number: {{ .Values.filer.grpcPort }}
{{- else }}
serviceName: {{ $serviceName }}
servicePort: {{ .Values.filer.grpcPort }}
{{- end }}
{{- end }}
+45 -24
View File
@@ -824,30 +824,50 @@ filer:
# allowPrivilegeEscalation: false
containerSecurityContext: {}
ingress:
enabled: false
className: ""
# host: false for "*" hostname
host: "seaweedfs.cluster.local"
path: "/sw-filer/?(.*)"
pathType: ImplementationSpecific
annotations: {}
# nginx.ingress.kubernetes.io/backend-protocol: GRPC
# nginx.ingress.kubernetes.io/auth-type: "basic"
# nginx.ingress.kubernetes.io/auth-secret: "default/ingress-basic-auth-secret"
# nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - SW-Filer'
# nginx.ingress.kubernetes.io/service-upstream: "true"
# nginx.ingress.kubernetes.io/rewrite-target: /$1
# nginx.ingress.kubernetes.io/use-regex: "true"
# nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
# nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
# nginx.ingress.kubernetes.io/configuration-snippet: |
# sub_filter '<head>' '<head> <base href="/sw-filer/">'; #add base url
# sub_filter '="/' '="./'; #make absolute paths to relative
# sub_filter '=/' '=./';
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
# sub_filter_once off;
ingresses:
http:
enabled: false
className: ""
# host: false for "*" hostname
host: "seaweedfs.cluster.local"
path: "/sw-filer/?(.*)"
pathType: ImplementationSpecific
annotations: {}
# nginx.ingress.kubernetes.io/backend-protocol: GRPC
# nginx.ingress.kubernetes.io/auth-type: "basic"
# nginx.ingress.kubernetes.io/auth-secret: "default/ingress-basic-auth-secret"
# nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - SW-Filer'
# nginx.ingress.kubernetes.io/service-upstream: "true"
# nginx.ingress.kubernetes.io/rewrite-target: /$1
# nginx.ingress.kubernetes.io/use-regex: "true"
# nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
# nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
# nginx.ingress.kubernetes.io/configuration-snippet: |
# sub_filter '<head>' '<head> <base href="/sw-filer/">'; #add base url
# sub_filter '="/' '="./'; #make absolute paths to relative
# sub_filter '=/' '=./';
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
# sub_filter_once off;
tls: []
grpc:
enabled: false
className: ""
host: "seaweedfs.cluster.local"
# gRPC methods are called at /<package>.<Service>/<Method>, so route the
# whole host, not the HTTP UI's regex path.
path: "/"
pathType: Prefix
annotations:
# Ingress terminates TLS and re-originates gRPC (HTTP/2) to the filer.
nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
# For end-to-end mTLS (the filer's own TLS reaches the client, not
# terminated at the edge), drop backend-protocol above and use TLS
# passthrough instead:
# nginx.ingress.kubernetes.io/ssl-passthrough: "true"
# Passthrough routes by SNI (set `host` above), ignores `path`, and
# requires ingress-nginx to run with --enable-ssl-passthrough.
tls: []
# extraEnvVars is a list of extra environment variables to set with the stateful set.
extraEnvironmentVars:
@@ -1745,6 +1765,7 @@ cosi:
certificates:
commonName: "SeaweedFS CA"
dnsNames: []
ipAddresses: []
keyAlgorithm: RSA
keySize: 2048
+30
View File
@@ -64,6 +64,9 @@ service Seaweed {
message DiskTag {
uint32 disk_id = 1;
repeated string tags = 2;
// Physical disk descriptor, reported for every location including empty ones.
string type = 3;
int64 max_volume_count = 4;
}
message Heartbeat {
@@ -96,6 +99,10 @@ message Heartbeat {
volume_server_pb.VolumeServerState state = 23;
repeated DiskTag disk_tags = 24;
// physical disk capacity per disk type, in bytes, from the underlying filesystem
map<string, uint64> disk_total_bytes = 25;
map<string, uint64> disk_free_bytes = 26;
}
message HeartbeatResponse {
@@ -206,6 +213,17 @@ message ClusterNodeUpdate {
message KeepConnectedResponse {
VolumeLocation volume_location = 1;
ClusterNodeUpdate cluster_node_update = 2;
LockRingUpdate lock_ring_update = 3;
}
// LockRingUpdate is sent by the master to all filers when the lock ring
// membership changes. The master batches rapid changes (e.g., node drop + join)
// and sends the complete member list atomically, avoiding intermediate ring
// states that would cause unnecessary lock churn.
message LockRingUpdate {
string filer_group = 1;
repeated string servers = 2;
int64 version = 3;
}
message LookupVolumeRequest {
@@ -308,8 +326,18 @@ message DiskInfo {
repeated VolumeInformationMessage volume_infos = 6;
repeated VolumeEcShardInformationMessage ec_shard_infos = 7;
int64 remote_volume_count = 8;
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
// identity; on the type-keyed aggregate it is only a representative fallback
// (the first volume's disk id).
uint32 disk_id = 9;
repeated string tags = 10;
// Max volume count for every physical disk of this type, keyed by disk id,
// including disks with no volumes or EC shards; recovers empty disks that
// carry no per-volume/per-shard records.
map<uint32, int64> max_volume_count_by_disk = 11;
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
uint64 disk_total_bytes = 12;
uint64 disk_free_bytes = 13;
}
message DataNodeInfo {
string id = 1;
@@ -360,11 +388,13 @@ message VacuumVolumeResponse {
}
message DisableVacuumRequest {
bool by_plugin = 1;
}
message DisableVacuumResponse {
}
message EnableVacuumRequest {
bool by_plugin = 1;
}
message EnableVacuumResponse {
}
+1
View File
@@ -708,6 +708,7 @@ message ScrubEcVolumeRequest {
VolumeScrubMode mode = 1;
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
repeated uint32 volume_ids = 2;
bool force_deleted_needles_check = 3; // FULL mode only; may report false positives when EC indexes disagree
}
message ScrubEcVolumeResponse {
uint64 total_volumes = 1;
+173 -14
View File
@@ -1516,9 +1516,16 @@ impl VolumeServer for VolumeGrpcService {
.find_volume(vid)
.ok_or_else(|| Status::not_found(format!("not found volume id {}", vid)))?;
// Check compaction revision
// Check compaction revision. Compare against the volume's live
// super_block.compaction_revision (matching Go's v.CompactionRevision,
// which is the embedded SuperBlock field). last_compact_revision() is
// a separate bookkeeping value recorded just before a compaction starts
// (for makeup-diff catch-up) and is intentionally left behind the live
// revision afterward — it is not interchangeable with the live value and
// must not be used here, or this check spuriously fails on every volume
// that has ever been compacted even once.
if req.compaction_revision != u32::MAX
&& v.last_compact_revision() != req.compaction_revision as u16
&& u32::from(v.super_block.compaction_revision) != req.compaction_revision
{
return Err(Status::failed_precondition(format!(
"volume {} is compacted",
@@ -4015,22 +4022,75 @@ impl VolumeServer for VolumeGrpcService {
}
}
2 => {
// FULL: verify every needle across local AND remote shards.
{
// Match Go: a missing requested volume is a hard error.
// FULL: Go-parity per-needle local+remote walk, PLUS a TEMPORARY
// local Reed-Solomon parity check. The needle walk only reads
// DATA-shard intervals of LIVE needles, so on its own it can't
// catch silent bitrot in a PARITY shard or an unwalked cold
// region. Go closes that gap with a separate CHECKSUM mode over
// .ecsum, which Rust does not have yet; running both here is a
// deliberate divergence from Go FULL to preserve coverage. Drop
// verify_ec_shards from this arm once mode 4 (CHECKSUM) lands.
//
// The RS recompute needs every shard co-located, so only run it
// when this node holds all data+parity shards (single-node EC);
// on a distributed layout it would report every non-local shard
// as missing. Snapshot under a brief lock; release before await.
let (dir, collection, data_shards, parity_shards, all_local) = {
let store = self.state.store.read().unwrap();
if store.find_ec_volume(vid).is_none() {
return Err(Status::not_found(format!(
"EC volume id {} not found",
vid.0
)));
}
}
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
Status::not_found(format!("EC volume id {} not found", vid.0))
})?;
let total = (ecv.data_shards + ecv.parity_shards) as usize;
let local = ecv.shards.iter().filter(|s| s.is_some()).count();
(
ecv.dir.clone(),
ecv.collection.clone(),
ecv.data_shards as usize,
ecv.parity_shards as usize,
local == total,
)
};
total_volumes += 1;
let (files, shard_infos, errs) =
// (1) Per-needle local+remote walk (Go ScrubEcVolume parity).
let (files, mut shard_infos, mut errs) =
crate::server::store_ec::scrub_ec_volume_distributed(&self.state, vid, false)
.await;
total_files += files as u64;
total_files += files as u64; // count comes from the needle walk only
// (2) Local parity check, gated on all-shards-local. Blocking RS
// verify -> spawn_blocking; inputs are owned, no lock held.
if all_local && !dir.is_empty() {
let collection_pc = collection.clone();
let (parity_broken, parity_details) = tokio::task::spawn_blocking(move || {
crate::storage::erasure_coding::ec_encoder::verify_ec_shards(
&dir,
&collection_pc,
vid,
data_shards,
parity_shards,
)
})
.await
.map_err(|e| Status::internal(format!("verify_ec_shards join: {}", e)))?
.unwrap_or_else(|e| (Vec::new(), vec![format!("verify_ec_shards: {}", e)]));
let mut seen: std::collections::HashSet<u32> =
shard_infos.iter().map(|s| s.shard_id).collect();
for sid in parity_broken {
if seen.insert(sid) {
shard_infos.push(volume_server_pb::EcShardInfo {
shard_id: sid,
collection: collection.clone(),
volume_id: vid.0,
..Default::default()
});
}
}
shard_infos.sort_by_key(|s| s.shard_id);
errs.extend(parity_details);
}
if !errs.is_empty() || !shard_infos.is_empty() {
broken_volume_ids.push(vid.0);
broken_shard_infos.extend(shard_infos);
@@ -5605,6 +5665,105 @@ mod tests {
}
}
// Regression test for comparing the wrong compaction-revision field.
// last_compact_revision() is bookkeeping recorded just before a compaction
// starts (for makeup-diff catch-up) and is intentionally left behind
// super_block.compaction_revision once the compaction commits. copy_file's
// precondition check must compare against the live super_block value
// (matching Go's v.CompactionRevision), not the stale bookkeeping one, or
// it fails "volume N is compacted" on every volume that has ever been
// compacted even once.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_copy_file_accepts_live_revision_after_compaction() {
let (service, _tmp) = make_local_service_with_volume("", None);
// Drive a real compaction to completion so the two revision fields
// actually diverge the way they do in production, rather than poking
// the struct fields directly.
let (revision_before, revision_after, last_compact_revision_after) = {
let mut store = service.state.store.write().unwrap();
let (_, v) = store.find_volume_mut(VolumeId(1)).unwrap();
let before = v.super_block.compaction_revision;
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
(before, v.super_block.compaction_revision, v.last_compact_revision())
};
assert_eq!(revision_before, 0, "fresh volume starts at revision 0");
assert_eq!(
revision_after, 1,
"live super_block.compaction_revision must advance after commit_compact"
);
assert_eq!(
last_compact_revision_after, 0,
"last_compact_revision() is recorded pre-compaction and must stay \
behind the live revision — this divergence is exactly what made \
the old check fail permanently"
);
// The live revision (1) must be accepted: this is what
// read_volume_file_status would report to a caller right now.
let response = service
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
volume_id: 1,
ext: ".dat".to_string(),
compaction_revision: revision_after as u32,
stop_offset: u64::MAX,
collection: String::new(),
is_ec_volume: false,
ignore_source_file_not_found: false,
}))
.await;
assert!(
response.is_ok(),
"copy_file must accept the live compaction_revision, got: {:?}",
response.err()
);
// A genuinely stale/wrong revision must still be rejected — the fix
// corrects which field is compared, it does not disable the check.
let stale_response = service
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
volume_id: 1,
ext: ".dat".to_string(),
compaction_revision: 99,
stop_offset: u64::MAX,
collection: String::new(),
is_ec_volume: false,
ignore_source_file_not_found: false,
}))
.await;
let err = match stale_response {
Ok(_) => panic!("a genuinely stale revision must be rejected"),
Err(e) => e,
};
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
assert!(err.message().contains("is compacted"));
// A request revision that only collides after truncating to u16 must be
// rejected: 65537 as u16 == 1 == the live revision, but as u32 they differ.
// Compare in u32 space (matching Go) so this cannot spuriously pass.
let truncating_response = service
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
volume_id: 1,
ext: ".dat".to_string(),
compaction_revision: u32::from(revision_after) + (1 << 16),
stop_offset: u64::MAX,
collection: String::new(),
is_ec_volume: false,
ignore_source_file_not_found: false,
}))
.await;
let err = match truncating_response {
Ok(_) => panic!("a revision that only matches after u16 truncation must be rejected"),
Err(e) => e,
};
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
assert!(err.message().contains("is compacted"));
}
#[tokio::test]
async fn test_volume_ec_shards_generate_persists_expire_at_sec() {
let ttl = crate::storage::needle::ttl::TTL::read("3m").unwrap();
+174 -69
View File
@@ -546,6 +546,23 @@ async fn do_replicated_request(
.await
.map_err(|e| format!("lookup volume failed: {}", e))?;
// Mirror Go's GetWritableRemoteReplications: reject when the master reports fewer replicas than
// the copy count. lookup_volume is uncached, so recovery is immediate once the replica re-registers.
let copy_count = {
let store = state.store.read().unwrap();
store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| {
v.super_block.replica_placement.get_copy_count()
})
};
if locations.len() < copy_count as usize {
return Err(format!(
"replicating operations [{}] is less than volume {} replication copy count [{}]",
locations.len(),
vid,
copy_count
));
}
let self_http = to_http_address(&state.self_url);
let remote_locations: Vec<_> = locations
.into_iter()
@@ -1262,7 +1279,9 @@ async fn get_or_head_handler_inner(
&query,
&etag,
&last_modified_str,
) {
)
.await
{
return resp;
}
// If manifest expansion fails (invalid JSON etc.), fall through to raw data
@@ -3179,12 +3198,11 @@ struct ChunkManifest {
struct ChunkInfo {
fid: String,
offset: i64,
#[allow(dead_code)]
size: i64,
}
/// Try to expand a chunk manifest needle. Returns None if manifest can't be parsed.
fn try_expand_chunk_manifest(
async fn try_expand_chunk_manifest(
state: &Arc<VolumeServerState>,
n: &Needle,
_headers: &HeaderMap,
@@ -3224,29 +3242,26 @@ fn try_expand_chunk_manifest(
return None;
}
// Read and concatenate all chunks
// Read and concatenate all chunks. Each chunk is resolved to wherever it
// lives — a local regular volume, a local EC volume (reconstruct-on-read),
// or a peer via master lookup — mirroring Go's ChunkedFileReader, which
// never assumes chunks are local regular needles.
let mut result = vec![0u8; manifest.size as usize];
let store = state.store.read().unwrap();
for chunk in &manifest.chunks {
let (chunk_vid, chunk_nid, chunk_cookie) = match parse_url_path(&chunk.fid) {
Some(p) => p,
None => {
return Some(
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("invalid chunk fid: {}", chunk.fid),
)
.into_response(),
// Validate the attacker-controlled chunk offset before indexing: a
// negative value would wrap to a huge usize, and an out-of-range one has
// nowhere to land.
if chunk.offset < 0 || chunk.size < 0 {
return Some(
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("invalid negative chunk offset/size in {}", chunk.fid),
)
}
};
let mut chunk_needle = Needle {
id: chunk_nid,
cookie: chunk_cookie,
..Needle::default()
};
match store.read_volume_needle(chunk_vid, &mut chunk_needle) {
Ok(_) => {}
.into_response(),
);
}
let data = match read_chunk_needle(state, &chunk.fid).await {
Ok(d) => d,
Err(e) => {
return Some(
(
@@ -3256,56 +3271,16 @@ fn try_expand_chunk_manifest(
.into_response(),
)
}
}
// Validate the attacker-controlled chunk offset before indexing: a
// negative value would wrap to a huge usize, and an out-of-range one has
// nowhere to land.
if chunk.offset < 0 {
return Some(
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("invalid negative chunk offset in {}", chunk.fid),
)
.into_response(),
);
}
};
let offset = chunk.offset as usize;
if offset >= result.len() {
continue;
}
// Write the chunk into its window in `result`. Compressed chunks inflate
// directly into the destination slice (bounded by the remaining window),
// so a chunk never allocates a second large buffer — peak memory stays at
// ~manifest.size instead of doubling. Bytes past the window are dropped,
// matching the prior truncation behavior.
if chunk_needle.is_compressed() {
use flate2::read::GzDecoder;
use std::io::Read as _;
let mut decoder = GzDecoder::new(&chunk_needle.data[..]);
let window = &mut result[offset..];
let mut written = 0usize;
let mut decode_failed = false;
while written < window.len() {
match decoder.read(&mut window[written..]) {
Ok(0) => break,
Ok(n) => written += n,
Err(_) => {
decode_failed = true;
break;
}
}
}
// On any decode failure, drop the partial output and fall back to the
// chunk's raw bytes (truncated to the window), preserving prior behavior.
if decode_failed {
window[..written].fill(0);
let copy_len = chunk_needle.data.len().min(window.len());
window[..copy_len].copy_from_slice(&chunk_needle.data[..copy_len]);
}
} else {
let copy_len = chunk_needle.data.len().min(result.len() - offset);
result[offset..offset + copy_len].copy_from_slice(&chunk_needle.data[..copy_len]);
}
// Clamp to the chunk's declared size so an over-long chunk can't bleed
// into the next chunk's window; also drop bytes past the buffer end.
let bound = (chunk.size as usize).min(result.len() - offset);
let copy_len = data.len().min(bound);
result[offset..offset + copy_len].copy_from_slice(&data[..copy_len]);
}
// Determine filename: URL path filename, then manifest name
@@ -3451,6 +3426,136 @@ fn try_expand_chunk_manifest(
Some((StatusCode::OK, response_headers, result).into_response())
}
/// Read one chunk-manifest chunk's final (decompressed) content bytes from
/// wherever it lives: a local regular volume, a local EC volume
/// (reconstruct-on-read from surviving shards), or a peer resolved via the
/// master. Mirrors Go's ChunkedFileReader, which looks every chunk up through
/// the master instead of assuming a local regular needle.
async fn read_chunk_needle(
state: &Arc<VolumeServerState>,
fid: &str,
) -> Result<Vec<u8>, String> {
let (vid, nid, cookie) =
parse_url_path(fid).ok_or_else(|| format!("invalid chunk fid: {}", fid))?;
// Decide where the chunk lives under one store read lock; drop it before any
// await (the EC and remote paths are async).
enum Placement {
Ec,
Remote,
}
let placement = {
let store = state.store.read().unwrap();
if store.find_volume(vid).is_some() {
let mut n = Needle {
id: nid,
cookie,
..Needle::default()
};
return store
.read_volume_needle(vid, &mut n)
.map_err(|e| format!("{}", e))
.and_then(|_| cookie_checked_chunk(n, cookie));
} else if store.find_ec_volume(vid).is_some() {
Placement::Ec
} else {
Placement::Remote
}
};
match placement {
Placement::Ec => {
match crate::server::store_ec::read_ec_shard_needle_distributed(state, vid, nid).await {
Ok(Some(n)) => cookie_checked_chunk(n, cookie),
Ok(None) => Err("not found".to_string()),
Err(e) => Err(format!("{}", e)),
}
}
// The peer serves through its own GET handler, which validates the cookie.
Placement::Remote => read_remote_chunk_needle(state, vid, fid).await,
}
}
/// Validate a locally-read chunk's cookie against the one in its fid, then return
/// its content bytes. The main GET paths check the cookie after a read; a chunk
/// read must do the same so a stale/guessed id can't serve another needle's data.
fn cookie_checked_chunk(n: Needle, cookie: Cookie) -> Result<Vec<u8>, String> {
if n.cookie != cookie {
return Err("not found".to_string());
}
decompress_chunk(n)
}
/// Return a needle's content bytes, decompressing gzip payloads the way the read
/// handler does for a client that did not ask for gzip.
fn decompress_chunk(n: Needle) -> Result<Vec<u8>, String> {
if n.is_compressed() {
match maybe_decompress_gzip(&n.data) {
Ok(d) => Ok(d),
Err(GunzipError::TooLarge) => {
Err("compressed chunk exceeds decompression limit".to_string())
}
// Not valid gzip; keep the raw bytes, matching the prior fallback.
Err(GunzipError::Decode) => Ok(n.data),
}
} else {
Ok(n.data)
}
}
/// Fetch a chunk that is not hosted locally from a peer volume server. The peer
/// serves the final (decompressed) bytes whether the chunk is on a regular or EC
/// volume, so a chunk whose EC shards live elsewhere is still reconstructed on
/// the holder's side. Mirrors Go's ChunkedFileReader.readChunkNeedle.
async fn read_remote_chunk_needle(
state: &Arc<VolumeServerState>,
vid: VolumeId,
fid: &str,
) -> Result<Vec<u8>, String> {
let locations = lookup_volume(
&state.http_client,
&state.outgoing_http_scheme,
&state.master_url,
vid.0,
)
.await?;
if locations.is_empty() {
return Err("not found".to_string());
}
let mut last_err = String::new();
for loc in &locations {
// Skip self: the local paths already ruled this server out.
if loc.url.contains(&state.self_url) {
continue;
}
let target_http = to_http_address(&loc.url);
let url = match normalize_outgoing_http_url(
&state.outgoing_http_scheme,
&format!("{}/{}?proxied=true", target_http, fid),
) {
Ok(u) => u,
Err(e) => {
last_err = e;
continue;
}
};
match state.http_client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => match resp.bytes().await {
Ok(b) => return Ok(b.to_vec()),
Err(e) => last_err = format!("read body from {}: {}", url, e),
},
Ok(resp) => last_err = format!("{} returned {}", url, resp.status()),
Err(e) => last_err = format!("request to {} failed: {}", url, e),
}
}
Err(if last_err.is_empty() {
"not found".to_string()
} else {
last_err
})
}
// ============================================================================
// Helpers
// ============================================================================
+112 -8
View File
@@ -625,7 +625,8 @@ async fn send_deregister_heartbeat(
) {
let empty = {
let store = state.store.read().unwrap();
let (location_uuids, disk_tags) = collect_location_metadata(&store);
// Deregister: no effective max computed, fall back to configured max.
let (location_uuids, disk_tags) = collect_location_metadata(&store, &[]);
master_pb::Heartbeat {
id: store.id.clone(),
ip: config.ip.clone(),
@@ -747,7 +748,10 @@ fn collect_heartbeat(
)
}
fn collect_location_metadata(store: &Store) -> (Vec<String>, Vec<master_pb::DiskTag>) {
fn collect_location_metadata(
store: &Store,
disk_max_by_id: &[i32],
) -> (Vec<String>, Vec<master_pb::DiskTag>) {
let location_uuids = store
.locations
.iter()
@@ -757,9 +761,17 @@ fn collect_location_metadata(store: &Store) -> (Vec<String>, Vec<master_pb::Disk
.locations
.iter()
.enumerate()
.map(|(disk_id, loc)| master_pb::DiskTag {
disk_id: disk_id as u32,
tags: loc.tags.clone(),
.map(|(disk_id, loc)| {
let max_volume_count = disk_max_by_id
.get(disk_id)
.copied()
.unwrap_or_else(|| loc.max_volume_count.load(Ordering::Relaxed));
master_pb::DiskTag {
disk_id: disk_id as u32,
tags: loc.tags.clone(),
r#type: loc.disk_type.to_string(),
max_volume_count: max_volume_count as i64,
}
})
.collect();
(location_uuids, disk_tags)
@@ -790,6 +802,8 @@ fn build_heartbeat_with_ec_status(
let mut volumes = Vec::new();
let mut max_file_key = NeedleId(0);
let mut max_volume_counts: HashMap<String, u32> = HashMap::new();
let mut disk_total_bytes: HashMap<String, u64> = HashMap::new();
let mut disk_free_bytes: HashMap<String, u64> = HashMap::new();
// Collect per-collection disk size and read-only counts for metrics
let mut disk_sizes: HashMap<String, (u64, u64)> = HashMap::new(); // (normal, deleted)
@@ -797,6 +811,9 @@ fn build_heartbeat_with_ec_status(
let volume_size_limit = store.volume_size_limit.load(Ordering::Relaxed);
// Per-disk effective max for DiskTag, captured alongside the per-type sum.
let mut disk_max_by_id = vec![0i32; store.locations.len()];
for (disk_id, loc) in store.locations.iter_mut().enumerate() {
let disk_type_str = loc.disk_type.to_string();
let mut effective_max_count = loc.max_volume_count.load(Ordering::Relaxed);
@@ -812,7 +829,15 @@ fn build_heartbeat_with_ec_status(
if effective_max_count < 0 {
effective_max_count = 0;
}
*max_volume_counts.entry(disk_type_str).or_insert(0) += effective_max_count as u32;
*max_volume_counts.entry(disk_type_str.clone()).or_insert(0) += effective_max_count as u32;
disk_max_by_id[disk_id] = effective_max_count;
// Sum capacity per disk type; assumes one location per filesystem. Locations
// sharing a mount over-report absolute bytes but not the used ratio the gate
// uses. Mirrors weed/storage/store.go.
*disk_total_bytes.entry(disk_type_str.clone()).or_insert(0) +=
loc.disk_total_bytes.load(Ordering::Relaxed);
*disk_free_bytes.entry(disk_type_str).or_insert(0) +=
loc.disk_free_bytes.load(Ordering::Relaxed);
let mut delete_vids = Vec::new();
for (_, vol) in loc.iter_volumes() {
@@ -861,7 +886,7 @@ fn build_heartbeat_with_ec_status(
replica_placement: vol.super_block.replica_placement.to_byte() as u32,
version: vol.super_block.version.0 as u32,
ttl: vol.super_block.ttl.to_u32(),
compact_revision: vol.last_compact_revision() as u32,
compact_revision: vol.super_block.compaction_revision as u32,
modified_at_second: vol.last_modified_ts() as i64,
disk_type: loc.disk_type.to_string(),
disk_id: disk_id as u32,
@@ -930,7 +955,7 @@ fn build_heartbeat_with_ec_status(
crate::metrics::MAX_VOLUMES.set(total_max);
let has_no_volumes = volumes.is_empty();
let (location_uuids, disk_tags) = collect_location_metadata(store);
let (location_uuids, disk_tags) = collect_location_metadata(store, &disk_max_by_id);
master_pb::Heartbeat {
id: store.id.clone(),
@@ -946,6 +971,8 @@ fn build_heartbeat_with_ec_status(
has_no_volumes,
has_no_ec_shards,
max_volume_counts,
disk_total_bytes,
disk_free_bytes,
grpc_port: config.grpc_port as u32,
location_uuids,
disk_tags,
@@ -1153,6 +1180,46 @@ mod tests {
heartbeat.disk_tags[0].tags,
vec!["fast".to_string(), "ssd".to_string()]
);
assert_eq!(heartbeat.disk_tags[0].r#type, DiskType::HardDrive.to_string());
assert_eq!(heartbeat.disk_tags[0].max_volume_count, 3);
}
#[test]
fn test_build_heartbeat_disk_tag_reflects_disk_space_low_override() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
3,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
vec![],
)
.unwrap();
store
.add_volume(
VolumeId(7),
"pics",
None,
None,
0,
DiskType::HardDrive,
Version::current(),
)
.unwrap();
// Low disk space caps the per-disk max at used slots (1 volume, 0 EC).
store.locations[0]
.is_disk_space_low
.store(true, std::sync::atomic::Ordering::Relaxed);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert_eq!(heartbeat.disk_tags[0].max_volume_count, 1);
assert_eq!(heartbeat.max_volume_counts[&DiskType::HardDrive.to_string()], 1);
}
#[test]
@@ -1262,6 +1329,43 @@ mod tests {
);
}
#[test]
fn test_build_heartbeat_reports_disk_bytes() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
8,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
// Populate the cached physical-capacity fields from a real statvfs probe.
store.locations[0].check_disk_space();
let heartbeat = build_heartbeat(&test_config(), &mut store);
let disk_type = store.locations[0].disk_type.to_string();
assert!(
heartbeat
.disk_total_bytes
.get(&disk_type)
.copied()
.unwrap_or(0)
> 0,
"expected nonzero disk_total_bytes for the temp filesystem"
);
assert!(
heartbeat.disk_free_bytes.contains_key(&disk_type),
"expected a disk_free_bytes entry for the disk type"
);
}
#[test]
fn test_collect_ec_heartbeat_sets_go_metadata_and_ec_metrics() {
let temp_dir = tempfile::tempdir().unwrap();
+168 -49
View File
@@ -115,8 +115,13 @@ pub async fn read_ec_shard_needle_distributed(
{
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
shard_locations = fresh.clone();
write_back_shard_locations(state, vid, fresh);
// A complete reply merges into the cache; an incomplete one
// (< data_shards) is left unwritten — keep the prior cache.
if let Some(merged) =
write_back_shard_locations(state, vid, fresh, snapshot.data_shards as usize)
{
shard_locations = merged;
}
}
Err(e) => {
// Lookup failed — proceed with cached values. If cache
@@ -144,7 +149,7 @@ pub async fn read_ec_shard_needle_distributed(
shard_offset,
size,
} => {
let buf = fetch_one_interval(
let (buf, is_deleted) = fetch_one_interval(
state,
vid,
needle_id,
@@ -157,6 +162,12 @@ pub async fn read_ec_shard_needle_distributed(
snapshot.encode_ts_ns,
)
.await?;
// A peer reports the needle deleted (a cross-server window where the
// local index still shows it live): treat as not-found rather than
// serving zeros, mirroring Go's ErrorDeleted.
if is_deleted {
return Ok(None);
}
assembled.push(buf);
}
}
@@ -241,11 +252,23 @@ pub async fn scrub_ec_volume_distributed(
let mut errs = seed_errs;
// Refresh the shard-location cache once up front (mirrors Go's
// cachedLookupEcShardLocations); a failed lookup is a hard error rather than
// a per-needle connect storm against a down master.
// cachedLookupEcShardLocations). A partial reply (< data_shards locations, a
// master mid-recovery) or a failed lookup is a hard, retryable error — never
// overwrite a good cache with a partial map or storm a down master per needle.
if needs_refresh(&cached_locations, cache_refreshed_at, data_shards, total_shards) {
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => write_back_shard_locations(state, vid, fresh),
Ok(fresh) => {
if write_back_shard_locations(state, vid, fresh, data_shards).is_none() {
return (
0,
Vec::new(),
vec![format!(
"failed to locate shard via master grpc: fewer than {} data-shard locations returned",
data_shards
)],
);
}
}
Err(e) => {
return (
0,
@@ -256,6 +279,24 @@ pub async fn scrub_ec_volume_distributed(
}
}
// Hoist the post-refresh shard-location map once; it is stable for the whole
// walk, so per-needle snapshots no longer clone it.
let locations: HashMap<ShardId, Vec<String>> = {
let store = state.store.read().unwrap();
let ecv = match store.find_ec_volume(vid) {
Some(v) => v,
None => {
return (
0,
Vec::new(),
vec![format!("EC volume id {} not found", vid.0)],
)
}
};
let map = ecv.shard_locations.read().unwrap().clone();
map
};
// Walk the .ecx (private fd, no lock) for the row count + live (id, offset, size).
let mut count: i64 = 0;
let mut needles: Vec<(NeedleId, Offset, Size)> = Vec::new();
@@ -263,7 +304,12 @@ pub async fn scrub_ec_volume_distributed(
Ok(mut f) => {
if let Err(e) = crate::storage::idx::walk_index_file(&mut f, 0, |id, offset, size| {
count += 1;
if !size.is_tombstone() {
// Skip ALL deleted entries: -1 tombstones (runtime delete folded
// into .ecx) and -originalSize entries (a needle deleted on the
// regular volume before EC encode). get_actual_size uses the raw
// signed size, so a negative would yield empty intervals
// (false-positive) or an under-16-byte buffer (parse panic).
if !size.is_deleted() {
needles.push((id, offset, size));
}
Ok(())
@@ -281,8 +327,13 @@ pub async fn scrub_ec_volume_distributed(
// Per-needle snapshot under the lock from the RAW .ecx (offset, size) so
// logically-deleted needles are still verified; lock dropped before await.
let snapshot = match scrub_snapshot_under_lock(state, vid, offset, size) {
Ok(Some(s)) => s,
Ok(None) => continue, // volume gone since the walk
Ok(s) => s,
// Volume unmounted mid-scan: abort with an error rather than skipping
// every remaining needle, which would report a false-CLEAN result.
Err(e) if e.kind() == io::ErrorKind::NotFound => {
errs.push(format!("EC volume {} unmounted during scrub: {}", vid.0, e));
break;
}
Err(e) => {
errs.push(format!("needle {} on EC volume {}: {}", id.0, vid.0, e));
continue;
@@ -301,14 +352,11 @@ pub async fn scrub_ec_volume_distributed(
shard_offset,
size: ssize,
} => {
let sources = snapshot
.cached_locations
.get(shard_id)
.cloned()
.unwrap_or_default();
let sources: &[String] =
locations.get(shard_id).map(Vec::as_slice).unwrap_or(&[]);
match read_remote_ec_shard_interval(
state,
&sources,
sources,
vid,
id,
*shard_id,
@@ -318,7 +366,11 @@ pub async fn scrub_ec_volume_distributed(
)
.await
{
Ok(buf) => data.extend_from_slice(&buf),
// A deleted shard yields no bytes; zero-fill the interval so
// the assembled needle reaches read_bytes -> SizeMismatch{0}
// -> the delete-state suppression (mirrors Go's pre-zeroed buffer).
Ok((_, true)) => data.resize(data.len() + *ssize, 0),
Ok((buf, false)) => data.extend_from_slice(&buf),
Err(_) => {
errs.push(format!(
"failed to read EC shard {} for needle {} on volume {} (interval {}/{})",
@@ -408,33 +460,52 @@ fn scrub_snapshot_under_lock(
vid: VolumeId,
offset: Offset,
size: Size,
) -> io::Result<Option<Snapshot>> {
) -> io::Result<ScrubSnapshot> {
let store = state.store.read().unwrap();
let ecv = match store.find_ec_volume(vid) {
Some(v) => v,
None => return Ok(None),
// Volume unmounted mid-scan: a distinct NotFound so the caller aborts
// with an error rather than silently skipping (which would false-CLEAN).
None => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("EC volume {} not found (unmounted mid-scan)", vid.0),
))
}
};
let intervals = ecv.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
build_snapshot(ecv, offset, size, &intervals).map(Some)
}
/// Read any locally-held shard intervals and assemble the rest as `NeedRemote`,
/// then snapshot the scalars + shard-location cache so the caller can drop the
/// store lock before awaiting remote reads. Shared by the read and scrub paths.
fn build_snapshot(
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
offset: Offset,
size: Size,
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
) -> io::Result<Snapshot> {
if intervals.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"no intervals for needle",
));
}
let actual = get_actual_size(size, ecv.version);
Ok(ScrubSnapshot {
version: ecv.version,
actual_size: get_actual_size(size, ecv.version) as usize,
size_for_parse: size,
intervals: read_local_intervals(ecv, &intervals),
encode_ts_ns: ecv.encode_ts_ns,
})
}
/// Scalars + locally-read intervals for the FULL scrub. Unlike `Snapshot` it
/// omits the shard-location cache: the scrub hoists the refreshed map once up
/// front instead of cloning it per needle.
struct ScrubSnapshot {
version: Version,
actual_size: usize,
size_for_parse: Size,
intervals: Vec<IntervalResult>,
encode_ts_ns: i64,
}
/// Read any locally-held shard intervals, marking the rest `NeedRemote`. Shared
/// by the read-path `build_snapshot` and the scrub snapshot.
fn read_local_intervals(
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
) -> Vec<IntervalResult> {
let mut interval_results = Vec::with_capacity(intervals.len());
for interval in intervals {
let (shard_id, shard_offset) = interval.to_shard_id_and_offset(ecv.data_shards);
@@ -459,7 +530,25 @@ fn build_snapshot(
}),
}
}
interval_results
}
/// Read local intervals, then snapshot the scalars + shard-location cache so the
/// read path can drop the store lock before awaiting remote reads.
fn build_snapshot(
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
offset: Offset,
size: Size,
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
) -> io::Result<Snapshot> {
if intervals.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"no intervals for needle",
));
}
let actual = get_actual_size(size, ecv.version);
let interval_results = read_local_intervals(ecv, intervals);
let cached_locations = ecv.shard_locations.read().unwrap().clone();
let cache_refreshed_at = *ecv.shard_locations_refresh_time.lock().unwrap();
@@ -555,19 +644,29 @@ async fn cached_lookup_ec_shard_locations(
Ok(out)
}
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
/// cache. Returns the merged map on success, or `None` when the reply is
/// incomplete (and was therefore NOT written) or the volume is gone.
///
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
/// partial, not ground truth — Go aborts the lookup with a retryable error and
/// leaves the cache + refresh time untouched. Returning `None` without writing
/// does the same, so a previously-complete cache is never clobbered with a
/// partial map. On a complete reply the write is a per-shard MERGE (see
/// `merge_shard_locations`), not a full replace.
fn write_back_shard_locations(
state: &Arc<VolumeServerState>,
vid: VolumeId,
locations: HashMap<ShardId, Vec<String>>,
) {
let store = state.store.read().unwrap();
if let Some(ecv) = store.find_ec_volume(vid) {
// Atomic swap + freshness stamp so a concurrent reader sees
// either the prior cache or the fresh one — never an
// intermediate half-replaced map with the freshness flag
// already flipped.
ecv.replace_shard_locations(locations);
data_shards: usize,
) -> Option<HashMap<ShardId, Vec<String>>> {
if locations.len() < data_shards {
return None;
}
let store = state.store.read().unwrap();
let ecv = store.find_ec_volume(vid)?;
Some(ecv.merge_shard_locations(locations))
}
/// Build a SeaweedFS-style `host:httpPort.grpcPort` address from a
@@ -599,7 +698,7 @@ async fn fetch_one_interval(
data_shards: usize,
parity_shards: usize,
expected_encode_ts_ns: i64,
) -> io::Result<Vec<u8>> {
) -> io::Result<(Vec<u8>, bool)> {
// Direct peer read against the cached locations for this shard.
if let Some(sources) = shard_locations.get(&shard_id) {
if !sources.is_empty() {
@@ -615,7 +714,9 @@ async fn fetch_one_interval(
)
.await
{
Ok(buf) => return Ok(buf),
// A deleted needle short-circuits: don't reconstruct (every shard
// would report deleted), let the caller return "deleted".
Ok((buf, is_deleted)) => return Ok((buf, is_deleted)),
Err(e) => {
tracing::debug!(
"direct read ec shard {}.{} from {:?} failed: {} — will reconstruct",
@@ -631,7 +732,7 @@ async fn fetch_one_interval(
// Reconstruct: fan-out reads to every other shard at the same
// (shard_offset, size). Mirrors `recoverOneRemoteEcShardInterval`.
recover_one_remote_ec_shard_interval(
let buf = recover_one_remote_ec_shard_interval(
state,
vid,
needle_id,
@@ -643,7 +744,8 @@ async fn fetch_one_interval(
parity_shards,
expected_encode_ts_ns,
)
.await
.await?;
Ok((buf, false))
}
async fn read_remote_ec_shard_interval(
@@ -655,7 +757,7 @@ async fn read_remote_ec_shard_interval(
shard_offset: i64,
size: usize,
expected_encode_ts_ns: i64,
) -> io::Result<Vec<u8>> {
) -> io::Result<(Vec<u8>, bool)> {
let mut last_err: Option<io::Error> = None;
for src in sources {
match do_read_remote_ec_shard_interval(
@@ -670,7 +772,7 @@ async fn read_remote_ec_shard_interval(
)
.await
{
Ok(buf) => return Ok(buf),
Ok(res) => return Ok(res),
Err(e) => last_err = Some(e),
}
}
@@ -691,7 +793,7 @@ async fn do_read_remote_ec_shard_interval(
shard_offset: i64,
size: usize,
expected_encode_ts_ns: i64,
) -> io::Result<Vec<u8>> {
) -> io::Result<(Vec<u8>, bool)> {
let grpc_addr =
parse_grpc_address(source).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
let endpoint = build_grpc_endpoint(&grpc_addr, state.outgoing_grpc_tls.as_ref())
@@ -740,6 +842,7 @@ async fn do_read_remote_ec_shard_interval(
let mut stream = resp.into_inner();
let mut out = Vec::with_capacity(size);
let mut is_deleted = false;
while let Some(msg) = stream
.message()
.await
@@ -757,10 +860,23 @@ async fn do_read_remote_ec_shard_interval(
),
));
}
if msg.is_deleted {
is_deleted = true;
}
if !msg.data.is_empty() {
out.extend_from_slice(&msg.data);
}
}
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
// at read time and answers is_deleted with no payload. Signal the deletion to
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
// into Reed-Solomon. Exempt from the short-read guard below.
if is_deleted {
return Ok((Vec::new(), true));
}
if out.len() < size {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
@@ -775,7 +891,7 @@ async fn do_read_remote_ec_shard_interval(
));
}
out.truncate(size);
Ok(out)
Ok((out, false))
}
async fn recover_one_remote_ec_shard_interval(
@@ -859,8 +975,11 @@ async fn recover_one_remote_ec_shard_interval(
for (sid, res) in results {
match res {
Ok(buf) => {
if (sid as usize) < total_shards {
// Exclude a deleted shard from reconstruction (Go gates on a full
// read): feeding the empty/zero buffer into Reed-Solomon would
// corrupt the recovered shard.
Ok((buf, is_deleted)) => {
if !is_deleted && (sid as usize) < total_shards {
bufs[sid as usize] = Some(buf);
}
}
@@ -38,6 +38,10 @@ pub struct DiskLocation {
ec_volumes: HashMap<VolumeId, EcVolume>,
pub is_disk_space_low: Arc<AtomicBool>,
pub available_space: AtomicU64,
// Physical filesystem capacity from the latest check_disk_space probe, reported
// to the master so balancing can see real disk fullness, not just slot counts.
pub disk_total_bytes: AtomicU64,
pub disk_free_bytes: AtomicU64,
pub min_free_space: MinFreeSpace,
}
@@ -74,6 +78,8 @@ impl DiskLocation {
ec_volumes: HashMap::new(),
is_disk_space_low: Arc::new(AtomicBool::new(false)),
available_space: AtomicU64::new(0),
disk_total_bytes: AtomicU64::new(0),
disk_free_bytes: AtomicU64::new(0),
min_free_space,
})
}
@@ -661,6 +667,8 @@ impl DiskLocation {
};
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
self.available_space.store(free, Ordering::Relaxed);
self.disk_total_bytes.store(total, Ordering::Relaxed);
self.disk_free_bytes.store(free, Ordering::Relaxed);
// Update resource gauges
crate::metrics::RESOURCE_GAUGE
@@ -248,18 +248,20 @@ impl ShardChecksumBuilder {
/// Atomically writes `prot` to `path`, wrapped in the on-disk header with a
/// CRC32C over the serialized payload (temp file + rename).
pub fn save_bitrot_sidecar(path: &str, prot: &EcBitrotProtection) -> io::Result<()> {
let payload = prot.encode_to_vec();
// The header records payload_len as a uint32 and the allocation below adds it
// to a constant. Bound the payload well under any overflow (a real manifest is
// a few KB) so neither the length field nor the buffer can wrap. Mirrors Go's
// SaveBitrotSidecar maxBitrotPayloadSize check.
// The header records payload_len as a uint32 and the buffer allocation below
// adds it to a constant. Bound the payload well under any overflow (a real
// manifest is a few KB) so neither the length field nor the buffer can wrap.
// Check the encoded length BEFORE serializing so an oversized manifest never
// allocates a huge buffer. Mirrors Go's SaveBitrotSidecar maxBitrotPayloadSize.
const MAX_BITROT_PAYLOAD_SIZE: usize = 1 << 30; // 1 GiB, vastly above any real sidecar
if payload.len() > MAX_BITROT_PAYLOAD_SIZE {
let payload_len = prot.encoded_len();
if payload_len > MAX_BITROT_PAYLOAD_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("bitrot sidecar payload too large: {} bytes", payload.len()),
format!("bitrot sidecar payload too large: {} bytes", payload_len),
));
}
let payload = prot.encode_to_vec();
let mut buf = Vec::with_capacity(BITROT_HEADER_SIZE + payload.len());
buf.extend_from_slice(&BITROT_MAGIC.to_be_bytes());
buf.extend_from_slice(&BITROT_FORMAT_VERSION.to_be_bytes());
@@ -258,13 +258,12 @@ pub fn rebuild_ec_files(
Ok(())
}
/// Verify EC shards by computing parity against the existing data and identifying corrupted shards.
///
/// No longer wired to a scrub mode: FULL is now Go's per-needle local+remote walk
/// (`store_ec::scrub_ec_volume_distributed`). Retained as a standalone Reed-Solomon
/// parity check — the only parity/cold-region verification available until the
/// `.ecsum` bitrot CHECKSUM path lands.
#[allow(dead_code)]
/// Reed-Solomon parity check over the locally-held shards: recompute parity from
/// the data shards and flag any shard whose bytes disagree. Wired into FULL
/// (scrub mode 2) as a TEMPORARY local parity/cold-region check — the per-needle
/// FULL walk only reads live data-shard intervals, so on its own it can't catch
/// bitrot in a parity shard or an unwalked region. Move to mode 4 (CHECKSUM) and
/// drop it from mode 2 once the `.ecsum` subsystem lands.
pub fn verify_ec_shards(
dir: &str,
collection: &str,
@@ -653,10 +653,10 @@ impl EcVolume {
/// against a half-populated cache and return NotFound for the
/// not-yet-inserted shards.
///
/// Callers populating the whole cache atomically should use
/// [`Self::replace_shard_locations`] instead — it swaps the
/// entire map under the write lock and advances the refresh
/// timestamp in one step.
/// Callers writing back a whole `LookupEcVolume` reply should use
/// [`Self::merge_shard_locations`] instead — it upserts the reply's
/// shards under the write lock and advances the refresh timestamp in
/// one step, retaining cached shards the reply omits.
pub fn set_shard_locations(&self, shard_id: ShardId, locations: Vec<String>) {
self.shard_locations
.write()
@@ -675,6 +675,29 @@ impl EcVolume {
*self.shard_locations_refresh_time.lock().unwrap() = Some(std::time::Instant::now());
}
/// Merge a fresh `LookupEcVolume` reply into the shard-locations cache and
/// stamp the refresh time, returning a clone of the resulting map.
///
/// Per-shard upsert (mirrors Go's `cachedLookupEcShardLocations`): each shard
/// id present in the reply overwrites its cached entry, while shard ids absent
/// from the reply keep their previously-cached locations — so a reply that
/// passes the data-shard completeness guard but omits a shard already in cache
/// does not drop that shard's known location (unlike a full replace).
pub fn merge_shard_locations(
&self,
locations: HashMap<ShardId, Vec<String>>,
) -> HashMap<ShardId, Vec<String>> {
let merged = {
let mut guard = self.shard_locations.write().unwrap();
for (shard_id, addrs) in locations {
guard.insert(shard_id, addrs);
}
guard.clone()
};
*self.shard_locations_refresh_time.lock().unwrap() = Some(std::time::Instant::now());
merged
}
/// Get a cloned list of server addresses for a given shard ID.
pub fn get_shard_locations(&self, shard_id: ShardId) -> Vec<String> {
self.shard_locations
+100
View File
@@ -834,3 +834,103 @@ async fn replicate_write_does_not_re_replicate() {
"plain write to a multi-copy volume must attempt replication"
);
}
// ============================================================================
// Chunk-manifest expansion resolves chunks on EC volumes
//
// A chunked object whose data chunks live on an EC-encoded volume must expand
// by reconstruct-on-read from the shards, not by a local regular-volume lookup
// (which finds nothing once the volume is EC-encoded). Mirrors Go's
// ChunkedFileReader, which resolves every chunk through the master.
// ============================================================================
#[tokio::test]
async fn chunk_manifest_expands_chunk_stored_on_ec_volume() {
use seaweed_volume::storage::erasure_coding::ec_encoder::write_ec_files;
use seaweed_volume::storage::needle::needle::{FileId, Needle};
use seaweed_volume::storage::types::{Cookie, NeedleId};
use seaweed_volume::storage::volume::Volume;
let (state, tmp) = test_state();
let dir = tmp.path().to_str().unwrap();
// A chunk large enough to be worth EC-encoding; its bytes are the payload we
// expect the manifest GET to return.
let chunk_data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
let chunk_nid = NeedleId(0x2a);
let chunk_cookie = Cookie(0x1234abcd);
// Build regular volume 2 holding the chunk, then EC-encode it and mount all
// 14 shards locally so reconstruct-on-read is a pure local read.
{
let mut v = Volume::new(
dir,
dir,
"",
VolumeId(2),
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap();
let mut n = Needle {
id: chunk_nid,
cookie: chunk_cookie,
data: chunk_data.clone(),
data_size: chunk_data.len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
v.sync_to_disk().unwrap();
v.close();
}
write_ec_files(dir, dir, "", VolumeId(2), 10, 4).unwrap();
// Volume 2 was built standalone (never registered in the store), so it only
// exists as EC shards — the chunk resolves through the EC path, as it would
// after ec.encode retired the regular volume.
{
let mut store = state.store.write().unwrap();
let shard_ids: Vec<u32> = (0..14).collect();
store.mount_ec_shards(VolumeId(2), "", &shard_ids).unwrap();
}
// Write the chunk-manifest needle to regular volume 1.
let chunk_fid = FileId::new(VolumeId(2), chunk_nid, chunk_cookie).to_string();
let manifest = format!(
r#"{{"name":"big.bin","mime":"application/octet-stream","size":{},"chunks":[{{"fid":"{}","offset":0,"size":{}}}]}}"#,
chunk_data.len(),
chunk_fid,
chunk_data.len()
);
let manifest_nid = NeedleId(0x7);
let manifest_cookie = Cookie(0x55667788);
{
let mut store = state.store.write().unwrap();
let mut n = Needle {
id: manifest_nid,
cookie: manifest_cookie,
data: manifest.into_bytes(),
..Needle::default()
};
n.data_size = n.data.len() as u32;
n.set_is_chunk_manifest();
store.write_volume_needle(VolumeId(1), &mut n).unwrap();
}
// GET the manifest object; expect the reconstructed chunk bytes.
let manifest_fid = FileId::new(VolumeId(1), manifest_nid, manifest_cookie).to_string();
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.uri(format!("/{}", manifest_fid))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_bytes(response).await, chunk_data);
}
+19 -2
View File
@@ -333,11 +333,19 @@ func (f *FuseTestFramework) waitForService(addr string, timeout time.Duration) e
return fmt.Errorf("service at %s not ready within timeout", addr)
}
// waitForMount waits for the FUSE mount to be ready
// waitForMount waits for the FUSE mount to be ready. A stat/ReadDir probe
// alone is not enough: the bare mount point directory passes both before the
// mount process finishes starting, letting tests race ahead and write to the
// local disk underneath the mount. The mount point's device ID differing from
// its parent's confirms a filesystem is actually mounted there.
func (f *FuseTestFramework) waitForMount(timeout time.Duration) error {
parentDev, err := deviceID(filepath.Dir(f.mountPoint))
if err != nil {
return fmt.Errorf("stat mount point parent: %v", err)
}
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if _, err := os.Stat(f.mountPoint); err == nil {
if dev, err := deviceID(f.mountPoint); err == nil && dev != parentDev {
if _, err := os.ReadDir(f.mountPoint); err == nil {
return nil
}
@@ -347,6 +355,15 @@ func (f *FuseTestFramework) waitForMount(timeout time.Duration) error {
return fmt.Errorf("mount point not ready within timeout")
}
// deviceID returns the device ID of the filesystem containing path.
func deviceID(path string) (uint64, error) {
var st syscall.Stat_t
if err := syscall.Stat(path, &st); err != nil {
return 0, err
}
return uint64(st.Dev), nil
}
// findWeedBinary locates the weed binary.
func findWeedBinary() string {
if p, err := exec.LookPath("weed"); err == nil {
@@ -88,13 +88,9 @@ func writeBufferCapConfig(debugPort int) *TestConfig {
"-writeBufferSizeMB=16",
"-debug=true",
fmt.Sprintf("-debug.port=%d", debugPort),
// Route glog to stderr so the framework's process log
// capture actually contains something — by default weed
// sends glog to /tmp/weed.* files which the CI artifact
// upload step never sees. Critical for diagnosing
// upload/saveToStorage errors on Linux runs.
"-logtostderr=true",
"-v=2",
// NOTE: glog flags (-logtostderr, -v) are globals parsed
// before the subcommand; passing them here makes weed
// mount exit with a usage error before ever mounting.
},
SkipCleanup: false,
}
+3 -9
View File
@@ -311,9 +311,7 @@ func (s *AdminServer) getFilerNodesStatus() []FilerNode {
// Get filer nodes from master using ListClusterNodes
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.FilerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
if err != nil {
return err
}
@@ -352,9 +350,7 @@ func (s *AdminServer) getMessageBrokerNodesStatus() []MessageBrokerNode {
// Get message broker nodes from master using ListClusterNodes
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.BrokerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
if err != nil {
return err
}
@@ -393,9 +389,7 @@ func (s *AdminServer) getS3NodesStatus() []S3Node {
// Get S3 nodes from master using ListClusterNodes
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.S3Type,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
if err != nil {
return err
}
+15 -14
View File
@@ -85,6 +85,7 @@ type AdminServer struct {
masterClient *wdclient.MasterClient
templateFS http.FileSystem
dataDir string
filerGroup string
grpcDialOption grpc.DialOption
cacheExpiration time.Duration
lastCacheUpdate time.Time
@@ -134,13 +135,13 @@ type AdminServer struct {
// Type definitions moved to types.go
func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string, icebergPort int) *AdminServer {
func NewAdminServer(masters string, filerGroup string, templateFS http.FileSystem, dataDir string, icebergPort int) *AdminServer {
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.admin")
// Create master client with multiple master support
masterClient := wdclient.NewMasterClient(
grpcDialOption,
"", // filerGroup - not needed for admin
filerGroup,
"admin", // clientType
"", // clientHost - not needed for admin
"", // dataCenter - not needed for admin
@@ -162,6 +163,7 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,
masterClient: masterClient,
templateFS: templateFS,
dataDir: dataDir,
filerGroup: filerGroup,
grpcDialOption: grpcDialOption,
cacheExpiration: defaultCacheTimeout,
filerCacheExpiration: defaultFilerCacheTimeout,
@@ -293,6 +295,13 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,
return server
}
func (s *AdminServer) listClusterNodesRequest(clientType string) *master_pb.ListClusterNodesRequest {
return &master_pb.ListClusterNodesRequest{
ClientType: clientType,
FilerGroup: s.filerGroup,
}
}
// vacuumToggler abstracts the master's vacuum enable/disable for testing.
type vacuumToggler interface {
disableVacuum() error
@@ -1112,9 +1121,7 @@ func (s *AdminServer) GetClusterFilers() (*ClusterFilersData, error) {
// Get filer information from master using ListClusterNodes
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.FilerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
if err != nil {
return err
}
@@ -1159,9 +1166,7 @@ func (s *AdminServer) GetClusterBrokers() (*ClusterBrokersData, error) {
// Get broker information from master using ListClusterNodes
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.BrokerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
if err != nil {
return err
}
@@ -1206,9 +1211,7 @@ func (s *AdminServer) GetClusterS3Servers() (*ClusterS3ServersData, error) {
// Get S3 server information from master using ListClusterNodes
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.S3Type,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
if err != nil {
return err
}
@@ -1642,9 +1645,7 @@ func (s *AdminServer) UpdateTopicRetention(namespace, name string, enabled bool,
// Get broker information from master
var brokerAddress string
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.BrokerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
if err != nil {
return err
}
@@ -0,0 +1,30 @@
package dash
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/cluster"
)
func TestListClusterNodesRequestIncludesFilerGroup(t *testing.T) {
server := &AdminServer{filerGroup: "tenant-a"}
req := server.listClusterNodesRequest(cluster.FilerType)
if req.ClientType != cluster.FilerType {
t.Fatalf("ClientType = %q, want %q", req.ClientType, cluster.FilerType)
}
if req.FilerGroup != "tenant-a" {
t.Fatalf("FilerGroup = %q, want %q", req.FilerGroup, "tenant-a")
}
}
func TestListClusterNodesRequestKeepsDefaultFilerGroupEmpty(t *testing.T) {
server := &AdminServer{}
req := server.listClusterNodesRequest(cluster.FilerType)
if req.FilerGroup != "" {
t.Fatalf("FilerGroup = %q, want empty", req.FilerGroup)
}
}
+1 -3
View File
@@ -76,9 +76,7 @@ func (s *AdminServer) getDiscoveredFilers() []string {
// Discover filers from masters
var filers []string
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.FilerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
if err != nil {
return err
}
+10 -1
View File
@@ -150,10 +150,19 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
var totalMaxVolumes int64
var totalSize int64
var totalFiles int64
// Prefer the real physical disk capacity the volume server
// reports per disk; the slot-based estimate overstates capacity
// when maxVolumeCount is configured higher than the disk holds.
var diskCapacity int64
for _, diskInfo := range node.DiskInfos {
totalVolumes += diskInfo.VolumeCount
totalMaxVolumes += diskInfo.MaxVolumeCount
if diskInfo.DiskTotalBytes > 0 {
diskCapacity += int64(diskInfo.DiskTotalBytes)
} else {
diskCapacity += diskInfo.MaxVolumeCount * int64(resp.VolumeSizeLimitMb) * 1024 * 1024
}
// Sum up individual volume information
for _, volInfo := range diskInfo.VolumeInfos {
@@ -198,7 +207,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
Volumes: int(totalVolumes),
MaxVolumes: int(totalMaxVolumes),
DiskUsage: totalSize,
DiskCapacity: totalMaxVolumes * int64(resp.VolumeSizeLimitMb) * 1024 * 1024,
DiskCapacity: diskCapacity,
LastHeartbeat: time.Now(),
}
+2 -4
View File
@@ -494,9 +494,7 @@ func (s *AdminServer) findBrokerLeader() (string, error) {
// First, try to find any broker from the cluster
var brokers []string
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.BrokerType,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
if err != nil {
return err
}
@@ -524,7 +522,7 @@ func (s *AdminServer) findBrokerLeader() (string, error) {
// Try to find broker leader
_, err := client.FindBrokerLeader(ctx, &mq_pb.FindBrokerLeaderRequest{
FilerGroup: "",
FilerGroup: s.filerGroup,
})
if err == nil {
return nil // This broker is the leader
+1 -3
View File
@@ -805,9 +805,7 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
s3Seen := map[string]struct{}{}
if err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.S3Type,
})
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
if err != nil {
return err
}
+8 -1
View File
@@ -471,7 +471,14 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
// Process disk information
for _, diskInfo := range node.DiskInfos {
vs.MaxVolumes += int(diskInfo.MaxVolumeCount)
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024 // Use actual volume size limit
// Prefer the real physical disk capacity the volume server
// reports; the slot-based estimate overstates capacity when
// maxVolumeCount is configured higher than the disk holds.
if diskInfo.DiskTotalBytes > 0 {
vs.DiskCapacity += int64(diskInfo.DiskTotalBytes)
} else {
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024
}
// Count regular volumes and calculate disk usage
for _, volInfo := range diskInfo.VolumeInfos {
+41 -35
View File
@@ -154,11 +154,11 @@ func (s *WorkerGrpcServer) Stop() error {
s.running = false
close(s.stopChan)
// Close all worker connections
// Close all worker connections. Cancelling the context stops each
// handleOutgoingMessages goroutine; the outgoing channel is never closed.
s.connMutex.Lock()
for _, conn := range s.connections {
conn.cancel()
s.safeCloseOutgoingChannel(conn, "Stop")
}
s.connections = make(map[string]*WorkerConnection)
s.connMutex.Unlock()
@@ -227,10 +227,9 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
s.connMutex.Lock()
if oldConn, exists := s.connections[workerID]; exists {
glog.Infof("Worker %s reconnected, cleaning up old connection", workerID)
// Cancel old connection to stop its goroutines
// Cancel old connection to stop its goroutines. Its handleOutgoingMessages
// exits on the cancelled context; the outgoing channel is never closed.
oldConn.cancel()
// Don't close oldConn.outgoing here as it may cause panic in handleOutgoingMessages
// Let the goroutine exit naturally when it detects context cancellation
}
s.connections[workerID] = conn
s.connMutex.Unlock()
@@ -255,11 +254,8 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
},
}
select {
case conn.outgoing <- regResponse:
if s.sendToWorker(conn, regResponse, 5*time.Second, "registration response") {
glog.V(1).Infof("Registration response sent to worker %s", workerID)
case <-time.After(5 * time.Second):
glog.Errorf("Failed to send registration response to worker %s", workerID)
}
// Handle incoming messages
@@ -384,11 +380,7 @@ func (s *WorkerGrpcServer) handleHeartbeat(conn *WorkerConnection, heartbeat *wo
},
}
select {
case conn.outgoing <- response:
case <-time.After(time.Second):
glog.Warningf("Failed to send heartbeat response to worker %s", conn.workerID)
}
s.sendToWorker(conn, response, time.Second, "heartbeat response")
}
// handleTaskRequest processes task requests from workers
@@ -435,11 +427,7 @@ func (s *WorkerGrpcServer) handleTaskRequest(conn *WorkerConnection, request *wo
},
}
select {
case conn.outgoing <- assignment:
case <-time.After(time.Second):
glog.Warningf("Failed to send task assignment to worker %s", conn.workerID)
}
s.sendToWorker(conn, assignment, time.Second, "task assignment")
} else {
// Send explicit "No Task" response to prevent worker timeout
// Workers expect a TaskAssignment message but will sleep if TaskId is empty
@@ -452,11 +440,8 @@ func (s *WorkerGrpcServer) handleTaskRequest(conn *WorkerConnection, request *wo
},
}
select {
case conn.outgoing <- noTaskAssignment:
if s.sendToWorker(conn, noTaskAssignment, time.Second, "no-task response") {
glog.V(4).Infof("Sent 'No Task' response to worker %s", conn.workerID)
case <-time.After(time.Second):
// If we can't send, the worker will eventually time out and reconnect, which is fine
}
}
}
@@ -596,14 +581,22 @@ func (s *WorkerGrpcServer) handleTaskLogResponse(conn *WorkerConnection, respons
s.logRequestsMutex.Unlock()
}
// safeCloseOutgoingChannel safely closes the outgoing channel for a worker connection.
func (s *WorkerGrpcServer) safeCloseOutgoingChannel(conn *WorkerConnection, source string) {
defer func() {
if r := recover(); r != nil {
glog.V(1).Infof("%s: recovered from panic closing outgoing channel for worker %s: %v", source, conn.workerID, r)
}
}()
close(conn.outgoing)
// sendToWorker queues a message on conn.outgoing, which is deliberately never
// closed: it has multiple concurrent senders, so closing it could panic one of
// them with "send on closed channel". Teardown is signaled via conn.ctx instead;
// handleOutgoingMessages drains the channel until that context is cancelled.
// Returns false if the connection closed or the send timed out.
func (s *WorkerGrpcServer) sendToWorker(conn *WorkerConnection, msg *worker_pb.AdminMessage, timeout time.Duration, description string) bool {
select {
case conn.outgoing <- msg:
return true
case <-conn.ctx.Done():
glog.V(2).Infof("Dropped %s for worker %s: connection closed", description, conn.workerID)
return false
case <-time.After(timeout):
glog.Warningf("Failed to send %s to worker %s: timeout", description, conn.workerID)
return false
}
}
// unregisterWorker removes a worker connection
@@ -628,12 +621,11 @@ func (s *WorkerGrpcServer) unregisterWorker(conn *WorkerConnection, event string
s.connMutex.Unlock()
stats_collect.AdminWorkerEventsTotal.WithLabelValues(event).Inc()
// Cancel context to signal goroutines to stop
// Cancel context to signal goroutines to stop. The outgoing channel is
// never closed (it has multiple senders); handleOutgoingMessages exits on
// the cancelled context.
conn.cancel()
// Safely close the outgoing channel with recover to handle potential double-close
s.safeCloseOutgoingChannel(conn, "unregisterWorker")
glog.V(1).Infof("Unregistered worker %s", conn.workerID)
}
@@ -732,6 +724,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i
select {
case conn.outgoing <- logRequest:
glog.V(1).Infof("Log request sent to worker %s for task %s", workerID, taskID)
case <-conn.ctx.Done():
s.logRequestsMutex.Lock()
if s.pendingLogRequests[requestKey] == requestContext {
delete(s.pendingLogRequests, requestKey)
}
s.logRequestsMutex.Unlock()
return nil, fmt.Errorf("worker %s connection closed", workerID)
case <-time.After(logSendTimeout):
// Clean up pending request on timeout
s.logRequestsMutex.Lock()
@@ -750,6 +749,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i
}
glog.V(1).Infof("Received %d log entries for task %s from worker %s", len(response.LogEntries), taskID, workerID)
return response.LogEntries, nil
case <-conn.ctx.Done():
s.logRequestsMutex.Lock()
if s.pendingLogRequests[requestKey] == requestContext {
delete(s.pendingLogRequests, requestKey)
}
s.logRequestsMutex.Unlock()
return nil, fmt.Errorf("worker %s connection closed", workerID)
case <-time.After(logResponseTimeout):
// Clean up pending request on timeout
s.logRequestsMutex.Lock()
@@ -0,0 +1,81 @@
package dash
import (
"context"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
)
func newTestWorkerConn(bufferSize int) *WorkerConnection {
ctx, cancel := context.WithCancel(context.Background())
return &WorkerConnection{
workerID: "w-test",
outgoing: make(chan *worker_pb.AdminMessage, bufferSize),
ctx: ctx,
cancel: cancel,
}
}
// TestSendToWorkerDropsOnCancelledContext verifies a send bails out via the
// connection context instead of blocking for the full timeout once the
// connection is torn down and its buffer is full.
func TestSendToWorkerDropsOnCancelledContext(t *testing.T) {
s := &WorkerGrpcServer{adminServer: &AdminServer{}}
conn := newTestWorkerConn(1)
// Fill the buffer so the next send cannot enqueue.
conn.outgoing <- &worker_pb.AdminMessage{}
conn.cancel()
start := time.Now()
if s.sendToWorker(conn, &worker_pb.AdminMessage{}, 5*time.Second, "heartbeat response") {
t.Fatal("expected send to be dropped when context cancelled and buffer full")
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("send blocked for %v; expected an immediate context-cancelled bail", elapsed)
}
}
// TestHeartbeatDuringUnregisterDoesNotPanic is a regression test for the
// "panic: send on closed channel" crash: unregisterWorker (called from the
// stale-connection cleanup routine) used to close conn.outgoing while the
// WorkerStream goroutine was still sending heartbeat responses to it.
func TestHeartbeatDuringUnregisterDoesNotPanic(t *testing.T) {
s := &WorkerGrpcServer{
adminServer: &AdminServer{},
connections: make(map[string]*WorkerConnection),
}
conn := newTestWorkerConn(100)
s.connections[conn.workerID] = conn
// Drain outgoing like handleOutgoingMessages would, until teardown.
go func() {
for {
select {
case <-conn.ctx.Done():
return
case <-conn.outgoing:
}
}
}()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 2000; i++ {
s.handleHeartbeat(conn, &worker_pb.WorkerHeartbeat{})
}
}()
go func() {
defer wg.Done()
s.unregisterWorker(conn, "test")
}()
// Under the old close()-based teardown this would panic the sender goroutine
// and crash the test binary.
wg.Wait()
}
@@ -459,6 +459,83 @@ func TestECPlannerSeesEachPhysicalDisk(t *testing.T) {
}
}
// TestVolumeIndexResolvesPhysicalDiskZero pins that a volume genuinely on
// physical disk 0 resolves to its own disk via GetVolumeLocations even when the
// aggregate DiskInfo.DiskId is seeded from a non-zero sibling (as ToDiskInfo
// does from volumes[0]). Re-deriving the per-record disk id would fold disk 0
// onto the sibling, then the lookup would find no matching volume and drop it.
func TestVolumeIndexResolvesPhysicalDiskZero(t *testing.T) {
topology := NewActiveTopology(10)
require.NoError(t, topology.UpdateTopology(&master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{
Id: "rack1",
DataNodeInfos: []*master_pb.DataNodeInfo{{
Id: "127.0.0.1:8080",
DiskInfos: map[string]*master_pb.DiskInfo{
"hdd": {
DiskId: 6, // seeded from volumes[0].DiskId
MaxVolumeCount: 200,
VolumeInfos: []*master_pb.VolumeInformationMessage{
{Id: 11, DiskId: 6, DiskType: "hdd"},
{Id: 10, DiskId: 0, DiskType: "hdd"},
},
},
},
}},
}},
}},
}))
loc10 := topology.GetVolumeLocations(10, "")
require.Len(t, loc10, 1, "volume on physical disk 0 must resolve to one disk")
assert.Equal(t, uint32(0), loc10[0].DiskID, "volume 10 lives on physical disk 0")
loc11 := topology.GetVolumeLocations(11, "")
require.Len(t, loc11, 1)
assert.Equal(t, uint32(6), loc11[0].DiskID, "volume 11 lives on physical disk 6")
}
// TestECShardIndexResolvesPhysicalDiskZero is the EC-shard twin of
// TestVolumeIndexResolvesPhysicalDiskZero: rebuildIndexes builds ecShardIndex
// the same way, so an EC shard on physical disk 0 must resolve via
// GetECShardLocations rather than being folded onto a non-zero sibling.
func TestECShardIndexResolvesPhysicalDiskZero(t *testing.T) {
topology := NewActiveTopology(10)
require.NoError(t, topology.UpdateTopology(&master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{
Id: "rack1",
DataNodeInfos: []*master_pb.DataNodeInfo{{
Id: "127.0.0.1:8080",
DiskInfos: map[string]*master_pb.DiskInfo{
"hdd": {
DiskId: 6, // seeded from a non-zero sibling
MaxVolumeCount: 200,
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
{Id: 21, DiskId: 6, Collection: "c1", EcIndexBits: 0b1},
{Id: 20, DiskId: 0, Collection: "c1", EcIndexBits: 0b1},
},
},
},
}},
}},
}},
}))
loc20 := topology.GetECShardLocations(20, "c1")
require.Len(t, loc20, 1, "EC shard on physical disk 0 must resolve to one disk")
assert.Equal(t, uint32(0), loc20[0].DiskID, "shard 20 lives on physical disk 0")
loc21 := topology.GetECShardLocations(21, "c1")
require.Len(t, loc21, 1)
assert.Equal(t, uint32(6), loc21[0].DiskID, "shard 21 lives on physical disk 6")
}
// TestPublicInterfaces tests the public interface methods
func TestPublicInterfaces(t *testing.T) {
topology := NewActiveTopology(10)
+4
View File
@@ -181,6 +181,8 @@ func (at *ActiveTopology) GetDisksWithEffectiveCapacity(taskType TaskType, exclu
ActiveVolumeCount: disk.DiskInfo.DiskInfo.ActiveVolumeCount,
FreeVolumeCount: disk.DiskInfo.DiskInfo.FreeVolumeCount,
Tags: append([]string(nil), disk.DiskInfo.DiskInfo.Tags...),
DiskTotalBytes: disk.DiskInfo.DiskInfo.DiskTotalBytes,
DiskFreeBytes: disk.DiskInfo.DiskInfo.DiskFreeBytes,
}
diskCopy.DiskInfo = diskInfoCopy
diskCopy.DiskInfo.MaxVolumeCount = disk.DiskInfo.DiskInfo.MaxVolumeCount // Ensure Max is set
@@ -246,6 +248,8 @@ func (at *ActiveTopology) GetDisksForPlanning(taskType TaskType, excludeNodeID s
ActiveVolumeCount: disk.DiskInfo.DiskInfo.ActiveVolumeCount,
FreeVolumeCount: disk.DiskInfo.DiskInfo.FreeVolumeCount,
Tags: append([]string(nil), disk.DiskInfo.DiskInfo.Tags...),
DiskTotalBytes: disk.DiskInfo.DiskInfo.DiskTotalBytes,
DiskFreeBytes: disk.DiskInfo.DiskInfo.DiskFreeBytes,
}
diskCopy.DiskInfo = diskInfoCopy
+10 -15
View File
@@ -216,27 +216,22 @@ func (at *ActiveTopology) rebuildIndexes() {
at.volumeIndex = make(map[uint32][]string)
at.ecShardIndex = make(map[uint32][]string)
// Index by the per-record DiskId (not the outer DiskInfo.DiskId) so the
// keys match the per-physical-disk activeDisk entries — see #9369.
// Derive index keys from the same SplitByPhysicalDisk reconstruction that
// builds at.disks, so every volume/EC lookup resolves to a real activeDisk
// entry. Re-deriving the per-record disk id here would diverge on physical
// disk 0, which the raw DiskId cannot tell apart from the "unset" default.
for _, dc := range at.topologyInfo.DataCenterInfos {
for _, rack := range dc.RackInfos {
for _, nodeInfo := range rack.DataNodeInfos {
for _, diskInfo := range nodeInfo.DiskInfos {
for _, volumeInfo := range diskInfo.VolumeInfos {
diskID := volumeInfo.DiskId
if diskID == 0 && diskInfo.DiskId != 0 {
diskID = diskInfo.DiskId
for _, perDisk := range diskInfo.SplitByPhysicalDisk() {
diskKey := fmt.Sprintf("%s:%d", nodeInfo.Id, perDisk.DiskId)
for _, volumeInfo := range perDisk.VolumeInfos {
at.volumeIndex[volumeInfo.Id] = append(at.volumeIndex[volumeInfo.Id], diskKey)
}
diskKey := fmt.Sprintf("%s:%d", nodeInfo.Id, diskID)
at.volumeIndex[volumeInfo.Id] = append(at.volumeIndex[volumeInfo.Id], diskKey)
}
for _, ecShardInfo := range diskInfo.EcShardInfos {
diskID := ecShardInfo.DiskId
if diskID == 0 && diskInfo.DiskId != 0 {
diskID = diskInfo.DiskId
for _, ecShardInfo := range perDisk.EcShardInfos {
at.ecShardIndex[ecShardInfo.Id] = append(at.ecShardIndex[ecShardInfo.Id], diskKey)
}
diskKey := fmt.Sprintf("%s:%d", nodeInfo.Id, diskID)
at.ecShardIndex[ecShardInfo.Id] = append(at.ecShardIndex[ecShardInfo.Id], diskKey)
}
}
}
+1 -6
View File
@@ -588,11 +588,6 @@ templ ClusterVolumes(data dash.ClusterVolumesData) {
window.location.href = url.toString();
}
function exportVolumes() {
// TODO: Implement volume export functionality
alert('Export functionality to be implemented');
}
function viewVolumeDetails(volumeId) {
// Get the server from the current row - works for both buttons and volume ID links
const clickedElement = event.target;
@@ -724,4 +719,4 @@ func maxInt(a, b int) int {
return a
}
return b
}
}
+1 -1
View File
@@ -1048,7 +1048,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "</small></div></div></div><!-- JavaScript for pagination and sorting --><script>\n // Initialize pagination links when page loads\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n \n // Add click handlers to view details buttons\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to volume ID links\n document.querySelectorAll('.volume-id-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to vacuum buttons\n document.querySelectorAll('.vacuum-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n const server = this.getAttribute('data-server');\n performVacuum(volumeId, server, this);\n });\n });\n });\n \n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n \n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function exportVolumes() {\n // TODO: Implement volume export functionality\n alert('Export functionality to be implemented');\n }\n \n function viewVolumeDetails(volumeId) {\n // Get the server from the current row - works for both buttons and volume ID links\n const clickedElement = event.target;\n const row = clickedElement.closest('tr');\n const serverCell = row.querySelector('td:nth-child(2) a');\n const server = serverCell ? serverCell.textContent.trim() : 'unknown';\n \n window.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${encodeURIComponent(server)}`;\n }\n\n function performVacuum(volumeId, server, button) {\n // Disable button and show loading state\n const originalHTML = button.innerHTML;\n button.disabled = true;\n button.innerHTML = '<i class=\"fas fa-spinner fa-spin\"></i>';\n\n // Send vacuum request\n fetch((window.__BASE_PATH__ || '') + `/api/volumes/${volumeId}/${encodeURIComponent(server)}/vacuum`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showMessage(data.error, 'error');\n } else {\n showMessage(data.message || 'Volume vacuum started successfully', 'success');\n // Optionally refresh the page after a delay to show updated vacuum status\n setTimeout(() => {\n Line truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "</small></div></div></div><!-- JavaScript for pagination and sorting --><script>\n // Initialize pagination links when page loads\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n \n // Add click handlers to view details buttons\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to volume ID links\n document.querySelectorAll('.volume-id-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to vacuum buttons\n document.querySelectorAll('.vacuum-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n const server = this.getAttribute('data-server');\n performVacuum(volumeId, server, this);\n });\n });\n });\n \n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n \n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function viewVolumeDetails(volumeId) {\n // Get the server from the current row - works for both buttons and volume ID links\n const clickedElement = event.target;\n const row = clickedElement.closest('tr');\n const serverCell = row.querySelector('td:nth-child(2) a');\n const server = serverCell ? serverCell.textContent.trim() : 'unknown';\n \n window.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${encodeURIComponent(server)}`;\n }\n\n function performVacuum(volumeId, server, button) {\n // Disable button and show loading state\n const originalHTML = button.innerHTML;\n button.disabled = true;\n button.innerHTML = '<i class=\"fas fa-spinner fa-spin\"></i>';\n\n // Send vacuum request\n fetch((window.__BASE_PATH__ || '') + `/api/volumes/${volumeId}/${encodeURIComponent(server)}/vacuum`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showMessage(data.error, 'error');\n } else {\n showMessage(data.message || 'Volume vacuum started successfully', 'success');\n // Optionally refresh the page after a delay to show updated vacuum status\n setTimeout(() => {\n window.location.reload();\n }, 2000);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n Line truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+5 -2
View File
@@ -44,6 +44,7 @@ type AdminOptions struct {
grpcPort *int
master *string
masters *string // deprecated, for backward compatibility
filerGroup *string
adminUser *string
adminPassword *string
readOnlyUser *string
@@ -65,6 +66,7 @@ func init() {
a.grpcPort = cmdAdmin.Flag.Int("port.grpc", 0, "gRPC server port for worker connections (default: http port + 10000)")
a.master = cmdAdmin.Flag.String("master", "localhost:9333", "comma-separated master servers")
a.masters = cmdAdmin.Flag.String("masters", "", "comma-separated master servers (deprecated, use -master instead)")
a.filerGroup = cmdAdmin.Flag.String("filerGroup", "", "filerGroup for the filers, brokers, and S3 servers")
a.dataDir = cmdAdmin.Flag.String("dataDir", ".", "directory to store admin configuration and data files (default current dir; required for maintenance task state to persist)")
a.adminUser = cmdAdmin.Flag.String("adminUser", "admin", "admin interface username")
@@ -82,7 +84,7 @@ func init() {
}
var cmdAdmin = &Command{
UsageLine: "admin -port=23646 -master=localhost:9333 [-port.grpc=33646] [-dataDir=/path/to/data]",
UsageLine: "admin -port=23646 -master=localhost:9333 [-filerGroup=group] [-port.grpc=33646] [-dataDir=/path/to/data]",
Short: "start SeaweedFS web admin interface",
Long: `Start a web admin interface for SeaweedFS cluster management.
@@ -99,6 +101,7 @@ var cmdAdmin = &Command{
Example Usage:
weed admin -port=23646 -master="master1:9333,master2:9333"
weed admin -port=23646 -master="localhost:9333" -filerGroup="tenant-a"
weed admin -port=23646 -master="localhost:9333" -dataDir="/var/lib/seaweedfs-admin"
weed admin -port=23646 -port.grpc=33646 -master="localhost:9333" -dataDir="~/seaweedfs-admin"
weed admin -port=9900 -port.grpc=19900 -master="localhost:9333"
@@ -383,7 +386,7 @@ func startAdminServer(ctx context.Context, options AdminOptions, enableUI bool,
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", admin.StaticHandler()))
// Create admin server (plugin is always enabled)
adminServer := dash.NewAdminServer(*options.master, nil, dataDir, icebergPort)
adminServer := dash.NewAdminServer(*options.master, *options.filerGroup, nil, dataDir, icebergPort)
// Show discovered filers
filers := adminServer.GetAllFilers()
-9
View File
@@ -371,9 +371,6 @@ func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) err
MimeType: mimeType,
PairMap: nil,
},
func(host, fileId string) string {
return fmt.Sprintf("http://%s/%s", host, fileId)
},
util.NewBytesReader(data),
)
if flushErr != nil {
@@ -456,9 +453,6 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
MimeType: "",
PairMap: nil,
},
func(host, fileId string) string {
return fmt.Sprintf("http://%s/%s", host, fileId)
},
io.NewSectionReader(f, i*chunkSize, chunkSize),
)
@@ -576,9 +570,6 @@ func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, off
MimeType: "",
PairMap: nil,
},
func(host, fileId string) string {
return fmt.Sprintf("http://%s/%s", host, fileId)
},
reader,
)
+110 -1
View File
@@ -58,6 +58,12 @@ var cmdFilerSyncVerify = &Command{
-modifiedTimeAgo to skip recently-modified files (sync-lag tolerance) and
-isActivePassive for unidirectional comparison.
A chunk-derived ETag (no stored attr.Md5) can differ between clusters only
because the chunk slice was assembled in a different order, since ETagChunks
does not sort by offset. Such files are byte-identical and reported as
CHUNK_REORDER: not counted as errors, always counted in the summary, listed
only at -v=1.
Exits with code 0 on agreement, 2 on differences or operational errors.
`,
@@ -123,6 +129,7 @@ type VerifyResult struct {
missingCount atomic.Int64
sizeMismatch atomic.Int64
etagMismatch atomic.Int64
chunkReorder atomic.Int64 // content-equal; chunks differ only in slice order
onlyInB atomic.Int64
skippedRecent atomic.Int64
@@ -139,6 +146,7 @@ const (
diffOnlyInB // in B but not in A
diffSizeMismatch // size differs
diffETagMismatch // etag differs
diffChunkReorder // etag differs but content is equal (chunk slice order only)
)
// diffRecord is the JSON Lines schema for a single diff entry.
@@ -167,6 +175,7 @@ type summaryRecord struct {
Missing int64 `json:"missing"`
SizeMismatch int64 `json:"sizeMismatch"`
ETagMismatch int64 `json:"etagMismatch"`
ChunkReorder int64 `json:"chunkReorder"`
OnlyInB int64 `json:"onlyInB"`
TotalErrors int64 `json:"totalErrors"`
}
@@ -236,6 +245,7 @@ func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
Missing: result.missingCount.Load(),
SizeMismatch: result.sizeMismatch.Load(),
ETagMismatch: result.etagMismatch.Load(),
ChunkReorder: result.chunkReorder.Load(),
OnlyInB: result.onlyInB.Load(),
TotalErrors: totalErrors,
}
@@ -250,6 +260,9 @@ func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
fmt.Fprintf(os.Stdout, " Missing in B: %d\n", result.missingCount.Load())
fmt.Fprintf(os.Stdout, " Size mismatch: %d\n", result.sizeMismatch.Load())
fmt.Fprintf(os.Stdout, " ETag mismatch: %d\n", result.etagMismatch.Load())
if n := result.chunkReorder.Load(); n > 0 {
fmt.Fprintf(os.Stdout, " Chunk reorder (equal): %d (content-equal, not an error; use -v=1 to list)\n", n)
}
if !isActivePassive {
fmt.Fprintf(os.Stdout, " Only in B: %d\n", result.onlyInB.Load())
}
@@ -496,11 +509,88 @@ func compareEntries(dir string, entryA, entryB *filer_pb.Entry, result *VerifyRe
etagA := filer.ETag(entryA)
etagB := filer.ETag(entryB)
if etagA != etagB {
reportDiff(diffETagMismatch, dir, entryA, entryB, result)
if isChunkReorder(entryA, entryB) {
// Same bytes, just a different chunk slice order — not a real diff.
reportDiff(diffChunkReorder, dir, entryA, entryB, result)
} else {
reportDiff(diffETagMismatch, dir, entryA, entryB, result)
}
return
}
}
// isChunkReorder reports whether two entries with differing file ETags are
// byte-identical, differing only in chunk slice order. filer.ETagChunks hashes
// per-chunk MD5s in stored order without sorting by offset, so the same bytes
// written by different paths (S3 multipart vs filer.backup) can hash
// differently. If both chunk lists sorted by offset match element-wise on
// (offset, size, ETag), the files cover the same bytes with the same content
// and only the slice order differed.
//
// Applies only when both ETags come from chunks (a stored attr.Md5 is
// order-independent, so a mismatch there is a real content difference) and the
// chunks form a manifest-free, non-overlapping set whose bytes are fully
// determined by the list — overlaps would need timestamp-based visible-interval
// resolution, so those stay ETAG_MISMATCH.
func isChunkReorder(entryA, entryB *filer_pb.Entry) bool {
if !usesChunkETag(entryA) || !usesChunkETag(entryB) {
return false
}
a := sortedSimpleChunks(entryA.GetChunks())
b := sortedSimpleChunks(entryB.GetChunks())
// nil means overlapping or manifest chunks we do not fast-path; a single
// chunk hashes directly and a differing count is a real divergence.
if a == nil || b == nil || len(a) != len(b) || len(a) < 2 {
return false
}
for i := range a {
if a[i].Offset != b[i].Offset || a[i].Size != b[i].Size || a[i].ETag != b[i].ETag {
return false
}
}
return true
}
// usesChunkETag reports whether filer.ETag falls back to ETagChunks for entry,
// i.e. no stored attr.Md5 whole-content hash is available. Mirrors filer.ETag's
// own condition so it agrees with how the compared ETag was computed.
func usesChunkETag(entry *filer_pb.Entry) bool {
return entry.Attributes == nil || entry.Attributes.Md5 == nil
}
// sortedSimpleChunks returns chunks sorted by (offset, ETag) if they are a
// manifest-free, non-overlapping set whose visible bytes are fully determined
// by the list and every chunk carries a usable per-chunk ETag; otherwise nil.
// Overlapping ranges would require resolving the visible interval by chunk
// timestamp, which this fast path does not attempt.
func sortedSimpleChunks(chunks []*filer_pb.FileChunk) []*filer_pb.FileChunk {
sorted := make([]*filer_pb.FileChunk, len(chunks))
copy(sorted, chunks)
sort.Slice(sorted, func(i, j int) bool {
if sorted[i].Offset != sorted[j].Offset {
return sorted[i].Offset < sorted[j].Offset
}
return sorted[i].ETag < sorted[j].ETag
})
prevEnd := int64(0)
for i, c := range sorted {
if c.IsChunkManifest {
return nil
}
// An empty or undecodable ETag is not a content fingerprint, so
// element-wise (offset, size, ETag) equality cannot prove the bytes
// match — decline rather than assert a false content-equality.
if len(util.Base64Md5ToBytes(c.ETag)) == 0 {
return nil
}
if i > 0 && c.Offset < prevEnd {
return nil
}
prevEnd = c.Offset + int64(c.Size)
}
return sorted
}
// mtimeRelation classifies B.mtime vs A.mtime. Both entries must be non-nil.
// Returns relation, absolute delta in seconds, and human-readable string.
func mtimeRelation(entryA, entryB *filer_pb.Entry) (relation, deltaStr string, deltaSec int64) {
@@ -557,11 +647,19 @@ func reportDiff(diffType verifyDiffType, dir string, entryA, entryB *filer_pb.En
result.sizeMismatch.Add(1)
case diffETagMismatch:
result.etagMismatch.Add(1)
case diffChunkReorder:
result.chunkReorder.Add(1)
}
if result.jsonOutput {
writeJSONDiff(result, diffType, dir, entryA, entryB)
} else {
// A chunk reorder is content-equal, not a real diff: keep it out of the
// default text report and list it only at -v=1. JSON always emits it so
// the per-record stream matches the summary count.
if diffType == diffChunkReorder && !glog.V(1) {
return
}
writeTextDiff(result, diffType, dir, entryA, entryB)
}
}
@@ -590,6 +688,9 @@ func writeTextDiff(result *VerifyResult, diffType verifyDiffType, dir string, en
ann := annotation(entryA, entryB)
fmt.Fprintf(os.Stdout, "[ETAG_MISMATCH] %s (a=%s, b=%s%s)\n",
entryPath, filer.ETag(entryA), filer.ETag(entryB), ann)
case diffChunkReorder:
fmt.Fprintf(os.Stdout, "[CHUNK_REORDER] %s (a=%s, b=%s, content-equal: chunks differ only in slice order)\n",
entryPath, filer.ETag(entryA), filer.ETag(entryB))
}
}
@@ -640,6 +741,14 @@ func writeJSONDiff(result *VerifyResult, diffType verifyDiffType, dir string, en
rec.MtimeRelation = relation
rec.MtimeDelta = delta
rec.Hint = hintFor(relation)
case diffChunkReorder:
rec.Type = "CHUNK_REORDER"
rec.A = toEntryRecord(entryA)
rec.B = toEntryRecord(entryB)
relation, delta, _ := mtimeRelation(entryA, entryB)
rec.MtimeRelation = relation
rec.MtimeDelta = delta
// no hint: content-equal, no action needed
}
writeJSONLine(result, rec)
+296
View File
@@ -4,11 +4,14 @@ import (
"context"
"fmt"
"io"
"os"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
@@ -101,6 +104,34 @@ func verifyDirEntry(name string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, IsDirectory: true}
}
// verifyChunk builds a FileChunk whose ETag is the base64 MD5 of seed, so
// filer.ETagChunks (which base64-decodes each chunk ETag) can hash it. Distinct
// seeds yield distinct per-chunk MD5s.
func verifyChunk(offset int64, size uint64, seed string) *filer_pb.FileChunk {
return &filer_pb.FileChunk{
Offset: offset,
Size: size,
ETag: util.Base64Encode(util.Md5([]byte(seed))),
}
}
// verifyChunkedEntry builds a chunk-backed entry with no stored attr.Md5, so
// its file ETag is derived from ETagChunks (the order-sensitive path). FileSize
// is the max chunk end, matching filer.FileSize, so size comparison passes.
func verifyChunkedEntry(name string, chunks []*filer_pb.FileChunk) *filer_pb.Entry {
var total uint64
for _, c := range chunks {
if end := uint64(c.Offset) + c.Size; end > total {
total = end
}
}
return &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileSize: total}, // Md5 nil → ETagChunks path
Chunks: chunks,
}
}
// --- tests ---
// TestVerifySyncMissingFile confirms that a file present in A but absent in B
@@ -280,6 +311,271 @@ func TestVerifySyncETagMismatch(t *testing.T) {
}
}
// TestVerifySyncChunkReorder confirms that two entries holding the SAME
// chunks (same offsets, same per-chunk MD5s) in a DIFFERENT slice order are
// classified as CHUNK_REORDER (content-equal), not ETAG_MISMATCH, and are
// therefore not counted as errors. This is the S3-multipart vs filer.backup
// reordering false positive.
func TestVerifySyncChunkReorder(t *testing.T) {
c0 := verifyChunk(0, 100, "chunk-0")
c1 := verifyChunk(100, 100, "chunk-1")
c2 := verifyChunk(200, 100, "chunk-2")
// A stores [c0,c1,c2]; B stores a permutation [c2,c0,c1] of the same chunks.
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c0, c1, c2})},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c2, c0, c1})},
},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.chunkReorder.Load(); got != 1 {
t.Errorf("chunkReorder = %d, want 1", got)
}
if got := result.etagMismatch.Load(); got != 0 {
t.Errorf("etagMismatch = %d, want 0 (reordered chunks are content-equal)", got)
}
if got := result.sizeMismatch.Load(); got != 0 {
t.Errorf("sizeMismatch = %d, want 0", got)
}
}
// TestVerifySyncGenuineChunkDivergence confirms that when one chunk's content
// actually differs (same offsets and count, different per-chunk MD5), the file
// stays classified as ETAG_MISMATCH and is NOT downgraded to CHUNK_REORDER.
func TestVerifySyncGenuineChunkDivergence(t *testing.T) {
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{
verifyChunk(0, 100, "chunk-0"),
verifyChunk(100, 100, "chunk-1"),
verifyChunk(200, 100, "chunk-2"),
})},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{
verifyChunk(0, 100, "chunk-0"),
verifyChunk(100, 100, "chunk-1"),
verifyChunk(200, 100, "chunk-2-DIFFERENT"), // real content divergence
})},
},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.etagMismatch.Load(); got != 1 {
t.Errorf("etagMismatch = %d, want 1 (genuine chunk content divergence)", got)
}
if got := result.chunkReorder.Load(); got != 0 {
t.Errorf("chunkReorder = %d, want 0 (content actually differs)", got)
}
}
// TestVerifySyncChunkCountDiffStaysEtagMismatch confirms that a differing chunk
// count with an equal file size (e.g. differently split content) is NOT treated
// as a reordering — it stays ETAG_MISMATCH.
func TestVerifySyncChunkCountDiffStaysEtagMismatch(t *testing.T) {
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{
verifyChunk(0, 100, "a"),
verifyChunk(100, 100, "b"),
verifyChunk(200, 100, "c"),
})},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{
verifyChunk(0, 150, "x"),
verifyChunk(150, 150, "y"),
})},
},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.sizeMismatch.Load(); got != 0 {
t.Errorf("sizeMismatch = %d, want 0 (both total 300 bytes)", got)
}
if got := result.etagMismatch.Load(); got != 1 {
t.Errorf("etagMismatch = %d, want 1", got)
}
if got := result.chunkReorder.Load(); got != 0 {
t.Errorf("chunkReorder = %d, want 0", got)
}
}
// TestVerifySyncDuplicateOffsetStaysEtagMismatch confirms that overlapping
// chunks at the same offset — where the visible bytes are resolved by chunk
// timestamp, not by the raw chunk list — are NOT fast-pathed to CHUNK_REORDER.
// Both sides hold the same two ETags at offset 0 in a different order, so the
// file ETags differ; the visible content is ambiguous from the list alone, so
// this must stay ETAG_MISMATCH.
func TestVerifySyncDuplicateOffsetStaysEtagMismatch(t *testing.T) {
c1 := verifyChunk(0, 100, "v1")
c2 := verifyChunk(0, 100, "v2") // same offset → overlap
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c1, c2})},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c2, c1})},
},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.etagMismatch.Load(); got != 1 {
t.Errorf("etagMismatch = %d, want 1 (overlapping offsets are not a safe reorder)", got)
}
if got := result.chunkReorder.Load(); got != 0 {
t.Errorf("chunkReorder = %d, want 0", got)
}
}
// TestVerifySyncManifestChunkStaysEtagMismatch confirms that entries containing
// a manifest chunk are not fast-pathed to CHUNK_REORDER: manifest chunks
// represent compacted, possibly overlapping history that this check does not
// resolve.
func TestVerifySyncManifestChunkStaysEtagMismatch(t *testing.T) {
manifest := func(offset int64, size uint64, seed string) *filer_pb.FileChunk {
c := verifyChunk(offset, size, seed)
c.IsChunkManifest = true
return c
}
a0, a1 := manifest(0, 100, "m0"), verifyChunk(100, 100, "m1")
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{a0, a1})},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{a1, a0})},
},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.etagMismatch.Load(); got != 1 {
t.Errorf("etagMismatch = %d, want 1 (manifest chunks are not fast-pathed)", got)
}
if got := result.chunkReorder.Load(); got != 0 {
t.Errorf("chunkReorder = %d, want 0", got)
}
}
// TestVerifySyncEmptyChunkETagStaysEtagMismatch confirms that a chunk with an
// empty per-chunk ETag is never fast-pathed to CHUNK_REORDER: an empty ETag is
// not a content fingerprint, so (offset, size, ETag) equality cannot prove the
// bytes match. The two sides reorder their non-empty chunks so the file ETags
// differ and the reorder check is reached, but the empty-ETag chunk in the
// middle must keep it ETAG_MISMATCH rather than assert a false content-equality.
func TestVerifySyncEmptyChunkETagStaysEtagMismatch(t *testing.T) {
c0 := verifyChunk(0, 100, "e0")
empty := &filer_pb.FileChunk{Offset: 100, Size: 100} // no ETag → not a fingerprint
c2 := verifyChunk(200, 100, "e2")
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c0, empty, c2})},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/root": {verifyChunkedEntry("data.bin", []*filer_pb.FileChunk{c2, c0, empty})},
},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.etagMismatch.Load(); got != 1 {
t.Errorf("etagMismatch = %d, want 1 (empty per-chunk ETag is not a content fingerprint)", got)
}
if got := result.chunkReorder.Load(); got != 0 {
t.Errorf("chunkReorder = %d, want 0", got)
}
}
// captureStdout runs fn with os.Stdout redirected to a pipe and returns what it
// wrote. Tests that assert on emitted diff records use it.
func captureStdout(t *testing.T, fn func()) string {
t.Helper()
orig := os.Stdout
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("os.Pipe: %v", err)
}
os.Stdout = w
fn()
w.Close()
os.Stdout = orig
data, err := io.ReadAll(r)
if err != nil {
t.Fatalf("read captured stdout: %v", err)
}
return string(data)
}
// TestVerifySyncChunkReorderJSONEmittedByDefault confirms that in JSON output
// mode a CHUNK_REORDER record is emitted at default verbosity: the -v=1 gate
// suppresses only the human text report, so the NDJSON per-record stream stays
// consistent with the summary count a machine consumer reads.
func TestVerifySyncChunkReorderJSONEmittedByDefault(t *testing.T) {
c0 := verifyChunk(0, 100, "chunk-0")
c1 := verifyChunk(100, 100, "chunk-1")
entryA := verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c0, c1})
entryB := verifyChunkedEntry("model.bin", []*filer_pb.FileChunk{c1, c0})
result := &VerifyResult{jsonOutput: true}
out := captureStdout(t, func() {
reportDiff(diffChunkReorder, "/root", entryA, entryB, result)
})
if got := result.chunkReorder.Load(); got != 1 {
t.Fatalf("chunkReorder = %d, want 1", got)
}
if !strings.Contains(out, `"type":"CHUNK_REORDER"`) {
t.Errorf("JSON output missing CHUNK_REORDER record at default verbosity; got %q", out)
}
}
// TestVerifySyncCutoffTime verifies that entries newer than cutoffTime are
// skipped in both the A-only (MISSING) and B-only (ONLY_IN_B) branches.
func TestVerifySyncCutoffTime(t *testing.T) {
+2
View File
@@ -543,6 +543,8 @@ func initMiniAdminFlags() {
miniAdminOptions.port = cmdMini.Flag.Int("admin.port", 23646, "admin server http listen port")
miniAdminOptions.grpcPort = cmdMini.Flag.Int("admin.port.grpc", 0, "admin server grpc listen port (default: admin http port + GrpcPortOffset)")
miniAdminOptions.master = cmdMini.Flag.String("admin.master", "", "master server address (automatically set)")
// admin discovery must query the same group the co-located filer registers under
miniAdminOptions.filerGroup = miniFilerOptions.filerGroup
miniAdminOptions.dataDir = cmdMini.Flag.String("admin.dataDir", "", "directory to store admin configuration and data files")
miniAdminOptions.adminUser = cmdMini.Flag.String("admin.user", "admin", "admin interface username")
miniAdminOptions.adminPassword = cmdMini.Flag.String("admin.password", "", "admin interface password (if empty, auth is disabled)")
+1 -1
View File
@@ -41,7 +41,7 @@ func NewChunkGroup(lookupFn wdclient.LookupFileIdFunctionType, chunkCache chunk_
group := &ChunkGroup{
lookupFn: lookupFn,
sections: make(map[SectionIndex]*FileChunkSection),
readerCache: NewReaderCache(readerCacheLimit, chunkCache, lookupFn),
readerCache: NewReaderCache(readerCacheLimit, chunkCache, lookupFn, nil),
concurrentReaders: concurrentReaders,
}
+2 -7
View File
@@ -17,7 +17,6 @@ type GatewayChunkUploader interface {
filerClient filer_pb.FilerClient,
assignRequest *filer_pb.AssignVolumeRequest,
uploadOption *operation.UploadOption,
genFileUrlFn func(host, fileId string) string,
reader io.Reader,
) (fileId string, uploadResult *operation.UploadResult, err error, data []byte)
}
@@ -120,11 +119,8 @@ func SaveGatewayDataAsChunk(req GatewayChunkUploadRequest) (*filer_pb.FileChunk,
PairMap: req.PairMap,
}
genFileUrlFn := func(host, fileId string) string {
if req.VolumeServerAccess == "filerProxy" && req.FilerHTTPAddress != "" {
return fmt.Sprintf("http://%s/?proxyChunkId=%s", req.FilerHTTPAddress, fileId)
}
return fmt.Sprintf("http://%s/%s", host, fileId)
if req.VolumeServerAccess == "filerProxy" && req.FilerHTTPAddress != "" {
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(req.FilerHTTPAddress)
}
assignRequest := &filer_pb.AssignVolumeRequest{
@@ -141,7 +137,6 @@ func SaveGatewayDataAsChunk(req GatewayChunkUploadRequest) (*filer_pb.FileChunk,
req.FilerClient,
assignRequest,
uploadOption,
genFileUrlFn,
req.Reader,
)
if uploadErr != nil {
+1 -1
View File
@@ -72,7 +72,7 @@ func (store *MysqlStore) initialize(dsn string, upsertQuery string, enableUpsert
}
gen := &SqlGenMysql{
CreateTableSqlTemplate: "",
DropTableSqlTemplate: "DROP TABLE `%s`",
DropTableSqlTemplate: "DROP TABLE IF EXISTS `%s`",
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
+1 -1
View File
@@ -65,7 +65,7 @@ func (store *MysqlStore2) initialize(createTable, upsertQuery string, enableUpse
}
gen := &mysql.SqlGenMysql{
CreateTableSqlTemplate: createTable,
DropTableSqlTemplate: "DROP TABLE `%s`",
DropTableSqlTemplate: "DROP TABLE IF EXISTS `%s`",
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
+1 -1
View File
@@ -64,7 +64,7 @@ func (store *PostgresStore) initialize(upsertQuery string, enableUpsert bool, us
}
gen := &SqlGenPostgres{
CreateTableSqlTemplate: "",
DropTableSqlTemplate: `drop table "%s"`,
DropTableSqlTemplate: `drop table if exists "%s"`,
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
+1 -1
View File
@@ -70,7 +70,7 @@ func (store *PostgresStore2) initialize(createTable, upsertQuery string, enableU
}
gen := &postgres.SqlGenPostgres{
CreateTableSqlTemplate: createTable,
DropTableSqlTemplate: `drop table "%s"`,
DropTableSqlTemplate: `drop table if exists "%s"`,
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
+5 -5
View File
@@ -77,7 +77,7 @@ func TestReaderAt(t *testing.T) {
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 10,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
@@ -124,7 +124,7 @@ func TestReaderAt0(t *testing.T) {
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 10,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
@@ -150,7 +150,7 @@ func TestReaderAt1(t *testing.T) {
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 20,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
@@ -183,7 +183,7 @@ func TestReaderAtGappedChunksDoNotLeak(t *testing.T) {
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 9,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
@@ -195,7 +195,7 @@ func TestReaderAtSparseFileDoesNotLeak(t *testing.T) {
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(NewIntervalList[*VisibleInterval](), 0, math.MaxInt64),
fileSize: 3,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil),
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
+92 -25
View File
@@ -14,9 +14,17 @@ import (
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
type CacheInvalidator interface {
InvalidateCache(fileId string)
}
type fetchChunkDataFnType func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, fileId string) (n int, err error)
type ReaderCache struct {
chunkCache chunk_cache.ChunkCache
lookupFileIdFn wdclient.LookupFileIdFunctionType
chunkCache chunk_cache.ChunkCache
lookupFileIdFn wdclient.LookupFileIdFunctionType
cacheInvalidator CacheInvalidator
fetchChunkDataFn fetchChunkDataFnType
sync.Mutex
downloaders map[string]*SingleChunkCacher
limit int
@@ -38,12 +46,14 @@ type SingleChunkCacher struct {
done chan struct{} // signals when download is complete
}
func NewReaderCache(limit int, chunkCache chunk_cache.ChunkCache, lookupFileIdFn wdclient.LookupFileIdFunctionType) *ReaderCache {
func NewReaderCache(limit int, chunkCache chunk_cache.ChunkCache, lookupFileIdFn wdclient.LookupFileIdFunctionType, cacheInvalidator CacheInvalidator) *ReaderCache {
return &ReaderCache{
limit: limit,
chunkCache: chunkCache,
lookupFileIdFn: lookupFileIdFn,
downloaders: make(map[string]*SingleChunkCacher),
limit: limit,
chunkCache: chunkCache,
lookupFileIdFn: lookupFileIdFn,
cacheInvalidator: cacheInvalidator,
fetchChunkDataFn: util_http.RetriedFetchChunkData,
downloaders: make(map[string]*SingleChunkCacher),
}
}
@@ -97,15 +107,29 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
rc.Lock()
if cacher, found := rc.downloaders[fileId]; found {
rc.Unlock()
n, err := cacher.readChunkAt(ctx, buffer, offset)
if n > 0 || err != nil {
return n, err
for {
if cacher, found := rc.downloaders[fileId]; found {
if cacher.hasCompletedError() {
delete(rc.downloaders, fileId)
rc.Unlock()
cacher.destroy()
rc.Lock()
continue
}
// Count this read on the cacher before releasing the map lock, so a
// concurrent destroy() (error eviction here, LRU, or UnCache) cannot
// start wg.Wait() on a zero counter while this read is about to register.
cacher.wg.Add(1)
rc.Unlock()
n, err := cacher.readChunkAt(ctx, buffer, offset)
if n > 0 || err != nil {
return n, err
}
// If n=0 and err=nil, the cacher couldn't provide data for this offset.
// Fall through to try chunkCache.
rc.Lock()
}
// If n=0 and err=nil, the cacher couldn't provide data for this offset.
// Fall through to try chunkCache.
rc.Lock()
break
}
if shouldCache || rc.lookupFileIdFn == nil {
n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset))
@@ -137,6 +161,7 @@ func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId st
go cacher.startCaching()
<-cacher.cacheStartedCh
rc.downloaders[fileId] = cacher
cacher.wg.Add(1)
rc.Unlock()
return cacher.readChunkAt(ctx, buffer, offset)
@@ -198,32 +223,74 @@ func (s *SingleChunkCacher) startCaching() {
// Lookup file ID without holding the lock
urlStrings, err := s.parent.lookupFileIdFn(context.Background(), s.chunkFileId)
if err != nil {
s.Lock()
s.err = fmt.Errorf("operation LookupFileId %s failed, err: %v", s.chunkFileId, err)
s.Unlock()
s.setError(fmt.Errorf("operation LookupFileId %s failed, err: %v", s.chunkFileId, err))
return
}
if len(urlStrings) == 0 {
s.setError(fmt.Errorf("operation LookupFileId %s failed, err: urls not found", s.chunkFileId))
return
}
// Allocate buffer and download without holding the lock
// This allows multiple downloads to proceed in parallel
data := mem.Allocate(s.chunkSize)
_, fetchErr := util_http.RetriedFetchChunkData(context.Background(), data, urlStrings, s.cipherKey, s.isGzipped, true, 0, s.chunkFileId)
data, fetchErr := s.fetchChunkData(context.Background(), urlStrings)
if fetchErr != nil {
data, fetchErr = s.retryFetchAfterCacheInvalidation(context.Background(), urlStrings, fetchErr)
}
// Now acquire lock to update state
s.Lock()
atomic.StoreInt64(&s.completedTimeNew, time.Now().UnixNano())
if fetchErr != nil {
mem.Free(data)
s.err = fetchErr
} else {
s.data = data
if s.shouldCache {
s.parent.chunkCache.SetChunk(s.chunkFileId, s.data)
}
atomic.StoreInt64(&s.completedTimeNew, time.Now().UnixNano())
}
s.Unlock()
}
func (s *SingleChunkCacher) setError(err error) {
s.Lock()
defer s.Unlock()
s.err = err
atomic.StoreInt64(&s.completedTimeNew, time.Now().UnixNano())
}
func (s *SingleChunkCacher) hasCompletedError() bool {
if atomic.LoadInt64(&s.completedTimeNew) == 0 {
return false
}
s.Lock()
defer s.Unlock()
return s.err != nil
}
func (s *SingleChunkCacher) fetchChunkData(ctx context.Context, urlStrings []string) ([]byte, error) {
// Allocate buffer and download without holding the lock.
// This allows multiple downloads to proceed in parallel.
data := mem.Allocate(s.chunkSize)
_, fetchErr := s.parent.fetchChunkDataFn(ctx, data, urlStrings, s.cipherKey, s.isGzipped, true, 0, s.chunkFileId)
if fetchErr != nil {
mem.Free(data)
return nil, fetchErr
}
return data, nil
}
func (s *SingleChunkCacher) retryFetchAfterCacheInvalidation(ctx context.Context, oldUrlStrings []string, originalErr error) ([]byte, error) {
var data []byte
err := retryFetchWithFreshLocations(ctx, s.parent.cacheInvalidator, s.parent.lookupFileIdFn, s.chunkFileId, oldUrlStrings, originalErr, func(newUrls []string) error {
var fetchErr error
data, fetchErr = s.fetchChunkData(ctx, newUrls)
return fetchErr
})
if err != nil {
return nil, err
}
return data, nil
}
func (s *SingleChunkCacher) destroy() {
// wait for all reads to finish before destroying the data
s.wg.Wait()
@@ -240,8 +307,8 @@ func (s *SingleChunkCacher) destroy() {
// It waits for the download to complete if it's still in progress.
// The ctx parameter allows the reader to cancel its wait (but the download continues
// for other readers - see comment in startCaching about shared resource semantics).
// The caller must s.wg.Add(1) under the ReaderCache lock before calling; this only releases it.
func (s *SingleChunkCacher) readChunkAt(ctx context.Context, buf []byte, offset int64) (int, error) {
s.wg.Add(1)
defer s.wg.Done()
// Wait for download to complete, but allow reader cancellation.
+154 -18
View File
@@ -16,6 +16,25 @@ type mockChunkCacheForReaderCache struct {
mu sync.Mutex
}
type mockCacheInvalidatorForReaderCache struct {
calls int32
mu sync.Mutex
fileId string
}
func (m *mockCacheInvalidatorForReaderCache) InvalidateCache(fileId string) {
atomic.AddInt32(&m.calls, 1)
m.mu.Lock()
defer m.mu.Unlock()
m.fileId = fileId
}
func (m *mockCacheInvalidatorForReaderCache) lastFileId() string {
m.mu.Lock()
defer m.mu.Unlock()
return m.fileId
}
func newMockChunkCacheForReaderCache() *mockChunkCacheForReaderCache {
return &mockChunkCacheForReaderCache{
data: make(map[string][]byte),
@@ -60,6 +79,113 @@ func (m *mockChunkCacheForReaderCache) IsInCache(fileId string, lockNeeded bool)
return ok
}
func TestReaderCacheRetryAfterCacheInvalidation(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
invalidator := &mockCacheInvalidatorForReaderCache{}
fileId := "425141,ef8914e9bdbbe8cb6838191f"
staleUrl := "http://fast-volume-1/" + fileId
freshUrl := "http://fast-volume-9/" + fileId
testData := []byte("fresh chunk data after cache invalidation")
var lookupCount int32
lookupFn := func(ctx context.Context, requestedFileId string) ([]string, error) {
if requestedFileId != fileId {
return nil, fmt.Errorf("unexpected lookup file id %s", requestedFileId)
}
atomic.AddInt32(&lookupCount, 1)
if atomic.LoadInt32(&invalidator.calls) == 0 {
return []string{staleUrl}, nil
}
return []string{freshUrl}, nil
}
var fetchCount int32
fetchFn := func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, requestedFileId string) (int, error) {
if requestedFileId != fileId {
return 0, fmt.Errorf("unexpected fetch file id %s", requestedFileId)
}
switch atomic.AddInt32(&fetchCount, 1) {
case 1:
if len(urlStrings) != 1 || urlStrings[0] != staleUrl {
return 0, fmt.Errorf("first fetch should use stale url %v", urlStrings)
}
return 0, fmt.Errorf("404 Not Found: not found")
case 2:
if len(urlStrings) != 1 || urlStrings[0] != freshUrl {
return 0, fmt.Errorf("retry fetch should use fresh url %v", urlStrings)
}
return copy(buffer, testData), nil
default:
return 0, fmt.Errorf("unexpected extra fetch with urls %v", urlStrings)
}
}
rc := NewReaderCache(10, cache, lookupFn, invalidator)
rc.fetchChunkDataFn = fetchFn
defer rc.destroy()
buffer := make([]byte, len(testData))
n, err := rc.ReadChunkAt(context.Background(), buffer, fileId, nil, false, 0, len(testData), true)
if err != nil {
t.Fatalf("expected successful retry, got %v", err)
}
if got := string(buffer[:n]); got != string(testData) {
t.Fatalf("expected %q, got %q", testData, got)
}
if got := atomic.LoadInt32(&invalidator.calls); got != 1 {
t.Fatalf("expected one cache invalidation, got %d", got)
}
if got := invalidator.lastFileId(); got != fileId {
t.Fatalf("expected invalidated file id %s, got %s", fileId, got)
}
if got := atomic.LoadInt32(&lookupCount); got != 2 {
t.Fatalf("expected lookup before fetch and after invalidation, got %d", got)
}
if got := atomic.LoadInt32(&fetchCount); got != 2 {
t.Fatalf("expected stale fetch and retry fetch, got %d", got)
}
}
func TestReaderCacheRemovesFailedDownloader(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
fileId := "425141,failed"
url := "http://fast-volume-1/" + fileId
var lookupCount int32
lookupFn := func(ctx context.Context, requestedFileId string) ([]string, error) {
if requestedFileId != fileId {
return nil, fmt.Errorf("unexpected lookup file id %s", requestedFileId)
}
atomic.AddInt32(&lookupCount, 1)
return []string{url}, nil
}
var fetchCount int32
fetchFn := func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, requestedFileId string) (int, error) {
atomic.AddInt32(&fetchCount, 1)
return 0, fmt.Errorf("fetch failed")
}
rc := NewReaderCache(10, cache, lookupFn, nil)
rc.fetchChunkDataFn = fetchFn
defer rc.destroy()
for i := 0; i < 2; i++ {
buffer := make([]byte, 8)
_, err := rc.ReadChunkAt(context.Background(), buffer, fileId, nil, false, 0, len(buffer), true)
if err == nil {
t.Fatalf("read %d should fail", i+1)
}
}
if got := atomic.LoadInt32(&lookupCount); got != 2 {
t.Fatalf("failed downloader should be removed so the second read re-lookups, got %d lookups", got)
}
if got := atomic.LoadInt32(&fetchCount); got != 2 {
t.Fatalf("failed downloader should be removed so the second read refetches, got %d fetches", got)
}
}
// TestReaderCacheContextCancellation tests that a reader can cancel its wait
// while the download continues for other readers
func TestReaderCacheContextCancellation(t *testing.T) {
@@ -67,7 +193,7 @@ func TestReaderCacheContextCancellation(t *testing.T) {
// Create a ReaderCache - we can't easily test the full flow without mocking HTTP,
// but we can test the context cancellation in readChunkAt
rc := NewReaderCache(10, cache, nil)
rc := NewReaderCache(10, cache, nil, nil)
defer rc.destroy()
// Pre-populate cache to avoid HTTP calls
@@ -106,7 +232,7 @@ func TestReaderCacheFallbackToChunkCache(t *testing.T) {
testData := []byte("fallback test data that should be found in chunk cache")
cache.SetChunk("fallback-file", testData)
rc := NewReaderCache(10, cache, nil)
rc := NewReaderCache(10, cache, nil, nil)
defer rc.destroy()
// Read should hit the chunk cache
@@ -138,7 +264,7 @@ func TestReaderCacheMultipleReadersWaitForSameChunk(t *testing.T) {
}
cache.SetChunk("shared-chunk", testData)
rc := NewReaderCache(10, cache, nil)
rc := NewReaderCache(10, cache, nil, nil)
defer rc.destroy()
// Launch multiple concurrent readers for the same chunk
@@ -184,7 +310,7 @@ func TestReaderCachePartialRead(t *testing.T) {
testData := []byte("0123456789ABCDEFGHIJ")
cache.SetChunk("partial-read-file", testData)
rc := NewReaderCache(10, cache, nil)
rc := NewReaderCache(10, cache, nil, nil)
defer rc.destroy()
tests := []struct {
@@ -222,7 +348,7 @@ func TestReaderCacheCleanup(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
// Create cache with limit of 3
rc := NewReaderCache(3, cache, nil)
rc := NewReaderCache(3, cache, nil, nil)
defer rc.destroy()
// Add data for multiple files
@@ -259,7 +385,7 @@ func TestReaderCacheCleanup(t *testing.T) {
// TestSingleChunkCacherDoneSignal tests that done channel is always closed
func TestSingleChunkCacherDoneSignal(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
rc := NewReaderCache(10, cache, nil)
rc := NewReaderCache(10, cache, nil, nil)
defer rc.destroy()
// Test that we can read even when data is in cache (done channel should work)
@@ -317,7 +443,7 @@ func TestSingleChunkCacherLookupError(t *testing.T) {
return nil, fmt.Errorf("lookup failed for %s", fileId)
}
rc := NewReaderCache(10, cache, lookupFn)
rc := NewReaderCache(10, cache, lookupFn, nil)
defer rc.destroy()
buffer := make([]byte, 100)
@@ -343,7 +469,7 @@ func TestSingleChunkCacherContextCancellationDuringLookup(t *testing.T) {
return nil, fmt.Errorf("lookup completed but reader should have cancelled")
}
rc := NewReaderCache(10, cache, lookupFn)
rc := NewReaderCache(10, cache, lookupFn, nil)
defer rc.destroy()
defer close(lookupCanFinish) // Ensure cleanup
@@ -391,7 +517,7 @@ func TestSingleChunkCacherMultipleReadersWaitForDownload(t *testing.T) {
return nil, fmt.Errorf("simulated lookup error")
}
rc := NewReaderCache(10, cache, lookupFn)
rc := NewReaderCache(10, cache, lookupFn, nil)
defer rc.destroy()
numReaders := 5
@@ -438,17 +564,25 @@ func TestSingleChunkCacherMultipleReadersWaitForDownload(t *testing.T) {
// the downloaders map deduplicates in-flight downloads.
func TestReaderCacheDownloaderDedup(t *testing.T) {
cache := newMockChunkCacheForReaderCache()
var lookupCount int32
lookupGate := make(chan struct{})
var fetchCount int32
fetchGate := make(chan struct{})
testData := []byte("deduplicated data")
lookupFn := func(ctx context.Context, fileId string) ([]string, error) {
atomic.AddInt32(&lookupCount, 1)
<-lookupGate
// Return an error so we don't need to mock the HTTP fetch.
return nil, fmt.Errorf("simulated lookup for %s", fileId)
return []string{"http://volume/" + fileId}, nil
}
rc := NewReaderCache(10, cache, lookupFn)
fetchFn := func(ctx context.Context, buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, fileId string) (int, error) {
atomic.AddInt32(&fetchCount, 1)
<-fetchGate
return copy(buffer, testData), nil
}
rc := NewReaderCache(10, cache, lookupFn, nil)
rc.fetchChunkDataFn = fetchFn
defer rc.destroy()
const numReaders = 10
@@ -464,13 +598,15 @@ func TestReaderCacheDownloaderDedup(t *testing.T) {
}
// Allow downloads to proceed.
close(lookupGate)
close(fetchGate)
wg.Wait()
count := atomic.LoadInt32(&lookupCount)
if count != 1 {
if count := atomic.LoadInt32(&lookupCount); count != 1 {
t.Errorf("expected exactly 1 lookup call, got %d", count)
}
if count := atomic.LoadInt32(&fetchCount); count != 1 {
t.Errorf("expected exactly 1 fetch call, got %d", count)
}
}
// TestSingleChunkCacherOneReaderCancelsOthersContinue tests that when one reader
@@ -487,7 +623,7 @@ func TestSingleChunkCacherOneReaderCancelsOthersContinue(t *testing.T) {
return nil, fmt.Errorf("simulated error after delay")
}
rc := NewReaderCache(10, cache, lookupFn)
rc := NewReaderCache(10, cache, lookupFn, nil)
defer rc.destroy()
cancelledReaderDone := make(chan error, 1)
+1 -1
View File
@@ -54,7 +54,7 @@ func (store *SqliteStore) initialize(dbFile, createTable, upsertQuery string) (e
store.SupportBucketTable = true
store.SqlGenerator = &mysql.SqlGenMysql{
CreateTableSqlTemplate: createTable,
DropTableSqlTemplate: "drop table `%s`",
DropTableSqlTemplate: "drop table if exists `%s`",
UpsertQueryTemplate: upsertQuery,
}
+38 -29
View File
@@ -102,10 +102,6 @@ func PrepareStreamContent(masterClient wdclient.HasLookupFileIdFunction, jwtFunc
type VolumeServerJwtFunction func(fileId string) string
type CacheInvalidator interface {
InvalidateCache(fileId string)
}
// urlSlicesEqual checks if two URL slices contain the same URLs (order-independent)
func urlSlicesEqual(a, b []string) bool {
if len(a) != len(b) {
@@ -126,6 +122,36 @@ func urlSlicesEqual(a, b []string) bool {
return true
}
// retryFetchWithFreshLocations is the shared self-heal for the read paths: when a chunk fetch
// fails, invalidate the cached volume locations, re-lookup, and call refetch only when the
// resolved locations actually changed (so we never retry against the same servers). originalErr
// is returned unchanged when no retry is attempted, so callers surface the real fetch failure.
func retryFetchWithFreshLocations(ctx context.Context, invalidator CacheInvalidator, lookupFn wdclient.LookupFileIdFunctionType, fileId string, oldUrls []string, originalErr error, refetch func(newUrls []string) error) error {
if invalidator == nil {
return originalErr
}
glog.V(0).InfofCtx(ctx, "read chunk %s failed, invalidating cache and retrying: %v", fileId, originalErr)
invalidator.InvalidateCache(fileId)
newUrls, lookupErr := lookupFn(ctx, fileId)
if lookupErr != nil {
glog.WarningfCtx(ctx, "failed to re-lookup chunk %s after cache invalidation: %v", fileId, lookupErr)
return fmt.Errorf("re-lookup chunk %s after cache invalidation: %w", fileId, lookupErr)
}
if len(newUrls) == 0 {
glog.WarningfCtx(ctx, "re-lookup for chunk %s returned no locations, skipping retry", fileId)
return fmt.Errorf("re-lookup chunk %s returned no locations", fileId)
}
if urlSlicesEqual(oldUrls, newUrls) {
glog.V(0).InfofCtx(ctx, "re-lookup returned same locations for chunk %s, skipping retry", fileId)
return originalErr
}
glog.V(0).InfofCtx(ctx, "retrying read chunk %s with %d new locations", fileId, len(newUrls))
return refetch(newUrls)
}
func PrepareStreamContentWithThrottler(ctx context.Context, masterClient wdclient.HasLookupFileIdFunction, jwtFunc VolumeServerJwtFunction, chunks []*filer_pb.FileChunk, offset int64, size int64, downloadMaxBytesPs int64) (DoStreamContent, error) {
glog.V(4).InfofCtx(ctx, "prepare to stream content for chunks: %d", len(chunks))
chunkViews := ViewFromChunks(ctx, masterClient.GetLookupFileIdFunction(), chunks, offset, size)
@@ -195,32 +221,15 @@ func PrepareStreamContentWithThrottler(ctx context.Context, masterClient wdclien
// If read failed, try to invalidate cache and re-lookup
if err != nil && written == 0 {
if invalidator, ok := masterClient.(CacheInvalidator); ok {
glog.V(0).InfofCtx(ctx, "read chunk %s failed, invalidating cache and retrying", chunkView.FileId)
invalidator.InvalidateCache(chunkView.FileId)
// Re-lookup
newUrlStrings, lookupErr := masterClient.GetLookupFileIdFunction()(ctx, chunkView.FileId)
if lookupErr == nil && len(newUrlStrings) > 0 {
// Check if new URLs are different from old ones to avoid infinite retry
if !urlSlicesEqual(urlStrings, newUrlStrings) {
glog.V(0).InfofCtx(ctx, "retrying read chunk %s with new locations: %v", chunkView.FileId, newUrlStrings)
_, err = retriedStreamFetchChunkData(ctx, writer, newUrlStrings, jwt, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.OffsetInChunk, int(chunkView.ViewSize))
// Update the map so subsequent references use fresh URLs
if err == nil {
fileId2Url[chunkView.FileId] = newUrlStrings
}
} else {
glog.V(0).InfofCtx(ctx, "re-lookup returned same locations for chunk %s, skipping retry", chunkView.FileId)
}
} else {
if lookupErr != nil {
glog.WarningfCtx(ctx, "failed to re-lookup chunk %s after cache invalidation: %v", chunkView.FileId, lookupErr)
} else {
glog.WarningfCtx(ctx, "re-lookup for chunk %s returned no locations, skipping retry", chunkView.FileId)
}
invalidator, _ := masterClient.(CacheInvalidator)
err = retryFetchWithFreshLocations(ctx, invalidator, masterClient.GetLookupFileIdFunction(), chunkView.FileId, urlStrings, err, func(newUrls []string) error {
_, refetchErr := retriedStreamFetchChunkData(ctx, writer, newUrls, jwt, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.OffsetInChunk, int(chunkView.ViewSize))
if refetchErr == nil {
// Update the map so subsequent references use fresh URLs
fileId2Url[chunkView.FileId] = newUrls
}
}
return refetchErr
})
}
offset += int64(chunkView.ViewSize)
+14 -34
View File
@@ -177,7 +177,7 @@ func streamChunksPrefetched(
consumeErr = err
break
}
retryErr := retryWithCacheInvalidation(localCtx, writer, chunkView, result.urlStrings, jwtFunc, masterClient)
retryErr := retryWithCacheInvalidation(localCtx, writer, chunkView, result.urlStrings, result.fetchErr, jwtFunc, masterClient)
if retryErr != nil {
stats.FilerHandlerCounter.WithLabelValues("chunkDownloadError").Inc()
consumeErr = fmt.Errorf("read chunk: %w", retryErr)
@@ -230,45 +230,25 @@ func streamChunksPrefetched(
return nil
}
// retryWithCacheInvalidation attempts to re-fetch a chunk after invalidating the URL cache.
// This mirrors the retry logic in PrepareStreamContentWithThrottler's sequential path.
// retryWithCacheInvalidation re-fetches a chunk via the shared location self-heal after the
// initial fetch failed with originalErr.
func retryWithCacheInvalidation(
ctx context.Context,
writer io.Writer,
chunkView *ChunkView,
oldUrlStrings []string,
originalErr error,
jwtFunc VolumeServerJwtFunction,
masterClient wdclient.HasLookupFileIdFunction,
) error {
invalidator, ok := masterClient.(CacheInvalidator)
if !ok {
return fmt.Errorf("read chunk %s failed and no cache invalidator available", chunkView.FileId)
}
glog.V(0).InfofCtx(ctx, "prefetch read chunk %s failed, invalidating cache and retrying", chunkView.FileId)
invalidator.InvalidateCache(chunkView.FileId)
newUrlStrings, lookupErr := masterClient.GetLookupFileIdFunction()(ctx, chunkView.FileId)
if lookupErr != nil {
glog.WarningfCtx(ctx, "failed to re-lookup chunk %s after cache invalidation: %v", chunkView.FileId, lookupErr)
return fmt.Errorf("re-lookup chunk %s: %w", chunkView.FileId, lookupErr)
}
if len(newUrlStrings) == 0 {
glog.WarningfCtx(ctx, "re-lookup for chunk %s returned no locations, skipping retry", chunkView.FileId)
return fmt.Errorf("re-lookup chunk %s: no locations", chunkView.FileId)
}
if urlSlicesEqual(oldUrlStrings, newUrlStrings) {
glog.V(0).InfofCtx(ctx, "re-lookup returned same locations for chunk %s, skipping retry", chunkView.FileId)
return fmt.Errorf("read chunk %s failed, same locations after cache invalidation", chunkView.FileId)
}
glog.V(0).InfofCtx(ctx, "retrying read chunk %s with new locations: %v", chunkView.FileId, newUrlStrings)
jwt := jwtFunc(chunkView.FileId)
_, err := retriedStreamFetchChunkData(
ctx, writer, newUrlStrings, jwt,
chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(),
chunkView.OffsetInChunk, int(chunkView.ViewSize),
)
return err
invalidator, _ := masterClient.(CacheInvalidator)
return retryFetchWithFreshLocations(ctx, invalidator, masterClient.GetLookupFileIdFunction(), chunkView.FileId, oldUrlStrings, originalErr, func(newUrls []string) error {
jwt := jwtFunc(chunkView.FileId)
_, err := retriedStreamFetchChunkData(
ctx, writer, newUrls, jwt,
chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(),
chunkView.OffsetInChunk, int(chunkView.ViewSize),
)
return err
})
}
+245
View File
@@ -0,0 +1,245 @@
package kms
import (
"context"
"crypto/sha256"
"encoding/binary"
"hash"
"sort"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
const (
// DefaultDataKeyCacheTTL is used when caching is enabled without an explicit TTL.
DefaultDataKeyCacheTTL = time.Hour
// DefaultDataKeyCacheSize bounds the number of cached decrypted data keys.
DefaultDataKeyCacheSize = 1000
)
// CachedKMSProvider wraps a KMSProvider with an in-memory cache of decrypted
// data keys. A KMS Decrypt call is deterministic for a given (ciphertext,
// encryption context) pair, so every read of the same SSE-KMS object would
// otherwise repeat an identical, network-bound KMS round-trip. Caching the
// plaintext data key removes that round-trip on the read hot path — this is
// what the cache_enabled / cache_ttl provider settings control.
//
// Only Decrypt is cached. GenerateDataKey must return a unique key per call,
// and DescribeKey / GetKeyID are cheap metadata lookups, so all three pass
// straight through to the wrapped provider via the embedded interface.
type CachedKMSProvider struct {
KMSProvider // wrapped provider; supplies the un-cached methods
ttl time.Duration
maxEntries int
mu sync.Mutex
entries map[string]*dataKeyCacheEntry
closed bool
}
type dataKeyCacheEntry struct {
keyID string
plaintext []byte
expiresAt time.Time
}
// NewCachedKMSProvider wraps provider with a decrypted-data-key cache. A
// non-positive ttl or maxEntries falls back to the package defaults.
func NewCachedKMSProvider(provider KMSProvider, ttl time.Duration, maxEntries int) *CachedKMSProvider {
if ttl <= 0 {
ttl = DefaultDataKeyCacheTTL
}
if maxEntries <= 0 {
maxEntries = DefaultDataKeyCacheSize
}
return &CachedKMSProvider{
KMSProvider: provider,
ttl: ttl,
maxEntries: maxEntries,
entries: make(map[string]*dataKeyCacheEntry),
}
}
// Decrypt returns the plaintext data key from cache when present, otherwise
// delegates to the wrapped provider and caches the result.
func (c *CachedKMSProvider) Decrypt(ctx context.Context, req *DecryptRequest) (*DecryptResponse, error) {
if req == nil || len(req.CiphertextBlob) == 0 {
// Let the wrapped provider produce its normal validation error.
return c.KMSProvider.Decrypt(ctx, req)
}
cacheKey := dataKeyCacheKey(req)
if resp := c.get(cacheKey); resp != nil {
glog.V(4).Infof("KMS data key cache hit")
return resp, nil
}
resp, err := c.KMSProvider.Decrypt(ctx, req)
if err != nil {
return nil, err
}
// Store our own copy, then hand the original back to the caller. The
// caller clears the plaintext it receives (ClearSensitiveData); keeping a
// private copy means later cache hits still return valid key material.
c.set(cacheKey, resp)
return resp, nil
}
// get returns a fresh copy of the cached response, or nil on miss/expiry. The
// copy is essential: callers clear the returned plaintext after use, which
// would otherwise wipe the cached key material for every subsequent reader.
func (c *CachedKMSProvider) get(cacheKey string) *DecryptResponse {
c.mu.Lock()
defer c.mu.Unlock()
entry, ok := c.entries[cacheKey]
if !ok {
return nil
}
if time.Now().After(entry.expiresAt) {
ClearSensitiveData(entry.plaintext)
delete(c.entries, cacheKey)
return nil
}
plaintext := make([]byte, len(entry.plaintext))
copy(plaintext, entry.plaintext)
return &DecryptResponse{KeyID: entry.keyID, Plaintext: plaintext}
}
// set stores a private copy of the plaintext data key.
func (c *CachedKMSProvider) set(cacheKey string, resp *DecryptResponse) {
if resp == nil {
return
}
plaintext := make([]byte, len(resp.Plaintext))
copy(plaintext, resp.Plaintext)
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
// A miss can finish its underlying Decrypt after Close scrubbed the
// map; don't repopulate it with key material that won't be cleared.
ClearSensitiveData(plaintext)
return
}
if old, exists := c.entries[cacheKey]; exists {
// Two readers can race on the same miss and both store; wipe the
// superseded key material instead of leaving it to linger in memory.
ClearSensitiveData(old.plaintext)
} else {
c.evictIfFullLocked()
}
c.entries[cacheKey] = &dataKeyCacheEntry{
keyID: resp.KeyID,
plaintext: plaintext,
expiresAt: time.Now().Add(c.ttl),
}
}
// evictIfFullLocked drops expired entries and, if still at capacity, the entry
// closest to expiry. Callers must hold c.mu.
func (c *CachedKMSProvider) evictIfFullLocked() {
if len(c.entries) < c.maxEntries {
return
}
now := time.Now()
for k, entry := range c.entries {
if now.After(entry.expiresAt) {
ClearSensitiveData(entry.plaintext)
delete(c.entries, k)
}
}
if len(c.entries) < c.maxEntries {
return
}
// Still full: evict the soonest-to-expire entry.
var oldestKey string
var oldestAt time.Time
for k, entry := range c.entries {
if oldestKey == "" || entry.expiresAt.Before(oldestAt) {
oldestKey = k
oldestAt = entry.expiresAt
}
}
if oldestKey != "" {
ClearSensitiveData(c.entries[oldestKey].plaintext)
delete(c.entries, oldestKey)
}
}
// Close clears cached key material and closes the wrapped provider.
func (c *CachedKMSProvider) Close() error {
c.mu.Lock()
c.closed = true
for k, entry := range c.entries {
ClearSensitiveData(entry.plaintext)
delete(c.entries, k)
}
c.mu.Unlock()
return c.KMSProvider.Close()
}
// sha256Pool reuses hash states across cache-key computations so the read hot
// path doesn't allocate a fresh one on every Decrypt.
var sha256Pool = sync.Pool{
New: func() interface{} { return sha256.New() },
}
// dataKeyCacheKey derives a stable cache key from the ciphertext blob and the
// encryption context. The context is part of the key because the same
// ciphertext decrypted under a different context is a different request, and
// caching by ciphertext alone would bypass the provider's context check.
func dataKeyCacheKey(req *DecryptRequest) string {
h := sha256Pool.Get().(hash.Hash)
// Length-prefix each field so distinct inputs cannot collide by concatenation.
writeLengthPrefixed(h, req.CiphertextBlob)
keys := make([]string, 0, len(req.EncryptionContext))
for k := range req.EncryptionContext {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
writeLengthPrefixed(h, []byte(k))
writeLengthPrefixed(h, []byte(req.EncryptionContext[k]))
}
key := string(h.Sum(nil))
h.Reset()
sha256Pool.Put(h)
return key
}
func writeLengthPrefixed(h hash.Hash, b []byte) {
var lenBuf [8]byte
binary.BigEndian.PutUint64(lenBuf[:], uint64(len(b)))
h.Write(lenBuf[:])
h.Write(b)
}
// wrapWithCacheIfEnabled returns provider wrapped in a data-key cache when the
// configuration enables caching, otherwise provider unchanged.
func wrapWithCacheIfEnabled(provider KMSProvider, config *KMSConfig) KMSProvider {
if provider == nil || config == nil || !config.CacheEnabled {
return provider
}
// Avoid double-wrapping if a cached provider is somehow reused.
if _, ok := provider.(*CachedKMSProvider); ok {
return provider
}
cached := NewCachedKMSProvider(provider, config.CacheTTL, config.MaxCacheSize)
glog.V(1).Infof("KMS data key caching enabled (ttl=%s, max=%d)", cached.ttl, cached.maxEntries)
return cached
}
+273
View File
@@ -0,0 +1,273 @@
package kms
import (
"bytes"
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// countingKMSProvider is a minimal KMSProvider that records how many times each
// method is invoked so tests can assert the cache actually avoids round-trips.
type countingKMSProvider struct {
decryptCalls int64
generateCalls int64
mu sync.Mutex
store map[string][]byte // ciphertext(string) -> plaintext data key
}
func newCountingKMSProvider() *countingKMSProvider {
return &countingKMSProvider{store: make(map[string][]byte)}
}
func (p *countingKMSProvider) GenerateDataKey(ctx context.Context, req *GenerateDataKeyRequest) (*GenerateDataKeyResponse, error) {
n := atomic.AddInt64(&p.generateCalls, 1)
plaintext := []byte(fmt.Sprintf("datakey-%d-abcdefghijklmnopqrstuv", n))[:32]
ciphertext := []byte(fmt.Sprintf("cipher-%d", n))
p.mu.Lock()
p.store[string(ciphertext)] = append([]byte(nil), plaintext...)
p.mu.Unlock()
return &GenerateDataKeyResponse{
KeyID: req.KeyID,
Plaintext: plaintext,
CiphertextBlob: ciphertext,
}, nil
}
func (p *countingKMSProvider) Decrypt(ctx context.Context, req *DecryptRequest) (*DecryptResponse, error) {
atomic.AddInt64(&p.decryptCalls, 1)
p.mu.Lock()
plaintext, ok := p.store[string(req.CiphertextBlob)]
p.mu.Unlock()
if !ok {
return nil, fmt.Errorf("ciphertext not found")
}
// Return a fresh copy, mirroring real providers that allocate per call.
return &DecryptResponse{
KeyID: "test-key",
Plaintext: append([]byte(nil), plaintext...),
}, nil
}
func (p *countingKMSProvider) DescribeKey(ctx context.Context, req *DescribeKeyRequest) (*DescribeKeyResponse, error) {
return &DescribeKeyResponse{KeyID: req.KeyID, KeyState: KeyStateEnabled, KeyUsage: KeyUsageEncryptDecrypt}, nil
}
func (p *countingKMSProvider) GetKeyID(ctx context.Context, keyIdentifier string) (string, error) {
return keyIdentifier, nil
}
func (p *countingKMSProvider) Close() error { return nil }
// TestCachedProviderDecryptHitsProviderOnce is the regression test for the
// reported bug: with caching enabled, repeated Decrypt of the same data key
// must consult the underlying KMS only once.
func TestCachedProviderDecryptHitsProviderOnce(t *testing.T) {
inner := newCountingKMSProvider()
cached := NewCachedKMSProvider(inner, time.Hour, 100)
ctx := context.Background()
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
if err != nil {
t.Fatalf("GenerateDataKey: %v", err)
}
req := &DecryptRequest{CiphertextBlob: dk.CiphertextBlob}
first, err := cached.Decrypt(ctx, req)
if err != nil {
t.Fatalf("first Decrypt: %v", err)
}
// Emulate the S3 read path clearing the returned plaintext after use. A
// correct cache must hand back an independent copy so this does not wipe
// the cached key material.
ClearSensitiveData(first.Plaintext)
second, err := cached.Decrypt(ctx, req)
if err != nil {
t.Fatalf("second Decrypt: %v", err)
}
if got := atomic.LoadInt64(&inner.decryptCalls); got != 1 {
t.Fatalf("expected underlying Decrypt to be called once, got %d", got)
}
// The cached result must still be the real data key. If the cache handed
// back the same buffer it stored, the ClearSensitiveData above would have
// zeroed it.
if bytes.Equal(second.Plaintext, make([]byte, len(second.Plaintext))) {
t.Fatalf("cached plaintext was zeroed by a previous caller clearing its copy")
}
}
// TestCachedProviderContextSensitivity ensures the encryption context is part
// of the cache key: a different context must not return a stale plaintext.
func TestCachedProviderContextSensitivity(t *testing.T) {
inner := newCountingKMSProvider()
cached := NewCachedKMSProvider(inner, time.Hour, 100)
ctx := context.Background()
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
if err != nil {
t.Fatalf("GenerateDataKey: %v", err)
}
// Same ciphertext, two different contexts. The counting provider ignores
// context, but the cache must still treat these as distinct entries so a
// real provider's context check is never short-circuited.
if _, err := cached.Decrypt(ctx, &DecryptRequest{CiphertextBlob: dk.CiphertextBlob, EncryptionContext: map[string]string{"a": "1"}}); err != nil {
t.Fatalf("Decrypt ctx a: %v", err)
}
if _, err := cached.Decrypt(ctx, &DecryptRequest{CiphertextBlob: dk.CiphertextBlob, EncryptionContext: map[string]string{"a": "2"}}); err != nil {
t.Fatalf("Decrypt ctx b: %v", err)
}
if got := atomic.LoadInt64(&inner.decryptCalls); got != 2 {
t.Fatalf("expected 2 underlying Decrypt calls for distinct contexts, got %d", got)
}
}
// TestCachedProviderTTLExpiry verifies expired entries fall through to the
// underlying provider.
func TestCachedProviderTTLExpiry(t *testing.T) {
inner := newCountingKMSProvider()
cached := NewCachedKMSProvider(inner, 20*time.Millisecond, 100)
ctx := context.Background()
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
if err != nil {
t.Fatalf("GenerateDataKey: %v", err)
}
req := &DecryptRequest{CiphertextBlob: dk.CiphertextBlob}
if _, err := cached.Decrypt(ctx, req); err != nil {
t.Fatalf("Decrypt: %v", err)
}
time.Sleep(40 * time.Millisecond)
if _, err := cached.Decrypt(ctx, req); err != nil {
t.Fatalf("Decrypt after expiry: %v", err)
}
if got := atomic.LoadInt64(&inner.decryptCalls); got != 2 {
t.Fatalf("expected 2 underlying Decrypt calls across TTL expiry, got %d", got)
}
}
// TestCachedProviderMaxEntries verifies the cache is size-bounded.
func TestCachedProviderMaxEntries(t *testing.T) {
inner := newCountingKMSProvider()
cached := NewCachedKMSProvider(inner, time.Hour, 2)
ctx := context.Background()
var blobs [][]byte
for i := 0; i < 3; i++ {
dk, err := cached.GenerateDataKey(ctx, &GenerateDataKeyRequest{KeyID: "k1", KeySpec: KeySpecAES256})
if err != nil {
t.Fatalf("GenerateDataKey: %v", err)
}
blobs = append(blobs, dk.CiphertextBlob)
if _, err := cached.Decrypt(ctx, &DecryptRequest{CiphertextBlob: dk.CiphertextBlob}); err != nil {
t.Fatalf("Decrypt: %v", err)
}
}
cached.mu.Lock()
size := len(cached.entries)
cached.mu.Unlock()
if size > 2 {
t.Fatalf("cache exceeded max entries: got %d, want <= 2", size)
}
}
// TestCachedProviderClearsOverwrittenPlaintext verifies that when an entry is
// replaced (two readers racing on the same miss), the superseded key material
// is zeroed rather than left lingering in memory.
func TestCachedProviderClearsOverwrittenPlaintext(t *testing.T) {
inner := newCountingKMSProvider()
cached := NewCachedKMSProvider(inner, time.Hour, 10)
cached.set("dupkey", &DecryptResponse{KeyID: "k", Plaintext: []byte("0123456789abcdef0123456789abcdef")})
cached.mu.Lock()
oldBuf := cached.entries["dupkey"].plaintext
cached.mu.Unlock()
cached.set("dupkey", &DecryptResponse{KeyID: "k", Plaintext: []byte("ffffffffffffffffffffffffffffffff")})
if !bytes.Equal(oldBuf, make([]byte, len(oldBuf))) {
t.Fatalf("superseded cache plaintext was not zeroed: %v", oldBuf)
}
}
// TestCachedProviderNoWriteAfterClose verifies a store that lands after Close
// does not repopulate the scrubbed cache with key material.
func TestCachedProviderNoWriteAfterClose(t *testing.T) {
inner := newCountingKMSProvider()
cached := NewCachedKMSProvider(inner, time.Hour, 10)
if err := cached.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
cached.set("k", &DecryptResponse{KeyID: "k", Plaintext: []byte("0123456789abcdef0123456789abcdef")})
cached.mu.Lock()
n := len(cached.entries)
cached.mu.Unlock()
if n != 0 {
t.Fatalf("cache repopulated after Close: %d entries", n)
}
}
// TestAddKMSProviderWiresCache is the wiring regression test: a provider
// configured with cache_enabled must actually be handed back wrapped in a
// caching provider (the bug was that the setting was parsed but never applied).
func TestAddKMSProviderWiresCache(t *testing.T) {
RegisterProvider("cache-wiring-test", func(config util.Configuration) (KMSProvider, error) {
return newCountingKMSProvider(), nil
})
mgr := &KMSManager{
providers: make(map[string]KMSProvider),
configs: make(map[string]*KMSConfig),
bucketKMS: make(map[string]string),
}
if err := mgr.AddKMSProvider("p-cached", &KMSConfig{
Provider: "cache-wiring-test",
CacheEnabled: true,
CacheTTL: time.Hour,
MaxCacheSize: 10,
}); err != nil {
t.Fatalf("AddKMSProvider (cached): %v", err)
}
p, err := mgr.GetKMSProviderByName("p-cached")
if err != nil {
t.Fatalf("GetKMSProviderByName: %v", err)
}
if _, ok := p.(*CachedKMSProvider); !ok {
t.Fatalf("expected *CachedKMSProvider when cache enabled, got %T", p)
}
if err := mgr.AddKMSProvider("p-plain", &KMSConfig{
Provider: "cache-wiring-test",
CacheEnabled: false,
}); err != nil {
t.Fatalf("AddKMSProvider (plain): %v", err)
}
p2, err := mgr.GetKMSProviderByName("p-plain")
if err != nil {
t.Fatalf("GetKMSProviderByName: %v", err)
}
if _, ok := p2.(*CachedKMSProvider); ok {
t.Fatalf("expected unwrapped provider when cache disabled, got %T", p2)
}
}
+5
View File
@@ -128,6 +128,7 @@ func InitializeGlobalKMS(config *KMSConfig) error {
if err != nil {
return err
}
provider = wrapWithCacheIfEnabled(provider, config)
globalKMSMutex.Lock()
defer globalKMSMutex.Unlock()
@@ -224,6 +225,10 @@ func (km *KMSManager) AddKMSProvider(name string, config *KMSConfig) error {
return fmt.Errorf("failed to create KMS provider %s: %w", name, err)
}
// Wrap with a decrypted-data-key cache when enabled so repeated reads of
// the same SSE-KMS object avoid a KMS round-trip per read.
provider = wrapWithCacheIfEnabled(provider, config)
// Store provider and configuration
km.providers[name] = provider
km.configs[name] = config
+5 -6
View File
@@ -35,12 +35,11 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
PairMap: nil,
WantMd5: true,
}
genFileUrlFn := func(host, fileId string) string {
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
if wfs.option.VolumeServerAccess == "filerProxy" {
fileUrl = fmt.Sprintf("http://%s/?proxyChunkId=%s", wfs.getCurrentFiler(), fileId)
if wfs.option.VolumeServerAccess == "filerProxy" {
// getCurrentFiler() can change on failover, so read it per attempt.
uploadOption.GenUploadUrl = func(host, fileId string) string {
return fmt.Sprintf("http://%s/?proxyChunkId=%s", wfs.getCurrentFiler(), fileId)
}
return fileUrl
}
fileId, uploadResult, err, data := uploader.UploadWithRetry(
@@ -54,7 +53,7 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
DataCenter: wfs.option.DataCenter,
Path: assignPath,
},
uploadOption, genFileUrlFn, reader,
uploadOption, reader,
)
if err != nil {
+13 -14
View File
@@ -161,27 +161,26 @@ func (b *MessageQueueBroker) assignAndUpload(targetFile string, data []byte) (fi
return
}
uploadOption := &operation.UploadOption{
Cipher: b.option.Cipher,
}
if b.option.VolumeServerAccess == "filerProxy" {
// b.currentFiler can change on failover, so read it per attempt.
uploadOption.GenUploadUrl = func(host, fileId string) string {
return fmt.Sprintf("http://%s/?proxyChunkId=%s", b.currentFiler, fileId)
}
}
fileId, uploadResult, err, _ = uploader.UploadWithRetry(
b,
&filer_pb.AssignVolumeRequest{
Count: 1,
Replication: b.option.DefaultReplication,
Collection: "topics",
// TtlSec: wfs.option.TtlSec,
// DiskType: string(wfs.option.DiskType),
DataCenter: b.option.DataCenter,
Path: targetFile,
},
&operation.UploadOption{
Cipher: b.option.Cipher,
},
func(host, fileId string) string {
fileUrl := fmt.Sprintf("http://%s/%s", host, fileId)
if b.option.VolumeServerAccess == "filerProxy" {
fileUrl = fmt.Sprintf("http://%s/?proxyChunkId=%s", b.currentFiler, fileId)
}
return fileUrl
DataCenter: b.option.DataCenter,
Path: targetFile,
},
uploadOption,
reader,
)
return
-3
View File
@@ -479,9 +479,6 @@ func saveParquetFileToPartitionDir(filerClient filer_pb.FilerClient, sourceFile
MimeType: "application/vnd.apache.parquet",
PairMap: nil,
},
func(host, fileId string) string {
return fmt.Sprintf("http://%s/%s", host, fileId)
},
io.NewSectionReader(sourceFile, i*chunkSize, chunkSize),
)
if err != nil {
+1 -1
View File
@@ -100,7 +100,7 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
fileSize := filer.FileSize(entry)
visibleIntervals, _ := filer.NonOverlappingVisibleIntervals(context.Background(), lookupFileIdFn, entry.Chunks, 0, int64(fileSize))
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, 0, int64(fileSize))
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn)
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn, nil)
readerAt := filer.NewChunkReaderAtFromClient(context.Background(), readerCache, chunkViews, int64(fileSize), filer.DefaultPrefetchCount)
// create parquet reader
+5
View File
@@ -61,6 +61,11 @@ func LookupVolumeId(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vid st
return results[vid], err
}
// InvalidateVolumeIdLocationCache drops cached locations for vid so the next lookup re-queries the master.
func InvalidateVolumeIdLocationCache(vid string) {
vc.Delete(vid)
}
// LookupVolumeIds find volume locations by cache and actual lookup
func LookupVolumeIds(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vids []string) (map[string]*LookupResult, error) {
ret := make(map[string]*LookupResult)
@@ -0,0 +1,83 @@
package operation
import (
"context"
"fmt"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type fakeLookupServer struct {
master_pb.UnimplementedSeaweedServer
mu sync.Mutex
calls int
locations int
}
func (s *fakeLookupServer) LookupVolume(_ context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.calls++
resp := &master_pb.LookupVolumeResponse{}
for _, vid := range req.VolumeOrFileIds {
var locs []*master_pb.Location
for i := 0; i < s.locations; i++ {
locs = append(locs, &master_pb.Location{Url: fmt.Sprintf("10.0.0.%d:8080", i)})
}
resp.VolumeIdLocations = append(resp.VolumeIdLocations, &master_pb.LookupVolumeResponse_VolumeIdLocation{
VolumeOrFileId: vid,
Locations: locs,
})
}
return resp, nil
}
// TestLookupVolumeIdCacheInvalidation reproduces the stale-lookup scenario: a
// volume that briefly reports too few replicas would be cached for the full TTL,
// so writes kept failing even after the master re-registered the missing replica.
// InvalidateVolumeIdLocationCache forces the next lookup to re-query the master.
func TestLookupVolumeIdCacheInvalidation(t *testing.T) {
fake := &fakeLookupServer{locations: 1}
master := startFakeMasterServer(t, fake)
masterFn := func(context.Context) pb.ServerAddress { return master }
dial := grpc.WithTransportCredentials(insecure.NewCredentials())
const vid = "778899"
InvalidateVolumeIdLocationCache(vid)
// first lookup queries the master and caches the single, under-replicated location
r1, err := LookupVolumeId(masterFn, dial, vid)
if err != nil {
t.Fatalf("first lookup: %v", err)
}
if len(r1.Locations) != 1 {
t.Fatalf("first lookup locations = %d, want 1", len(r1.Locations))
}
// a second lookup is served from cache, so the master is not queried again
if _, err := LookupVolumeId(masterFn, dial, vid); err != nil {
t.Fatalf("second lookup: %v", err)
}
fake.mu.Lock()
calls := fake.calls
fake.locations = 2 // master heals: both replicas are registered again
fake.mu.Unlock()
if calls != 1 {
t.Fatalf("expected a cache hit, master queried %d times", calls)
}
// invalidation drops the stale entry, so the next lookup re-queries and sees both replicas
InvalidateVolumeIdLocationCache(vid)
r3, err := LookupVolumeId(masterFn, dial, vid)
if err != nil {
t.Fatalf("third lookup: %v", err)
}
if len(r3.Locations) != 2 {
t.Fatalf("after invalidation locations = %d, want 2", len(r3.Locations))
}
}
+10
View File
@@ -60,3 +60,13 @@ func (vc *VidCache) Set(vid string, locations []Location, duration time.Duration
NextRefreshTime: time.Now().Add(duration),
}
}
func (vc *VidCache) Delete(vid string) {
id, err := strconv.ParseUint(vid, 10, 32)
if err != nil || id == 0 {
return
}
vc.Lock()
defer vc.Unlock()
delete(vc.cache, uint32(id))
}
+17
View File
@@ -25,6 +25,23 @@ func TestCaching(t *testing.T) {
}
}
// a stale under-replicated result must not linger for the full cache TTL
func TestCachingDelete(t *testing.T) {
var vc VidCache
locations := []Location{{Url: "a.com:8080"}}
vc.Set("123", locations, time.Minute)
if ret, _ := vc.Get("123"); ret == nil {
t.Fatal("expected vid 123 to be cached")
}
vc.Delete("123")
if ret, _ := vc.Get("123"); ret != nil {
t.Fatal("expected vid 123 to be evicted after Delete")
}
// deleting a missing or out-of-range id must not panic
vc.Delete("123")
vc.Delete("4294967296")
}
// a single large volume id must not allocate an entry per id below it
func TestCachingLargeVolumeId(t *testing.T) {
var vc VidCache
+9
View File
@@ -5,6 +5,7 @@ import (
"context"
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"hash"
"io"
@@ -18,6 +19,11 @@ import (
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// ErrTruncatedBody tags a source read that ended before the expected bytes
// arrived, so callers can tell a truncated input (client abort, reverse-proxy
// timeout) apart from a volume-server upload fault.
var ErrTruncatedBody = errors.New("truncated request body")
// ChunkedUploadResult contains the result of a chunked upload
type ChunkedUploadResult struct {
FileChunks []*filer_pb.FileChunk
@@ -104,6 +110,9 @@ uploadLoop:
// before any data (offset=0,got=0) from mid-stream truncation.
// A bare io.ErrUnexpectedEOF is not actionable on its own (see #9149).
wrapped := fmt.Errorf("read chunk at offset %d (got %d bytes): %w", chunkOffset, dataSize, err)
if errors.Is(err, io.ErrUnexpectedEOF) {
wrapped = fmt.Errorf("%w: %w", ErrTruncatedBody, wrapped)
}
glog.V(2).Infof("UploadReaderInChunks: %v", wrapped)
chunkBufferPool.Put(bytesBuffer)
<-bytesBufferLimitChan
+43
View File
@@ -372,3 +372,46 @@ func TestUploadReaderInChunksReaderFailure(t *testing.T) {
t.Logf("✓ Got partial result on read failure: chunks=%d, totalSize=%d",
len(result.FileChunks), result.TotalSize)
}
// truncatedReader yields some bytes then reports io.ErrUnexpectedEOF, mimicking a
// request body cut short by a client abort or reverse-proxy timeout.
type truncatedReader struct {
data []byte
pos int
}
func (r *truncatedReader) Read(p []byte) (int, error) {
if r.pos >= len(r.data) {
return 0, io.ErrUnexpectedEOF
}
n := copy(p, r.data[r.pos:])
r.pos += n
return n, nil
}
func TestUploadReaderInChunksTagsTruncatedBody(t *testing.T) {
reader := &truncatedReader{data: bytes.Repeat([]byte("x"), 10000)}
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) {
return nil, &AssignResult{Fid: "test-fid,1234", Url: "http://test-volume:8080", Count: 1}, nil
}
uploadFunc := func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) {
return &UploadResult{Size: uint32(len(data))}, nil
}
_, err := UploadReaderInChunks(context.Background(), reader, &ChunkedUploadOption{
ChunkSize: 8 * 1024,
Collection: "test",
AssignFunc: assignFunc,
UploadFunc: uploadFunc,
})
if err == nil {
t.Fatal("expected an error for a truncated body")
}
if !errors.Is(err, ErrTruncatedBody) {
t.Errorf("expected ErrTruncatedBody, got %v", err)
}
if !errors.Is(err, io.ErrUnexpectedEOF) {
t.Errorf("expected io.ErrUnexpectedEOF to remain in the chain, got %v", err)
}
}
+26 -6
View File
@@ -30,6 +30,21 @@ import (
util_http_client "github.com/seaweedfs/seaweedfs/weed/util/http/client"
)
// GenUploadUrlProxy returns a function that builds a chunk upload URL via the
// filer proxy. Identical to the inline logic used by weed mount -filerProxy
// and weed filer gateway:
//
// - without filerProxy: "http://{host}/{fileId}"
// - with filerProxy: "http://{filerAddress}/?proxyChunkId={fileId}"
func GenUploadUrlProxy(filerAddress string) func(host, fileId string) string {
return func(host, fileId string) string {
if filerAddress == "" {
return fmt.Sprintf("http://%s/%s", host, fileId)
}
return fmt.Sprintf("http://%s/?proxyChunkId=%s", filerAddress, fileId)
}
}
type UploadOption struct {
UploadUrl string
Filename string
@@ -43,8 +58,9 @@ type UploadOption struct {
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
SourceUrl string // optional: for logging when reading from a remote source
MaxAttempts int // <=0 uses the default
GenUploadUrl func(host, fileId string) string // if nil → fallback "http://{host}/{fileId}"
}
type UploadResult struct {
@@ -153,7 +169,7 @@ func NewUploaderWithHttpClient(httpClient HTTPClient) *Uploader {
}
}
func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, host string, auth security.EncodedJwt, err error), uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, data []byte) (fileId string, uploadResult *UploadResult, err error) {
func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, host string, auth security.EncodedJwt, err error), uploadOption *UploadOption, data []byte) (fileId string, uploadResult *UploadResult, err error) {
doUploadFunc := func() error {
var host string
var auth security.EncodedJwt
@@ -162,7 +178,11 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
return err
}
uploadOption.UploadUrl = genFileUrlFn(host, fileId)
genUrl := uploadOption.GenUploadUrl
if genUrl == nil {
genUrl = func(host, fileId string) string { return fmt.Sprintf("http://%s/%s", host, fileId) }
}
uploadOption.UploadUrl = genUrl(host, fileId)
uploadOption.Jwt = auth
uploadResult, err = uploader.retriedUploadData(context.Background(), data, uploadOption)
@@ -183,7 +203,7 @@ func (uploader *Uploader) uploadWithRetryData(assignFn func() (fileId string, ho
// UploadWithRetry will retry both assigning volume request and uploading content
// The option parameter does not need to specify UploadUrl and Jwt, which will come from assigning volume.
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, genFileUrlFn func(host, fileId string) string, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assignRequest *filer_pb.AssignVolumeRequest, uploadOption *UploadOption, reader io.Reader) (fileId string, uploadResult *UploadResult, err error, data []byte) {
bytesReader, ok := reader.(*util.BytesReader)
if ok {
data = bytesReader.Bytes
@@ -234,7 +254,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi
err = fmt.Errorf("filerGrpcAddress assign volume: %w", grpcAssignErr)
}
return
}, uploadOption, genFileUrlFn, data)
}, uploadOption, data)
return
}
+1 -4
View File
@@ -107,9 +107,7 @@ func TestUploadWithRetryDataReassignsOnVolumeSizeExceeded(t *testing.T) {
return "1,first", "volume-a", "", nil
}
return "2,second", "volume-b", "", nil
}, &UploadOption{Filename: "test.bin"}, func(host, fileId string) string {
return "http://" + host + "/" + fileId
}, []byte("abc"))
}, &UploadOption{Filename: "test.bin"}, []byte("abc"))
if err != nil {
t.Fatalf("expected success after reassignment, got %v", err)
@@ -210,7 +208,6 @@ func TestUploadWithRetryBoundsAssignVolume(t *testing.T) {
_, _, err, _ := uploader.UploadWithRetry(client,
&filer_pb.AssignVolumeRequest{Count: 1},
&UploadOption{Filename: "test.bin"},
func(host, fileId string) string { return "http://" + host + "/" + fileId },
bytes.NewReader([]byte("abc")),
)
done <- err
+99 -148
View File
@@ -2,6 +2,7 @@ package pb
import (
"container/heap"
"errors"
"fmt"
"io"
"strings"
@@ -17,6 +18,17 @@ import (
// LogFileReaderFn creates an io.ReadCloser for a set of file chunks.
type LogFileReaderFn func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error)
// logEntryChannelSize bounds decoded entries in flight per filer stream.
const logEntryChannelSize = 512
// maxLogEntrySize guards the per-entry allocation against a corrupt size
// prefix, mirroring the filer package's unexported constant.
const maxLogEntrySize = 1 << 30
// errReaderStopped signals that the entry consumer asked to stop (the merge
// loop aborted or the caller hit a processing error). It is not a read failure.
var errReaderStopped = errors.New("log entry reader stopped")
// PathFilter holds subscription path filtering parameters, matching the
// server-side eachEventNotificationFn filtering logic.
type PathFilter struct {
@@ -30,8 +42,8 @@ type PathFilter struct {
// (same algorithm as the server's OrderedLogVisitor), applies path filtering,
// and invokes processEventFn for each matching event.
//
// Filers are read in parallel (one goroutine per filer). Within each filer,
// the next file is prefetched while the current file's entries are consumed.
// Filers are read in parallel (one goroutine per filer), each streaming
// entries through a bounded channel.
func ReadLogFileRefs(
refs []*filer_pb.LogFileChunkRef,
newReader LogFileReaderFn,
@@ -61,73 +73,14 @@ func ReadLogFileRefs(
return
}
// Single filer fast path: no merge heap needed.
if len(filerOrder) == 1 {
return readFilerFilesWithPrefetch(perFiler[filerOrder[0]], newReader, startTsNs, stopTsNs, filter, processEventFn)
}
// Multiple filers: read each in parallel with prefetching, merge via min-heap.
return readMultiFilersMerged(filerOrder, perFiler, newReader, startTsNs, stopTsNs, filter, processEventFn)
return readFilersMerged(filerOrder, perFiler, newReader, startTsNs, stopTsNs, filter, processEventFn)
}
// readFilerFilesWithPrefetch reads files for a single filer, prefetching the
// next file while processing entries from the current one.
func readFilerFilesWithPrefetch(
refs []*filer_pb.LogFileChunkRef,
newReader LogFileReaderFn,
startTsNs, stopTsNs int64,
filter PathFilter,
processEventFn ProcessMetadataFunc,
) (lastTsNs int64, err error) {
type prefetchResult struct {
entries []*filer_pb.LogEntry
err error
}
startPrefetch := func(ref *filer_pb.LogFileChunkRef) chan prefetchResult {
ch := make(chan prefetchResult, 1)
go func() {
entries, readErr := readLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs)
ch <- prefetchResult{entries, readErr}
}()
return ch
}
var pendingCh chan prefetchResult
if len(refs) > 0 {
pendingCh = startPrefetch(refs[0])
}
for i, ref := range refs {
result := <-pendingCh
// Start prefetching next file while we process current
if i+1 < len(refs) {
pendingCh = startPrefetch(refs[i+1])
}
if result.err != nil {
if isChunkNotFound(result.err) {
glog.V(0).Infof("skip log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
continue
}
return lastTsNs, fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, result.err)
}
for _, logEntry := range result.entries {
lastTsNs, err = processOneLogEntry(logEntry, filter, processEventFn)
if err != nil {
return
}
}
}
return
}
// readMultiFilersMerged reads files from multiple filers in parallel (one goroutine
// per filer with prefetching), then merges entries in timestamp order via min-heap.
func readMultiFilersMerged(
// readFilersMerged reads files from each filer in parallel (one producer
// goroutine per filer streaming decoded entries through a bounded channel),
// then merges entries in timestamp order via min-heap. A single filer is the
// degenerate one-stream merge.
func readFilersMerged(
filerOrder []string,
perFiler map[string][]*filer_pb.LogFileChunkRef,
newReader LogFileReaderFn,
@@ -142,14 +95,19 @@ func readMultiFilersMerged(
}
streams := make([]filerStream, len(filerOrder))
var wg sync.WaitGroup
// A genuine (non chunk-not-found) read error must fail the whole replay: the
// caller advances its cursor only on success, so a swallowed error leaves a
// permanent gap. stop aborts the other readers; fatalErr is read on exit.
//
// Closing stop is the only cleanup: producers observe it at every send and
// every file boundary and exit on their own. An abort must not wait for
// them — a producer can be wedged in an uncancellable chunk read, and
// joining it would stall the caller's retry loop behind a dead connection.
stop := make(chan struct{})
var stopOnce sync.Once
closeStop := func() { stopOnce.Do(func() { close(stop) }) }
defer closeStop()
var fatalMu sync.Mutex
var fatalErr error
setFatal := func(e error) {
@@ -160,35 +118,33 @@ func readMultiFilersMerged(
fatalMu.Unlock()
closeStop()
}
fatal := func() error {
fatalMu.Lock()
defer fatalMu.Unlock()
return fatalErr
}
for i, filerId := range filerOrder {
entryCh := make(chan *filer_pb.LogEntry, 512)
entryCh := make(chan *filer_pb.LogEntry, logEntryChannelSize)
streams[i] = filerStream{filerId: filerId, entryCh: entryCh}
wg.Add(1)
go func(refs []*filer_pb.LogFileChunkRef, ch chan *filer_pb.LogEntry) {
defer wg.Done()
defer close(ch)
readFilerFilesToChannel(refs, newReader, startTsNs, stopTsNs, ch, stop, setFatal)
}(perFiler[filerId], entryCh)
}
// Stop readers, drain channels so none block on a send, then wait for exit.
drainAndWait := func() {
closeStop()
for i := range streams {
for range streams[i].entryCh {
}
}
wg.Wait()
}
// Seed the min-heap with the first entry from each filer
pq := &logEntryHeap{}
heap.Init(pq)
for i := range streams {
if entry, ok := <-streams[i].entryCh; ok {
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: i})
select {
case entry, ok := <-streams[i].entryCh:
if ok {
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: i})
}
case <-stop:
return lastTsNs, fatal()
}
}
@@ -198,11 +154,7 @@ func readMultiFilersMerged(
// aborted; lock-free bail on the hot path.
select {
case <-stop:
drainAndWait()
fatalMu.Lock()
fe := fatalErr
fatalMu.Unlock()
return lastTsNs, fe
return lastTsNs, fatal()
default:
}
@@ -210,20 +162,22 @@ func readMultiFilersMerged(
lastTsNs, err = processOneLogEntry(item.entry, filter, processEventFn)
if err != nil {
drainAndWait()
return
}
if entry, ok := <-streams[item.filerIdx].entryCh; ok {
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: item.filerIdx})
select {
case entry, ok := <-streams[item.filerIdx].entryCh:
if ok {
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: item.filerIdx})
}
case <-stop:
return lastTsNs, fatal()
}
}
drainAndWait()
fatalMu.Lock()
fe := fatalErr
fatalMu.Unlock()
if fe != nil {
// All channels closed: every producer has finished (setFatal, if any,
// happened before its close).
if fe := fatal(); fe != nil {
return lastTsNs, fe
}
return
@@ -237,53 +191,45 @@ func readFilerFilesToChannel(
stop <-chan struct{},
setFatal func(error),
) {
type prefetchResult struct {
entries []*filer_pb.LogEntry
err error
var sent int
sendEntry := func(entry *filer_pb.LogEntry) error {
// Prefer stop over a send the buffer could still absorb, so an aborted
// producer quits at the next entry instead of filling the channel.
select {
case <-stop:
return errReaderStopped
default:
}
select {
case ch <- entry:
sent++
return nil
case <-stop:
return errReaderStopped
}
}
startPrefetch := func(ref *filer_pb.LogFileChunkRef) chan prefetchResult {
resultCh := make(chan prefetchResult, 1)
go func() {
entries, err := readLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs)
resultCh <- prefetchResult{entries, err}
}()
return resultCh
}
var pendingCh chan prefetchResult
if len(refs) > 0 {
pendingCh = startPrefetch(refs[0])
}
for i, ref := range refs {
var result prefetchResult
for _, ref := range refs {
select {
case result = <-pendingCh:
case <-stop:
return
default:
}
if i+1 < len(refs) {
pendingCh = startPrefetch(refs[i+1])
}
if result.err != nil {
if isChunkNotFound(result.err) {
glog.V(0).Infof("skip log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
continue
}
glog.Errorf("read log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
setFatal(fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, result.err))
sentBefore := sent
streamErr := streamLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs, sendEntry)
if streamErr == errReaderStopped {
return
}
for _, entry := range result.entries {
select {
case ch <- entry:
case <-stop:
return
if streamErr != nil {
if isChunkNotFound(streamErr) {
// A mid-file not-found still delivered the readable prefix; say so
// rather than pretending the whole file was skipped.
glog.V(0).Infof("skip log file filer=%s ts=%d after %d entries: %v", ref.FilerId, ref.FileTsNs, sent-sentBefore, streamErr)
continue
}
setFatal(fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, streamErr))
return
}
}
}
@@ -352,45 +298,50 @@ func (h *logEntryHeap) Pop() any {
// --- log file parsing (uses io.ReadFull for correct partial-read handling) ---
func readLogFileEntries(newReader LogFileReaderFn, chunks []*filer_pb.FileChunk, startTsNs, stopTsNs int64) ([]*filer_pb.LogEntry, error) {
// streamLogFileEntries reads a log file's chunks and invokes eachFn for every
// entry as it is decoded, without buffering the whole file: a multi-GB log
// file costs one entry plus the chunk reader's buffer at a time, not O(file
// size). An eachFn error stops the read and is propagated verbatim.
func streamLogFileEntries(newReader LogFileReaderFn, chunks []*filer_pb.FileChunk, startTsNs, stopTsNs int64, eachFn func(*filer_pb.LogEntry) error) error {
reader, err := newReader(chunks)
if err != nil {
return nil, fmt.Errorf("create reader: %w", err)
return fmt.Errorf("create reader: %w", err)
}
defer reader.Close()
sizeBuf := make([]byte, 4)
var entries []*filer_pb.LogEntry
for {
_, err := io.ReadFull(reader, sizeBuf)
if err != nil {
if _, err := io.ReadFull(reader, sizeBuf); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
return nil
}
return entries, err
return err
}
size := util.BytesToUint32(sizeBuf)
if size > maxLogEntrySize {
return fmt.Errorf("entry size %d exceeds %d", size, maxLogEntrySize)
}
entryData := make([]byte, size)
_, err = io.ReadFull(reader, entryData)
if err != nil {
return entries, err
if _, err := io.ReadFull(reader, entryData); err != nil {
return err
}
logEntry := &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
return entries, err
if err := proto.Unmarshal(entryData, logEntry); err != nil {
return err
}
if logEntry.TsNs <= startTsNs {
continue
}
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
break
return nil
}
entries = append(entries, logEntry)
if err := eachFn(logEntry); err != nil {
return err
}
}
return entries, nil
}
+135 -15
View File
@@ -2,8 +2,10 @@ package pb
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"sync/atomic"
"testing"
"time"
@@ -145,10 +147,10 @@ func (t *testLogFiles) totalEvents() int {
return total
}
// TestReadLogFileRefsMergeOrder verifies that entries from multiple filers are
// delivered in correct timestamp order.
func TestReadLogFileRefsMergeOrder(t *testing.T) {
files := newTestLogFiles(3, 2, 50, 0)
// assertOrderedReplay reads all refs and checks every event arrives exactly
// once, in timestamp order.
func assertOrderedReplay(t *testing.T, files *testLogFiles) {
t.Helper()
var timestamps []int64
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
@@ -161,20 +163,21 @@ func TestReadLogFileRefsMergeOrder(t *testing.T) {
t.Fatalf("ReadLogFileRefs: %v", err)
}
expected := files.totalEvents()
if len(timestamps) != expected {
t.Fatalf("expected %d events, got %d", expected, len(timestamps))
if got, want := len(timestamps), files.totalEvents(); got != want {
t.Fatalf("expected %d events, got %d", want, got)
}
for i := 1; i < len(timestamps); i++ {
if timestamps[i] < timestamps[i-1] {
t.Errorf("out of order at index %d: ts[%d]=%d > ts[%d]=%d",
t.Fatalf("out of order at index %d: ts[%d]=%d > ts[%d]=%d",
i, i-1, timestamps[i-1], i, timestamps[i])
break
}
}
}
t.Logf("Verified %d events from 3 filers in correct timestamp order", len(timestamps))
// TestReadLogFileRefsMergeOrder verifies that entries from multiple filers are
// delivered in correct timestamp order.
func TestReadLogFileRefsMergeOrder(t *testing.T) {
assertOrderedReplay(t, newTestLogFiles(3, 2, 50, 0))
}
// TestReadLogFileRefsPathFilter verifies path filtering including system log exclusion.
@@ -218,7 +221,7 @@ func TestReadLogFileRefsPathFilter(t *testing.T) {
// TestDirectReadVsServerSideThroughput compares:
// - Server-side: sequential file read → gRPC send per event
// - Client direct-read: parallel filers + prefetching + no gRPC
// - Client direct-read: parallel filers + streaming + no gRPC
func TestDirectReadVsServerSideThroughput(t *testing.T) {
const (
numFilers = 3
@@ -255,7 +258,7 @@ func TestDirectReadVsServerSideThroughput(t *testing.T) {
})
var directRate float64
t.Run("client_direct_read_parallel_prefetch", func(t *testing.T) {
t.Run("client_direct_read_parallel_streaming", func(t *testing.T) {
var processed int64
start := time.Now()
@@ -270,12 +273,12 @@ func TestDirectReadVsServerSideThroughput(t *testing.T) {
}
elapsed := time.Since(start)
directRate = float64(processed) / elapsed.Seconds()
t.Logf("direct-read: %d events %v %6.0f events/sec (%d filers parallel + prefetch, no gRPC)",
t.Logf("direct-read: %d events %v %6.0f events/sec (%d filers parallel + streaming, no gRPC)",
processed, elapsed.Round(time.Millisecond), directRate, numFilers)
})
if serverRate > 0 {
t.Logf("Speedup: %.1fx (parallel + prefetch + no gRPC vs server-side sequential)", directRate/serverRate)
t.Logf("Speedup: %.1fx (parallel + streaming + no gRPC vs server-side sequential)", directRate/serverRate)
}
}
@@ -329,3 +332,120 @@ func TestReadLogFileRefsMultiFilerNotFoundSkips(t *testing.T) {
t.Fatalf("expected %d events after skipping one file, got %d", expected, count)
}
}
// TestReadLogFileRefsSingleFilerOrder covers the single-filer path: every
// entry across all files, in order.
func TestReadLogFileRefsSingleFilerOrder(t *testing.T) {
assertOrderedReplay(t, newTestLogFiles(1, 4, 50, 0))
}
// TestReadLogFileRefsSingleFilerProcessErrorStops verifies that the callback's
// own error propagates and aborts the stream promptly, mid-file.
func TestReadLogFileRefsSingleFilerProcessErrorStops(t *testing.T) {
files := newTestLogFiles(1, 3, 100, 0)
var count int
wantErr := fmt.Errorf("boom")
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
PathFilter{PathPrefix: "/"},
func(resp *filer_pb.SubscribeMetadataResponse) error {
count++
if count == 5 {
return wantErr
}
return nil
})
if !errors.Is(err, wantErr) {
t.Fatalf("expected processing error to propagate, got: %v", err)
}
// Should stop near the failing event, not process the whole 300-event set.
if count > 20 {
t.Fatalf("expected prompt stop after error, processed %d events", count)
}
}
// A corrupt size prefix must fail the replay instead of allocating gigabytes.
func TestReadLogFileRefsCorruptSizePrefix(t *testing.T) {
data := make([]byte, 4)
util.Uint32toBytes(data, 0xFFFFFFF0)
refs := []*filer_pb.LogFileChunkRef{{
Chunks: []*filer_pb.FileChunk{{FileId: "corrupt"}},
FileTsNs: 1,
FilerId: "filer00",
}}
readerFn := func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(data)), nil
}
_, err := ReadLogFileRefs(refs, readerFn, 0, 0, PathFilter{PathPrefix: "/"},
func(*filer_pb.SubscribeMetadataResponse) error { return nil })
if err == nil || !strings.Contains(err.Error(), "exceeds") {
t.Fatalf("expected size-cap error, got: %v", err)
}
}
// blockingReader blocks in Read until released.
type blockingReader struct{ release chan struct{} }
func (r *blockingReader) Read(p []byte) (int, error) { <-r.release; return 0, io.EOF }
func (r *blockingReader) Close() error { return nil }
// An abort (fatal error on one filer) must not wait for another filer's
// in-flight chunk read: the replay returns promptly and the wedged producer
// exits on its own once its read completes.
func TestReadLogFileRefsAbortDoesNotJoinWedgedReader(t *testing.T) {
files := newTestLogFiles(2, 1, 10, 0)
release := make(chan struct{})
t.Cleanup(func() { close(release) })
wedgedKey := files.refs[0].Chunks[0].FileId // filer00 wedges mid-read
failKey := files.refs[1].Chunks[0].FileId // filer01 fails for real
base := files.readerFn()
readerFn := func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
switch chunks[0].FileId {
case wedgedKey:
return &blockingReader{release: release}, nil
case failKey:
return nil, fmt.Errorf("failed to locate %s", failKey)
}
return base(chunks)
}
done := make(chan error, 1)
go func() {
_, err := ReadLogFileRefs(files.refs, readerFn, 0, 0, PathFilter{PathPrefix: "/"},
func(*filer_pb.SubscribeMetadataResponse) error { return nil })
done <- err
}()
select {
case err := <-done:
if err == nil {
t.Fatalf("expected the fatal read error to propagate")
}
case <-time.After(5 * time.Second):
t.Fatalf("ReadLogFileRefs did not return while a peer reader was wedged")
}
}
// TestReadLogFileRefsSingleFilerNotFoundSkips confirms a chunk-not-found on the
// single-filer path skips just that file, not the whole replay.
func TestReadLogFileRefsSingleFilerNotFoundSkips(t *testing.T) {
files := newTestLogFiles(1, 3, 10, 0)
skipKey := files.refs[1].Chunks[0].FileId // second file
readerFn := failingReaderFn(files.readerFn(), skipKey, fmt.Errorf("volume not found: %s", skipKey))
var count int
_, err := ReadLogFileRefs(files.refs, readerFn, 0, 0,
PathFilter{PathPrefix: "/"},
func(resp *filer_pb.SubscribeMetadataResponse) error {
count++
return nil
})
if err != nil {
t.Fatalf("chunk-not-found should be skipped, got error: %v", err)
}
if want := files.totalEvents() - 10; count != want {
t.Fatalf("expected %d events after skipping one file, got %d", want, count)
}
}
+17
View File
@@ -64,6 +64,9 @@ service Seaweed {
message DiskTag {
uint32 disk_id = 1;
repeated string tags = 2;
// Physical disk descriptor, reported for every location including empty ones.
string type = 3;
int64 max_volume_count = 4;
}
message Heartbeat {
@@ -96,6 +99,10 @@ message Heartbeat {
volume_server_pb.VolumeServerState state = 23;
repeated DiskTag disk_tags = 24;
// physical disk capacity per disk type, in bytes, from the underlying filesystem
map<string, uint64> disk_total_bytes = 25;
map<string, uint64> disk_free_bytes = 26;
}
message HeartbeatResponse {
@@ -319,8 +326,18 @@ message DiskInfo {
repeated VolumeInformationMessage volume_infos = 6;
repeated VolumeEcShardInformationMessage ec_shard_infos = 7;
int64 remote_volume_count = 8;
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
// identity; on the type-keyed aggregate it is only a representative fallback
// (the first volume's disk id).
uint32 disk_id = 9;
repeated string tags = 10;
// Max volume count for every physical disk of this type, keyed by disk id,
// including disks with no volumes or EC shards; recovers empty disks that
// carry no per-volume/per-shard records.
map<uint32, int64> max_volume_count_by_disk = 11;
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
uint64 disk_total_bytes = 12;
uint64 disk_free_bytes = 13;
}
message DataNodeInfo {
string id = 1;
+215 -127
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v6.33.4
// protoc v7.35.0
// source: master.proto
package master_pb
@@ -23,11 +23,14 @@ const (
)
type DiskTag struct {
state protoimpl.MessageState `protogen:"open.v1"`
DiskId uint32 `protobuf:"varint,1,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
Tags []string `protobuf:"bytes,2,rep,name=tags,proto3" json:"tags,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
DiskId uint32 `protobuf:"varint,1,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
Tags []string `protobuf:"bytes,2,rep,name=tags,proto3" json:"tags,omitempty"`
// Physical disk descriptor, reported for every location including empty ones.
Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"`
MaxVolumeCount int64 `protobuf:"varint,4,opt,name=max_volume_count,json=maxVolumeCount,proto3" json:"max_volume_count,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DiskTag) Reset() {
@@ -74,6 +77,20 @@ func (x *DiskTag) GetTags() []string {
return nil
}
func (x *DiskTag) GetType() string {
if x != nil {
return x.Type
}
return ""
}
func (x *DiskTag) GetMaxVolumeCount() int64 {
if x != nil {
return x.MaxVolumeCount
}
return 0
}
type Heartbeat struct {
state protoimpl.MessageState `protogen:"open.v1"`
Ip string `protobuf:"bytes,1,opt,name=ip,proto3" json:"ip,omitempty"`
@@ -99,10 +116,13 @@ type Heartbeat struct {
LocationUuids []string `protobuf:"bytes,21,rep,name=location_uuids,json=locationUuids,proto3" json:"location_uuids,omitempty"`
Id string `protobuf:"bytes,22,opt,name=id,proto3" json:"id,omitempty"` // volume server id, independent of ip:port for stable identification
// state flags
State *volume_server_pb.VolumeServerState `protobuf:"bytes,23,opt,name=state,proto3" json:"state,omitempty"`
DiskTags []*DiskTag `protobuf:"bytes,24,rep,name=disk_tags,json=diskTags,proto3" json:"disk_tags,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
State *volume_server_pb.VolumeServerState `protobuf:"bytes,23,opt,name=state,proto3" json:"state,omitempty"`
DiskTags []*DiskTag `protobuf:"bytes,24,rep,name=disk_tags,json=diskTags,proto3" json:"disk_tags,omitempty"`
// physical disk capacity per disk type, in bytes, from the underlying filesystem
DiskTotalBytes map[string]uint64 `protobuf:"bytes,25,rep,name=disk_total_bytes,json=diskTotalBytes,proto3" json:"disk_total_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
DiskFreeBytes map[string]uint64 `protobuf:"bytes,26,rep,name=disk_free_bytes,json=diskFreeBytes,proto3" json:"disk_free_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Heartbeat) Reset() {
@@ -282,6 +302,20 @@ func (x *Heartbeat) GetDiskTags() []*DiskTag {
return nil
}
func (x *Heartbeat) GetDiskTotalBytes() map[string]uint64 {
if x != nil {
return x.DiskTotalBytes
}
return nil
}
func (x *Heartbeat) GetDiskFreeBytes() map[string]uint64 {
if x != nil {
return x.DiskFreeBytes
}
return nil
}
type HeartbeatResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
VolumeSizeLimit uint64 `protobuf:"varint,1,opt,name=volume_size_limit,json=volumeSizeLimit,proto3" json:"volume_size_limit,omitempty"`
@@ -2121,10 +2155,20 @@ type DiskInfo struct {
VolumeInfos []*VolumeInformationMessage `protobuf:"bytes,6,rep,name=volume_infos,json=volumeInfos,proto3" json:"volume_infos,omitempty"`
EcShardInfos []*VolumeEcShardInformationMessage `protobuf:"bytes,7,rep,name=ec_shard_infos,json=ecShardInfos,proto3" json:"ec_shard_infos,omitempty"`
RemoteVolumeCount int64 `protobuf:"varint,8,opt,name=remote_volume_count,json=remoteVolumeCount,proto3" json:"remote_volume_count,omitempty"`
DiskId uint32 `protobuf:"varint,9,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
Tags []string `protobuf:"bytes,10,rep,name=tags,proto3" json:"tags,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
// identity; on the type-keyed aggregate it is only a representative fallback
// (the first volume's disk id).
DiskId uint32 `protobuf:"varint,9,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
Tags []string `protobuf:"bytes,10,rep,name=tags,proto3" json:"tags,omitempty"`
// Max volume count for every physical disk of this type, keyed by disk id,
// including disks with no volumes or EC shards; recovers empty disks that
// carry no per-volume/per-shard records.
MaxVolumeCountByDisk map[uint32]int64 `protobuf:"bytes,11,rep,name=max_volume_count_by_disk,json=maxVolumeCountByDisk,proto3" json:"max_volume_count_by_disk,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
DiskTotalBytes uint64 `protobuf:"varint,12,opt,name=disk_total_bytes,json=diskTotalBytes,proto3" json:"disk_total_bytes,omitempty"`
DiskFreeBytes uint64 `protobuf:"varint,13,opt,name=disk_free_bytes,json=diskFreeBytes,proto3" json:"disk_free_bytes,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DiskInfo) Reset() {
@@ -2227,6 +2271,27 @@ func (x *DiskInfo) GetTags() []string {
return nil
}
func (x *DiskInfo) GetMaxVolumeCountByDisk() map[uint32]int64 {
if x != nil {
return x.MaxVolumeCountByDisk
}
return nil
}
func (x *DiskInfo) GetDiskTotalBytes() uint64 {
if x != nil {
return x.DiskTotalBytes
}
return 0
}
func (x *DiskInfo) GetDiskFreeBytes() uint64 {
if x != nil {
return x.DiskFreeBytes
}
return 0
}
type DataNodeInfo struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
@@ -4059,7 +4124,7 @@ type SuperBlockExtra_ErasureCoding struct {
func (x *SuperBlockExtra_ErasureCoding) Reset() {
*x = SuperBlockExtra_ErasureCoding{}
mi := &file_master_proto_msgTypes[65]
mi := &file_master_proto_msgTypes[67]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4071,7 +4136,7 @@ func (x *SuperBlockExtra_ErasureCoding) String() string {
func (*SuperBlockExtra_ErasureCoding) ProtoMessage() {}
func (x *SuperBlockExtra_ErasureCoding) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[65]
mi := &file_master_proto_msgTypes[67]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4120,7 +4185,7 @@ type LookupVolumeResponse_VolumeIdLocation struct {
func (x *LookupVolumeResponse_VolumeIdLocation) Reset() {
*x = LookupVolumeResponse_VolumeIdLocation{}
mi := &file_master_proto_msgTypes[66]
mi := &file_master_proto_msgTypes[68]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4132,7 +4197,7 @@ func (x *LookupVolumeResponse_VolumeIdLocation) String() string {
func (*LookupVolumeResponse_VolumeIdLocation) ProtoMessage() {}
func (x *LookupVolumeResponse_VolumeIdLocation) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[66]
mi := &file_master_proto_msgTypes[68]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4186,7 +4251,7 @@ type LookupEcVolumeResponse_EcShardIdLocation struct {
func (x *LookupEcVolumeResponse_EcShardIdLocation) Reset() {
*x = LookupEcVolumeResponse_EcShardIdLocation{}
mi := &file_master_proto_msgTypes[71]
mi := &file_master_proto_msgTypes[74]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4198,7 +4263,7 @@ func (x *LookupEcVolumeResponse_EcShardIdLocation) String() string {
func (*LookupEcVolumeResponse_EcShardIdLocation) ProtoMessage() {}
func (x *LookupEcVolumeResponse_EcShardIdLocation) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[71]
mi := &file_master_proto_msgTypes[74]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4241,7 +4306,7 @@ type ListClusterNodesResponse_ClusterNode struct {
func (x *ListClusterNodesResponse_ClusterNode) Reset() {
*x = ListClusterNodesResponse_ClusterNode{}
mi := &file_master_proto_msgTypes[72]
mi := &file_master_proto_msgTypes[75]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4253,7 +4318,7 @@ func (x *ListClusterNodesResponse_ClusterNode) String() string {
func (*ListClusterNodesResponse_ClusterNode) ProtoMessage() {}
func (x *ListClusterNodesResponse_ClusterNode) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[72]
mi := &file_master_proto_msgTypes[75]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4316,7 +4381,7 @@ type RaftListClusterServersResponse_ClusterServers struct {
func (x *RaftListClusterServersResponse_ClusterServers) Reset() {
*x = RaftListClusterServersResponse_ClusterServers{}
mi := &file_master_proto_msgTypes[73]
mi := &file_master_proto_msgTypes[76]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4328,7 +4393,7 @@ func (x *RaftListClusterServersResponse_ClusterServers) String() string {
func (*RaftListClusterServersResponse_ClusterServers) ProtoMessage() {}
func (x *RaftListClusterServersResponse_ClusterServers) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[73]
mi := &file_master_proto_msgTypes[76]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4376,10 +4441,13 @@ var File_master_proto protoreflect.FileDescriptor
const file_master_proto_rawDesc = "" +
"\n" +
"\fmaster.proto\x12\tmaster_pb\x1a\x13volume_server.proto\"6\n" +
"\fmaster.proto\x12\tmaster_pb\x1a\x13volume_server.proto\"t\n" +
"\aDiskTag\x12\x17\n" +
"\adisk_id\x18\x01 \x01(\rR\x06diskId\x12\x12\n" +
"\x04tags\x18\x02 \x03(\tR\x04tags\"\xbc\b\n" +
"\x04tags\x18\x02 \x03(\tR\x04tags\x12\x12\n" +
"\x04type\x18\x03 \x01(\tR\x04type\x12(\n" +
"\x10max_volume_count\x18\x04 \x01(\x03R\x0emaxVolumeCount\"\xe6\n" +
"\n" +
"\tHeartbeat\x12\x0e\n" +
"\x02ip\x18\x01 \x01(\tR\x02ip\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12\x1d\n" +
@@ -4407,10 +4475,18 @@ const file_master_proto_rawDesc = "" +
"\x0elocation_uuids\x18\x15 \x03(\tR\rlocationUuids\x12\x0e\n" +
"\x02id\x18\x16 \x01(\tR\x02id\x129\n" +
"\x05state\x18\x17 \x01(\v2#.volume_server_pb.VolumeServerStateR\x05state\x12/\n" +
"\tdisk_tags\x18\x18 \x03(\v2\x12.master_pb.DiskTagR\bdiskTags\x1aB\n" +
"\tdisk_tags\x18\x18 \x03(\v2\x12.master_pb.DiskTagR\bdiskTags\x12R\n" +
"\x10disk_total_bytes\x18\x19 \x03(\v2(.master_pb.Heartbeat.DiskTotalBytesEntryR\x0ediskTotalBytes\x12O\n" +
"\x0fdisk_free_bytes\x18\x1a \x03(\v2'.master_pb.Heartbeat.DiskFreeBytesEntryR\rdiskFreeBytes\x1aB\n" +
"\x14MaxVolumeCountsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\rR\x05value:\x028\x01\"\xcd\x02\n" +
"\x05value\x18\x02 \x01(\rR\x05value:\x028\x01\x1aA\n" +
"\x13DiskTotalBytesEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\x04R\x05value:\x028\x01\x1a@\n" +
"\x12DiskFreeBytesEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\x04R\x05value:\x028\x01\"\xcd\x02\n" +
"\x11HeartbeatResponse\x12*\n" +
"\x11volume_size_limit\x18\x01 \x01(\x04R\x0fvolumeSizeLimit\x12\x16\n" +
"\x06leader\x18\x02 \x01(\tR\x06leader\x12'\n" +
@@ -4600,7 +4676,7 @@ const file_master_proto_rawDesc = "" +
"\vcollections\x18\x01 \x03(\v2\x15.master_pb.CollectionR\vcollections\"-\n" +
"\x17CollectionDeleteRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"\x1a\n" +
"\x18CollectionDeleteResponse\"\xbe\x03\n" +
"\x18CollectionDeleteResponse\"\xc0\x05\n" +
"\bDiskInfo\x12\x12\n" +
"\x04type\x18\x01 \x01(\tR\x04type\x12!\n" +
"\fvolume_count\x18\x02 \x01(\x03R\vvolumeCount\x12(\n" +
@@ -4612,7 +4688,13 @@ const file_master_proto_rawDesc = "" +
"\x13remote_volume_count\x18\b \x01(\x03R\x11remoteVolumeCount\x12\x17\n" +
"\adisk_id\x18\t \x01(\rR\x06diskId\x12\x12\n" +
"\x04tags\x18\n" +
" \x03(\tR\x04tags\"\xee\x01\n" +
" \x03(\tR\x04tags\x12e\n" +
"\x18max_volume_count_by_disk\x18\v \x03(\v2-.master_pb.DiskInfo.MaxVolumeCountByDiskEntryR\x14maxVolumeCountByDisk\x12(\n" +
"\x10disk_total_bytes\x18\f \x01(\x04R\x0ediskTotalBytes\x12&\n" +
"\x0fdisk_free_bytes\x18\r \x01(\x04R\rdiskFreeBytes\x1aG\n" +
"\x19MaxVolumeCountByDiskEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\rR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\x03R\x05value:\x028\x01\"\xee\x01\n" +
"\fDataNodeInfo\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12D\n" +
"\tdiskInfos\x18\x02 \x03(\v2&.master_pb.DataNodeInfo.DiskInfosEntryR\tdiskInfos\x12\x1b\n" +
@@ -4800,7 +4882,7 @@ func file_master_proto_rawDescGZIP() []byte {
return file_master_proto_rawDescData
}
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 74)
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 77)
var file_master_proto_goTypes = []any{
(*DiskTag)(nil), // 0: master_pb.DiskTag
(*Heartbeat)(nil), // 1: master_pb.Heartbeat
@@ -4866,17 +4948,20 @@ var file_master_proto_goTypes = []any{
(*RaftLeadershipTransferResponse)(nil), // 61: master_pb.RaftLeadershipTransferResponse
(*VolumeGrowResponse)(nil), // 62: master_pb.VolumeGrowResponse
nil, // 63: master_pb.Heartbeat.MaxVolumeCountsEntry
nil, // 64: master_pb.StorageBackend.PropertiesEntry
(*SuperBlockExtra_ErasureCoding)(nil), // 65: master_pb.SuperBlockExtra.ErasureCoding
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 66: master_pb.LookupVolumeResponse.VolumeIdLocation
nil, // 67: master_pb.DataNodeInfo.DiskInfosEntry
nil, // 68: master_pb.RackInfo.DiskInfosEntry
nil, // 69: master_pb.DataCenterInfo.DiskInfosEntry
nil, // 70: master_pb.TopologyInfo.DiskInfosEntry
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 71: master_pb.LookupEcVolumeResponse.EcShardIdLocation
(*ListClusterNodesResponse_ClusterNode)(nil), // 72: master_pb.ListClusterNodesResponse.ClusterNode
(*RaftListClusterServersResponse_ClusterServers)(nil), // 73: master_pb.RaftListClusterServersResponse.ClusterServers
(*volume_server_pb.VolumeServerState)(nil), // 74: volume_server_pb.VolumeServerState
nil, // 64: master_pb.Heartbeat.DiskTotalBytesEntry
nil, // 65: master_pb.Heartbeat.DiskFreeBytesEntry
nil, // 66: master_pb.StorageBackend.PropertiesEntry
(*SuperBlockExtra_ErasureCoding)(nil), // 67: master_pb.SuperBlockExtra.ErasureCoding
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 68: master_pb.LookupVolumeResponse.VolumeIdLocation
nil, // 69: master_pb.DiskInfo.MaxVolumeCountByDiskEntry
nil, // 70: master_pb.DataNodeInfo.DiskInfosEntry
nil, // 71: master_pb.RackInfo.DiskInfosEntry
nil, // 72: master_pb.DataCenterInfo.DiskInfosEntry
nil, // 73: master_pb.TopologyInfo.DiskInfosEntry
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 74: master_pb.LookupEcVolumeResponse.EcShardIdLocation
(*ListClusterNodesResponse_ClusterNode)(nil), // 75: master_pb.ListClusterNodesResponse.ClusterNode
(*RaftListClusterServersResponse_ClusterServers)(nil), // 76: master_pb.RaftListClusterServersResponse.ClusterServers
(*volume_server_pb.VolumeServerState)(nil), // 77: volume_server_pb.VolumeServerState
}
var file_master_proto_depIdxs = []int32{
3, // 0: master_pb.Heartbeat.volumes:type_name -> master_pb.VolumeInformationMessage
@@ -4886,91 +4971,94 @@ var file_master_proto_depIdxs = []int32{
5, // 4: master_pb.Heartbeat.new_ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
5, // 5: master_pb.Heartbeat.deleted_ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
63, // 6: master_pb.Heartbeat.max_volume_counts:type_name -> master_pb.Heartbeat.MaxVolumeCountsEntry
74, // 7: master_pb.Heartbeat.state:type_name -> volume_server_pb.VolumeServerState
77, // 7: master_pb.Heartbeat.state:type_name -> volume_server_pb.VolumeServerState
0, // 8: master_pb.Heartbeat.disk_tags:type_name -> master_pb.DiskTag
6, // 9: master_pb.HeartbeatResponse.storage_backends:type_name -> master_pb.StorageBackend
64, // 10: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
65, // 11: master_pb.SuperBlockExtra.erasure_coding:type_name -> master_pb.SuperBlockExtra.ErasureCoding
10, // 12: master_pb.KeepConnectedResponse.volume_location:type_name -> master_pb.VolumeLocation
11, // 13: master_pb.KeepConnectedResponse.cluster_node_update:type_name -> master_pb.ClusterNodeUpdate
13, // 14: master_pb.KeepConnectedResponse.lock_ring_update:type_name -> master_pb.LockRingUpdate
66, // 15: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
16, // 16: master_pb.AssignResponse.replicas:type_name -> master_pb.Location
16, // 17: master_pb.AssignResponse.location:type_name -> master_pb.Location
22, // 18: master_pb.CollectionListResponse.collections:type_name -> master_pb.Collection
3, // 19: master_pb.DiskInfo.volume_infos:type_name -> master_pb.VolumeInformationMessage
5, // 20: master_pb.DiskInfo.ec_shard_infos:type_name -> master_pb.VolumeEcShardInformationMessage
67, // 21: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
28, // 22: master_pb.RackInfo.data_node_infos:type_name -> master_pb.DataNodeInfo
68, // 23: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
29, // 24: master_pb.DataCenterInfo.rack_infos:type_name -> master_pb.RackInfo
69, // 25: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
30, // 26: master_pb.TopologyInfo.data_center_infos:type_name -> master_pb.DataCenterInfo
70, // 27: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
31, // 28: master_pb.VolumeListResponse.topology_info:type_name -> master_pb.TopologyInfo
71, // 29: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
6, // 30: master_pb.GetMasterConfigurationResponse.storage_backends:type_name -> master_pb.StorageBackend
72, // 31: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
73, // 32: master_pb.RaftListClusterServersResponse.cluster_servers:type_name -> master_pb.RaftListClusterServersResponse.ClusterServers
16, // 33: master_pb.LookupVolumeResponse.VolumeIdLocation.locations:type_name -> master_pb.Location
27, // 34: master_pb.DataNodeInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
27, // 35: master_pb.RackInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
27, // 36: master_pb.DataCenterInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
27, // 37: master_pb.TopologyInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
16, // 38: master_pb.LookupEcVolumeResponse.EcShardIdLocation.locations:type_name -> master_pb.Location
1, // 39: master_pb.Seaweed.SendHeartbeat:input_type -> master_pb.Heartbeat
9, // 40: master_pb.Seaweed.KeepConnected:input_type -> master_pb.KeepConnectedRequest
14, // 41: master_pb.Seaweed.LookupVolume:input_type -> master_pb.LookupVolumeRequest
17, // 42: master_pb.Seaweed.Assign:input_type -> master_pb.AssignRequest
17, // 43: master_pb.Seaweed.StreamAssign:input_type -> master_pb.AssignRequest
20, // 44: master_pb.Seaweed.Statistics:input_type -> master_pb.StatisticsRequest
23, // 45: master_pb.Seaweed.CollectionList:input_type -> master_pb.CollectionListRequest
25, // 46: master_pb.Seaweed.CollectionDelete:input_type -> master_pb.CollectionDeleteRequest
32, // 47: master_pb.Seaweed.VolumeList:input_type -> master_pb.VolumeListRequest
34, // 48: master_pb.Seaweed.LookupEcVolume:input_type -> master_pb.LookupEcVolumeRequest
36, // 49: master_pb.Seaweed.VacuumVolume:input_type -> master_pb.VacuumVolumeRequest
38, // 50: master_pb.Seaweed.DisableVacuum:input_type -> master_pb.DisableVacuumRequest
40, // 51: master_pb.Seaweed.EnableVacuum:input_type -> master_pb.EnableVacuumRequest
42, // 52: master_pb.Seaweed.VolumeMarkReadonly:input_type -> master_pb.VolumeMarkReadonlyRequest
44, // 53: master_pb.Seaweed.GetMasterConfiguration:input_type -> master_pb.GetMasterConfigurationRequest
46, // 54: master_pb.Seaweed.ListClusterNodes:input_type -> master_pb.ListClusterNodesRequest
48, // 55: master_pb.Seaweed.LeaseAdminToken:input_type -> master_pb.LeaseAdminTokenRequest
50, // 56: master_pb.Seaweed.ReleaseAdminToken:input_type -> master_pb.ReleaseAdminTokenRequest
52, // 57: master_pb.Seaweed.Ping:input_type -> master_pb.PingRequest
58, // 58: master_pb.Seaweed.RaftListClusterServers:input_type -> master_pb.RaftListClusterServersRequest
54, // 59: master_pb.Seaweed.RaftAddServer:input_type -> master_pb.RaftAddServerRequest
56, // 60: master_pb.Seaweed.RaftRemoveServer:input_type -> master_pb.RaftRemoveServerRequest
60, // 61: master_pb.Seaweed.RaftLeadershipTransfer:input_type -> master_pb.RaftLeadershipTransferRequest
18, // 62: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
2, // 63: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
12, // 64: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
15, // 65: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
19, // 66: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
19, // 67: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
21, // 68: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
24, // 69: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
26, // 70: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
33, // 71: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
35, // 72: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
37, // 73: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
39, // 74: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
41, // 75: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
43, // 76: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
45, // 77: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
47, // 78: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
49, // 79: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
51, // 80: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
53, // 81: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
59, // 82: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
55, // 83: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
57, // 84: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
61, // 85: master_pb.Seaweed.RaftLeadershipTransfer:output_type -> master_pb.RaftLeadershipTransferResponse
62, // 86: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
63, // [63:87] is the sub-list for method output_type
39, // [39:63] is the sub-list for method input_type
39, // [39:39] is the sub-list for extension type_name
39, // [39:39] is the sub-list for extension extendee
0, // [0:39] is the sub-list for field type_name
64, // 9: master_pb.Heartbeat.disk_total_bytes:type_name -> master_pb.Heartbeat.DiskTotalBytesEntry
65, // 10: master_pb.Heartbeat.disk_free_bytes:type_name -> master_pb.Heartbeat.DiskFreeBytesEntry
6, // 11: master_pb.HeartbeatResponse.storage_backends:type_name -> master_pb.StorageBackend
66, // 12: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
67, // 13: master_pb.SuperBlockExtra.erasure_coding:type_name -> master_pb.SuperBlockExtra.ErasureCoding
10, // 14: master_pb.KeepConnectedResponse.volume_location:type_name -> master_pb.VolumeLocation
11, // 15: master_pb.KeepConnectedResponse.cluster_node_update:type_name -> master_pb.ClusterNodeUpdate
13, // 16: master_pb.KeepConnectedResponse.lock_ring_update:type_name -> master_pb.LockRingUpdate
68, // 17: master_pb.LookupVolumeResponse.volume_id_locations:type_name -> master_pb.LookupVolumeResponse.VolumeIdLocation
16, // 18: master_pb.AssignResponse.replicas:type_name -> master_pb.Location
16, // 19: master_pb.AssignResponse.location:type_name -> master_pb.Location
22, // 20: master_pb.CollectionListResponse.collections:type_name -> master_pb.Collection
3, // 21: master_pb.DiskInfo.volume_infos:type_name -> master_pb.VolumeInformationMessage
5, // 22: master_pb.DiskInfo.ec_shard_infos:type_name -> master_pb.VolumeEcShardInformationMessage
69, // 23: master_pb.DiskInfo.max_volume_count_by_disk:type_name -> master_pb.DiskInfo.MaxVolumeCountByDiskEntry
70, // 24: master_pb.DataNodeInfo.diskInfos:type_name -> master_pb.DataNodeInfo.DiskInfosEntry
28, // 25: master_pb.RackInfo.data_node_infos:type_name -> master_pb.DataNodeInfo
71, // 26: master_pb.RackInfo.diskInfos:type_name -> master_pb.RackInfo.DiskInfosEntry
29, // 27: master_pb.DataCenterInfo.rack_infos:type_name -> master_pb.RackInfo
72, // 28: master_pb.DataCenterInfo.diskInfos:type_name -> master_pb.DataCenterInfo.DiskInfosEntry
30, // 29: master_pb.TopologyInfo.data_center_infos:type_name -> master_pb.DataCenterInfo
73, // 30: master_pb.TopologyInfo.diskInfos:type_name -> master_pb.TopologyInfo.DiskInfosEntry
31, // 31: master_pb.VolumeListResponse.topology_info:type_name -> master_pb.TopologyInfo
74, // 32: master_pb.LookupEcVolumeResponse.shard_id_locations:type_name -> master_pb.LookupEcVolumeResponse.EcShardIdLocation
6, // 33: master_pb.GetMasterConfigurationResponse.storage_backends:type_name -> master_pb.StorageBackend
75, // 34: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
76, // 35: master_pb.RaftListClusterServersResponse.cluster_servers:type_name -> master_pb.RaftListClusterServersResponse.ClusterServers
16, // 36: master_pb.LookupVolumeResponse.VolumeIdLocation.locations:type_name -> master_pb.Location
27, // 37: master_pb.DataNodeInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
27, // 38: master_pb.RackInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
27, // 39: master_pb.DataCenterInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
27, // 40: master_pb.TopologyInfo.DiskInfosEntry.value:type_name -> master_pb.DiskInfo
16, // 41: master_pb.LookupEcVolumeResponse.EcShardIdLocation.locations:type_name -> master_pb.Location
1, // 42: master_pb.Seaweed.SendHeartbeat:input_type -> master_pb.Heartbeat
9, // 43: master_pb.Seaweed.KeepConnected:input_type -> master_pb.KeepConnectedRequest
14, // 44: master_pb.Seaweed.LookupVolume:input_type -> master_pb.LookupVolumeRequest
17, // 45: master_pb.Seaweed.Assign:input_type -> master_pb.AssignRequest
17, // 46: master_pb.Seaweed.StreamAssign:input_type -> master_pb.AssignRequest
20, // 47: master_pb.Seaweed.Statistics:input_type -> master_pb.StatisticsRequest
23, // 48: master_pb.Seaweed.CollectionList:input_type -> master_pb.CollectionListRequest
25, // 49: master_pb.Seaweed.CollectionDelete:input_type -> master_pb.CollectionDeleteRequest
32, // 50: master_pb.Seaweed.VolumeList:input_type -> master_pb.VolumeListRequest
34, // 51: master_pb.Seaweed.LookupEcVolume:input_type -> master_pb.LookupEcVolumeRequest
36, // 52: master_pb.Seaweed.VacuumVolume:input_type -> master_pb.VacuumVolumeRequest
38, // 53: master_pb.Seaweed.DisableVacuum:input_type -> master_pb.DisableVacuumRequest
40, // 54: master_pb.Seaweed.EnableVacuum:input_type -> master_pb.EnableVacuumRequest
42, // 55: master_pb.Seaweed.VolumeMarkReadonly:input_type -> master_pb.VolumeMarkReadonlyRequest
44, // 56: master_pb.Seaweed.GetMasterConfiguration:input_type -> master_pb.GetMasterConfigurationRequest
46, // 57: master_pb.Seaweed.ListClusterNodes:input_type -> master_pb.ListClusterNodesRequest
48, // 58: master_pb.Seaweed.LeaseAdminToken:input_type -> master_pb.LeaseAdminTokenRequest
50, // 59: master_pb.Seaweed.ReleaseAdminToken:input_type -> master_pb.ReleaseAdminTokenRequest
52, // 60: master_pb.Seaweed.Ping:input_type -> master_pb.PingRequest
58, // 61: master_pb.Seaweed.RaftListClusterServers:input_type -> master_pb.RaftListClusterServersRequest
54, // 62: master_pb.Seaweed.RaftAddServer:input_type -> master_pb.RaftAddServerRequest
56, // 63: master_pb.Seaweed.RaftRemoveServer:input_type -> master_pb.RaftRemoveServerRequest
60, // 64: master_pb.Seaweed.RaftLeadershipTransfer:input_type -> master_pb.RaftLeadershipTransferRequest
18, // 65: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
2, // 66: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
12, // 67: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
15, // 68: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
19, // 69: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
19, // 70: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
21, // 71: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
24, // 72: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
26, // 73: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
33, // 74: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
35, // 75: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
37, // 76: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
39, // 77: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
41, // 78: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
43, // 79: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
45, // 80: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
47, // 81: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
49, // 82: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
51, // 83: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
53, // 84: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
59, // 85: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
55, // 86: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
57, // 87: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
61, // 88: master_pb.Seaweed.RaftLeadershipTransfer:output_type -> master_pb.RaftLeadershipTransferResponse
62, // 89: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
66, // [66:90] is the sub-list for method output_type
42, // [42:66] is the sub-list for method input_type
42, // [42:42] is the sub-list for extension type_name
42, // [42:42] is the sub-list for extension extendee
0, // [0:42] is the sub-list for field type_name
}
func init() { file_master_proto_init() }
@@ -4984,7 +5072,7 @@ func file_master_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_master_proto_rawDesc), len(file_master_proto_rawDesc)),
NumEnums: 0,
NumMessages: 74,
NumMessages: 77,
NumExtensions: 0,
NumServices: 1,
},
+76 -36
View File
@@ -6,50 +6,46 @@ func (v *VolumeLocation) IsEmptyUrl() bool {
return v.Url == "" || v.Url == ":0"
}
// SplitByPhysicalDisk returns one DiskInfo per physical disk_id observed in
// VolumeInfos / EcShardInfos. The wire format keys DataNodeInfo.DiskInfos by
// disk type, so multiple same-type physical disks on one DataNode collapse
// into a single DiskInfo entry. Per-volume and per-shard records carry the
// real physical DiskId; this helper rebuilds a per-physical-disk view from
// those records so consumers (topology indexes, shell output) can target
// individual disks instead of treating each node as one big disk.
//
// ActiveVolumeCount and RemoteVolumeCount are computed exactly from each
// disk's VolumeInfos (read-only and remote-backed are known per-volume).
// MaxVolumeCount and FreeVolumeCount are not derivable from per-volume
// records, so they are split across reconstructed disks with the remainder
// distributed to the lowest disk ids — the sums are preserved exactly.
// SplitByPhysicalDisk returns one DiskInfo per physical disk. The wire format
// keys DataNodeInfo.DiskInfos by disk type, collapsing same-type disks into one
// entry, so this rebuilds the per-disk view. MaxVolumeCountByDisk, when present,
// is the authoritative set (empty disks included) and gives each disk its exact
// max; otherwise the set is the DiskIds seen on records with aggregate Max/Free
// split evenly.
func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
if d == nil {
return nil
}
// DiskId 0 is overloaded: it is both the first physical disk (Locations[0])
// and the protobuf default for "unset". Only treat 0 as unset when every
// record reports 0 (the legacy case where the volume server didn't populate
// DiskId). If any record carries a non-zero DiskId, the reporting is real and
// a 0 means physical disk 0 — keep it distinct instead of folding it onto
// d.DiskId, which would merge two physical disks and drop disk 0 from view.
hasNonZero := false
for _, vi := range d.VolumeInfos {
if vi.DiskId != 0 {
hasNonZero = true
break
}
}
if !hasNonZero {
for _, eci := range d.EcShardInfos {
if eci.DiskId != 0 {
hasNonZero = true
break
}
}
}
normalize := func(id uint32) uint32 {
if id == 0 && d.DiskId != 0 {
if id == 0 && !hasNonZero && d.DiskId != 0 {
return d.DiskId
}
return id
}
diskIDs := make(map[uint32]struct{})
for _, vi := range d.VolumeInfos {
diskIDs[normalize(vi.DiskId)] = struct{}{}
}
for _, eci := range d.EcShardInfos {
diskIDs[normalize(eci.DiskId)] = struct{}{}
}
if len(diskIDs) == 0 {
diskIDs[d.DiskId] = struct{}{}
}
if len(diskIDs) == 1 {
for diskID := range diskIDs {
if diskID == d.DiskId {
return []*DiskInfo{d}
}
}
}
perDiskVolumes := make(map[uint32][]*VolumeInformationMessage)
for _, vi := range d.VolumeInfos {
id := normalize(vi.DiskId)
@@ -61,6 +57,35 @@ func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
perDiskShards[id] = append(perDiskShards[id], eci)
}
diskIDs := make(map[uint32]struct{})
for id := range perDiskVolumes {
diskIDs[id] = struct{}{}
}
for id := range perDiskShards {
diskIDs[id] = struct{}{}
}
// MaxVolumeCountByDisk (when present) is the authoritative set with each
// disk's exact max.
exactMax := len(d.MaxVolumeCountByDisk) > 0
for diskID := range d.MaxVolumeCountByDisk {
diskIDs[diskID] = struct{}{}
}
if len(diskIDs) == 0 {
diskIDs[d.DiskId] = struct{}{}
}
// A lone disk equal to the aggregate needs no reconstruction; exactMax disks
// always reconstruct so they report their own max.
if !exactMax && len(diskIDs) == 1 {
for diskID := range diskIDs {
if diskID == d.DiskId {
return []*DiskInfo{d}
}
}
}
// Sort disk IDs so the remainder distribution is deterministic and the
// reconstructed slice is in DiskId order, which is what downstream
// renderers expect.
@@ -94,17 +119,32 @@ func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
remoteCount++
}
}
volumeCount := int64(len(perDiskVolumes[diskID]))
maxVolumeCount := share(d.MaxVolumeCount, i)
freeVolumeCount := share(d.FreeVolumeCount, i)
if exactMax {
maxVolumeCount = d.MaxVolumeCountByDisk[diskID]
// EC slots aren't subtracted (needs the configurable ratio, outside
// this package); planners subtract them from EcShardInfos. Clamp so an
// over-allocated disk can't report negative free.
freeVolumeCount = maxVolumeCount - (volumeCount - remoteCount)
if freeVolumeCount < 0 {
freeVolumeCount = 0
}
}
result = append(result, &DiskInfo{
Type: d.Type,
MaxVolumeCount: share(d.MaxVolumeCount, i),
VolumeCount: int64(len(perDiskVolumes[diskID])),
FreeVolumeCount: share(d.FreeVolumeCount, i),
MaxVolumeCount: maxVolumeCount,
VolumeCount: volumeCount,
FreeVolumeCount: freeVolumeCount,
ActiveVolumeCount: activeCount,
RemoteVolumeCount: remoteCount,
VolumeInfos: perDiskVolumes[diskID],
EcShardInfos: perDiskShards[diskID],
DiskId: diskID,
Tags: append([]string(nil), d.Tags...),
DiskTotalBytes: uint64(share(int64(d.DiskTotalBytes), i)),
DiskFreeBytes: uint64(share(int64(d.DiskFreeBytes), i)),
})
}
return result
+122 -3
View File
@@ -5,6 +5,75 @@ import (
"testing"
)
// MaxVolumeCountByDisk surfaces empty disks and gives each its exact max.
func TestDiskInfoSplitByPhysicalDisk_includesEmptyDiskFromPhysicalDisks(t *testing.T) {
d := &DiskInfo{
Type: "hdd",
MaxVolumeCount: 1000, // per-type aggregate
VolumeInfos: []*VolumeInformationMessage{
{Id: 10, DiskId: 0},
{Id: 11, DiskId: 1},
},
MaxVolumeCountByDisk: map[uint32]int64{
0: 350,
1: 350,
2: 300, // empty disk, no volumes/shards
},
}
got := d.SplitByPhysicalDisk()
if len(got) != 3 {
t.Fatalf("want 3 physical disks including the empty one, got %d", len(got))
}
byID := map[uint32]*DiskInfo{}
for _, di := range got {
byID[di.DiskId] = di
}
empty, ok := byID[2]
if !ok {
t.Fatalf("empty disk 2 not surfaced; got %v", byID)
}
if empty.VolumeCount != 0 {
t.Errorf("empty disk: want 0 volumes, got %d", empty.VolumeCount)
}
if empty.FreeVolumeCount != 300 {
t.Errorf("empty disk free: want its full max 300, got %d", empty.FreeVolumeCount)
}
// Exact per-disk max, not the even split (which would give ~334/333/333).
if byID[0].MaxVolumeCount != 350 || byID[1].MaxVolumeCount != 350 || byID[2].MaxVolumeCount != 300 {
t.Errorf("want exact per-disk max 350/350/300, got %d/%d/%d",
byID[0].MaxVolumeCount, byID[1].MaxVolumeCount, byID[2].MaxVolumeCount)
}
if byID[0].FreeVolumeCount != 349 {
t.Errorf("disk 0 free: want 349 (350-1 volume), got %d", byID[0].FreeVolumeCount)
}
}
// An over-allocated disk reports zero free, not negative.
func TestDiskInfoSplitByPhysicalDisk_clampsNegativeFreeOnOverAllocation(t *testing.T) {
d := &DiskInfo{
Type: "hdd",
VolumeInfos: []*VolumeInformationMessage{
{Id: 1, DiskId: 0},
{Id: 2, DiskId: 0},
{Id: 3, DiskId: 0},
},
MaxVolumeCountByDisk: map[uint32]int64{
0: 2, // 3 volumes on a max-2 disk
},
}
got := d.SplitByPhysicalDisk()
if len(got) != 1 {
t.Fatalf("want 1 disk, got %d", len(got))
}
if got[0].FreeVolumeCount != 0 {
t.Errorf("over-allocated disk free: want clamped 0, got %d", got[0].FreeVolumeCount)
}
}
func TestDiskInfoSplitByPhysicalDisk_collapsesOnSingleDisk(t *testing.T) {
d := &DiskInfo{
Type: "hdd",
@@ -138,9 +207,9 @@ func TestDiskInfoSplitByPhysicalDisk_countsActiveAndRemoteExactly(t *testing.T)
}
cases := []struct {
id uint32
wantActive int64
wantRemote int64
id uint32
wantActive int64
wantRemote int64
}{
{0, 1, 0},
{1, 1, 1},
@@ -203,6 +272,56 @@ func TestDiskInfoSplitByPhysicalDisk_normalizesZeroToOuterDiskId(t *testing.T) {
}
}
// TestDiskInfoSplitByPhysicalDisk_keepsRealDiskZeroWhenMixed reproduces a
// multi-disk node where physical disk 0 (Locations[0]) holds volumes and the
// aggregate DiskId is seeded from a non-zero sibling (volumes[0] landed on
// disk 6). DiskId 0 must stay its own physical disk, not get folded onto disk
// 6 — folding drops a disk from the count and doubles the sibling's volumes.
func TestDiskInfoSplitByPhysicalDisk_keepsRealDiskZeroWhenMixed(t *testing.T) {
d := &DiskInfo{
Type: "hdd",
MaxVolumeCount: 30,
DiskId: 6, // seeded from volumes[0].DiskId in ToDiskInfo
VolumeInfos: []*VolumeInformationMessage{
{Id: 60, DiskId: 6},
{Id: 61, DiskId: 6},
{Id: 1, DiskId: 0}, // real disk 0, must not be remapped to 6
{Id: 2, DiskId: 0},
{Id: 30, DiskId: 3},
},
}
got := d.SplitByPhysicalDisk()
byID := map[uint32]*DiskInfo{}
for _, di := range got {
byID[di.DiskId] = di
}
if len(got) != 3 {
t.Fatalf("want 3 physical disks (0, 3, 6), got %d: %v", len(got), byID)
}
if _, ok := byID[0]; !ok {
t.Fatalf("physical disk 0 was dropped; got disks %v", byID)
}
if byID[0].VolumeCount != 2 {
t.Errorf("disk 0: want 2 volumes, got %d", byID[0].VolumeCount)
}
if byID[6].VolumeCount != 2 {
t.Errorf("disk 6: want 2 volumes (not merged with disk 0), got %d", byID[6].VolumeCount)
}
if byID[3].VolumeCount != 1 {
t.Errorf("disk 3: want 1 volume, got %d", byID[3].VolumeCount)
}
var sumMax int64
for _, di := range got {
sumMax += di.MaxVolumeCount
}
if sumMax != 30 {
t.Errorf("sum of MaxVolumeCount = %d, want 30 (lossless split)", sumMax)
}
}
func TestDiskInfoSplitByPhysicalDisk_nilSafe(t *testing.T) {
var d *DiskInfo
if got := d.SplitByPhysicalDisk(); got != nil {
+1
View File
@@ -711,6 +711,7 @@ message ScrubEcVolumeRequest {
VolumeScrubMode mode = 1;
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
repeated uint32 volume_ids = 2;
bool force_deleted_needles_check = 3; // FULL mode only; may report false positives when EC indexes disagree
}
message ScrubEcVolumeResponse {
uint64 total_volumes = 1;
+14 -5
View File
@@ -6018,9 +6018,10 @@ type ScrubEcVolumeRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Mode VolumeScrubMode `protobuf:"varint,1,opt,name=mode,proto3,enum=volume_server_pb.VolumeScrubMode" json:"mode,omitempty"`
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
VolumeIds []uint32 `protobuf:"varint,2,rep,packed,name=volume_ids,json=volumeIds,proto3" json:"volume_ids,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
VolumeIds []uint32 `protobuf:"varint,2,rep,packed,name=volume_ids,json=volumeIds,proto3" json:"volume_ids,omitempty"`
ForceDeletedNeedlesCheck bool `protobuf:"varint,3,opt,name=force_deleted_needles_check,json=forceDeletedNeedlesCheck,proto3" json:"force_deleted_needles_check,omitempty"` // FULL mode only; may report false positives when EC indexes disagree
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ScrubEcVolumeRequest) Reset() {
@@ -6067,6 +6068,13 @@ func (x *ScrubEcVolumeRequest) GetVolumeIds() []uint32 {
return nil
}
func (x *ScrubEcVolumeRequest) GetForceDeletedNeedlesCheck() bool {
if x != nil {
return x.ForceDeletedNeedlesCheck
}
return false
}
type ScrubEcVolumeResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
TotalVolumes uint64 `protobuf:"varint,1,opt,name=total_volumes,json=totalVolumes,proto3" json:"total_volumes,omitempty"`
@@ -7510,11 +7518,12 @@ const file_volume_server_proto_rawDesc = "" +
"\vtotal_files\x18\x02 \x01(\x04R\n" +
"totalFiles\x12*\n" +
"\x11broken_volume_ids\x18\x03 \x03(\rR\x0fbrokenVolumeIds\x12\x18\n" +
"\adetails\x18\x04 \x03(\tR\adetails\"l\n" +
"\adetails\x18\x04 \x03(\tR\adetails\"\xab\x01\n" +
"\x14ScrubEcVolumeRequest\x125\n" +
"\x04mode\x18\x01 \x01(\x0e2!.volume_server_pb.VolumeScrubModeR\x04mode\x12\x1d\n" +
"\n" +
"volume_ids\x18\x02 \x03(\rR\tvolumeIds\"\xf0\x01\n" +
"volume_ids\x18\x02 \x03(\rR\tvolumeIds\x12=\n" +
"\x1bforce_deleted_needles_check\x18\x03 \x01(\bR\x18forceDeletedNeedlesCheck\"\xf0\x01\n" +
"\x15ScrubEcVolumeResponse\x12#\n" +
"\rtotal_volumes\x18\x01 \x01(\x04R\ftotalVolumes\x12\x1f\n" +
"\vtotal_files\x18\x02 \x01(\x04R\n" +
+1 -1
View File
@@ -1166,7 +1166,7 @@ func (h *HybridMessageScanner) extractParquetFileStats(entry *filer_pb.Entry, lo
fileSize := filer.FileSize(entry)
visibleIntervals, _ := filer.NonOverlappingVisibleIntervals(context.Background(), lookupFileIdFn, entry.Chunks, 0, int64(fileSize))
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, 0, int64(fileSize))
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn)
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn, nil)
readerAt := filer.NewChunkReaderAtFromClient(context.Background(), readerCache, chunkViews, int64(fileSize), filer.DefaultPrefetchCount)
// Create parquet reader - this only reads metadata, not data
@@ -283,6 +283,9 @@ func (gcs *gcsRemoteStorageClient) UpdateFileMetadata(loc *remote_pb.RemoteStora
func (gcs *gcsRemoteStorageClient) DeleteFile(loc *remote_pb.RemoteStorageLocation) (err error) {
key := loc.Path[1:]
if err = gcs.client.Bucket(loc.Bucket).Object(key).Delete(context.Background()); err != nil {
if errors.Is(err, storage.ErrObjectNotExist) {
return remote_storage.ErrRemoteObjectNotFound
}
return fmt.Errorf("gcs delete %s%s: %v", loc.Bucket, key, err)
}
return
+25 -32
View File
@@ -187,6 +187,17 @@ func (fs *FilerSink) uploadManifestChunk(path string, sourceMtimeNs int64, sourc
retryName := fmt.Sprintf("replicate manifest chunk %s", sourceFileId)
err = util.RetryUntil(retryName, func() error {
uploadOption := &operation.UploadOption{
Filename: "",
Cipher: false,
IsInputCompressed: false,
MimeType: "application/octet-stream",
PairMap: nil,
RetryForever: false,
}
if fs.writeChunkByFiler {
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(fs.address)
}
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
fs,
&filer_pb.AssignVolumeRequest{
@@ -198,17 +209,7 @@ func (fs *FilerSink) uploadManifestChunk(path string, sourceMtimeNs int64, sourc
DiskType: fs.diskType,
Path: path,
},
&operation.UploadOption{
Filename: "",
Cipher: false,
IsInputCompressed: false,
MimeType: "application/octet-stream",
PairMap: nil,
RetryForever: false,
},
func(host, fileId string) string {
return fs.buildUploadUrl(host, fileId)
},
uploadOption,
bytes.NewReader(manifestData),
)
if uploadErr != nil {
@@ -302,6 +303,18 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
transferStatus.Status = "uploading"
transferStatus.mu.Unlock()
uploadOption := &operation.UploadOption{
Filename: savedFilename,
Cipher: false,
IsInputCompressed: "gzip" == savedHeader.Get("Content-Encoding"),
MimeType: savedHeader.Get("Content-Type"),
PairMap: nil,
RetryForever: false,
SourceUrl: savedSourceUrl,
}
if fs.writeChunkByFiler {
uploadOption.GenUploadUrl = operation.GenUploadUrlProxy(fs.address)
}
currentFileId, uploadResult, uploadErr, _ := uploader.UploadWithRetry(
fs,
&filer_pb.AssignVolumeRequest{
@@ -313,20 +326,7 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
DiskType: fs.diskType,
Path: path,
},
&operation.UploadOption{
Filename: savedFilename,
Cipher: false,
IsInputCompressed: "gzip" == savedHeader.Get("Content-Encoding"),
MimeType: savedHeader.Get("Content-Type"),
PairMap: nil,
RetryForever: false,
SourceUrl: savedSourceUrl,
},
func(host, fileId string) string {
fileUrl := fs.buildUploadUrl(host, fileId)
glog.V(4).Infof("replicating %s to %s header:%+v", savedFilename, fileUrl, savedHeader)
return fileUrl
},
uploadOption,
util.NewBytesReader(fullData),
)
if uploadErr != nil {
@@ -435,13 +435,6 @@ func validateReplicatedReadSize(sourceChunk *filer_pb.FileChunk, readSize int) e
return nil
}
func (fs *FilerSink) buildUploadUrl(host, fileId string) string {
if fs.writeChunkByFiler {
return fmt.Sprintf("http://%s/?proxyChunkId=%s", fs.address, fileId)
}
return fmt.Sprintf("http://%s/%s", host, fileId)
}
// hasSourceNewerVersion reports whether the source's current entry for targetPath
// has moved past sourceMtimeNs — gone, or a strictly-newer mtime — meaning the
// version being replayed is stale. The lookup runs regardless of sourceMtimeNs so
+7 -4
View File
@@ -2059,18 +2059,21 @@ func (iam *IdentityAccessManagement) PruneBucketFromConfiguration(ctx context.Co
}
// actionScopedToBucket reports whether a configured action string like
// "Read:bucket" or "Write:bucket/prefix" is scoped exclusively to the given
// bucket. Wildcard resources are never considered scoped to a single bucket.
// "Read:bucket", "Write:bucket/prefix" or "Write:bucket/prefix/*" is scoped
// exclusively to the given bucket. A wildcard in the bucket segment (e.g. "*"
// or "buck*/x") may cover other buckets and is never single-bucket scoped; a
// wildcard confined to the object path stays scoped to this bucket.
func actionScopedToBucket(action, bucket string) bool {
idx := strings.Index(action, ":")
if idx < 0 {
return false
}
resource := action[idx+1:]
if strings.ContainsAny(resource, "*?") {
bucketSeg, _, _ := strings.Cut(resource, "/")
if strings.ContainsAny(bucketSeg, "*?") {
return false
}
return resource == bucket || strings.HasPrefix(resource, bucket+"/")
return bucketSeg == bucket
}
// LoadS3ApiConfigurationFromCredentialManager loads configuration using the credential manager
+26
View File
@@ -0,0 +1,26 @@
package s3api
import "testing"
func TestActionScopedToBucket(t *testing.T) {
cases := []struct {
action string
bucket string
want bool
}{
{"Read:bucket", "bucket", true},
{"Write:bucket/prefix", "bucket", true},
{"Write:bucket/prefix/*", "bucket", true},
{"Write:bucket/*", "bucket", true},
{"Read:other/prefix/*", "bucket", false},
{"Write:*", "bucket", false},
{"Write:buck*/x", "bucket", false},
{"Write:bucketother", "bucket", false},
{"Admin", "bucket", false},
}
for _, c := range cases {
if got := actionScopedToBucket(c.action, c.bucket); got != c.want {
t.Errorf("actionScopedToBucket(%q, %q) = %v, want %v", c.action, c.bucket, got, c.want)
}
}
}
+28 -8
View File
@@ -361,8 +361,12 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
entries, _, err := s3a.list(uploadDirectory, "", "", false, s3_constants.MaxS3MultipartParts+1)
if err != nil {
glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
return nil, nil, s3err.ErrNoSuchUpload
if isFilerListNotFound(err) {
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
return nil, nil, s3err.ErrNoSuchUpload
}
// a store error must not read as "upload gone": the client would drop a fully-uploaded object
return nil, nil, s3err.ErrInternalError
}
if len(entries) == 0 {
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
@@ -372,8 +376,11 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
pentry, err := s3a.getEntry(s3a.genUploadsFolder(*input.Bucket), *input.UploadId)
if err != nil {
glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
return nil, nil, s3err.ErrNoSuchUpload
if errors.Is(err, filer_pb.ErrNotFound) {
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedNoSuchUpload).Inc()
return nil, nil, s3err.ErrNoSuchUpload
}
return nil, nil, s3err.ErrInternalError
}
deleteEntries := make([]*filer_pb.Entry, 0)
@@ -882,8 +889,10 @@ func (s3a *S3ApiServer) abortMultipartUpload(input *s3.AbortMultipartUploadInput
exists, err := s3a.exists(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true)
if err != nil {
glog.V(1).Infof("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
return nil, s3err.ErrNoSuchUpload
// filer_pb.Exists reports not-found as (false, nil), so an error here is
// always a store failure; answering NoSuchUpload would leak the parts.
glog.Errorf("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
return nil, s3err.ErrInternalError
}
if exists {
err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true, true)
@@ -930,8 +939,14 @@ func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput
entries, _, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), "", *input.UploadIdMarker, false, math.MaxInt32)
if err != nil {
// A missing .uploads folder normally lists as empty with no error; a
// store that reports it as not-found still means an empty list.
if isFilerListNotFound(err) {
return output, s3err.ErrNone
}
// surface a real store error; a masked empty 200 makes a resuming client treat the upload as gone
glog.Errorf("listMultipartUploads %s error: %v", *input.Bucket, err)
return
return output, s3err.ErrInternalError
}
uploadsCount := int64(0)
@@ -991,8 +1006,13 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d%s", *input.PartNumberMarker, multipartExt), false, uint32(*input.MaxParts))
if err != nil {
// A store that reports the missing upload directory as not-found means
// the upload is gone (completed or aborted), not a store error.
if isFilerListNotFound(err) {
return nil, s3err.ErrNoSuchUpload
}
glog.Errorf("listObjectParts %s %s error: %v", *input.Bucket, *input.UploadId, err)
return nil, s3err.ErrNoSuchUpload
return nil, s3err.ErrInternalError
}
// Note: The upload directory is sort of a marker of the existence of an multipart upload request.
+12
View File
@@ -1,10 +1,22 @@
package s3api
import (
"errors"
"strings"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
// isFilerListNotFound reports whether a filer list error is a not-found.
// Unlike lookups (normalized in filer_pb.LookupEntry), list errors cross gRPC
// as raw status errors, so the sentinel survives only as text. Callers must
// pass errors from paths without user-controlled segments that could spoof it.
func isFilerListNotFound(err error) bool {
return errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(err.Error(), filer_pb.ErrNotFound.Error())
}
// ErrorHandlers provide common error handling patterns for S3 API operations
// handleMultipartError logs an error and returns the standard multipart error format
@@ -0,0 +1,48 @@
package s3api
import (
"errors"
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestClassifyCopySourceError(t *testing.T) {
deleteMarker := &filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte("true")},
}
tests := []struct {
name string
entry *filer_pb.Entry
err error
want s3err.ErrorCode
}{
{"regular entry", &filer_pb.Entry{Name: "o"}, nil, s3err.ErrNone},
{"nil entry", nil, nil, s3err.ErrInvalidCopySource},
{"directory entry", &filer_pb.Entry{IsDirectory: true}, nil, s3err.ErrInvalidCopySource},
{"delete marker entry", deleteMarker, nil, s3err.ErrNoSuchKey},
{"not found sentinel", nil, filer_pb.ErrNotFound, s3err.ErrInvalidCopySource},
{"wrapped not found", nil, fmt.Errorf("read %s: %w", "o", filer_pb.ErrNotFound), s3err.ErrInvalidCopySource},
{"grpc not found", nil, status.Error(codes.NotFound, "no entry"), s3err.ErrInvalidCopySource},
{"invalid version id", nil, errInvalidVersionID, s3err.ErrInvalidCopySource},
{"delete marker error", nil, ErrDeleteMarker, s3err.ErrInvalidCopySource},
{"transient unavailable", nil, status.Error(codes.Unavailable, "filer down"), s3err.ErrServiceUnavailable},
{"store error", nil, errors.New("connection reset"), s3err.ErrInternalError},
// A message merely mentioning the sentinel text must not downgrade a store error.
{"sentinel text in message", nil, fmt.Errorf("peer said: %s", filer_pb.ErrNotFound.Error()), s3err.ErrInternalError},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := classifyCopySourceError(tt.entry, tt.err); got != tt.want {
t.Errorf("classifyCopySourceError() = %v, want %v", got, tt.want)
}
})
}
}
+5 -9
View File
@@ -989,15 +989,11 @@ func (e *EmbeddedIamApi) getActions(policy *policy_engine.PolicyDocument) ([]str
// Bucket-level or bucket/* - use just bucket name
actions = append(actions, fmt.Sprintf("%s:%s", statementAction, bucket))
} else {
// Path-specific: bucket/path/* -> Action:bucket/path
// Remove trailing /* if present for cleaner action format
objectPath = strings.TrimSuffix(objectPath, "/*")
objectPath = strings.TrimSuffix(objectPath, "*")
if objectPath == "" {
actions = append(actions, fmt.Sprintf("%s:%s", statementAction, bucket))
} else {
actions = append(actions, fmt.Sprintf("%s:%s/%s", statementAction, bucket, objectPath))
}
// Path-specific: preserve the object path, including any
// trailing wildcard, so CanDo can match objects under the
// prefix. Stripping the wildcard yielded a non-wildcard
// action that only matched at bucket level.
actions = append(actions, fmt.Sprintf("%s:%s/%s", statementAction, bucket, objectPath))
}
}
}
+37
View File
@@ -2095,6 +2095,43 @@ func TestEmbeddedIamGetActionsFromPolicy(t *testing.T) {
assert.Contains(t, actions, "Write:mybucket")
}
// TestEmbeddedIamGetActionsPrefixScopedResource verifies that a prefix-scoped
// resource keeps its trailing wildcard so CanDo authorizes objects under the
// prefix. Stripping the wildcard produced a non-wildcard action that only
// matched at bucket level, denying every PutObject under the prefix.
func TestEmbeddedIamGetActionsPrefixScopedResource(t *testing.T) {
api := NewEmbeddedIamApiForTest()
policyDoc := `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:Get*", "s3:Put*", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::mcp-upload/mcp/TMS/api_keys/example/*"]
}]
}`
policy, err := api.GetPolicyDocument(&policyDoc)
require.NoError(t, err)
actions, err := api.getActions(&policy)
require.NoError(t, err)
assert.Contains(t, actions, "Read:mcp-upload/mcp/TMS/api_keys/example/*")
assert.Contains(t, actions, "Write:mcp-upload/mcp/TMS/api_keys/example/*")
identity := &Identity{Name: "prefix-user"}
for _, a := range actions {
identity.Actions = append(identity.Actions, Action(a))
}
assert.True(t, identity.CanDo(ACTION_WRITE, "mcp-upload", "mcp/TMS/api_keys/example/logo.png"),
"PutObject under the allowed prefix should be authorized")
assert.True(t, identity.CanDo(ACTION_READ, "mcp-upload", "mcp/TMS/api_keys/example/logo.png"),
"GetObject under the allowed prefix should be authorized")
assert.False(t, identity.CanDo(ACTION_WRITE, "mcp-upload", "other/logo.png"),
"PutObject outside the allowed prefix should be denied")
}
// TestEmbeddedIamPutUserPolicyAllResourceWildcard reproduces issue #9209:
// an AWS-style policy using "Action":"s3:*" with a bare "Resource":"*" is
// valid AWS IAM syntax (meaning "any resource") but was rejected with
+51 -8
View File
@@ -24,6 +24,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
@@ -67,6 +69,31 @@ func hasPrefixFold(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
}
// classifyCopySourceError maps a copy-source lookup to an S3 error: a missing,
// invalid, or directory source stays a client error, but a transient store
// error becomes a retryable 5xx so a resumable copy/commit survives a blip.
func classifyCopySourceError(entry *filer_pb.Entry, err error) s3err.ErrorCode {
if err == nil {
if entry == nil || entry.IsDirectory {
return s3err.ErrInvalidCopySource
}
// The latest-version pointer tracks delete markers too; copying one
// must be NoSuchKey like every other handler, not a copy of the stub.
if deleteMarker, ok := entry.Extended[s3_constants.ExtDeleteMarkerKey]; ok && string(deleteMarker) == "true" {
return s3err.ErrNoSuchKey
}
return s3err.ErrNone
}
if errors.Is(err, filer_pb.ErrNotFound) || status.Code(err) == codes.NotFound ||
errors.Is(err, errInvalidVersionID) || errors.Is(err, ErrDeleteMarker) {
return s3err.ErrInvalidCopySource
}
if isTransientFilerError(err) {
return s3err.ErrServiceUnavailable
}
return s3err.ErrInternalError
}
func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request) {
t := time.Now().UTC().Truncate(time.Millisecond)
@@ -144,13 +171,19 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
srcVersioningState, err := s3a.getVersioningState(srcBucket)
if err != nil {
glog.Errorf("Error checking versioning state for source bucket %s: %v", srcBucket, err)
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
// Only a missing bucket is the client's fault; a store error must stay
// retryable, matching the destination-bucket lookup.
if errors.Is(err, filer_pb.ErrNotFound) {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
return
}
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
entry, err := s3a.resolveCopySourceEntry(srcBucket, srcObject, srcVersionId, srcVersioningState)
if err != nil || entry.IsDirectory {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
if errCode := classifyCopySourceError(entry, err); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
@@ -216,8 +249,8 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
routeInPlace := owner != "" && dstVersioningState == "" && !mimeChanged
selfCopyBody := func() s3err.ErrorCode {
currentEntry, currentErr := s3a.resolveCopySourceEntry(srcBucket, srcObject, srcVersionId, srcVersioningState)
if currentErr != nil || currentEntry.IsDirectory {
return s3err.ErrInvalidCopySource
if errCode := classifyCopySourceError(currentEntry, currentErr); errCode != s3err.ErrNone {
return errCode
}
if errCode := s3a.validateConditionalCopyHeaders(r, currentEntry); errCode != s3err.ErrNone {
return errCode
@@ -828,12 +861,22 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPart)
return
}
if partID < 1 {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPart)
return
}
// Get detailed versioning state for source bucket
srcVersioningState, err := s3a.getVersioningState(srcBucket)
if err != nil {
glog.Errorf("Error checking versioning state for source bucket %s: %v", srcBucket, err)
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
// Only a missing bucket is the client's fault; a store error must stay
// retryable, matching the destination-bucket lookup.
if errors.Is(err, filer_pb.ErrNotFound) {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
return
}
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
@@ -856,8 +899,8 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
entry, err = s3a.getEntry(dir, name)
}
if err != nil || entry.IsDirectory {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
if errCode := classifyCopySourceError(entry, err); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
+17 -4
View File
@@ -545,10 +545,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
s3a.deleteOrphanedChunks(chunkResult.FileChunks)
}
if strings.Contains(err.Error(), s3err.ErrMsgPayloadChecksumMismatch) {
return "", s3err.ErrInvalidDigest, SSEResponseMetadata{}
}
return "", s3err.ErrInternalError, SSEResponseMetadata{}
return "", mapChunkedUploadErrorToS3Error(err), SSEResponseMetadata{}
}
// Step 3: Calculate MD5 hash and add SSE metadata to chunks
@@ -1170,6 +1167,22 @@ func filerErrorToS3Error(err error) s3err.ErrorCode {
}
}
// mapChunkedUploadErrorToS3Error classifies a failed streaming upload. A truncated
// request body (client abort or reverse-proxy timeout) is a request error, so report
// IncompleteBody (400) rather than a 500 a reverse proxy would relay as a confusing
// 502. Only the source read is tagged, so a volume-server upload fault still maps to
// InternalError.
func mapChunkedUploadErrorToS3Error(err error) s3err.ErrorCode {
switch {
case strings.Contains(err.Error(), s3err.ErrMsgPayloadChecksumMismatch):
return s3err.ErrInvalidDigest
case errors.Is(err, operation.ErrTruncatedBody):
return s3err.ErrIncompleteBody
default:
return s3err.ErrInternalError
}
}
// setObjectOwnerFromRequest sets the object owner metadata based on the bucket ownership policy.
// When BucketOwnerEnforced (the modern AWS default), the bucket owner owns all objects.
// Otherwise, the uploader's account ID is used (ObjectWriter mode).
@@ -0,0 +1,51 @@
package s3api
import (
"errors"
"fmt"
"io"
"testing"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
func TestMapChunkedUploadErrorToS3Error(t *testing.T) {
tests := []struct {
name string
err error
want s3err.ErrorCode
}{
{
// A truncated body (client abort or reverse-proxy timeout) reaches
// putToFiler tagged exactly like UploadReaderInChunks reports it.
name: "truncated source read maps to IncompleteBody",
err: fmt.Errorf("%w: read chunk at offset %d (got %d bytes): %w", operation.ErrTruncatedBody, 0, 8056500, io.ErrUnexpectedEOF),
want: s3err.ErrIncompleteBody,
},
{
// A volume-server upload dropping mid-write is a server fault, not a
// client truncation, even though it also carries io.ErrUnexpectedEOF.
name: "volume upload unexpected EOF maps to InternalError",
err: fmt.Errorf("upload chunk: %w", io.ErrUnexpectedEOF),
want: s3err.ErrInternalError,
},
{
name: "payload checksum mismatch maps to InvalidDigest",
err: errors.New(s3err.ErrMsgPayloadChecksumMismatch),
want: s3err.ErrInvalidDigest,
},
{
name: "other errors map to InternalError",
err: errors.New("assign volume: no free volumes"),
want: s3err.ErrInternalError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := mapChunkedUploadErrorToS3Error(tt.err); got != tt.want {
t.Errorf("mapChunkedUploadErrorToS3Error(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}
+1 -1
View File
@@ -1849,7 +1849,7 @@ func (s3a *S3ApiServer) recoverLatestVersionWithoutPointer(bucket, normalizedObj
return nil, healErr
}
return nil, fmt.Errorf("no version metadata in .versions directory and no regular object found for %s/%s", bucket, normalizedObject)
return nil, fmt.Errorf("no version metadata in .versions directory and no regular object found for %s/%s: %w", bucket, normalizedObject, filer_pb.ErrNotFound)
}
// versionIdFromEntry returns a .versions child entry's version id, preferring
+1 -1
View File
@@ -277,7 +277,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
} else {
chunkCache = (*chunk_cache.TieredChunkCache)(nil)
}
readerCache := filer.NewReaderCache(s3ReaderCacheDownloaderLimit, chunkCache, filerClient.GetLookupFileIdFunction())
readerCache := filer.NewReaderCache(s3ReaderCacheDownloaderLimit, chunkCache, filerClient.GetLookupFileIdFunction(), filerClient)
s3ApiServer = &S3ApiServer{
option: option,
+8
View File
@@ -155,6 +155,9 @@ const (
ErrKeyTooLongError
ErrNoSuchConfiguration
// Truncated request body (fewer bytes than Content-Length)
ErrIncompleteBody
)
// Error message constants for checksum validation
@@ -297,6 +300,11 @@ var errorCodeResponse = map[ErrorCode]APIError{
Description: "We encountered an internal error, please try again.",
HTTPStatusCode: http.StatusInternalServerError,
},
ErrIncompleteBody: {
Code: "IncompleteBody",
Description: "You did not provide the number of bytes specified by the Content-Length HTTP header.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrInvalidPart: {
Code: "InvalidPart",
+25 -12
View File
@@ -173,19 +173,11 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry cleanupChunks %s %s: %v", req.Directory, req.Entry.Name, err2)
}
so, err := fs.detectStorageOption(ctx, string(util.NewFullPath(req.Directory, req.Entry.Name)), "", "", 0, "", "", "", "")
if err != nil {
return nil, err
}
newEntry := filer.FromPbEntry(req.Directory, req.Entry)
newEntry.Chunks = chunks
// Don't apply TTL to remote entries - they're managed by remote storage
if newEntry.Remote == nil {
if newEntry.TtlSec == 0 {
newEntry.TtlSec = so.TtlSeconds
}
} else {
newEntry.TtlSec = 0
so, err := fs.applyStorageDefaultsToEntry(ctx, newEntry)
if err != nil {
return nil, err
}
// Serialize concurrent mutations to the same path on this filer so the
@@ -361,6 +353,23 @@ func (fs *FilerServer) ObjectTransactionBatch(ctx context.Context, req *filer_pb
return resp, nil
}
// applyStorageDefaultsToEntry enforces the path's storage rule (read-only
// prefixes reject the write) and fills in the rule TTL when the entry carries
// none. Remote entries never expire locally; the remote storage owns their
// lifecycle.
func (fs *FilerServer) applyStorageDefaultsToEntry(ctx context.Context, entry *filer.Entry) (*operation.StorageOption, error) {
so, err := fs.detectStorageOption(ctx, string(entry.FullPath), "", "", 0, "", "", "", "")
if err != nil {
return nil, err
}
if entry.Remote != nil {
entry.TtlSec = 0
} else if entry.TtlSec == 0 {
entry.TtlSec = so.TtlSeconds
}
return so, nil
}
// applyObjectMutation applies a single mutation while the transaction's path
// lock is held. PUT entries are expected to be fully prepared by the caller
// (chunks resolved); mutations here are metadata-scoped. A DELETE of an absent
@@ -373,7 +382,11 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
return fmt.Errorf("PUT requires an entry")
}
newEntry := filer.FromPbEntry(m.Directory, m.Entry)
return fs.filer.CreateEntry(ctx, newEntry, nil, false, fromOtherCluster, signatures, false, fs.filer.MaxFilenameLength)
so, err := fs.applyStorageDefaultsToEntry(ctx, newEntry)
if err != nil {
return err
}
return fs.filer.CreateEntry(ctx, newEntry, nil, false, fromOtherCluster, signatures, false, so.MaxFileNameLength)
case filer_pb.ObjectMutation_DELETE:
fullpath := util.NewFullPath(m.Directory, m.Name)
@@ -0,0 +1,247 @@
package weed_server
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func mustSetObjectTxnStorageConf(t *testing.T, fs *FilerServer, conf *filer_pb.FilerConf_PathConf) {
t.Helper()
if err := fs.filer.FilerConf.SetLocationConf(conf); err != nil {
t.Fatalf("SetLocationConf(%q): %v", conf.LocationPrefix, err)
}
}
func TestObjectTransactionPutAppliesConfiguredTTLAndExpires(t *testing.T) {
fs, store := newTxnTestServer(nil)
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/video/",
Ttl: "1h",
})
old := time.Now().Add(-2 * time.Hour)
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/video/expired.mp4",
Mutations: []*filer_pb.ObjectMutation{
{
Type: filer_pb.ObjectMutation_PUT,
Directory: "/buckets/video",
Entry: &filer_pb.Entry{
Name: "expired.mp4",
Attributes: &filer_pb.FuseAttributes{
Crtime: old.Unix(),
Mtime: old.Unix(),
FileMode: 0644,
FileSize: 123,
TtlSec: 0,
},
},
},
},
})
if err != nil {
t.Fatalf("ObjectTransaction transport error: %v", err)
}
if resp.Error != "" {
t.Fatalf("ObjectTransaction response error: %q", resp.Error)
}
entry := store.entries["/buckets/video/expired.mp4"]
if entry == nil {
t.Fatalf("PUT should create /buckets/video/expired.mp4")
}
if got := entry.TtlSec; got != 3600 {
t.Fatalf("TtlSec = %d, want 3600 from fs.configure storage rule", got)
}
_, err = fs.filer.FindEntry(context.Background(), util.FullPath("/buckets/video/expired.mp4"))
if err != filer_pb.ErrNotFound {
t.Fatalf("expired entry lookup error = %v, want %v", err, filer_pb.ErrNotFound)
}
if _, ok := store.entries["/buckets/video/expired.mp4"]; ok {
t.Fatalf("expired entry should be deleted from metadata store")
}
}
func TestObjectTransactionPutPreservesExplicitTTL(t *testing.T) {
fs, store := newTxnTestServer(nil)
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/video/",
Ttl: "1h",
})
now := time.Unix(1700000000, 0)
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/video/lifecycle.mp4",
Mutations: []*filer_pb.ObjectMutation{
{
Type: filer_pb.ObjectMutation_PUT,
Directory: "/buckets/video",
Entry: &filer_pb.Entry{
Name: "lifecycle.mp4",
Attributes: &filer_pb.FuseAttributes{
Crtime: now.Unix(),
Mtime: now.Unix(),
FileMode: 0644,
FileSize: 123,
TtlSec: 7200,
},
},
},
},
})
if err != nil {
t.Fatalf("ObjectTransaction transport error: %v", err)
}
if resp.Error != "" {
t.Fatalf("ObjectTransaction response error: %q", resp.Error)
}
entry := store.entries["/buckets/video/lifecycle.mp4"]
if entry == nil {
t.Fatalf("PUT should create /buckets/video/lifecycle.mp4")
}
if got := entry.TtlSec; got != 7200 {
t.Fatalf("TtlSec = %d, want explicit TTL 7200 to win over fs.configure", got)
}
}
func TestObjectTransactionPutClearsTTLForRemoteEntry(t *testing.T) {
fs, store := newTxnTestServer(nil)
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/video/",
Ttl: "1h",
})
now := time.Unix(1700000000, 0)
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/video/remote",
Mutations: []*filer_pb.ObjectMutation{
{
Type: filer_pb.ObjectMutation_PUT,
Directory: "/buckets/video",
Entry: &filer_pb.Entry{
Name: "remote",
Attributes: &filer_pb.FuseAttributes{
Crtime: now.Unix(),
Mtime: now.Unix(),
FileMode: 0644,
FileSize: 123,
TtlSec: 7200,
},
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 123},
},
},
},
})
if err != nil {
t.Fatalf("ObjectTransaction transport error: %v", err)
}
if resp.Error != "" {
t.Fatalf("ObjectTransaction response error: %q", resp.Error)
}
entry := store.entries["/buckets/video/remote"]
if entry == nil {
t.Fatalf("remote entry should be created")
}
if got := entry.TtlSec; got != 0 {
t.Fatalf("remote entry TtlSec = %d, want 0", got)
}
}
func TestObjectTransactionPutHonorsMaxFileNameLengthRule(t *testing.T) {
fs, store := newTxnTestServer(nil)
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/video/",
MaxFileNameLength: 8,
})
now := time.Unix(1700000000, 0)
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/video/toolong.mp4",
Mutations: []*filer_pb.ObjectMutation{
{
Type: filer_pb.ObjectMutation_PUT,
Directory: "/buckets/video",
Entry: &filer_pb.Entry{
Name: "toolong.mp4",
Attributes: &filer_pb.FuseAttributes{
Crtime: now.Unix(),
Mtime: now.Unix(),
FileMode: 0644,
FileSize: 123,
},
},
},
},
})
if err != nil {
t.Fatalf("ObjectTransaction transport error: %v", err)
}
if resp.Error == "" {
t.Fatalf("ObjectTransaction should reject a name longer than the rule's max_file_name_length")
}
if _, ok := store.entries["/buckets/video/toolong.mp4"]; ok {
t.Fatalf("over-long name must not create the entry")
}
}
func TestObjectTransactionPutFailsOnReadOnlyStorageConfig(t *testing.T) {
// An explicit TTL must not bypass the read-only rule.
for _, ttlSec := range []int32{0, 7200} {
fs, store := newTxnTestServer(nil)
mustSetObjectTxnStorageConf(t, fs, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/video/",
ReadOnly: true,
})
now := time.Unix(1700000000, 0)
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/video/readonly.mp4",
Mutations: []*filer_pb.ObjectMutation{
{
Type: filer_pb.ObjectMutation_PUT,
Directory: "/buckets/video",
Entry: &filer_pb.Entry{
Name: "readonly.mp4",
Attributes: &filer_pb.FuseAttributes{
Crtime: now.Unix(),
Mtime: now.Unix(),
FileMode: 0644,
FileSize: 123,
TtlSec: ttlSec,
},
},
},
},
})
if err != nil {
t.Fatalf("TtlSec=%d: ObjectTransaction transport error: %v", ttlSec, err)
}
if resp.Error == "" {
t.Fatalf("TtlSec=%d: ObjectTransaction should report read-only storage config error", ttlSec)
}
if _, ok := store.entries["/buckets/video/readonly.mp4"]; ok {
t.Fatalf("TtlSec=%d: read-only storage config must not create the entry", ttlSec)
}
}
}
+12 -1
View File
@@ -254,5 +254,16 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
}
func (fs *FilerServer) maybeGetVolumeReadJwtAuthorizationToken(fileId string) string {
return string(security.GenJwtForVolumeServer(fs.volumeGuard.ReadSigningKey(), fs.volumeGuard.ReadExpiresAfterSec(), fileId))
// Generate a read JWT for volume server access. If the dedicated
// read key (jwt.signing.read.key) is not configured, fall back to the
// general signing key (jwt.signing.key) so the proxy can still
// authenticate to volume servers that require JWT.
key := fs.volumeGuard.ReadSigningKey()
if len(key) == 0 {
key = fs.volumeGuard.SigningKey()
}
if len(key) == 0 {
return ""
}
return string(security.GenJwtForVolumeServer(key, fs.volumeGuard.ReadExpiresAfterSec(), fileId))
}
+1
View File
@@ -172,6 +172,7 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
}
dn.AdjustMaxVolumeCounts(heartbeat.MaxVolumeCounts)
dn.AdjustDiskUsageBytes(heartbeat.DiskTotalBytes, heartbeat.DiskFreeBytes)
dn.UpdateDiskTags(heartbeat.DiskTags)
glog.V(4).Infof("master received heartbeat %s", heartbeat.String())
+8 -2
View File
@@ -93,6 +93,13 @@ func (vs *VolumeServer) ScrubVolume(ctx context.Context, req *volume_server_pb.S
}
func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb.ScrubEcVolumeRequest) (*volume_server_pb.ScrubEcVolumeResponse, error) {
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
return nil, err
}
if req.GetForceDeletedNeedlesCheck() && req.GetMode() != volume_server_pb.VolumeScrubMode_FULL {
return nil, fmt.Errorf("deleted needle checks are only supported for FULL scrubs")
}
vids := []needle.VolumeId{}
if len(req.GetVolumeIds()) == 0 {
for _, l := range vs.store.Locations {
@@ -124,8 +131,7 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
case volume_server_pb.VolumeScrubMode_LOCAL:
files, shardInfos, serrs = v.ScrubLocal()
case volume_server_pb.VolumeScrubMode_FULL:
// TODO: expose force_deleted_needles_check in the RPC and weed shell.
files, shardInfos, serrs = vs.store.ScrubEcVolume(v.VolumeId, false)
files, shardInfos, serrs = vs.store.ScrubEcVolume(v.VolumeId, req.GetForceDeletedNeedlesCheck())
case volume_server_pb.VolumeScrubMode_CHECKSUM:
// Verify each local shard's raw bytes against the bitrot sidecar,
// exercising cold parity shards. Read-only. ChecksumScrub's first
+1 -1
View File
@@ -137,7 +137,7 @@ func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) {
chunkCache: chunkCache,
signature: util.RandomInt32(),
}
t.readerCache = filer.NewReaderCache(32, chunkCache, filer.LookupFn(t))
t.readerCache = filer.NewReaderCache(32, chunkCache, filer.LookupFn(t), nil)
return t, nil
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more