Compare commits

..
45 Commits
Author SHA1 Message Date
github-actions[bot] 875cd1f67e 4.40 2026-07-20 03:57:03 +00:00
Chris Lu eb6d8ebd5f remove unused files 2026-07-18 23:11:07 -07:00
Chris Lu 07c9e0db85 iceberg maintenance: write absolute s3:// locations into table metadata (#10363)
The maintenance operations built manifest, manifest-list, data-file and
metadata-log paths with a bare path.Join("metadata", ...), so a single
maintenance run wrote scheme-less relative paths into the new snapshot,
the metadata-log and the table xattr. SeaweedFS reads those back fine
because normalizeIcebergPath accepts both forms, but strict readers
resolve every location through S3FileIO and fail with "Invalid S3 URI,
cannot determine scheme", leaving the whole table unreadable after any
maintenance commit.

Add absoluteIcebergPath, the inverse of normalizeIcebergPath, and apply
it at every site that authors locations: rewrite_manifests, compact,
rewrite_position_delete_files, and the shared commit path. The base is
derived from the bucket and table path since that is where the worker
physically writes, matching the locations the REST catalog generates.
2026-07-18 19:21:35 -07:00
Chris Lu d8196428e7 s3: invalid tagging on CopyObject returns InvalidTag, not InvalidCopySource (#10362) 2026-07-18 13:58:10 -07:00
Chris Lu efdfeaba44 cassandra: do not mask KvGet backend errors as not-found (#10361)
* cassandra: do not mask KvGet backend errors as not-found

* use errors.Is for the gocql sentinel check
2026-07-18 13:57:24 -07:00
Chris Lu 02df1cf428 shell: cluster.ps lists s3 servers (#10359)
* shell: cluster.ps lists s3 servers

* explicit returns in listClusterNodes helper
2026-07-18 13:56:47 -07:00
Chris Lu fba01ae2dd worker: balance pre-move check compares addresses in http form (#10360)
The pre-move stale check compared the master's location urls (host:port)
literally against the proposal's node addresses, which carry the grpc
suffix (host:port.grpcPort). Every move failed as "stale move: volume no
longer on source" even though the volume was still there. Normalize both
sides through pb.ServerAddress before comparing.
2026-07-18 13:52:34 -07:00
Chris Lu 564803becd shell: show who holds the cluster lock (#10353)
* regenerate master_grpc.pb.go with protoc-gen-go-grpc v1.6.2

The other generated pb files are already on v1.6.2; this one was stale.

* shell: keep unlock from racing the lease renewal

A renewal RPC in flight while ReleaseLock runs re-creates the lock on the
master after the release deletes it, and can blank the client name if the
renewal reads it mid-release. The stale-token release is then ignored, so
the lock stays held (sometimes anonymously) until it expires. Serialize
the renew and release RPCs, and set the client name before flipping
isLocked so the renewal never sends a partial acquisition.

* shell: restart lease renewal after a failed renewal

The renewal goroutine exits on error but never cleared its running flag,
so later locks in the same process were never renewed and silently
expired after ten seconds.

* shell: show who holds the cluster lock

A blocked lock command gave no hint that another client holds the lock
(the refusals only surfaced at -v=2), and cluster.status reported the
shell's own lock state as if it were the cluster's. Add a
GetAdminLockStatus RPC to the master so lock prints the holder before
blocking and cluster.status shows the actual cluster-wide holder. Both
degrade silently against masters without the RPC.

* shell: bound admin lock RPC attempts with timeouts

The lease, renew, release, and holder-status calls all ran without a
deadline, so an unresponsive master could hang the renewal goroutine,
an unlock (which now waits on the renewal mutex), or the shell prompt.
Give each attempt its own short context; the retry loops still resolve
a fresh leader on the next try.

* master: reject admin token release on non-leaders

A follower holds no lock state, so it answered a release with success
while the leader kept the lock until expiry. Refuse like LeaseAdminToken
does so the client can try the leader instead.

* shell: leave the lock release call unbounded

A release cut short by a deadline leaves the lock held on the master
until it expires, so a slow master would turn every unlock into a
ten-second ghost lock. Restore the single fire-and-forget attempt;
the timeouts stay on the lease and renew paths, where a stalled call
forfeits the lease anyway.

* shell: release only the token unlock started with

A RequestLock racing a slow release (the admin presence lock does this
on shutdown) could have its freshly acquired token sent in the release
request or zeroed by the trailing stores. Capture the token once under
the mutex and compare on clear so a concurrent acquisition survives an
in-flight unlock.
2026-07-17 12:30:42 -07:00
Chris Lu 6f14be1138 stats: remote-mount bucket cache hit/miss metrics (#10352)
Reads of remote-backed entries now record hit or miss in
SeaweedFS_remote_cache_read_total{source,bucket,result} on the filer HTTP
path and the S3 gateway, so cache effectiveness of mounted buckets can be
graphed. Inline-content entries count as hits since they are served
locally without chunks. The filer purges the per-bucket series when the
bucket directory is deleted, so a standalone filer does not accumulate
series across bucket delete/recreate churn.
2026-07-16 16:58:45 -07:00
Chris Lu 1f8d0a9ccf volume server: fill in ModifiedAtSecond on the /status volume list (#10351)
Only the heartbeat path read the .dat mtime; collectStatForOneVolume left
the field at 0, so /status consumers could not tell how long a volume had
been idle.
2026-07-16 15:18:38 -07:00
Chris Lu 267f595660 batch delete: align the shard test and Rust server with continue-past-mismatch (#10349)
Commit 8bff3b32 changed BatchDelete to keep processing after a cookie
mismatch but left the integration test asserting the old early-break
behavior, breaking Volume Server Integration Tests (grpc - Shard 1) on
master. Align the test with the new semantics and port the same
break->continue to the Rust volume server, which runs the same suite
via VOLUME_SERVER_IMPL=rust.
2026-07-16 13:55:52 -07:00
Chris Lu 1fda7aa7f1 master: assign re-picks once after its growth concludes instead of shedding (#10348)
The initiator's shed check (initiatedGrow != HasGrowRequest) compares
against an err from a PickForWrite that may predate the growth
concluding: the grower registers its volumes before clearing the flag,
so when growth lands between the failed pick and the check, the assign
shed ResourceExhausted even though a writable volume was already
registered. Re-pick once after observing the conclusion and shed only
if the volume layout still has nothing writable. Applies to both the
gRPC Assign and the HTTP dirAssign paths, which share the shed logic.

Flaked in CI as TestAssignInitiatorWaitsForItsOwnGrowth; reproduced
deterministically by widening the enqueue-to-check window.
2026-07-16 13:55:38 -07:00
8a71327324 fix: report short S3 ReaderAt reads (#10345)
* fix: report short S3 ReaderAt reads

Problem: S3BackendStorageFile.ReadAt returned a short buffer with a nil error, hiding truncated remote data.

Root cause: Every terminal io.EOF was cleared regardless of how many bytes were read.

Fix: Clear io.EOF only when the requested buffer was completely filled.

Validation: go test ./weed/storage/backend/...
Co-authored-by: Codex <noreply@openai.com>

* fix: validate S3 ReaderAt requests

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

* s3 ReadAt: simplify negative offset error

* s3 ReadAt: stop reading once the buffer is full

Skips the extra Read that only collected the terminal EOF, and bounds
the loop if the server ignores the Range header and returns more data
than requested, where Read on an empty slice can spin forever.

* s3 ReadAt: cover full reads that arrive with io.EOF

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-16 02:05:20 -07:00
8bff3b3213 fix(volume): reject overflowing needle ID deltas (#10342)
* fix: reject overflowing needle ID deltas

Problem: Parsing a file ID with a delta can wrap a valid maximum needle ID back to zero without returning an error.

Root cause: Needle.ParsePath added the parsed uint64 delta without checking whether the sum exceeded the needle ID range.

Fix: Compare the delta with the remaining uint64 capacity before addition and return a contextual overflow error when it does not fit.

Validation: go test ./weed/storage/needle -run ^TestNeedleParsePathRejectsDeltaOverflow$ -count=1; go test ./weed/storage/needle -count=1; git diff --check 10cdaf381875492a2c752d1038797e96ff18208f..HEAD
Co-authored-by: Codex <noreply@openai.com>

* fix: propagate needle ID delta parse errors

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

* print the needle id in hex in the delta overflow error

* batch delete: keep processing after a cookie mismatch

* rust volume: reject overflowing needle id deltas

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-15 23:24:04 -07:00
Chris Lu ae46e79e98 trigger dev container builds on seaweed-volume changes (#10344)
The dev container workflow prebuilds the Rust volume server from
seaweed-volume/ but did not watch that directory, so Rust build fixes
landed without this workflow validating them.
2026-07-15 23:22:13 -07:00
Chris Lu 7bfc44432d fix Rust build with protoc versions lacking native proto3 optional (#10343)
pass --experimental_allow_proto3_optional to protoc in the Rust build

filer.proto now carries a proto3 optional field, which the protoc 3.12
shipped in ubuntu-22.04 apt rejects unless this flag is set. Newer
protoc versions still accept the flag, so it is safe everywhere.
2026-07-15 22:52:17 -07:00
Chris Lu 5553e7b876 mount: surface ENOSPC instead of endless waiting when the cluster is full (#10341)
When every volume is full, a chunk upload fails only after the assign
retry budget, the failed chunk's data is dropped, and the mount kept
accepting writes anyway. cp would crawl for hours pushing the rest of
the file through a pipeline that could not persist it, and only close()
reported an error - a generic EIO.

Poison the file handle on the first failed chunk upload so subsequent
writes fail immediately, and map "no writable volumes" / "no free
volumes" upload errors to ENOSPC so the writing process aborts with
"No space left on device". Also guard lastErr with a mutex: it was
written concurrently by uploader goroutines, and keep the first error
so later failures do not mask the root cause.
2026-07-15 22:01:19 -07:00
Chris Lu 25ab4c3cac preserve Content-Encoding for remote-mounted objects (#10340)
* remote storage: carry Content-Encoding into mounted entries

A RemoteEntry now records the remote object's Content-Encoding, and every
path that materializes a local entry from remote metadata (lazy fetch, lazy
listing, remote.mount, remote.meta.sync, remote.cache) stamps it into the
entry extended attributes, so HTTP and S3 HeadObject/GetObject return the
header. GCS and Azure populate it on listing and stat; S3 only exposes it
via HeadObject, so listings leave it empty.

* remote storage: set Content-Encoding when uploading to the remote

An entry carrying Content-Encoding in its extended attributes (a native S3
upload, or a value pulled from the remote) now keeps it when
filer.remote.sync or remote.copy.local writes the object to GCS, S3, or
Azure, instead of silently dropping it.

* gcs: read remote objects without decompressive transcoding

GCS transparently decompresses gzip-encoded objects on download, which
ignores range requests and returns byte counts that disagree with the
tracked RemoteSize. Request the stored bytes instead; chunked reads of
gzip-encoded objects then behave like any other object.

* remote storage: track Content-Encoding presence so removals propagate

A listing that does not report encodings (S3) leaves the field unset and
the local header untouched, while an authoritative report of no encoding
(GCS, Azure, any stat) now clears a previously stamped header instead of
leaving it stale. remote.cache also schedules a metadata update when only
the reported encoding changes.

* remote storage: propagate Content-Encoding on metadata-only updates

filer.remote.sync routes same-content changes through UpdateFileMetadata,
which only touched custom metadata (GCS, Azure) or tags (S3), so a
Content-Encoding change in the extended attributes never reached the
remote object's real header. GCS now patches contentEncoding alongside
the metadata, and Azure reissues the blob's HTTP headers with the new
value, carrying the others over since the call replaces the full set.
S3 stays tags-only: changing the header there means rewriting the
object, which the sync already does whenever content changes.

* remote.meta.sync: optional per-file stat for listing-omitted metadata

S3 listings carry no Content-Encoding, so entries synced from them never
learn it and the lazy-stat path never runs once an entry exists. With
-statFiles, each new or changed file whose listing left the encoding
unreported is stat-ed before reconciling, and the stat-derived value is
persisted so the next run only stats files that changed. Off by default:
it costs one remote request per file, and GCS and Azure listings already
carry the encoding.

* s3: apply metadata-only Content-Encoding changes with an in-place copy

Content-Encoding is S3 system metadata, so the tags-only metadata update
silently left the object's real header untouched. When the encoding
differs, reissue the object as a self-copy with replaced metadata,
carrying the content type and configured storage class like a fresh
write does. CopyObject caps at 5 GiB; beyond that the change is logged
and applies on the next content write.

* azure: skip the metadata call when user metadata is unchanged

An encoding-only change reissues the blob's HTTP headers; sending the
unchanged user metadata alongside it wastes a round trip and bumps the
blob's ETag once more than needed.

* s3: carry existing object metadata through the encoding copy

The replace directive drops everything not resent, and a mounted entry
usually has no local mime or user metadata, so the in-place copy wiped
the object's Content-Type, Cache-Control, user metadata, encryption
settings, and storage class. Read them back with a HeadObject first and
carry them over, overriding only what SeaweedFS manages: the encoding,
a locally set mime, and the configured storage class. S3 reports
Expires as a string while the copy input wants a time, so it is parsed
and skipped when malformed.
2026-07-15 19:20:00 -07:00
Chris Lu c015cc3939 generate vtproto marshalers for filer_pb and use them on the metadata log path (#10337)
* generate vtproto marshalers for filer_pb and use them on the metadata log path

Reflection-based proto.Unmarshal allocates a fresh message tree through
reflect.New on every call. On the metadata subscription fan-out the same
event is decoded once per subscriber, so reflect.New tops the decode
churn under many mounts.

Generate MarshalVT/UnmarshalVT/SizeVT for filer.proto (a separate
filer_vtproto.pb.go, filer.pb.go untouched) and call them on the log
entry marshal and the subscribe/replay decode paths. UnmarshalVT
allocates message structs directly and copies byte and string fields, so
it stays wire-compatible with proto.Unmarshal and preserves the
non-aliasing the persisted-log cache depends on.

For SubscribeMetadataResponse this cuts decode allocations 69 -> 50 and
~4.5us -> ~2.1us per event; the win scales with subscriber overlap.

* marshal log entries directly into the buffer

SizeVT is allocation-free and MarshalToSizedBufferVT writes into a
pre-sized slice, so the log entry can be marshaled straight into
logBuffer.buf. This drops the per-entry MarshalVT allocation and the
follow-up copy on the write path.

* expand vtproto benchmarks: marshal, decode, and marshal-into-buffer by chunk count

Parametrize by nested-message count (chunks per event) and add encode +
zero-alloc marshal-into-buffer benchmarks alongside the decode one, so
the write-path win from MarshalToSizedBufferVT is measurable too.

* keep proto.Unmarshal for metadata events to preserve UTF-8 validation

UnmarshalVT skips proto3's UTF-8 validation of string fields, so a
SubscribeMetadataResponse with an invalid-UTF-8 string (e.g. Directory
"\xff") that proto.Unmarshal rejects would decode and reach path
filtering and subscribers. Decode events with proto.Unmarshal again;
UnmarshalVT stays on the log entry paths, whose only variable-length
fields are bytes and so carry no UTF-8 constraint.

Tests cover the codec difference and that a malformed event is skipped
before delivery.
2026-07-15 02:32:05 -07:00
Chris Lu 0ad83d5061 Fix object tagging writing back to the wrong object for nested keys (#10338)
Put/DeleteObjectTagging set the update directory to the bucket root for a
null version, so a tag change on allowed/protected.txt landed on
protected.txt at the bucket root instead. A principal scoped to one
nested key could overwrite a different object sharing the basename, the
same class of scope bypass fixed for PutObjectAcl. Share the object's
parent-directory resolver across both paths.
2026-07-15 02:31:51 -07:00
Chris Lu 8f29d0a91e route log buffer flush copies through the shared slab pool (#10336)
* route log buffer flush copies through the shared slab pool

Each flush copied the sealed window into a bytes.Buffer drawn from a
package-local sync.Pool. GC drains that pool, so once collections run
often (e.g. under GOMEMLIMIT) most flushes miss and Write grows a fresh
window-sized array, the dominant bytes.growSlice source under write load.

Copy into a size-classed slab from weed/util/mem instead. Slabs are
reused process-wide and returned to their exact size class after the
flush, so variable-sized flushes across many partitions stop churning
mismatched buffers.

* guard nil slab in flush releaseMemory

mem.Free(nil) resolves to the smallest slot pool and stores a zero-cap
slice, so a later mem.Allocate could return nil and panic. The current
call sites never pass nil, but the guard keeps a double release harmless.
2026-07-15 00:51:41 -07:00
Chris Lu 68e6fc5f7c fuse test: keep derived filer gRPC port below the ephemeral floor (#10334)
The FUSE harness picks the filer HTTP port and lets "weed mount" derive the
filer gRPC port as HTTP+10000. freePort kept the HTTP port under the Linux
ephemeral floor (32768) but not the derived gRPC port, which ranged up to
42000. When the gRPC port landed above the floor an outbound connection could
transiently hold it, so mini relocated its filer gRPC port while mount kept
dialing HTTP+10000, timing the mount out.

Cap the HTTP port at 22000 so the gRPC sibling stays at or below 32000, and
verify both ports are bindable before returning.
2026-07-14 12:46:54 -07:00
Chris Lu f3e4a73696 s3: return NoSuchKey/NoSuchBucket for a missing CopyObject source (#10332)
* s3: CopyObject returns NoSuchKey for a missing copy source

* s3: CopyObject returns NoSuchBucket for a missing source bucket
2026-07-14 11:53:53 -07:00
Chris Lu 311bc3a6df Fix PutObjectAcl writing back to the wrong object for nested keys (#10333)
* Fix PutObjectAcl writing back to the wrong object for nested keys

PutObjectAcl set the update directory to the bucket root, so an ACL
change on allowed/protected.txt landed on protected.txt at the bucket
root instead. A principal scoped to one nested key could overwrite a
different object sharing the basename. Target the object's own parent
directory.

* Test object ACL update directory resolution for nested keys
2026-07-14 11:46:37 -07:00
Chris Lu 10cdaf3818 Introduce weed shell command ec.check.replication. (#10328)
* Introduce weed shell command `ec.check.replication`.

This command performs a quick check of EC volume shard replication, reporting
volumes whose shards are over- or under-replicated. Each volume is checked
against its own data+parity ratio, obtained via
erasure_coding.EcShardsVolume{Data,Parity}Shards, so builds that derive the EC
ratio per volume report custom ratios correctly.

The name follows the shell's convention (cluster.check, volume.check.disk); the
closest normal-volume counterpart is volume.fix.replication.

* shell: ec.check.replication reports mixed under+over-replication in both lists
2026-07-13 17:18:42 -07:00
dependabot[bot] cd7c8ae784 build(deps): bump github.com/ydb-platform/ydb-go-sdk/v3 from 3.141.0 to 3.143.0 (#10322)
build(deps): bump github.com/ydb-platform/ydb-go-sdk/v3

Bumps [github.com/ydb-platform/ydb-go-sdk/v3](https://github.com/ydb-platform/ydb-go-sdk) from 3.141.0 to 3.143.0.
- [Release notes](https://github.com/ydb-platform/ydb-go-sdk/releases)
- [Changelog](https://github.com/ydb-platform/ydb-go-sdk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ydb-platform/ydb-go-sdk/compare/v3.141.0...v3.143.0)

---
updated-dependencies:
- dependency-name: github.com/ydb-platform/ydb-go-sdk/v3
  dependency-version: 3.143.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-13 11:45:03 -07:00
dependabot[bot] a7073a9778 build(deps): bump golang.org/x/crypto from 0.53.0 to 0.54.0 (#10323)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.53.0 to 0.54.0.
- [Commits](https://github.com/golang/crypto/compare/v0.53.0...v0.54.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.54.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-13 11:44:56 -07:00
dependabot[bot] 0dc504733e build(deps): bump github.com/schollz/progressbar/v3 from 3.19.0 to 3.19.1 (#10324)
build(deps): bump github.com/schollz/progressbar/v3

Bumps [github.com/schollz/progressbar/v3](https://github.com/schollz/progressbar) from 3.19.0 to 3.19.1.
- [Release notes](https://github.com/schollz/progressbar/releases)
- [Commits](https://github.com/schollz/progressbar/compare/v3.19.0...v3.19.1)

---
updated-dependencies:
- dependency-name: github.com/schollz/progressbar/v3
  dependency-version: 3.19.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-13 11:44:46 -07:00
dependabot[bot] 9964d5b82a build(deps): bump github.com/aws/aws-sdk-go-v2/credentials from 1.19.26 to 1.19.28 (#10325)
build(deps): bump github.com/aws/aws-sdk-go-v2/credentials

Bumps [github.com/aws/aws-sdk-go-v2/credentials](https://github.com/aws/aws-sdk-go-v2) from 1.19.26 to 1.19.28.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/credentials/v1.19.26...credentials/v1.19.28)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-13 11:44:37 -07:00
dependabot[bot] 7b2bee9890 build(deps): bump github.com/cognusion/imaging from 1.0.3 to 1.0.4 (#10326)
Bumps [github.com/cognusion/imaging](https://github.com/cognusion/imaging) from 1.0.3 to 1.0.4.
- [Commits](https://github.com/cognusion/imaging/compare/v1.0.3...v1.0.4)

---
updated-dependencies:
- dependency-name: github.com/cognusion/imaging
  dependency-version: 1.0.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-13 11:44:28 -07:00
Chris Lu bd9b5c25ff rust volume: verify the .dat ends at the last indexed needle (#10320)
* rust volume: verify the .dat ends at the last indexed needle

The Go loader quarantines a volume whose .dat extends past the last
indexed needle - the leftover of a torn shutdown - but the Rust check
only verified header fields of the trailing index entries and never
compared file sizes, so a torn tail loaded clean and writable. Appends
land at the raw file end, and past a misaligned tail the next needle
sits at an offset the 8-byte-unit .idx encoding rounds down, pointing
the index a few bytes before the needle.

Replace the last-10-entries walk with the current Go shape: find the
entry physically last in the .dat (append-ordered fast path, max-offset
scan for key-sorted rebuilds), verify that needle - tombstones with
their on-disk Size=0 - and require the file to end exactly at it,
marking the volume read-only otherwise.

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

* rust volume: buffer the .idx max-offset scan

The slow path read one 16-byte entry per syscall; a BufReader batches
the sequential scan like Go's WalkIndexFile does.

Claude-Session: https://claude.ai/code/session_01XgGXMLknzaNgQzHMyo2Vhb
2026-07-12 19:37:58 -07:00
Chris Lu 19dc085e33 master: statistics used size covers all collections and layouts (#10319)
StatFs on a mount reported cluster-wide total capacity but used size from
a single volume layout keyed by collection, replication, ttl, and disk
type. A mount without -collection therefore showed only the default
collection's usage, hiding data in named collections, and even a
collection-scoped mount missed volumes with a different replication,
ttl, or disk type.

Aggregate used size and file count across all layouts of the requested
collection, and across every collection when the collection is empty,
matching how Topology.Lookup treats an empty collection. Looking up
stats no longer creates a phantom collection as a side effect.
2026-07-12 12:56:10 -07:00
Chris Lu 013281b498 shell: volume.check.disk -resurrectMissingNeedles for never-vacuumed replicas (#10316)
An absent needle is normally indistinguishable from a vacuumed delete,
so check.disk skips it and replicas diverged by replication failures
cannot be reunited. But a replica with compaction revision 0 has never
been vacuumed: every delete it processed still holds its tombstone, so
a needle absent there is provably a missing write.

The new flag resurrects absent needles in exactly that case. The
receiving replica's live compaction revision is read after the index
snapshot and must be 0; vacuumed replicas keep the skip, now with the
revision in the message. The decision is passed per direction since
pass 2 runs pairs concurrently. Resurrected needles count toward
-nonRepairThreshold as before.
2026-07-12 00:14:16 -07:00
Chris Lu fa549e9c83 filer: harden TUS session authorization against cross-prefix access (#10315)
* filer: authorize TUS existing-session verbs against the validated stored target

Scope-check on TUS HEAD/PATCH/DELETE only populated a resource path for POST,
so a prefix-restricted token that learned another tenant's session id could act
on that session and land content at a TargetPath its own AllowedPrefixes forbid.

Split the filer JWT check into authenticateFilerJwt (signature and method) and
authorizeFilerJwtPaths (resource scope), and make the scope check fail closed:
a prefix-restricted token with no resolved resource path is denied instead of
authorized on signature alone. The TUS handler now authenticates first, reads
and validates the session once, authorizes the stored TargetPath, then operates
on that single pinned snapshot. readTusSessionInfo rejects a session whose id,
target or size is unusable, and getTusSession is split so the authorization
lookup no longer lists chunks.

* filer: reject non-canonical TUS upload ids

The uploads route took the first path component as the session id, so a trailing
path or other non-canonical spelling aliased one session under several URLs.
Require the id to be a canonical UUID, the only form the server mints, both at
routing and when reading a session's metadata, so one URL maps to one resource.

* filer: revalidate the pinned TUS session before completing an upload

Completion re-read chunks but not the session identity, so a PATCH finishing
after a concurrent DELETE or metadata replacement could still land at the id's
stored path. Before completing, confirm the session still exists and its target,
size and creation time are unchanged from the authorized snapshot; otherwise the
completion fails instead of writing to a path the request never authorized.

* filer: log TUS session lookup failures before returning not-found

readTusSessionInfo and loadTusSessionChunks failures answered "not found" with
no log line, so a transient filer or listing error was indistinguishable from a
genuinely missing session. Log the lookup at V(1) (a missing session is common
and benign) and the chunk-load error at Errorf (the session already resolved).
2026-07-11 22:45:28 -07:00
Chris Lu c1a1e3c1e3 shell: volume.tier.upload keeps volume replicas (#10314)
* volume: copying a remote-backed volume only needs space for the index

VolumeCopy sized its target-location check by the source .dat even when
that .dat lives in a cloud tier and only .idx/.vif land locally, so
re-replicating a tiered volume demanded the full remote size in free
disk. Require the index size instead.

* shell: volume.tier.upload keeps volume replicas

Tiering a replicated volume deleted every replica but the upload
source, leaving one server holding the only .idx and the only .vif
that knows the remote object key — losing that server orphaned the
volume even though its data sat intact in the cloud.

Replicate the uploaded .idx/.vif onto the other replica servers
instead (VolumeCopy skips the .dat for remote-backed volumes), so all
replicas serve reads from the same remote object and the volume keeps
its replica count. An already-tiered replica is preferred as the
upload source, so a rerun after a partial failure reuses the existing
remote object instead of uploading a second copy under a new key.

* shell: group tier upload locations instead of re-prepending

* rust volume: copying a remote-backed volume only needs space for the index

Mirror the Go VolumeCopy change: size the free-location check by the
source .idx when the .dat lives in a cloud tier, since only .idx/.vif
land locally.
2026-07-11 13:49:36 -07:00
Chris Lu 40ee4a08c5 admin: show bucket lifecycle rules in the Admin UI (#10313)
* admin: surface lifecycle rule counts in bucket listing

* admin: add bucket lifecycle JSON endpoint

* admin: show lifecycle rules on the buckets page

* admin: make the lifecycle count badge keyboard-accessible

* admin: match buckets empty-state colspan to the column count

* admin: drop stale lifecycle modal responses

* make
2026-07-11 11:31:30 -07:00
Chris Lu 29981f8d24 sftp: match permission paths on path-component boundaries (#10311)
* sftp: match permission paths on path-component boundaries

Permission checks compared paths with raw string prefixes, so a
permission entry for /tenants/alice also matched sibling paths such as
/tenants/alice-archive, letting a scoped user read and overwrite
another tenant's files. The home directory containment check had the
same flaw. Route both through pathWithin, which cleans the paths and
requires exact equality or a separator-delimited descendant.

* sftp: clean permission path into a local when ranking matches
2026-07-10 22:10:01 -07:00
Chris Lu e7be6bb2f8 filer: allow clearing a bucket read-only flag stuck after quota removal (#10310)
* filer: allow clearing a bucket read-only flag stuck after quota removal

Once s3.bucket.quota.enforce marks a bucket read-only, removing or
disabling the quota orphans the flag: enforcement skips buckets with a
non-positive quota, and fs.configure merges booleans with OR so
-readOnly=false could never turn it off. The only way out was deleting
the whole path rule.

- s3.bucket.quota -op=remove/disable and the admin server quota update
  now lift the read-only flag on the bucket's path rule
- fs.configure now honors explicitly passed false boolean flags
  (-readOnly, -fsync, -worm) instead of OR-merging them away

* filer: ClearBucketReadOnly reports unchanged when the save fails
2026-07-10 22:09:39 -07:00
Eliah RusinandChris Lu c006dc563e ec: remove .ecsum sidecars on destroy / shard delete; align Go and Rust cleanup (#10307)
* fix(rust-volume): remove .ecsum sidecars on EC destroy / shard delete

Rust EcVolume::destroy removed shards and .ecx/.ecj/.vif but left bitrot
checksum sidecars (.ecsum / .ecsum.v*). On clusters that run weed-volume
(not Go weed volume), collection.delete therefore orphans every sidecar
while correctly wiping shards — observed live on 4.39 (14/14 .ecsum
survived after collection.delete on a freshly encoded EC volume).

Go Destroy already calls RemoveBitrotSidecars; this brings Rust to parity:
- hoist remove_bitrot_sidecars into ec_bitrot (shared helper)
- call it from EcVolume::destroy for dir / dir_idx / ecx_actual_dir
- call it from Store::delete_ec_shards when a disk has no remaining shards
- unit test: test_destroy_removes_bitrot_sidecar

* rust volume: gate the shard-delete sidecar sweep on a local shard removal

Only sweep a disk's .ecsum when this delete actually removed a shard file
there, matching Go's found gate: a delete that never touched a disk must not
strip a sidecar it does not own — a shared -dir.idx sibling with surviving
shards, or an ec.rebuild index-prep copy that lands .ecx/.ecsum before any
shard. The shard-presence probe now treats unexpected stat errors as
"exists" so a transient failure cannot orphan-classify live shards, and
check_all_ec_shards_deleted reuses it.

* rust volume: destroy() sidecar sweep needs only the data and idx bases

ecx_actual_dir is always one of the two, so the third branch could never
run; this is now exactly Go Destroy()'s two-base sweep.

* rust volume: call the shared sidecar removal helper directly

* rust volume: unit-test remove_bitrot_sidecars

Mirrors Go's TestRemoveBitrotSidecars: legacy and versioned sidecars are
removed, a shard file and a longer-vid sidecar survive, absent is success.

* rust volume: keep the shared idx-base sidecar while a sibling disk has shards

One -dir.idx serves every location, so emptying one disk must not sweep
<idx>/<vol>.ecsum out from under a sibling that still holds shards. Nothing
reads the idx-base sidecar today, but .ecx shows index-dir files are real;
this keeps the defensive sweep safe if a writer ever lands one there.

* ec shard delete: keep the shared idx-base sidecar while a sibling disk has shards

One -dir.idx serves every disk, so emptying one disk must not sweep
<idx>/<vol>.ecsum out from under a sibling that still holds shards of the
volume — the same gate the Rust volume server applies. A status error counts
as in-use so a transient failure never strips it early.

* rust volume: drop a shard-only disk's stale .vif with the node's last shard

Go's removeEcSharedIndexFiles also clears the data-base .vif in the
all-shards-gone pass, gated on .idx absence so a disk still hosting the
source volume keeps its live .vif; the Rust delete path left it behind.
Unexpected stat errors count as .idx-present so a transient failure never
strips a live volume's .vif.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-10 22:06:36 -07:00
Chris Lu ce82e3a057 filer: scope TUS HEAD/PATCH/DELETE against the session target path (#10309)
* filer: scope TUS HEAD/PATCH/DELETE against the session target path

checkTusJwtAuthorization only populated the scoped-path list for POST, so
a prefix-restricted token was scope-checked at session creation but not on
HEAD/PATCH/DELETE, which act on an existing session addressed by id. A
low-privilege tenant holding a valid write token who learns another
upload's session id could PATCH attacker bytes into that session, or
DELETE/HEAD it, landing content at a target path its own AllowedPrefixes
forbids. The session id is unguessable to an unauthenticated attacker but
is not an authorization boundary against a legitimate tenant.

Resolve the effective target for HEAD/PATCH/DELETE from the session's
stored TargetPath and scope the prefix check against it, the same way POST
scopes the create target. The scoped paths are resolved lazily so the
session read runs only for a prefix-restricted token; unrestricted tokens
and deployments without a signing key touch no extra state. An unknown
session stays unscoped so the handler still answers 404.

* filer: fail closed when a TUS session target cannot be resolved

The lazy scope resolver swallowed every readTusSessionInfo error and left
the request unscoped, so a filer read error or a corrupt session .info
would authorize a prefix-restricted token against a target the server
never resolved. Only a genuinely missing session should stay unscoped (so
the handler answers 404); any other failure now propagates and denies the
request. checkJwtAuthorizationScoped's resolver returns an error and a
failed resolution is treated as not-authorized.

* filer: fold the scoped-path resolver into checkJwtAuthorization

checkJwtAuthorization now takes the lazy resolver directly instead of a
separate checkJwtAuthorizationScoped wrapper, and the surrounding comments
are trimmed to the load-bearing why.
2026-07-10 20:33:01 -07:00
Chris Lu 298ab35fd7 shell: default batch size for ec.encode and ec.decode (#10308)
* shell: ec.encode batches 10 volumes by default

Encoding a whole collection as one batch means a late failure leaves
everything half-converted. Default -batchSize to 10 so each batch is
encoded, rebalanced, verified, and its originals deleted before the
next starts. -batchSize=0 keeps the all-at-once behavior. Batch
progress messages now print only when there is more than one batch,
so small runs read as before.

* shell: ec.decode decodes in batches, refreshing topology in between

ec.decode walked every volume off the single topology snapshot taken
at startup, which goes stale as earlier decodes move shards around and
create volumes. Decode 10 volumes per batch by default, re-collecting
the topology and rebuilding the free-space accounting between batches.
-batchSize=0 keeps the single-snapshot behavior.
2026-07-10 16:44:46 -07:00
Chris Lu 5c511c4894 ec.encode: don't rebalance against a topology that predates the new shards (#10303)
Mounting freshly generated shards notifies the master asynchronously, while the post-encode rebalance plans from a fresh VolumeList snapshot; a snapshot that predates the delta shows zero shards, so the balance plans no moves and silently succeeds, and the original .dat is deleted with all shards on the generation host. Poll until every encoded volume reports a full shard set before balancing — across all disk types, since fresh shards register under the source volume's disk type, and scoped to the newest encode generation so an orphaned older generation neither satisfies the wait nor defeats the clump check. As defense in depth, refuse to delete originals when a volume's shards still sit on one node while another node has free EC slots.
2026-07-10 12:41:16 -07:00
Chris Lu 76ec1d8f0f s3: accept raw semicolons in query strings (#10305)
* s3: accept raw semicolons in query strings

Go's url.ParseQuery drops any key=value pair containing a raw ';'. A
presigned PUT that signs content-type carries
X-Amz-SignedHeaders=content-type%3Bhost; when a client or proxy decodes
the %3B, the parameter vanished and the upload failed with
MissingFields, while AWS accepts the raw ';' as query data. Re-encode
it before routing so the pair survives parsing and signature
verification.

* iam, iceberg: recover raw-semicolon query pairs on the other listeners

The standalone IAM API verifies SigV4 with a canonical query recomputed
from the parsed query, and Iceberg REST warehouse/parent values may
legally contain ';'. Move the normalization middleware to util/http and
attach it to both routers.
2026-07-10 12:17:35 -07:00
Chris Lu ac524e140a s3: enforce role trust policy on direct OIDC bearer authentication (#10302)
A raw OIDC token sent as Authorization: Bearer was validated and mapped
to a role through the provider's roleMapping, then authorized against
the role's attached policies without ever consulting the role's trust
policy. A federated user could act as a role that
AssumeRoleWithWebIdentity would refuse to issue a session for with the
same token. Run the same trust-policy validation before returning the
principal on the bearer path.
2026-07-10 12:14:18 -07:00
Jaehoon KimandClaude Fable 5 c17aebeecf fix(filer.backup): prevent silent backup data loss on transient not-found (#10295)
* fix(filer.backup): stop silently dropping events on transient not-found

Under a write burst, filer.backup could consume a metadata event (advancing
the persisted offset) without replicating the file, with no error logged:

1. filersink CreateEntry/UpdateEntry swallowed replicateChunks errors
   (glog.Warningf + return nil), so the offset advanced past entries that
   were never written.
2. The manifest-chunk branch of replicateChunks resolved via LookupFileId
   with no retry, unlike the data-chunk branch — transient lookup races
   dropped exactly the large manifest-backed files while small
   inline-content siblings landed.
3. isIgnorable404 matched "LookupFileId" / "volume id ... not found",
   misclassifying those races as genuine source 404s at the backup layer.

Fix: on a replicateChunks failure the filer sink now skips only when the
live source has moved past the replayed version (deleted or strictly-newer
mtime) — lossless, a later event carries the current content — and
propagates otherwise so the event is retried. The manifest resolve retries
transient errors like the data-chunk path. isIgnorable404 is narrowed to
genuine 404s; non-filer sinks and the initial-snapshot walk, which relied
on the broad match as their only lossless-skip valve, now make the same
live-source decision (filersink.SourceSupersedes) instead of retrying
forever on a permanently gone volume.

Tests cover propagation of unconfirmed lookup failures, the narrowed 404
classification, and the supersession guards.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(filer.backup): derive supersession path with directory fallback

eventSourceSuperseded built the source path from NewParentPath alone.
Legacy metadata events (persisted by older filers) carry an empty
NewParentPath, so the probe looked up "/<name>", read the miss as
"source gone", and skipped a live file on a transient lookup error —
the silent drop this change is meant to eliminate.

Derive the path via MetadataEventTargetFullPath (the same directory
fallback genProcessFunction uses) and cover both event shapes with
TestEventSupersessionProbe_PathDerivation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(filersink): retry manifest resolve only for transient errors, bounded when unverifiable

The manifest-resolve retry stopped only when hasSourceNewerVersion proved
the source moved past the replayed version, which wedged the sink in two
cases: incremental sinks use dated target keys that cannot map back to a
source path (supersession never provable), and permanent resolve errors
(corrupt manifest data, bad file ids) fail forever while the source entry
stays live.

Gate the retry instead: keep retrying only transient errors (volume-lookup
races, network interruptions), stop after a few attempts when supersession
cannot be checked, and propagate everything else immediately so the
configured metadata error policy applies (-disableErrorRetry included).
Propagation is lossless: filer.backup's fallback decides with the event's
real source key, and both filer.backup and filer.sync re-deliver the event
(RetryForeverOnError) without advancing the offset.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(filer.backup): make error classifiers nil-safe

isIgnorable404, isSourceLookupError, and isTransientResolveError called
err.Error() without a nil guard. All current call sites pass a non-nil
error, but the guard is free and matches isRetryableNetworkError.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 01:47:46 -07:00
144 changed files with 30215 additions and 1114 deletions

No files matched your search

+1
View File
@@ -5,6 +5,7 @@ on:
branches: [ master ]
paths:
- 'weed/**'
- 'seaweed-volume/**'
- 'docker/**'
- 'go.mod'
- 'go.sum'
+17 -17
View File
@@ -50,7 +50,7 @@ require (
github.com/kurin/blazer v0.5.3
github.com/linxGnu/grocksdb v1.10.8
github.com/mailru/easyjson v0.9.1 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/olivere/elastic/v7 v7.0.32
@@ -91,14 +91,14 @@ require (
gocloud.dev v0.46.0
gocloud.dev/pubsub/natspubsub v0.46.0
gocloud.dev/pubsub/rabbitpubsub v0.46.0
golang.org/x/crypto v0.53.0
golang.org/x/crypto v0.54.0
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
golang.org/x/image v0.43.0
golang.org/x/net v0.56.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sys v0.46.0
golang.org/x/text v0.38.0 // indirect
golang.org/x/tools v0.45.0 // indirect
golang.org/x/sys v0.47.0
golang.org/x/text v0.40.0 // indirect
golang.org/x/tools v0.47.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.287.0
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
@@ -125,9 +125,9 @@ require (
github.com/armon/go-metrics v0.4.1
github.com/aws/aws-sdk-go-v2 v1.42.1
github.com/aws/aws-sdk-go-v2/config v1.32.25
github.com/aws/aws-sdk-go-v2/credentials v1.19.26
github.com/aws/aws-sdk-go-v2/credentials v1.19.28
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2
github.com/cognusion/imaging v1.0.3
github.com/cognusion/imaging v1.0.4
github.com/fluent/fluent-logger-golang v1.10.1
github.com/getsentry/sentry-go v0.44.1
github.com/go-ldap/ldap/v3 v3.4.13
@@ -147,7 +147,7 @@ require (
github.com/rclone/rclone v1.74.3
github.com/rdleal/intervalst v1.5.0
github.com/redis/go-redis/v9 v9.21.0
github.com/schollz/progressbar/v3 v3.19.0
github.com/schollz/progressbar/v3 v3.19.1
github.com/seaweedfs/go-fuse/v2 v2.9.3
github.com/shirou/gopsutil/v4 v4.26.5
github.com/tarantool/go-tarantool/v2 v2.4.2
@@ -155,10 +155,10 @@ require (
github.com/tikv/client-go/v2 v2.0.7
github.com/xeipuuv/gojsonschema v1.2.0
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2
github.com/ydb-platform/ydb-go-sdk/v3 v3.141.0
github.com/ydb-platform/ydb-go-sdk/v3 v3.143.0
go.etcd.io/etcd/client/pkg/v3 v3.6.12
go.uber.org/atomic v1.11.0
golang.org/x/sync v0.21.0
golang.org/x/sync v0.22.0
golang.org/x/tools/godoc v0.1.0-deprecated
google.golang.org/grpc/security/advancedtls v1.0.0
)
@@ -181,7 +181,7 @@ require (
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/arrow-go/v18 v18.6.0 // indirect
github.com/apache/thrift v0.23.0 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.2.2 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.4.0 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/bazelbuild/rules_go v0.46.0 // indirect
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
@@ -280,7 +280,7 @@ require (
go.uber.org/mock v0.5.2 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.36.0 // indirect
golang.org/x/mod v0.37.0 // indirect
gonum.org/v1/gonum v0.17.0 // indirect
)
@@ -330,9 +330,9 @@ require (
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.31.5 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.8 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.43.5
github.com/aws/aws-sdk-go-v2/service/sso v1.32.0 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.44.0
github.com/aws/smithy-go v1.27.3
github.com/boltdb/bolt v1.3.1 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
@@ -442,7 +442,7 @@ require (
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/xattr v0.4.12 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
github.com/relvacode/iso8601 v1.7.0 // indirect
@@ -492,7 +492,7 @@ require (
go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect
golang.org/x/term v0.44.0
golang.org/x/term v0.45.0
golang.org/x/time v0.15.0
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d // indirect
+32 -32
View File
@@ -715,8 +715,8 @@ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24g
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
github.com/aws/aws-sdk-go-v2/config v1.32.25 h1:ACCejvStYoilgwrfegSt5ZntCbPrk52qfwyNcnl3omM=
github.com/aws/aws-sdk-go-v2/config v1.32.25/go.mod h1:LJyU8sDRbXUxFn8xMJIGP+v9QYYwveNLI8a/giAOiAs=
github.com/aws/aws-sdk-go-v2/credentials v1.19.26 h1:Si8kk1kyJnuJWCEgiwpBtTdtgSdR7i611596NnC0YIQ=
github.com/aws/aws-sdk-go-v2/credentials v1.19.26/go.mod h1:lBckz+W9SAdNtSDw3pYgQUJDJFcBBWry0GSzw+bK0TY=
github.com/aws/aws-sdk-go-v2/credentials v1.19.28 h1:zTXJSsNcoO91/mTXsZoYf0AK8dvNPiA58/VtyGXR+wM=
github.com/aws/aws-sdk-go-v2/credentials v1.19.28/go.mod h1:Kd9E0JzDBW/q1xbsHFrev/GnbAf5J0Ng8xoyc7HZ91Q=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 h1:/hi1JADLEW9YYryEz1w4GQu0EtP23pP553Cf9KgsDV4=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30/go.mod h1:/3AOgy4K17Dm4ucMZVC/MJkzy5kmfKUcINRHZyo0koQ=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 h1:uMC4oL6G3MNhodo358QEqSDjrgvzV3TUQ58nyQSGq2E=
@@ -739,18 +739,18 @@ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDb
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
github.com/aws/aws-sdk-go-v2/service/signin v1.2.2 h1:69JEZSDTQ+UNbTWQJCZMmbpQb5sfc79KUt0O7Pyfjmo=
github.com/aws/aws-sdk-go-v2/service/signin v1.2.2/go.mod h1:mxC0nT/C8wMMS97DemZPzvUZxvIt+2Iq+eS3JdFZGgg=
github.com/aws/aws-sdk-go-v2/service/signin v1.4.0 h1:sLzmJGCMv+C8KqiJgEqDLB6vxaJGmobRh4rr//ZpA3w=
github.com/aws/aws-sdk-go-v2/service/signin v1.4.0/go.mod h1:mxC0nT/C8wMMS97DemZPzvUZxvIt+2Iq+eS3JdFZGgg=
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 h1:p8WdWDh5AwSZdp19Haa3XMyPCICi9Z375a/Nu3IIEZY=
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14/go.mod h1:NKVY7DER6VXHkt2I/ycmHakALNboi3Rqwt4eEf/1Cnk=
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 h1:JP2wjWGmUp8lTCZb13Dv0Eciyc1jbO8pd0HZVMHFlrc=
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24/go.mod h1:Ql9ziDutk8ERAN9HMaYANCW3lop451ppebkxEJMLCTM=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.5 h1:xlK3Tdc8FO7Tq1k0+hL+otF33glj+dE+qeM5iINiDvU=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.5/go.mod h1:u8af9Nqkmqnr96f7v9nHqzZT9XBwbXEkTiqT4ROuJSE=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.8 h1:yX1IbiBfC7SdEgDwIGnRaZyPPDRbQPDOJxl8102PcGk=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.8/go.mod h1:DMPWJBjYs6+3+f/qhBFEFPPlQ6NlhWjai3dJNvipJ84=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.5 h1:T3ANO8QWDbzQD8f4+UaX+fvJlyGnOFMKLbW+NGBHg04=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.5/go.mod h1:9gdl4RrflIdpDb2TlXshWgR1F9TeCkvqDx77Vpr4Z/Q=
github.com/aws/aws-sdk-go-v2/service/sso v1.32.0 h1:qjMmry/cBDee1E/2gyvel0uRYCi3mwRZ2hf6N+GAodo=
github.com/aws/aws-sdk-go-v2/service/sso v1.32.0/go.mod h1:u8af9Nqkmqnr96f7v9nHqzZT9XBwbXEkTiqT4ROuJSE=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0 h1:fpOlDPI55HdszaxapEGk6HsGosOUaM2YPWJpjMgp8UI=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0/go.mod h1:DMPWJBjYs6+3+f/qhBFEFPPlQ6NlhWjai3dJNvipJ84=
github.com/aws/aws-sdk-go-v2/service/sts v1.44.0 h1:bLZ0PolJ8J+HkJHztcXORUpHXBye2U8298lCEMi6ZCU=
github.com/aws/aws-sdk-go-v2/service/sts v1.44.0/go.mod h1:9gdl4RrflIdpDb2TlXshWgR1F9TeCkvqDx77Vpr4Z/Q=
github.com/aws/smithy-go v1.27.3 h1:F3Zb497UhhskkfpJmfkXswyo+t0sh9OTBnIHjogWbVY=
github.com/aws/smithy-go v1.27.3/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
@@ -860,8 +860,8 @@ github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwP
github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg=
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2 h1:8Vfw2iNEpYIV6aLtMwT5UOGuPmp9MKlEKWKFTuB+MPU=
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2/go.mod h1:P9WiZOdQ1R/ZZDL0WzF5wlyRvrjtfhNOwMZymFpBwjE=
github.com/cognusion/imaging v1.0.3 h1:nHyIeEVDV8JkBbuhgx8iSBW72W8rHbDEyruA0Jh7Lnk=
github.com/cognusion/imaging v1.0.3/go.mod h1:38tFLFhGK81ORThZG8dVXPtp1uhd+3xM1WXuMn+unOA=
github.com/cognusion/imaging v1.0.4 h1:hrmWVa4S9fiLJJFKEHYYRNBUnHEKZD8/oxnC77xTUa0=
github.com/cognusion/imaging v1.0.4/go.mod h1:X1mPSSZpMyiva54chCO/1NROp+b6xG4uMcud8VLii+U=
github.com/colinmarc/hdfs/v2 v2.4.0 h1:v6R8oBx/Wu9fHpdPoJJjpGSUxo8NhHIwrwsfhFvU9W0=
github.com/colinmarc/hdfs/v2 v2.4.0/go.mod h1:0NAO+/3knbMx6+5pCv+Hcbaz4xn/Zzbn9+WIib2rKVI=
github.com/compose-spec/compose-go/v2 v2.10.2 h1:USa1NUbDcl/cjb8T9iwnuFsnO79H+2ho2L5SjFKz3uI=
@@ -1516,8 +1516,8 @@ github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stg
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.22 h1:76lXsPn6FyHtTY+jt2fTTvsMUCZq1k0qwRsAMuxzKAk=
@@ -1804,8 +1804,8 @@ github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 h1:PKK9DyHxif4LZo+uQSgXNqs0jj5+x
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/sasha-s/go-deadlock v0.3.1 h1:sqv7fDNShgjcaxkO0JNcOAlr8B9+cV5Ey/OB71efZx0=
github.com/sasha-s/go-deadlock v0.3.1/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM=
github.com/schollz/progressbar/v3 v3.19.0 h1:Ea18xuIRQXLAUidVDox3AbwfUhD0/1IvohyTutOIFoc=
github.com/schollz/progressbar/v3 v3.19.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vPZYa2EdrU=
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:TgxPraf1NmF6XTcUG53ULpLQrKvhtUJxQ3hyekxSDNQ=
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
github.com/seaweedfs/go-fuse/v2 v2.9.3 h1:rJufGrHImTx7yoGUmetUi+To4LrmTQJROJnBHWt92ic=
@@ -2032,8 +2032,8 @@ github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2 h1:e2nGQPGC5OEPBWlMnLPFpd
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
github.com/ydb-platform/ydb-go-sdk/v3 v3.44.0/go.mod h1:oSLwnuilwIpaF5bJJMAofnGgzPJusoI3zWMNb8I+GnM=
github.com/ydb-platform/ydb-go-sdk/v3 v3.47.3/go.mod h1:bWnOIcUHd7+Sl7DN+yhyY1H/I61z53GczvwJgXMgvj0=
github.com/ydb-platform/ydb-go-sdk/v3 v3.141.0 h1:VLrLlCEk21r9PgiH5Hkm0/ACad9gEDMjFUxVWY8wWOw=
github.com/ydb-platform/ydb-go-sdk/v3 v3.141.0/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
github.com/ydb-platform/ydb-go-sdk/v3 v3.143.0 h1:kCrI6EtKLeuFCNJzDeweUZf+wKB3ms4TJL3aWnkTV0c=
github.com/ydb-platform/ydb-go-sdk/v3 v3.143.0/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
github.com/ydb-platform/ydb-go-yc v0.12.1 h1:qw3Fa+T81+Kpu5Io2vYHJOwcrYrVjgJlT6t/0dOXJrA=
github.com/ydb-platform/ydb-go-yc v0.12.1/go.mod h1:t/ZA4ECdgPWjAb4jyDe8AzQZB5dhpGbi3iCahFaNwBY=
github.com/ydb-platform/ydb-go-yc-metadata v0.6.1 h1:9E5q8Nsy2RiJMZDNVy0A3KUrIMBPakJ2VgloeWbcI84=
@@ -2179,8 +2179,8 @@ golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
@@ -2246,8 +2246,8 @@ golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -2368,8 +2368,8 @@ golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -2474,8 +2474,8 @@ golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@@ -2492,8 +2492,8 @@ golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -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.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
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=
@@ -2593,8 +2593,8 @@ golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/tools/godoc v0.1.0-deprecated h1:o+aZ1BOj6Hsx/GBdJO/s815sqftjSnrZZwyYTHODvtk=
golang.org/x/tools/godoc v0.1.0-deprecated/go.mod h1:qM63CriJ961IHWmnWa9CjZnBndniPt4a3CK0PVB9bIg=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.39"
appVersion: "4.40"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.39.0
version: 4.40.0
@@ -143,6 +143,9 @@ message RemoteEntry {
string remote_e_tag = 3;
int64 remote_mtime = 4;
int64 remote_size = 5;
// unset when the remote listing does not report encodings (S3);
// empty when the remote object authoritatively has none
optional string remote_content_encoding = 6;
}
message Entry {
string name = 1;
@@ -528,6 +531,7 @@ message AssignVolumeResponse {
string replication = 7;
string error = 8;
Location location = 9;
repeated Location replicas = 10;
}
message LookupVolumeRequest {
+3
View File
@@ -3,6 +3,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure()
.build_server(true)
.build_client(true)
// filer.proto uses proto3 optional; older protoc (e.g. 3.12 from ubuntu-22.04 apt)
// rejects it without this flag, and newer protoc still accepts the flag
.protoc_arg("--experimental_allow_proto3_optional")
.file_descriptor_set_path(out_dir.join("seaweed_descriptor.bin"))
.compile_protos(
&[
+11
View File
@@ -45,6 +45,8 @@ service Seaweed {
}
rpc ReleaseAdminToken (ReleaseAdminTokenRequest) returns (ReleaseAdminTokenResponse) {
}
rpc GetAdminLockStatus (GetAdminLockStatusRequest) returns (GetAdminLockStatusResponse) {
}
rpc Ping (PingRequest) returns (PingResponse) {
}
rpc RaftListClusterServers (RaftListClusterServersRequest) returns (RaftListClusterServersResponse) {
@@ -464,6 +466,15 @@ message ReleaseAdminTokenRequest {
message ReleaseAdminTokenResponse {
}
message GetAdminLockStatusRequest {
string lock_name = 1;
}
message GetAdminLockStatusResponse {
bool is_locked = 1;
string client_name = 2;
string message = 3;
}
message PingRequest {
string target = 1; // default to ping itself
string target_type = 2;
+14 -8
View File
@@ -380,7 +380,7 @@ impl VolumeServer for VolumeGrpcService {
size: 0,
version: 0,
});
break;
continue;
}
}
@@ -1234,12 +1234,24 @@ impl VolumeServer for VolumeGrpcService {
DiskType::from_string(&vol_info.disk_type)
};
let has_remote_dat = vol_info
.volume_info
.as_ref()
.map(|vi| !vi.files.is_empty())
.unwrap_or(false);
// a remote-backed volume only lands its .idx/.vif locally; the .dat stays in the tier
let needed_space = if has_remote_dat {
vol_info.idx_file_size
} else {
vol_info.dat_file_size
};
// Find a free disk location using Go's Store.FindFreeLocation semantics.
let (data_base, idx_base, selected_disk_type) = {
let store = self.state.store.read().unwrap();
let Some(loc_idx) = store.find_free_location_predicate(|loc| {
loc.disk_type == requested_disk_type
&& loc.available_space.load(Ordering::Relaxed) > vol_info.dat_file_size
&& loc.available_space.load(Ordering::Relaxed) > needed_space
}) else {
return Err(Status::internal(format!(
"no space left {}",
@@ -1266,12 +1278,6 @@ impl VolumeServer for VolumeGrpcService {
Status::internal(format!("write .note for volume {}: {}", vid, e))
})?;
let has_remote_dat = vol_info
.volume_info
.as_ref()
.map(|vi| !vi.files.is_empty())
.unwrap_or(false);
let (tx, rx) =
tokio::sync::mpsc::channel::<Result<volume_server_pb::VolumeCopyResponse, Status>>(16);
let state = self.state.clone();
+1 -43
View File
@@ -13,6 +13,7 @@ use std::sync::Arc;
use tracing::warn;
use crate::config::MinFreeSpace;
use crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars;
use crate::storage::erasure_coding::ec_shard::{
EcVolumeShard, DATA_SHARDS_COUNT, ERASURE_CODING_LARGE_BLOCK_SIZE,
ERASURE_CODING_SMALL_BLOCK_SIZE,
@@ -1095,49 +1096,6 @@ fn rm_if_present(path: String) -> io::Result<()> {
}
}
/// Remove the bitrot checksum sidecars for a base file name: the legacy
/// `<base>.ecsum` (generation 0) and any versioned `<base>.ecsum.v<N>`.
/// Already-gone is success; returns the first real removal failure (and surfaces
/// a directory-scan error) so a stale sidecar left behind is not reported as
/// cleaned. Mirrors Go's removeBitrotSidecars.
fn remove_bitrot_sidecars(base: &str) -> io::Result<()> {
use crate::storage::erasure_coding::ec_bitrot::BITROT_SIDECAR_EXT;
let rm = |path: std::path::PathBuf| -> io::Result<()> {
match fs::remove_file(&path) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
};
let mut first_err: Option<io::Error> = None;
let mut record = |res: io::Result<()>| {
if let Err(e) = res {
if first_err.is_none() {
first_err = Some(e);
}
}
};
record(rm(format!("{}{}", base, BITROT_SIDECAR_EXT).into()));
let path = std::path::Path::new(base);
if let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) {
let prefix = format!("{}{}.v", fname.to_string_lossy(), BITROT_SIDECAR_EXT);
match fs::read_dir(parent) {
Ok(entries) => {
for entry in entries.flatten() {
if entry.file_name().to_string_lossy().starts_with(&prefix) {
record(rm(entry.path()));
}
}
}
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
Err(_) => {}
}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
fn ec_data_shards_from_vif(directory: &str, idx_directory: &str, collection: &str, vid: VolumeId) -> usize {
for dir in [directory, idx_directory] {
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
@@ -146,6 +146,52 @@ pub fn bitrot_sidecar_path(base: &str, generation: u32) -> String {
}
}
/// Remove the bitrot checksum sidecars for a base file name: the legacy
/// `<base>.ecsum` (generation 0) and any versioned `<base>.ecsum.v<N>`.
///
/// Already-gone is success; returns the first real removal failure (and surfaces
/// a directory-scan error) so a stale sidecar left behind is not reported as
/// cleaned. Mirrors Go's `RemoveBitrotSidecars` / `removeBitrotSidecars`.
pub fn remove_bitrot_sidecars(base: &str) -> io::Result<()> {
use std::fs;
use std::path::Path;
let rm = |path: std::path::PathBuf| -> io::Result<()> {
match fs::remove_file(&path) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
};
let mut first_err: Option<io::Error> = None;
let mut record = |res: io::Result<()>| {
if let Err(e) = res {
if first_err.is_none() {
first_err = Some(e);
}
}
};
record(rm(format!("{}{}", base, BITROT_SIDECAR_EXT).into()));
let path = Path::new(base);
if let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) {
let prefix = format!("{}{}.v", fname.to_string_lossy(), BITROT_SIDECAR_EXT);
match fs::read_dir(parent) {
Ok(entries) => {
for entry in entries.flatten() {
if entry.file_name().to_string_lossy().starts_with(&prefix) {
record(rm(entry.path()));
}
}
}
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
Err(_) => {}
}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
/// Returns a fresh random per-encode identity used to detect a stale sidecar
/// left behind by an in-place re-encode.
pub fn new_encode_uuid() -> Vec<u8> {
@@ -553,6 +599,40 @@ mod tests {
assert_eq!(bitrot_sidecar_path("/d/1", 3), "/d/1.ecsum.v3");
}
/// Mirrors Go's TestRemoveBitrotSidecars: legacy + versioned sidecars go,
/// unrelated files (a shard, a longer-vid sidecar) survive, absent is success.
#[test]
fn test_remove_bitrot_sidecars() {
let tmp = tempfile::TempDir::new().unwrap();
let base = tmp.path().join("5").to_str().unwrap().to_string();
for p in [
format!("{}.ecsum", base),
format!("{}.ecsum.v1", base),
format!("{}.ecsum.v7", base),
] {
std::fs::write(&p, b"x").unwrap();
}
let keep_shard = format!("{}.ec00", base);
let keep_other_vid = format!("{}0.ecsum", base);
std::fs::write(&keep_shard, b"x").unwrap();
std::fs::write(&keep_other_vid, b"x").unwrap();
remove_bitrot_sidecars(&base).unwrap();
for p in [
format!("{}.ecsum", base),
format!("{}.ecsum.v1", base),
format!("{}.ecsum.v7", base),
] {
assert!(!std::path::Path::new(&p).exists(), "{} should be removed", p);
}
assert!(std::path::Path::new(&keep_shard).exists());
assert!(std::path::Path::new(&keep_other_vid).exists());
// Already-gone is success.
remove_bitrot_sidecars(&base).unwrap();
}
#[test]
fn test_is_pow2_multiple_of_1mib() {
assert!(is_pow2_multiple_of_1mib(1 << 20)); // 1 MiB
@@ -1453,6 +1453,21 @@ impl EcVolume {
let _ = fs::remove_file(format!("{}.ecj", data_base));
let _ = fs::remove_file(format!("{}.vif", data_base));
}
// Go's Destroy() also removes bitrot checksum sidecars so a later
// volume-id reuse cannot load stale protection, and so
// collection.delete does not leave orphaned <base>.ecsum files.
// ecx_actual_dir is always one of these two dirs.
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(
&self.base_name(),
);
if self.dir_idx != self.dir {
let idx_base = crate::storage::volume::volume_file_name(
&self.dir_idx,
&self.collection,
self.volume_id,
);
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&idx_base);
}
self.ecx_file = None;
self.ecj_file = None;
}
@@ -1463,6 +1478,82 @@ mod tests {
use super::*;
use tempfile::TempDir;
/// `destroy()` must remove co-located `.ecsum` sidecars (Go Destroy parity).
/// Without this, `collection.delete` leaves orphaned bitrot files that
/// inflate EC-health scanners after the shards are gone.
#[test]
fn test_destroy_removes_bitrot_sidecar() {
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::volume::Volume;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = Volume::new(
dir,
dir,
"ec1c",
VolumeId(2074),
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap();
for i in 1..=3 {
let data = format!("needle {}", i);
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: data.as_bytes().to_vec(),
data_size: data.len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
}
v.sync_to_disk().unwrap();
v.close();
crate::storage::erasure_coding::ec_encoder::write_ec_files(
dir,
dir,
"ec1c",
VolumeId(2074),
10,
4,
)
.unwrap();
let base = crate::storage::volume::volume_file_name(dir, "ec1c", VolumeId(2074));
let ecsum = format!("{}.ecsum", base);
assert!(
std::path::Path::new(&ecsum).exists(),
"precondition: encode must write generation-0 .ecsum"
);
assert!(
std::path::Path::new(&format!("{}.ec00", base)).exists(),
"precondition: encode must write shards"
);
let mut vol = EcVolume::new(dir, dir, "ec1c", VolumeId(2074)).unwrap();
// Mount at least one local shard so destroy's shard loop has work.
vol.add_shard(EcVolumeShard::new(dir, "ec1c", VolumeId(2074), 0))
.unwrap();
vol.destroy();
assert!(
!std::path::Path::new(&format!("{}.ec00", base)).exists(),
"destroy should remove shards"
);
assert!(
!std::path::Path::new(&ecsum).exists(),
"destroy should remove co-located .ecsum (Go Destroy parity)"
);
assert!(
!std::path::Path::new(&format!("{}.ecx", base)).exists(),
"destroy should remove .ecx"
);
}
/// Mounting an EC volume loads and validates its generation-0 `.ecsum`
/// sidecar, so `bitrot_protection()` reports `On` with the parsed manifest.
#[test]
+13 -2
View File
@@ -712,7 +712,7 @@ fn format_needle_id_cookie(key: NeedleId, cookie: Cookie) -> String {
/// Parse "needle_id_cookie_hex" or "needle_id_cookie_hex_delta" into (NeedleId, Cookie).
/// Matches Go's ParsePath + ParseNeedleIdCookie: supports an optional `_delta` suffix
/// where delta is a decimal number added to the NeedleId (used for sub-file addressing).
/// Rejects strings that are too short or too long.
/// Rejects strings that are too short or too long, and deltas that overflow the needle id.
pub fn parse_needle_id_cookie(s: &str) -> Result<(NeedleId, Cookie), String> {
// Go ParsePath: check for "_" suffix containing a decimal delta
let (hex_part, delta) = if let Some(underscore_pos) = s.rfind('_') {
@@ -754,7 +754,11 @@ pub fn parse_needle_id_cookie(s: &str) -> Result<(NeedleId, Cookie), String> {
// Apply delta if present (Go: n.Id += Uint64ToNeedleId(d))
if let Some(d) = delta {
key = NeedleId(key.0.wrapping_add(d));
key = NeedleId(
key.0
.checked_add(d)
.ok_or_else(|| format!("delta {} overflows needle id {:x}", d, key.0))?,
);
}
Ok((key, cookie))
@@ -937,6 +941,13 @@ mod tests {
assert_eq!(cookie, Cookie(0x12345678));
}
#[test]
fn test_parse_rejects_delta_overflow() {
assert!(parse_needle_id_cookie("ffffffffffffffff00000000_1").is_err());
let (key, _) = parse_needle_id_cookie("fffffffffffffffe00000000_1").unwrap();
assert_eq!(key, NeedleId(u64::MAX));
}
#[test]
fn test_parse_odd_length_needle_id() {
// Go's shell formats purge fids with strconv.FormatUint, which does not
+183 -11
View File
@@ -934,46 +934,108 @@ impl Store {
/// Delete EC shard files from disk.
pub fn delete_ec_shards(&mut self, vid: VolumeId, collection: &str, shard_ids: &[u32]) {
// Delete shard files from disk
for loc in &self.locations {
// Delete shard files from disk, tracking which locations actually held one.
let mut deleted_at = vec![false; self.locations.len()];
for (i, loc) in self.locations.iter().enumerate() {
for &shard_id in shard_ids {
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id as u8);
let path = shard.file_name();
let _ = std::fs::remove_file(&path);
if std::fs::remove_file(shard.file_name()).is_ok() {
deleted_at[i] = true;
}
}
}
// Also unmount if mounted
self.unmount_ec_shards(vid, shard_ids);
// Per-disk: when this delete removed the location's last shards, the local
// bitrot sidecar is orphaned — remove it (Go deleteEcShardIdsForEachLocation
// when found && existingShardCount == 0). The `deleted_at` gate keeps a
// delete that never touched a disk from stripping a sidecar it does not
// own: a shared -dir.idx sibling with surviving shards, or an ec.rebuild
// index-prep copy that lands .ecx/.ecsum before any shard.
for (i, loc) in self.locations.iter().enumerate() {
if !deleted_at[i] || Self::location_has_ec_shards(loc, collection, vid) {
continue;
}
let data_base =
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&data_base);
if loc.idx_directory != loc.directory {
// A single -dir.idx is shared by every location: leave the idx-base
// sidecar alone while any sibling still holds shards of this volume.
let idx_in_use = self.locations.iter().any(|other| {
other.idx_directory == loc.idx_directory
&& Self::location_has_ec_shards(other, collection, vid)
});
if !idx_in_use {
let idx_base = crate::storage::volume::volume_file_name(
&loc.idx_directory,
collection,
vid,
);
let _ =
crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&idx_base);
}
}
}
// If all shards are gone, remove .ecx and .ecj files from both idx and data dirs
let all_gone = self.check_all_ec_shards_deleted(vid, collection);
if all_gone {
for loc in &self.locations {
let idx_base =
crate::storage::volume::volume_file_name(&loc.idx_directory, collection, vid);
let data_base =
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
let _ = std::fs::remove_file(format!("{}.ecx", idx_base));
let _ = std::fs::remove_file(format!("{}.ecj", idx_base));
// Also try data directory in case .ecx/.ecj were created before -dir.idx
if loc.idx_directory != loc.directory {
let data_base =
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
let _ = std::fs::remove_file(format!("{}.ecx", data_base));
let _ = std::fs::remove_file(format!("{}.ecj", data_base));
}
// A shard-only disk also drops its stale .vif (Go
// removeEcSharedIndexFiles): a live .idx means this disk still
// hosts the source volume and the .vif belongs to it. Unexpected
// stat errors count as present so a transient failure never
// strips a live volume's .vif.
let has_idx = [&idx_base, &data_base].iter().any(|base| {
match std::fs::metadata(format!("{}.idx", base)) {
Ok(_) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(_) => true,
}
});
if !has_idx {
let _ = std::fs::remove_file(format!("{}.vif", data_base));
}
}
}
}
/// True if `loc` still has any on-disk EC shard for this volume. An
/// unexpected stat error (permission, I/O) counts as "exists" so a
/// transient failure never classifies live shards as gone and deletes
/// their sidecar or shared index.
fn location_has_ec_shards(loc: &DiskLocation, collection: &str, vid: VolumeId) -> bool {
for shard_id in 0..MAX_SHARD_COUNT as u8 {
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
match std::fs::metadata(shard.file_name()) {
Ok(_) => return true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => return true,
}
}
false
}
/// Check if all EC shard files have been deleted for a volume.
/// Uses MAX_SHARD_COUNT to support non-standard EC configurations.
fn check_all_ec_shards_deleted(&self, vid: VolumeId, collection: &str) -> bool {
for loc in &self.locations {
for shard_id in 0..MAX_SHARD_COUNT as u8 {
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
if std::path::Path::new(&shard.file_name()).exists() {
return false;
}
if Self::location_has_ec_shards(loc, collection, vid) {
return false;
}
}
true
@@ -1682,6 +1744,116 @@ mod tests {
);
}
/// Deleting a disk's last shard removes that disk's now-orphaned `.ecsum`;
/// a disk this delete never changed keeps its sidecar. Disk 0 models
/// ec.rebuild's index-prep state (`.ecsum` landed, no shards yet) — an
/// unrelated shard delete must not strip its just-copied protection.
#[test]
fn test_delete_ec_shards_sidecar_gated_on_local_delete() {
let (mut store, _tmp) = make_ec_target_test_store(2);
let collection = "c";
let vid = VolumeId(7);
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
std::fs::write(format!("{}.ecsum", base0), b"x").unwrap();
std::fs::write(format!("{}.ec00", base1), b"x").unwrap();
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
std::fs::write(format!("{}.ecsum", base1), b"x").unwrap();
// Disk 1 still has .ec01 afterwards: both sidecars survive.
store.delete_ec_shards(vid, collection, &[0]);
assert!(std::path::Path::new(&format!("{}.ecsum", base0)).exists());
assert!(std::path::Path::new(&format!("{}.ecsum", base1)).exists());
// Disk 1's last shard goes: its sidecar is orphaned and removed, but
// disk 0 was never touched by either delete and keeps its sidecar.
store.delete_ec_shards(vid, collection, &[1]);
assert!(!std::path::Path::new(&format!("{}.ec01", base1)).exists());
assert!(
!std::path::Path::new(&format!("{}.ecsum", base1)).exists(),
"orphaned sidecar should be removed with the disk's last shard"
);
assert!(
std::path::Path::new(&format!("{}.ecsum", base0)).exists(),
"a delete that removed nothing on this disk must not strip its sidecar"
);
}
/// With one -dir.idx shared by every location, emptying disk 0 must not
/// remove the idx-base sidecar while disk 1 still holds shards; it goes
/// only when the last location sharing the idx dir is emptied too.
#[test]
fn test_delete_ec_shards_preserves_shared_idx_sidecar() {
let tmp = TempDir::new().unwrap();
let idx = tmp.path().join("idx");
std::fs::create_dir_all(&idx).unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
for i in 0..2 {
let path = tmp.path().join(format!("data{}", i));
std::fs::create_dir_all(&path).unwrap();
store
.add_location(
path.to_str().unwrap(),
idx.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
let collection = "c";
let vid = VolumeId(7);
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
let idx_base = volume_file_name(&store.locations[0].idx_directory, collection, vid);
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
std::fs::write(format!("{}.ecsum", idx_base), b"x").unwrap();
store.delete_ec_shards(vid, collection, &[0]);
assert!(
std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
"shared idx sidecar must survive while a sibling disk still has shards"
);
store.delete_ec_shards(vid, collection, &[1]);
assert!(
!std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
"shared idx sidecar should go with the last location's last shard"
);
}
/// When the node's last shard goes, a shard-only disk also drops its stale
/// .vif (Go removeEcSharedIndexFiles); a disk with a live .idx still hosts
/// the source volume and keeps its .vif.
#[test]
fn test_delete_ec_shards_vif_removal_gated_on_idx() {
let (mut store, _tmp) = make_ec_target_test_store(2);
let collection = "c";
let vid = VolumeId(7);
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
std::fs::write(format!("{}.vif", base0), b"x").unwrap();
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
std::fs::write(format!("{}.vif", base1), b"x").unwrap();
std::fs::write(format!("{}.idx", base1), b"x").unwrap();
store.delete_ec_shards(vid, collection, &[0, 1]);
assert!(
!std::path::Path::new(&format!("{}.vif", base0)).exists(),
"shard-only disk should drop its stale .vif with the node's last shard"
);
assert!(
std::path::Path::new(&format!("{}.vif", base1)).exists(),
"a disk with a live .idx keeps its .vif"
);
}
/// An already-mounted EC volume on disk 1 must win over a stray
/// `.ecx` on disk 2. Protects the post-startup steady state from
/// being perturbed by leftover index files from a prior failed move.
+358 -84
View File
@@ -1866,104 +1866,216 @@ impl Volume {
// needle map's max_needle_end accumulator, so we don't pay for a
// second linear scan of the .idx here.
// Check last 10 index entries (matching Go's CheckVolumeDataIntegrity).
// Go starts healthyIndexSize = indexSize and reduces on EOF.
// On success: break (err != ErrorSizeMismatch when err == nil).
// On EOF: set healthyIndexSize = position of corrupt entry, continue.
// On ErrorSizeMismatch: continue (try next entry).
// After loop: if healthyIndexSize < indexSize → error.
// Verify the needle physically last in the .dat (the highest offset)
// and that the .dat ends exactly at it. The .idx is not always in .dat
// append order: weed fix and other rebuilds could rewrite it sorted by
// key, which puts the highest-key needle last instead of the .dat-tail
// needle. Picking the last file-position entry there compares a
// mid-file needle's tail against the full .dat size and falsely flips
// the volume read-only on every load. Mirrors Go's
// findDatTailEntryOffset + doCheckAndFixVolumeData.
let mut idx_file = File::open(&idx_path)?;
let max_entries = std::cmp::min(10, idx_size / NEEDLE_MAP_ENTRY_SIZE as i64);
let mut healthy_index_size: i64 = idx_size;
let tail_entry_pos = self.find_dat_tail_entry_offset(&mut idx_file, idx_size, version)?;
if tail_entry_pos < 0 {
// pre-allocated / all-zero index, nothing to verify against the .dat
return Ok(());
}
for i in 1..=max_entries {
let entry_offset = idx_size - i * NEEDLE_MAP_ENTRY_SIZE as i64;
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_file.seek(SeekFrom::Start(entry_offset as u64))?;
idx_file.read_exact(&mut buf)?;
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_file.seek(SeekFrom::Start(tail_entry_pos as u64))?;
idx_file.read_exact(&mut buf)?;
let (key, offset, size) = idx_entry_from_bytes(&buf);
if offset.is_zero() {
return Ok(());
}
if size.is_deleted() {
// Deletion tombstone: the .idx carries TombstoneFileSize (-1) but
// the appended needle in .dat carries Size=0, so verify with
// Size=0 — comparing against -1 would mismatch the on-disk header
// and send every volume with a trailing deletion read-only.
self.verify_deleted_needle_integrity(offset.to_actual_offset(), key, version)
} else {
self.verify_needle_integrity(offset.to_actual_offset(), key, size, version)
}
}
let (key, offset, size) = idx_entry_from_bytes(&buf);
if offset.is_zero() {
continue;
}
let actual_offset = offset.to_actual_offset() as u64;
// Read needle header at the offset
let mut header = [0u8; NEEDLE_HEADER_SIZE];
match self.read_exact_at_backend(&mut header, actual_offset) {
Ok(()) => {}
Err(VolumeError::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
// Match Go: on EOF, mark this entry as corrupt and continue
// checking earlier entries (healthyIndexSize tracks the boundary).
healthy_index_size = entry_offset;
continue;
}
Err(e) => return Err(e),
}
let (_cookie, needle_id, needle_size) = Needle::parse_header(&header);
// Verify the needle ID matches the index entry
if !key.is_empty() && needle_id != key {
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"index key {:?} does not match needle Id {:?} at offset {}",
key, needle_id, actual_offset
),
)));
}
// For non-deleted entries, verify the size matches
if !size.is_deleted() && size.0 > 0 && needle_size.0 != size.0 {
// Try with MaxPossibleVolumeSize offset adjustment (Go parity)
let alt_offset = actual_offset + MAX_POSSIBLE_VOLUME_SIZE as u64;
let mut alt_header = [0u8; NEEDLE_HEADER_SIZE];
if self
.read_exact_at_backend(&mut alt_header, alt_offset)
.is_ok()
{
let (_, _, alt_size) = Needle::parse_header(&alt_header);
if alt_size.0 == size.0 {
continue;
}
}
// Match Go: ErrorSizeMismatch breaks out of the loop
break;
}
// If V3, try to read the append timestamp from the last verified entry.
// Go reads AppendAtNs from both live and deleted (tombstone) entries
// via verifyNeedleIntegrity and verifyDeletedNeedleIntegrity.
if version == VERSION_3 {
// For tombstones (deleted), body size on disk is 0.
// For live entries, body size is size.0.
let body_size = if size.is_deleted() { 0u64 } else { size.0 as u64 };
let ts_offset =
actual_offset + NEEDLE_HEADER_SIZE as u64 + body_size + 4; // skip checksum
let mut ts_buf = [0u8; 8];
if self.read_exact_at_backend(&mut ts_buf, ts_offset).is_ok() {
let ts = u64::from_be_bytes(ts_buf);
if ts > 0 {
self.last_append_at_ns = ts;
}
/// .idx file position of the entry whose needle is physically last in the
/// .dat (highest offset). The common case — an append-ordered .idx — is
/// resolved in O(1): the last entry's on-disk end equals the .dat size. A
/// key-sorted .idx (e.g. legacy weed fix output) falls back to a single
/// linear scan for the maximum offset. Returns -1 when no entry has a
/// non-zero offset (a pre-allocated / all-zero index).
fn find_dat_tail_entry_offset(
&self,
idx_file: &mut File,
idx_size: i64,
version: Version,
) -> Result<i64, VolumeError> {
if let Ok(dat_size) = self.dat_file_size() {
if dat_size > 0 {
let last_pos = idx_size - NEEDLE_MAP_ENTRY_SIZE as i64;
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_file.seek(SeekFrom::Start(last_pos as u64))?;
idx_file.read_exact(&mut buf)?;
let (_, offset, size) = idx_entry_from_bytes(&buf);
if !offset.is_zero() && needle_disk_end(offset, size, version) == dat_size as i64 {
return Ok(last_pos);
}
}
}
// Match Go: if healthyIndexSize < indexSize, trailing entries are corrupt
if healthy_index_size < idx_size {
// Slow path: scan the whole .idx for the entry at the maximum offset.
// Tombstone entries are not skipped: a trailing deletion is a real
// on-disk record and can be the needle physically last in the .dat.
let mut max_entry_pos: i64 = -1;
let mut max_actual_offset: i64 = -1;
let mut entry_pos: i64 = 0;
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_file.seek(SeekFrom::Start(0))?;
let mut reader = io::BufReader::new(idx_file);
while entry_pos < idx_size {
reader.read_exact(&mut buf)?;
let (_, offset, _) = idx_entry_from_bytes(&buf);
if !offset.is_zero() {
let ao = offset.to_actual_offset();
if ao > max_actual_offset {
max_actual_offset = ao;
max_entry_pos = entry_pos;
}
}
entry_pos += NEEDLE_MAP_ENTRY_SIZE as i64;
}
Ok(max_entry_pos)
}
/// Verify the live needle at the .dat tail: its header must match the
/// .idx entry and the .dat must end exactly at its on-disk end. Extra
/// bytes mean an unindexed trailing record (a torn append); appending
/// after one would place the next needle at an offset the 8-byte .idx
/// encoding may not represent, so the volume is quarantined read-only
/// instead. Mirrors Go's verifyNeedleIntegrity.
fn verify_needle_integrity(
&mut self,
actual_offset: i64,
key: NeedleId,
size: Size,
version: Version,
) -> Result<(), VolumeError> {
let mut header = [0u8; NEEDLE_HEADER_SIZE];
self.read_exact_at_backend(&mut header, actual_offset as u64)?;
let (_cookie, needle_id, needle_size) = Needle::parse_header(&header);
let mut checked_offset = actual_offset;
let mut checked_id = needle_id;
if needle_size != size {
// Go parity: on a size mismatch, retry past the 32GB offset
// wrap-around before giving up.
let alt_offset = actual_offset + MAX_POSSIBLE_VOLUME_SIZE as i64;
let mut alt_header = [0u8; NEEDLE_HEADER_SIZE];
self.read_exact_at_backend(&mut alt_header, alt_offset as u64)
.map_err(|_| size_mismatch_error(actual_offset, needle_id, needle_size, size))?;
let (_, alt_id, alt_size) = Needle::parse_header(&alt_header);
if alt_size != size {
return Err(size_mismatch_error(actual_offset, needle_id, needle_size, size));
}
checked_offset = alt_offset;
checked_id = alt_id;
}
if !key.is_empty() && checked_id != key {
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"healthy index size {} is less than expected {}",
healthy_index_size, idx_size
"index key {:?} does not match needle Id {:?} at offset {}",
key, checked_id, checked_offset
),
)));
}
Ok(())
if version == VERSION_3 {
let ts_offset =
checked_offset as u64 + NEEDLE_HEADER_SIZE as u64 + size.0 as u64 + 4; // skip checksum
let mut ts_buf = [0u8; 8];
self.read_exact_at_backend(&mut ts_buf, ts_offset)?;
let ts = u64::from_be_bytes(ts_buf);
if ts > 0 {
self.last_append_at_ns = ts;
}
}
self.verify_dat_ends_at(checked_offset + get_actual_size(size, version))
}
/// Verify the deletion tombstone at the .dat tail. Tombstones are appended
/// with DataSize=0, so the on-disk header carries Size=0; verify with that
/// and then require the .dat to end exactly at the tombstone. Mirrors Go's
/// verifyDeletedNeedleIntegrity.
fn verify_deleted_needle_integrity(
&mut self,
actual_offset: i64,
key: NeedleId,
version: Version,
) -> Result<(), VolumeError> {
let record_size = get_actual_size(Size(0), version) as usize;
let mut record = vec![0u8; record_size];
self.read_exact_at_backend(&mut record, actual_offset as u64)?;
let mut n = Needle::default();
n.read_bytes(&record, actual_offset, Size(0), version)
.map_err(|e| {
VolumeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!("read tombstone at offset {}: {}", actual_offset, e),
))
})?;
if !key.is_empty() && n.id != key {
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"index key {:?} does not match needle Id {:?} at offset {}",
key, n.id, actual_offset
),
)));
}
if n.append_at_ns > 0 {
self.last_append_at_ns = n.append_at_ns;
}
self.verify_dat_ends_at(actual_offset + get_actual_size(Size(0), version))
}
/// The checked needle is the one physically last in the .dat, so the file
/// must end exactly at it; extra bytes mean an unindexed trailing record.
fn verify_dat_ends_at(&self, file_tail_offset: i64) -> Result<(), VolumeError> {
let file_size = self.dat_file_size().map_err(VolumeError::Io)? as i64;
if file_size == file_tail_offset {
return Ok(());
}
let dat_path = self.file_name(".dat");
if file_size > file_tail_offset {
warn!(
"data file {} actual {} bytes expected {} bytes!",
dat_path, file_size, file_tail_offset
);
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"data file {} actual {} bytes expected {} bytes",
dat_path, file_size, file_tail_offset
),
)));
}
warn!(
"data file {} has {} bytes, less than expected {} bytes!",
dat_path, file_size, file_tail_offset
);
Err(VolumeError::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"data file {} has {} bytes, less than expected {} bytes",
dat_path, file_size, file_tail_offset
),
)))
}
/// Open the on-disk .idx for scrubbing and apply Go openIndex's zero-size
@@ -3421,6 +3533,24 @@ impl Volume {
// ============================================================================
/// Generate volume file base name: dir/collection_id or dir/id
/// Byte offset just past the needle's on-disk record. Deletion tombstones
/// carry TombstoneFileSize (-1) in the .idx but are written with DataSize=0,
/// so their on-disk record is sized as 0. Mirrors Go's needleDiskEnd.
fn needle_disk_end(offset: Offset, size: Size, version: Version) -> i64 {
let on_disk_size = if size.is_deleted() { Size(0) } else { size };
offset.to_actual_offset() + get_actual_size(on_disk_size, version)
}
fn size_mismatch_error(offset: i64, id: NeedleId, found: Size, expected: Size) -> VolumeError {
VolumeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"entry not found: offset {} found id {:?} size {}, expected size {}",
offset, id, found.0, expected.0
),
))
}
pub fn volume_file_name(dir: &str, collection: &str, id: VolumeId) -> String {
if collection.is_empty() {
format!("{}/{}", dir, id.0)
@@ -3881,6 +4011,150 @@ mod tests {
);
}
fn write_three_needles(dir: &str) {
let mut v = make_test_volume(dir);
for i in 1..=3u64 {
let data = format!("data {}", i);
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: data.as_bytes().to_vec(),
data_size: data.len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
}
v.sync_to_disk().unwrap();
}
fn reload_volume(dir: &str) -> Volume {
Volume::new(
dir,
dir,
"",
VolumeId(1),
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap()
}
// A torn shutdown can leave bytes in the .dat past the last indexed
// needle. Appending after such a tail would place the next needle at an
// offset the 8-byte-unit .idx encoding may not represent, so the load
// check must quarantine the volume read-only, matching Go's
// verifyNeedleIntegrity "actual N bytes expected M bytes" behavior.
#[test]
fn test_integrity_detects_unindexed_dat_tail() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
write_three_needles(dir);
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
let mut f = OpenOptions::new().append(true).open(&dat_path).unwrap();
f.write_all(&[0xFFu8; 100]).unwrap();
f.sync_all().unwrap();
drop(f);
let v = reload_volume(dir);
assert!(
v.is_no_write_or_delete(),
"volume with unindexed .dat tail must load read-only"
);
}
// Same torn tail, but with a deletion tombstone as the last indexed
// record — the tombstone path must also verify the .dat ends at it.
#[test]
fn test_integrity_detects_tail_after_tombstone() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
{
let mut v = make_test_volume(dir);
let data = b"data 1".to_vec();
let mut n = Needle {
id: NeedleId(1),
cookie: Cookie(1),
data: data.clone(),
data_size: data.len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
v.delete_needle(&mut Needle {
id: NeedleId(1),
cookie: Cookie(1),
..Needle::default()
})
.unwrap();
v.sync_to_disk().unwrap();
}
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
let mut f = OpenOptions::new().append(true).open(&dat_path).unwrap();
f.write_all(&[0xFFu8; 64]).unwrap();
f.sync_all().unwrap();
drop(f);
let v = reload_volume(dir);
assert!(
v.is_no_write_or_delete(),
"volume with unindexed tail after tombstone must load read-only"
);
}
// A key-sorted .idx (legacy weed fix output) puts the highest-key needle
// last by file position, not the .dat-tail needle. The check must find
// the true tail entry via the max-offset scan instead of falsely flipping
// a healthy volume read-only.
#[test]
fn test_integrity_key_sorted_idx_no_false_readonly() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
write_three_needles(dir);
// Swap the last two .idx entries so the file-position-last entry
// references a mid-file needle.
let idx_path = volume_file_name(dir, "", VolumeId(1)) + ".idx";
let content = fs::read(&idx_path).unwrap();
assert_eq!(content.len(), 3 * NEEDLE_MAP_ENTRY_SIZE);
let mut swapped = content.clone();
swapped[NEEDLE_MAP_ENTRY_SIZE..2 * NEEDLE_MAP_ENTRY_SIZE]
.copy_from_slice(&content[2 * NEEDLE_MAP_ENTRY_SIZE..]);
swapped[2 * NEEDLE_MAP_ENTRY_SIZE..]
.copy_from_slice(&content[NEEDLE_MAP_ENTRY_SIZE..2 * NEEDLE_MAP_ENTRY_SIZE]);
fs::write(&idx_path, swapped).unwrap();
let v = reload_volume(dir);
assert!(
!v.is_no_write_or_delete(),
"healthy volume with key-sorted .idx must not load read-only"
);
}
// A .dat truncated mid-needle (crash during append) must quarantine.
#[test]
fn test_integrity_detects_truncated_dat_tail() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
write_three_needles(dir);
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
let len = fs::metadata(&dat_path).unwrap().len();
let f = OpenOptions::new().write(true).open(&dat_path).unwrap();
f.set_len(len - 5).unwrap();
f.sync_all().unwrap();
drop(f);
let v = reload_volume(dir);
assert!(
v.is_no_write_or_delete(),
"volume with truncated .dat tail must load read-only"
);
}
#[test]
fn test_scrub_empty_volume() {
// Mirror of Go's TestScrubVolumeData "zero-size volume without index"
BIN
View File
Binary file not shown.
+25 -13
View File
@@ -86,35 +86,47 @@ func NewFuseTestFramework(t *testing.T, config *TestConfig) *FuseTestFramework {
}
}
// freePort asks the OS for a free TCP port in a range where the gRPC
// offset (port + 10000) won't collide with well-known ports.
// Stay below the Linux ephemeral floor (32768) so the kernel does not
// reuse the chosen port for an outbound connection between close() here
// and re-bind in the child "weed mini" process.
// grpcPortOffset mirrors weed's HTTP->gRPC port convention (gRPC = HTTP + offset);
// "weed mount" derives the filer gRPC port from the filer HTTP address the same way.
const grpcPortOffset = 10000
// freePort returns a free filer HTTP port whose gRPC sibling (port+grpcPortOffset)
// is also free. Both must stay below the Linux ephemeral floor (32768): a gRPC port
// above it can be transiently grabbed by an outbound connection, forcing mini to
// relocate its filer gRPC port while "weed mount" keeps dialing HTTP+10000 — the
// mount then never connects and the test times out. Capping HTTP at 22000 keeps the
// gRPC port at or below 32000.
func freePort(t *testing.T) int {
t.Helper()
const (
minServicePort = 20000
maxServicePort = 32000
maxServicePort = 22000
)
portCount := maxServicePort - minServicePort + 1
start := minServicePort + int(time.Now().UnixNano()%int64(portCount))
for attempt := 0; attempt < 512; attempt++ {
for attempt := 0; attempt < portCount; attempt++ {
port := minServicePort + (start-minServicePort+attempt)%portCount
l, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
if err != nil {
continue
if portIsFree(port) && portIsFree(port+grpcPortOffset) {
return port
}
l.Close()
return port
}
t.Fatalf("failed to allocate port <= %d after repeated attempts", maxServicePort)
t.Fatalf("failed to allocate a free HTTP/gRPC port pair in [%d,%d]", minServicePort, maxServicePort)
return 0
}
// portIsFree reports whether a TCP port can currently be bound on 127.0.0.1.
func portIsFree(port int) bool {
l, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
if err != nil {
return false
}
l.Close()
return true
}
// Setup starts "weed mini" and mounts the FUSE filesystem.
func (f *FuseTestFramework) Setup(config *TestConfig) error {
if f.isSetup {
+72
View File
@@ -0,0 +1,72 @@
package sftp
import (
"io"
"testing"
"github.com/stretchr/testify/require"
)
// TestScopedUserCannotAccessSiblingPrefix verifies that a permission entry
// for /tenants/alice does not leak onto sibling paths such as
// /tenants/alice-archive that merely share the string prefix.
func TestScopedUserCannotAccessSiblingPrefix(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
config := DefaultTestConfig()
config.EnableDebug = testing.Verbose()
fw := NewSftpTestFramework(t, config)
require.NoError(t, fw.Setup(config))
defer fw.Cleanup()
// admin seeds both tenants
admin, adminConn, err := fw.ConnectSFTP("admin", "adminpassword")
require.NoError(t, err)
defer adminConn.Close()
defer admin.Close()
require.NoError(t, admin.MkdirAll("/tenants/alice"))
require.NoError(t, admin.MkdirAll("/tenants/alice-archive"))
secret, err := admin.Create("/tenants/alice-archive/secret.txt")
require.NoError(t, err)
_, err = secret.Write([]byte("SIBLING-SECRET"))
require.NoError(t, err)
require.NoError(t, secret.Close())
scoped, scopedConn, err := fw.ConnectSFTP("scoped", "scopedpassword")
require.NoError(t, err)
defer scopedConn.Close()
defer scoped.Close()
// positive control: the scoped user can write within its own prefix
own, err := scoped.Create("/tenants/alice/own.txt")
require.NoError(t, err)
_, err = own.Write([]byte("ok"))
require.NoError(t, err)
require.NoError(t, own.Close())
// reading the sibling tenant's file must fail
if f, err := scoped.Open("/tenants/alice-archive/secret.txt"); err == nil {
data, _ := io.ReadAll(f)
f.Close()
t.Fatalf("ACL for /tenants/alice read sibling /tenants/alice-archive: %q", data)
}
// overwriting the sibling tenant's file must fail
if f, err := scoped.Create("/tenants/alice-archive/secret.txt"); err == nil {
f.Write([]byte("OVERWRITTEN-BY-SCOPED-USER"))
f.Close()
t.Fatal("ACL for /tenants/alice overwrote sibling /tenants/alice-archive")
}
// the sibling file is intact
f, err := admin.Open("/tenants/alice-archive/secret.txt")
require.NoError(t, err)
data, err := io.ReadAll(f)
require.NoError(t, err)
require.NoError(t, f.Close())
require.Equal(t, "SIBLING-SECRET", string(data))
}
+11
View File
@@ -31,6 +31,17 @@
},
"Uid": 1002,
"Gid": 1002
},
{
"Username": "scoped",
"Password": "scopedpassword",
"PublicKeys": [],
"HomeDir": "/",
"Permissions": {
"/tenants/alice": ["read", "write", "list"]
},
"Uid": 1003,
"Gid": 1003
}
]
+13 -10
View File
@@ -119,7 +119,7 @@ func TestBatchDeleteCookieMismatchAndSkipCheck(t *testing.T) {
}
}
func TestBatchDeleteMixedStatusesAndMismatchStopsProcessing(t *testing.T) {
func TestBatchDeleteMixedStatusesAndMismatchContinuesProcessing(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
@@ -188,29 +188,32 @@ func TestBatchDeleteMixedStatusesAndMismatchStopsProcessing(t *testing.T) {
}
wrongCookieB := framework.NewFileID(volumeID, needleB, cookieB+1)
stopResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
mismatchContinueResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
FileIds: []string{wrongCookieB, fidC},
})
if err != nil {
t.Fatalf("BatchDelete mismatch-stop request failed: %v", err)
t.Fatalf("BatchDelete mismatch-continue request failed: %v", err)
}
if len(stopResp.GetResults()) != 1 {
t.Fatalf("BatchDelete mismatch-stop expected 1 result due early break, got %d", len(stopResp.GetResults()))
if len(mismatchContinueResp.GetResults()) != 2 {
t.Fatalf("BatchDelete mismatch-continue expected 2 results, got %d", len(mismatchContinueResp.GetResults()))
}
if stopResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
t.Fatalf("BatchDelete mismatch-stop expected 400, got %d", stopResp.GetResults()[0].GetStatus())
if mismatchContinueResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
t.Fatalf("BatchDelete mismatch-continue result[0] expected 400, got %d", mismatchContinueResp.GetResults()[0].GetStatus())
}
if mismatchContinueResp.GetResults()[1].GetStatus() != http.StatusAccepted {
t.Fatalf("BatchDelete mismatch-continue result[1] expected 202, got %d", mismatchContinueResp.GetResults()[1].GetStatus())
}
readB := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidB)
_ = framework.ReadAllAndClose(t, readB)
if readB.StatusCode != http.StatusOK {
t.Fatalf("fidB should remain after cookie mismatch path, got %d", readB.StatusCode)
t.Fatalf("fidB should remain after cookie mismatch, got %d", readB.StatusCode)
}
readC := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidC)
_ = framework.ReadAllAndClose(t, readC)
if readC.StatusCode != http.StatusOK {
t.Fatalf("fidC should remain when batch processing stops on mismatch, got %d", readC.StatusCode)
if readC.StatusCode != http.StatusNotFound {
t.Fatalf("fidC should be deleted when processing continues past a mismatch, got %d", readC.StatusCode)
}
}
+100 -13
View File
@@ -33,7 +33,10 @@ import (
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/s3api"
"github.com/seaweedfs/seaweedfs/weed/s3api/lifecycle_xml"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
@@ -797,20 +800,23 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
lastModified = time.Unix(resp.Entry.Attributes.Mtime, 0)
}
readOnly := fc.MatchStorageRule(filerConfig.BucketsPath + "/" + bucketName + "/").ReadOnly
lifecycleRuleCount, lifecycleEnabledCount := extractLifecycleCountsFromEntry(resp.Entry)
bucket := S3Bucket{
Name: bucketName,
CreatedAt: createdAt,
LogicalSize: logicalSize,
PhysicalSize: physicalSize,
LastModified: lastModified,
Quota: quota,
QuotaEnabled: quotaEnabled,
ReadOnly: readOnly,
VersioningStatus: versioningStatus,
ObjectLockEnabled: objectLockEnabled,
ObjectLockMode: objectLockMode,
ObjectLockDuration: objectLockDuration,
Owner: owner,
Name: bucketName,
CreatedAt: createdAt,
LogicalSize: logicalSize,
PhysicalSize: physicalSize,
LastModified: lastModified,
Quota: quota,
QuotaEnabled: quotaEnabled,
ReadOnly: readOnly,
VersioningStatus: versioningStatus,
ObjectLockEnabled: objectLockEnabled,
ObjectLockMode: objectLockMode,
ObjectLockDuration: objectLockDuration,
Owner: owner,
LifecycleRuleCount: lifecycleRuleCount,
LifecycleEnabledCount: lifecycleEnabledCount,
}
buckets = append(buckets, bucket)
}
@@ -915,6 +921,7 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
details.Bucket.ObjectLockMode = objectLockMode
details.Bucket.ObjectLockDuration = objectLockDuration
details.Bucket.Owner = owner
details.Bucket.LifecycleRuleCount, details.Bucket.LifecycleEnabledCount = extractLifecycleCountsFromEntry(bucketResp.Entry)
return nil
})
@@ -926,6 +933,68 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
return details, nil
}
// GetBucketLifecycle returns the lifecycle configuration stored on a bucket's filer entry
func (s *AdminServer) GetBucketLifecycle(bucketName string) (*BucketLifecycle, error) {
filerConfig, err := s.getFilerConfig()
if err != nil {
glog.Warningf("Failed to get filer configuration, using defaults: %v", err)
}
lifecycle := &BucketLifecycle{
Bucket: bucketName,
Rules: []BucketLifecycleRule{},
}
err = s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: filerConfig.BucketsPath,
Name: bucketName,
})
if err != nil {
return fmt.Errorf("bucket not found: %w", err)
}
xmlBytes := resp.Entry.Extended[scheduler.BucketLifecycleConfigurationXMLKey]
if len(xmlBytes) == 0 {
return nil
}
rules, err := lifecycle_xml.ParseCanonical(xmlBytes)
if err != nil {
return fmt.Errorf("parse lifecycle configuration: %w", err)
}
lifecycle.XML = string(xmlBytes)
for _, rule := range rules {
lifecycle.Rules = append(lifecycle.Rules, toBucketLifecycleRule(rule))
}
return nil
})
if err != nil {
return nil, err
}
return lifecycle, nil
}
func toBucketLifecycleRule(rule *s3lifecycle.Rule) BucketLifecycleRule {
out := BucketLifecycleRule{
ID: rule.ID,
Status: rule.Status,
Prefix: rule.Prefix,
Tags: rule.FilterTags,
SizeGreaterThan: rule.FilterSizeGreaterThan,
SizeLessThan: rule.FilterSizeLessThan,
ExpirationDays: rule.ExpirationDays,
ExpiredObjectDeleteMarker: rule.ExpiredObjectDeleteMarker,
NoncurrentVersionExpirationDays: rule.NoncurrentVersionExpirationDays,
NewerNoncurrentVersions: rule.NewerNoncurrentVersions,
AbortMultipartDays: rule.AbortMPUDaysAfterInitiation,
}
if !rule.ExpirationDate.IsZero() {
out.ExpirationDate = rule.ExpirationDate.Format(time.DateOnly)
}
return out
}
// CreateS3Bucket creates a new S3 bucket
func (s *AdminServer) CreateS3Bucket(bucketName string) error {
return s.CreateS3BucketWithQuota(bucketName, 0, false)
@@ -1812,6 +1881,24 @@ func extractVersioningFromEntry(entry *filer_pb.Entry) string {
return s3api.GetVersioningStatus(entry)
}
func extractLifecycleCountsFromEntry(entry *filer_pb.Entry) (ruleCount, enabledCount int) {
xmlBytes := entry.Extended[scheduler.BucketLifecycleConfigurationXMLKey]
if len(xmlBytes) == 0 {
return
}
rules, err := lifecycle_xml.ParseCanonical(xmlBytes)
if err != nil {
return
}
for _, rule := range rules {
ruleCount++
if rule.Status == s3lifecycle.StatusEnabled {
enabledCount++
}
}
return
}
// GetConfigPersistence returns the config persistence manager
func (as *AdminServer) GetConfigPersistence() *ConfigPersistence {
return as.configPersistence
+26
View File
@@ -9,6 +9,7 @@ import (
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
@@ -84,6 +85,23 @@ func (s *AdminServer) ShowBucketDetails(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, details)
}
// ShowBucketLifecycle returns the lifecycle configuration for a specific bucket
func (s *AdminServer) ShowBucketLifecycle(w http.ResponseWriter, r *http.Request) {
bucketName := mux.Vars(r)["bucket"]
if bucketName == "" {
writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
return
}
lifecycle, err := s.GetBucketLifecycle(bucketName)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to get bucket lifecycle: "+err.Error())
return
}
writeJSON(w, http.StatusOK, lifecycle)
}
// CreateBucket creates a new S3 bucket
func (s *AdminServer) CreateBucket(w http.ResponseWriter, r *http.Request) {
var req CreateBucketRequest
@@ -397,6 +415,14 @@ func (s *AdminServer) SetBucketQuota(bucketName string, quotaBytes int64, quotaE
return fmt.Errorf("failed to update bucket quota: %w", err)
}
if quota <= 0 {
// with no active quota, quota enforcement can no longer clear a
// read-only flag it turned on, so lift it here
if _, err := filer.ClearBucketReadOnly(context.Background(), client, "/buckets", bucketName); err != nil {
return fmt.Errorf("failed to clear bucket read-only flag: %w", err)
}
}
return nil
})
}
+24
View File
@@ -85,6 +85,9 @@ type S3Bucket struct {
ObjectLockMode string `json:"object_lock_mode"` // Object lock mode: "GOVERNANCE" or "COMPLIANCE"
ObjectLockDuration int32 `json:"object_lock_duration"` // Default retention duration in days
Owner string `json:"owner,omitempty"` // Bucket owner identity; empty means admin-only access
LifecycleRuleCount int `json:"lifecycle_rule_count"`
LifecycleEnabledCount int `json:"lifecycle_enabled_count"`
}
type S3Object struct {
@@ -100,6 +103,27 @@ type BucketDetails struct {
UpdatedAt time.Time `json:"updated_at"`
}
type BucketLifecycleRule struct {
ID string `json:"id,omitempty"`
Status string `json:"status"`
Prefix string `json:"prefix,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
SizeGreaterThan int64 `json:"size_greater_than,omitempty"`
SizeLessThan int64 `json:"size_less_than,omitempty"`
ExpirationDays int `json:"expiration_days,omitempty"`
ExpirationDate string `json:"expiration_date,omitempty"`
ExpiredObjectDeleteMarker bool `json:"expired_object_delete_marker,omitempty"`
NoncurrentVersionExpirationDays int `json:"noncurrent_version_expiration_days,omitempty"`
NewerNoncurrentVersions int `json:"newer_noncurrent_versions,omitempty"`
AbortMultipartDays int `json:"abort_multipart_days,omitempty"`
}
type BucketLifecycle struct {
Bucket string `json:"bucket"`
Rules []BucketLifecycleRule `json:"rules"`
XML string `json:"xml,omitempty"`
}
// ObjectStoreUser is defined in admin_data.go
// Volume management structures
+1
View File
@@ -178,6 +178,7 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
s3Api.Handle("/buckets", wrapWrite(h.adminServer.CreateBucket)).Methods(http.MethodPost)
s3Api.Handle("/buckets/{bucket}", wrapWrite(h.adminServer.DeleteBucket)).Methods(http.MethodDelete)
s3Api.HandleFunc("/buckets/{bucket}", h.adminServer.ShowBucketDetails).Methods(http.MethodGet)
s3Api.HandleFunc("/buckets/{bucket}/lifecycle", h.adminServer.ShowBucketLifecycle).Methods(http.MethodGet)
s3Api.Handle("/buckets/{bucket}/quota", wrapWrite(h.adminServer.UpdateBucketQuota)).Methods(http.MethodPut)
s3Api.Handle("/buckets/{bucket}/owner", wrapWrite(h.adminServer.UpdateBucketOwner)).Methods(http.MethodPut)
+207 -1
View File
@@ -150,6 +150,7 @@ templ S3Buckets(data dash.S3BucketsData) {
<th>Quota</th>
<th>Versioning</th>
<th>Object Lock</th>
<th>Lifecycle</th>
<th>Actions</th>
</tr>
</thead>
@@ -232,6 +233,28 @@ templ S3Buckets(data dash.S3BucketsData) {
<span class="text-muted">Not configured</span>
}
</td>
<td>
if bucket.LifecycleRuleCount > 0 {
<div>
<button type="button" class="badge bg-primary border-0 lifecycle-btn"
data-bucket-name={bucket.Name}
title="View Lifecycle Rules">
if bucket.LifecycleRuleCount == 1 {
1 rule
} else {
{fmt.Sprintf("%d rules", bucket.LifecycleRuleCount)}
}
</button>
if bucket.LifecycleEnabledCount < bucket.LifecycleRuleCount {
<div class="small text-muted">
{fmt.Sprintf("%d enabled", bucket.LifecycleEnabledCount)}
</div>
}
</div>
} else {
<span class="text-muted">Not configured</span>
}
</td>
<td>
<div class="btn-group btn-group-sm" role="group">
<a href={dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name))}
@@ -239,12 +262,18 @@ templ S3Buckets(data dash.S3BucketsData) {
title="Browse Files">
<i class="fas fa-folder-open"></i>
</a>
<button type="button"
<button type="button"
class="btn btn-outline-primary btn-sm view-details-btn"
data-bucket-name={bucket.Name}
title="View Details">
<i class="fas fa-eye"></i>
</button>
<button type="button"
class="btn btn-outline-secondary btn-sm lifecycle-btn"
data-bucket-name={bucket.Name}
title="Lifecycle Rules">
<i class="fas fa-recycle"></i>
</button>
<button type="button"
class="btn btn-outline-info btn-sm owner-btn"
data-bucket-name={bucket.Name}
@@ -606,6 +635,26 @@ templ S3Buckets(data dash.S3BucketsData) {
</div>
</div>
<!-- Bucket Lifecycle Modal -->
<div class="modal fade" id="bucketLifecycleModal" tabindex="-1" aria-labelledby="bucketLifecycleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="bucketLifecycleModalLabel">
<i class="fas fa-recycle me-2"></i>Lifecycle
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="bucketLifecycleContent"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Manage Owner Modal -->
<div class="modal fade" id="manageOwnerModal" tabindex="-1" aria-labelledby="manageOwnerModalLabel" aria-hidden="true">
<div class="modal-dialog">
@@ -659,6 +708,8 @@ templ S3Buckets(data dash.S3BucketsData) {
let quotaModalInstance = null;
let ownerModalInstance = null;
let detailsModalInstance = null;
let lifecycleModalInstance = null;
let lifecycleRequestSeq = 0;
let cachedUsers = null;
document.addEventListener('DOMContentLoaded', function() {
@@ -676,6 +727,7 @@ templ S3Buckets(data dash.S3BucketsData) {
quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));
ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));
detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));
lifecycleModalInstance = new bootstrap.Modal(document.getElementById('bucketLifecycleModal'));
const quotaCheckbox = document.getElementById('enableQuota');
const quotaSettings = document.getElementById('quotaSettings');
@@ -1016,6 +1068,52 @@ templ S3Buckets(data dash.S3BucketsData) {
});
});
});
// Lifecycle buttons: column badge and action button
document.querySelectorAll('.lifecycle-btn').forEach(button => {
button.addEventListener('click', function() {
const bucketName = this.dataset.bucketName;
document.getElementById('bucketLifecycleModalLabel').innerHTML =
'<i class="fas fa-recycle me-2"></i>Lifecycle - ' + bucketName;
document.getElementById('bucketLifecycleContent').innerHTML =
'<div class="text-center py-4">' +
'<div class="spinner-border text-primary" role="status">' +
'<span class="visually-hidden">Loading...</span>' +
'<\/div>' +
'<div class="mt-2">Loading lifecycle rules...</div>' +
'<\/div>';
lifecycleModalInstance.show();
// Drop responses that arrive after another bucket was opened
const requestSeq = ++lifecycleRequestSeq;
fetch(basePath('/api/s3/buckets/' + bucketName + '/lifecycle'))
.then(response => response.json())
.then(data => {
if (requestSeq !== lifecycleRequestSeq) return;
if (data.error) {
document.getElementById('bucketLifecycleContent').innerHTML =
'<div class="alert alert-danger">' +
'<i class="fas fa-exclamation-triangle me-2"></i>' +
'Error loading lifecycle rules: ' + data.error +
'<\/div>';
} else {
displayBucketLifecycle(data);
}
})
.catch(error => {
if (requestSeq !== lifecycleRequestSeq) return;
console.error('Error fetching bucket lifecycle:', error);
document.getElementById('bucketLifecycleContent').innerHTML =
'<div class="alert alert-danger">' +
'<i class="fas fa-exclamation-triangle me-2"></i>' +
'Error loading lifecycle rules: ' + error.message +
'<\/div>';
});
});
});
});
function deleteBucket() {
@@ -1134,6 +1232,114 @@ function displayBucketDetails(data) {
document.getElementById('bucketDetailsContent').innerHTML = rows.join('');
}
function displayBucketLifecycle(data) {
function escapeHtml(v) {
return String(v ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function days(n) {
return n + (n === 1 ? ' day' : ' days');
}
const rules = data.rules || [];
if (rules.length === 0) {
document.getElementById('bucketLifecycleContent').innerHTML =
'<div class="text-center text-muted py-4">No lifecycle configuration<\/div>';
return;
}
function describeScope(rule) {
const parts = [];
if (rule.prefix) {
parts.push('<code>' + escapeHtml(rule.prefix) + '<\/code>');
}
Object.entries(rule.tags || {}).forEach(([k, v]) => {
parts.push('<span class="badge bg-light text-dark border">' + escapeHtml(k) + '=' + escapeHtml(v) + '<\/span>');
});
if (rule.size_greater_than) {
parts.push('size &gt; ' + formatBytes(rule.size_greater_than));
}
if (rule.size_less_than) {
parts.push('size &lt; ' + formatBytes(rule.size_less_than));
}
return parts.length ? parts.join(' ') : '<span class="text-muted">Whole bucket<\/span>';
}
function describeActions(rule) {
const actions = [];
if (rule.expiration_days) {
actions.push('Expire after ' + days(rule.expiration_days));
}
if (rule.expiration_date) {
actions.push('Expire on ' + escapeHtml(rule.expiration_date));
}
if (rule.expired_object_delete_marker) {
actions.push('Remove expired object delete markers');
}
if (rule.noncurrent_version_expiration_days) {
let action = 'Expire noncurrent versions after ' + days(rule.noncurrent_version_expiration_days);
if (rule.newer_noncurrent_versions) {
action += ', keep ' + rule.newer_noncurrent_versions + ' newest';
}
actions.push(action);
}
if (rule.abort_multipart_days) {
actions.push('Abort incomplete multipart uploads after ' + days(rule.abort_multipart_days));
}
if (actions.length === 0) {
return '<span class="text-muted">None<\/span>';
}
return actions.join('<br>');
}
const rows = [
'<div class="table-responsive">',
'<table class="table table-sm">',
'<thead><tr><th>Rule<\/th><th>Status<\/th><th>Scope<\/th><th>Actions<\/th><\/tr><\/thead>',
'<tbody>'
];
rules.forEach(rule => {
const statusHtml = rule.status === 'Enabled'
? '<span class="badge bg-success">Enabled<\/span>'
: '<span class="badge bg-secondary">' + escapeHtml(rule.status) + '<\/span>';
rows.push(
'<tr>' +
'<td>' + (rule.id ? escapeHtml(rule.id) : '<span class="text-muted">unnamed<\/span>') + '<\/td>' +
'<td>' + statusHtml + '<\/td>' +
'<td>' + describeScope(rule) + '<\/td>' +
'<td>' + describeActions(rule) + '<\/td>' +
'<\/tr>'
);
});
rows.push('<\/tbody>', '<\/table>', '<\/div>');
if (data.xml) {
rows.push(
'<details class="mt-2">',
'<summary class="text-muted small">Raw XML<\/summary>',
'<pre class="bg-light border rounded p-2 mt-2 small mb-0">' + escapeHtml(data.xml) + '<\/pre>',
'<\/details>'
);
}
document.getElementById('bucketLifecycleContent').innerHTML = rows.join('');
}
function goToPage(page) {
const url = new URL(window.location);
url.searchParams.set('page', page);
+267 -183
View File
@@ -153,7 +153,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</a></th><th>Quota</th><th>Versioning</th><th>Object Lock</th><th>Actions</th></tr></thead> <tbody>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</a></th><th>Quota</th><th>Versioning</th><th>Object Lock</th><th>Lifecycle</th><th>Actions</th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -165,7 +165,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var5 templ.SafeURL
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 160, Col: 124}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 161, Col: 124}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -178,7 +178,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 163, Col: 64}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 164, Col: 64}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
@@ -206,7 +206,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 174, Col: 101}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 175, Col: 101}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -229,7 +229,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 180, Col: 92}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 181, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -242,7 +242,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.LogicalSize))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 182, Col: 85}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 183, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -260,7 +260,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1fx overhead", float64(bucket.PhysicalSize)/float64(bucket.LogicalSize)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 185, Col: 144}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 186, Col: 144}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -278,7 +278,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.PhysicalSize))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 189, Col: 81}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 190, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
@@ -318,7 +318,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 194, Col: 86}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 195, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
@@ -336,7 +336,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.LogicalSize)/float64(bucket.Quota)*100))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 198, Col: 146}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 199, Col: 146}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
@@ -394,7 +394,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 228, Col: 82}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 229, Col: 82}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
@@ -407,7 +407,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 228, Col: 138}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 229, Col: 138}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -423,296 +423,380 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "</td><td>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 templ.SafeURL
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 237, Col: 128}
if bucket.LifecycleRuleCount > 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "<div><button type=\"button\" class=\"badge bg-primary border-0 lifecycle-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 240, Col: 93}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\" title=\"View Lifecycle Rules\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if bucket.LifecycleRuleCount == 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "1 rule")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d rules", bucket.LifecycleRuleCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 245, Col: 115}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</button> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if bucket.LifecycleEnabledCount < bucket.LifecycleRuleCount {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<div class=\"small text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d enabled", bucket.LifecycleEnabledCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 250, Col: 120}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "<span class=\"text-muted\">Not configured</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "</td><td><div class=\"btn-group btn-group-sm\" role=\"group\"><a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
var templ_7745c5c3_Var21 templ.SafeURL
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 244, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 250, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\" data-current-owner=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 251, Col: 92}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 260, Col: 128}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "\" class=\"btn btn-outline-success btn-sm\" title=\"Browse Files\"><i class=\"fas fa-folder-open\"></i></a> <button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 257, Col: 89}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 267, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "\" data-current-quota=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "\" title=\"View Details\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm lifecycle-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 258, Col: 125}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 273, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "\" data-quota-enabled=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "\" title=\"Lifecycle Rules\"><i class=\"fas fa-recycle\"></i></button> <button type=\"button\" class=\"btn btn-outline-info btn-sm owner-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 259, Col: 118}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 279, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "\" data-current-owner=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 265, Col: 89}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 280, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.Buckets) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "<tr><td colspan=\"10\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "</tbody></table></div><!-- Pagination Controls -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "<div class=\"d-flex justify-content-between align-items-center mt-3\"><small class=\"text-muted\">Showing ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "\" title=\"Manage Owner\"><i class=\"fas fa-user-edit\"></i></button> <button type=\"button\" class=\"btn btn-outline-warning btn-sm quota-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 297, Col: 101}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 286, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, " to ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "\" data-current-quota=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 297, Col: 185}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 287, Col: 125}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, " of ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "\" data-quota-enabled=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 297, Col: 229}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 288, Col: 118}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, " buckets</small><nav aria-label=\"Buckets pagination\"><ul class=\"pagination pagination-sm mb-0\"><!-- Previous Button -->")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" title=\"Manage Quota\"><i class=\"fas fa-tachometer-alt\"></i></button> <button type=\"button\" class=\"btn btn-outline-danger btn-sm delete-bucket-btn\" data-bucket-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 294, Col: 89}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "\" title=\"Delete Bucket\"><i class=\"fas fa-trash\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.Buckets) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<tr><td colspan=\"10\" class=\"text-center text-muted py-4\"><i class=\"fas fa-cube fa-3x mb-3 text-muted\"></i><div><h5>No Object Store buckets found</h5><p>Create your first bucket to get started with S3 storage.</p><button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#createBucketModal\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "</tbody></table></div><!-- Pagination Controls -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "<div class=\"d-flex justify-content-between align-items-center mt-3\"><small class=\"text-muted\">Showing ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 326, Col: 101}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, " to ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 326, Col: 185}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, " of ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 326, Col: 229}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, " buckets</small><nav aria-label=\"Buckets pagination\"><ul class=\"pagination pagination-sm mb-0\"><!-- Previous Button -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 304, Col: 142}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-left\"></i></span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "<!-- Page Numbers -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for i := maxInt(1, data.CurrentPage-2); i <= minInt(data.TotalPages, data.CurrentPage+2); i++ {
if i == data.CurrentPage {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<li class=\"page-item active\"><span class=\"page-link\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 320, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 324, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 324, Col: 152}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "<!-- Next Button -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage < data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 332, Col: 142}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 333, Col: 142}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-right\"></i></span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-left\"></i></span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</ul></nav></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "<!-- Page Numbers -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for i := maxInt(1, data.CurrentPage-2); i <= minInt(data.TotalPages, data.CurrentPage+2); i++ {
if i == data.CurrentPage {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "<li class=\"page-item active\"><span class=\"page-link\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 349, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 353, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 353, Col: 152}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<!-- Next Button -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage < data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var37 string
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 361, Col: 142}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-right\"></i></span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "</ul></nav></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "</div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "</div></div></div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 357, Col: 81}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 386, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+59 -11
View File
@@ -17,6 +17,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/replication/repl_util"
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
"github.com/seaweedfs/seaweedfs/weed/replication/sink/filersink"
"github.com/seaweedfs/seaweedfs/weed/replication/source"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -207,6 +208,10 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
glog.V(0).Infof("got 404 error for %s, ignore it: %s", getSourceKey(resp), err.Error())
return nil
}
if isSourceLookupError(err) && eventSourceSuperseded(filerSource, resp) {
glog.V(0).Infof("source superseded %s during lookup failure, skip it: %s", getSourceKey(resp), err.Error())
return nil
}
return err
}
} else {
@@ -271,22 +276,57 @@ func getSourceKey(resp *filer_pb.SubscribeMetadataResponse) string {
return ""
}
// isIgnorable404 returns true if the error represents a 404/not-found condition
// that should be silently ignored during backup. This covers:
// - errors wrapping http.ErrNotFound (direct volume server 404 via non-S3 sinks)
// - errors containing the "404 Not Found: not found" status string (S3 sink path
// where AWS SDK breaks the errors.Is unwrap chain)
// - LookupFileId or volume-id-not-found errors from the volume id map
// isIgnorable404 returns true only for a genuine source-side 404, where skipping
// the event is lossless: errors wrapping http.ErrNotFound, or carrying the S3
// "404 Not Found: not found" status string (the AWS SDK breaks the unwrap chain).
// It deliberately does not match "LookupFileId" / "volume id ... not found" —
// usually transient lookup races whose skip drops live files; those are resolved
// against the live source instead (isSourceLookupError + eventSourceSuperseded).
func isIgnorable404(err error) bool {
if err == nil {
return false
}
if errors.Is(err, http.ErrNotFound) {
return true
}
return strings.Contains(err.Error(), ignorable404ErrString)
}
// isSourceLookupError reports whether err is a source volume-lookup failure.
// The same strings cover a transient race and a permanently gone volume, so
// the caller must consult the live source to pick skip or retry.
func isSourceLookupError(err error) bool {
if err == nil {
return false
}
errStr := err.Error()
return strings.Contains(errStr, ignorable404ErrString) ||
strings.Contains(errStr, "LookupFileId") ||
return strings.Contains(errStr, "LookupFileId") ||
(strings.Contains(errStr, "volume id") && strings.Contains(errStr, "not found"))
}
// eventSourceSuperseded reports whether the live source has moved past the
// version carried by this event (entry gone or strictly newer), making a skip
// lossless. Without a NewEntry it reports false so the error propagates.
func eventSourceSuperseded(filerSource *source.FilerSource, resp *filer_pb.SubscribeMetadataResponse) bool {
sourcePath, mtimeNs, ok := eventSupersessionProbe(resp)
if !ok {
return false
}
return filersink.SourceSupersedes(context.Background(), filerSource, sourcePath, mtimeNs)
}
// eventSupersessionProbe derives the source path and replayed mtime of the
// event's landing entry. Legacy events can carry an empty NewParentPath, so the
// path comes from MetadataEventTargetFullPath (falls back to resp.Directory) —
// a wrong path here would read as "gone" and skip a live file.
func eventSupersessionProbe(resp *filer_pb.SubscribeMetadataResponse) (util.FullPath, int64, bool) {
if resp == nil || resp.EventNotification == nil || resp.EventNotification.NewEntry == nil {
return "", 0, false
}
return util.FullPath(filer_pb.MetadataEventTargetFullPath(resp)),
filersink.EntryMtimeNs(resp.EventNotification.NewEntry), true
}
// persistSnapshotOffset writes the snapshot high-water mark to the source
// filer's KV, retrying a few times with exponential backoff on transient
// errors. Losing this write forces a full re-walk on the next retry loop
@@ -386,9 +426,17 @@ func runInitialSnapshot(
// -ignore404Error is set; apply the same policy here so the walk
// doesn't abort (and trigger a full re-walk on retry) just because
// a single entry disappeared mid-snapshot.
if ignore404Error && isIgnorable404(err) {
glog.V(0).Infof("initialSnapshot: source entry %s disappeared, ignore it: %s", sourceKey, err.Error())
return nil
if ignore404Error {
if isIgnorable404(err) {
glog.V(0).Infof("initialSnapshot: source entry %s disappeared, ignore it: %s", sourceKey, err.Error())
return nil
}
// Same decision as the follow phase; lossless because the
// post-walk subscription replays the newer change.
if isSourceLookupError(err) && filersink.SourceSupersedes(ctx, filerSource, sourceKey, filersink.EntryMtimeNs(entry)) {
glog.V(0).Infof("initialSnapshot: source superseded %s mid-walk, skip it: %s", sourceKey, err.Error())
return nil
}
}
return fmt.Errorf("seed %s: %w", targetKey, err)
}
+135
View File
@@ -77,6 +77,141 @@ func TestIsIgnorable404_NonIgnorableError(t *testing.T) {
}
}
// Regression for the partial-landing swallow: transient volume-lookup races
// ("LookupFileId ... failed", "volume id N not found") raised while replicating
// a checkpoint write burst must NOT be classified as a genuine source 404.
// They previously matched isIgnorable404 by substring, so the event was treated
// as a deletion — the subscription offset advanced and the file (typically a
// large manifest-backed .pt) was never replicated, with no error logged. They
// are now propagated so the offset stays put and the event is reprocessed; only
// a genuinely-gone source (verified live by the filer sink) is ever skipped.
func TestIsIgnorable404_TransientLookupNotSwallowed(t *testing.T) {
cases := []struct {
name string
err error
}{
{
"lookup file id race",
fmt.Errorf("create entry1 : %w",
fmt.Errorf("replicate manifest data chunks 3,01abc: LookupFileId 3,01abc failed, err: context deadline exceeded")),
},
{
"volume id not found race",
fmt.Errorf("create entry1 : %w",
fmt.Errorf("replicate entry chunks /buckets/x/model.pt: copy 7,02def: read part 7,02def: volume id 7 not found")),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if isIgnorable404(tc.err) {
t.Errorf("transient lookup race must not be ignorable (would swallow a live file): %v", tc.err)
}
if !isSourceLookupError(tc.err) {
t.Errorf("lookup race must classify as a source lookup error (resolved via the live source): %v", tc.err)
}
})
}
}
func TestErrorClassifiersNilSafe(t *testing.T) {
if isIgnorable404(nil) {
t.Error("isIgnorable404(nil) must be false")
}
if isSourceLookupError(nil) {
t.Error("isSourceLookupError(nil) must be false")
}
}
func TestIsSourceLookupError_NonLookupErrors(t *testing.T) {
cases := []struct {
name string
err error
}{
{"genuine S3 404", fmt.Errorf("upload part: 404 Not Found: not found")},
{"network error", fmt.Errorf("dial tcp 10.0.0.1:8080: connection refused")},
{"plain not found without volume id", fmt.Errorf("entry not found")},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if isSourceLookupError(tc.err) {
t.Errorf("must not classify as a source lookup error: %v", tc.err)
}
})
}
}
// Legacy events carry an empty NewParentPath; the probe must fall back to
// resp.Directory instead of building "/<name>", which would read as "gone"
// and skip a live file.
func TestEventSupersessionProbe_PathDerivation(t *testing.T) {
entry := &filer_pb.Entry{
Name: "f",
Attributes: &filer_pb.FuseAttributes{Mtime: 123},
}
cases := []struct {
name string
resp *filer_pb.SubscribeMetadataResponse
want string
}{
{
"legacy event without NewParentPath",
&filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/x",
EventNotification: &filer_pb.EventNotification{NewEntry: entry},
},
"/buckets/x/f",
},
{
"rename event with NewParentPath",
&filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/x",
EventNotification: &filer_pb.EventNotification{
NewParentPath: "/buckets/y",
NewEntry: entry,
},
},
"/buckets/y/f",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
path, mtimeNs, ok := eventSupersessionProbe(tc.resp)
if !ok {
t.Fatal("probe must succeed when NewEntry is present")
}
if string(path) != tc.want {
t.Errorf("path = %q, want %q", path, tc.want)
}
if mtimeNs != 123*int64(1e9) {
t.Errorf("mtimeNs = %d, want %d", mtimeNs, 123*int64(1e9))
}
})
}
}
// When supersession cannot be proven, never skip — that would drop a live file.
func TestEventSourceSuperseded_Guards(t *testing.T) {
if eventSourceSuperseded(nil, nil) {
t.Error("nil response must not be skippable")
}
if eventSourceSuperseded(nil, &filer_pb.SubscribeMetadataResponse{
EventNotification: &filer_pb.EventNotification{},
}) {
t.Error("event without NewEntry must not be skippable")
}
if eventSourceSuperseded(nil, &filer_pb.SubscribeMetadataResponse{
EventNotification: &filer_pb.EventNotification{
NewParentPath: "/buckets/x",
NewEntry: &filer_pb.Entry{
Name: "model.pt",
Attributes: &filer_pb.FuseAttributes{Mtime: 1234567890},
},
},
}) {
t.Error("nil filerSource must not be skippable")
}
}
// stubSink is a minimal ReplicationSink used to exercise initialSnapshotTargetKey
// without standing up a real sink. Only the two methods read by the key builder
// (GetName, IsIncremental) need meaningful behavior; the rest satisfy the interface.
+4
View File
@@ -29,6 +29,7 @@ import (
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/util/version"
)
@@ -524,6 +525,9 @@ func (s3opt *S3Options) startS3Server() bool {
// startIcebergServer starts the Iceberg REST Catalog server on a separate port.
func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
icebergRouter := mux.NewRouter().SkipClean(true)
// warehouse/parent query values may legally contain ';', which Go's
// url.ParseQuery would otherwise drop
icebergRouter.Use(util_http.EscapeSemicolonsInQuery)
// Create Iceberg server using the S3ApiServer as filer client
icebergServer := iceberg.NewServer(s3ApiServer, s3ApiServer)
+3 -1
View File
@@ -3,6 +3,7 @@ package cassandra
import (
"context"
"encoding/base64"
"errors"
"fmt"
gocql "github.com/apache/cassandra-gocql-driver/v2"
@@ -27,9 +28,10 @@ func (store *CassandraStore) KvGet(ctx context.Context, key []byte) (data []byte
if err := store.session.Query(
"SELECT meta FROM filemeta WHERE directory=? AND name=?",
dir, name).Scan(&data); err != nil {
if err != gocql.ErrNotFound {
if errors.Is(err, gocql.ErrNotFound) {
return nil, filer.ErrKvNotFound
}
return nil, fmt.Errorf("kv get: %w", err)
}
if len(data) == 0 {
+3 -1
View File
@@ -3,6 +3,7 @@ package cassandra2
import (
"context"
"encoding/base64"
"errors"
"fmt"
gocql "github.com/apache/cassandra-gocql-driver/v2"
@@ -28,9 +29,10 @@ func (store *Cassandra2Store) KvGet(ctx context.Context, key []byte) (data []byt
if err := store.session.Query(
"SELECT meta FROM filemeta WHERE dirhash=? AND directory=? AND name=?",
util.HashStringToLong(dir), dir, name).Scan(&data); err != nil {
if err != gocql.ErrNotFound {
if errors.Is(err, gocql.ErrNotFound) {
return nil, filer.ErrKvNotFound
}
return nil, fmt.Errorf("kv get: %w", err)
}
if len(data) == 0 {
+43
View File
@@ -262,6 +262,49 @@ func (fc *FilerConf) ApplyBucketQuotaReadOnly(locationPrefix string, usedSize, q
return locConf.ReadOnly, true
}
// ClearReadOnly clears the read-only flag on the rule at exactly locationPrefix,
// reporting whether the flag was set. This is the explicit unlock for a flag that
// ApplyBucketQuotaReadOnly can no longer clear once the quota is gone.
func (fc *FilerConf) ClearReadOnly(locationPrefix string) (changed bool) {
locConf, found := fc.GetLocationConf(locationPrefix)
if !found || !locConf.ReadOnly {
return false
}
locConf.ReadOnly = false
fc.SetLocationConf(locConf)
return true
}
// ClearBucketReadOnly lifts the read-only flag that quota enforcement may have
// left on the bucket's path rule, saving the updated configuration back to the
// filer. It reports whether anything was cleared.
func ClearBucketReadOnly(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketsPath, bucketName string) (changed bool, err error) {
data, err := ReadInsideFiler(ctx, client, DirectoryEtcSeaweedFS, FilerConfName)
if err == filer_pb.ErrNotFound || (err == nil && len(data) == 0) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("read %s/%s: %v", DirectoryEtcSeaweedFS, FilerConfName, err)
}
fc := NewFilerConf()
if err = fc.LoadFromBytes(data); err != nil {
return false, fmt.Errorf("parse %s/%s: %v", DirectoryEtcSeaweedFS, FilerConfName, err)
}
// join the rule key exactly as s3.bucket.quota.enforce writes it, so the
// exact-match lookup finds the rule even for a non-canonical bucketsPath
if !fc.ClearReadOnly(bucketsPath + "/" + bucketName + "/") {
return false, nil
}
var buf bytes.Buffer
if err = fc.ToText(&buf); err != nil {
return false, err
}
if err = SaveInsideFiler(ctx, client, DirectoryEtcSeaweedFS, FilerConfName, buf.Bytes()); err != nil {
return false, err
}
return true, nil
}
func (fc *FilerConf) GetCollectionTtls(collection string) (ttls map[string]string) {
ttls = make(map[string]string)
fc.rules.Walk(func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
+21
View File
@@ -161,3 +161,24 @@ func TestApplyBucketQuotaReadOnly(t *testing.T) {
_, changed = fc.ApplyBucketQuotaReadOnly(prefix, 50, 100)
assert.False(t, changed)
}
func TestClearReadOnly(t *testing.T) {
const prefix = "/buckets/b/"
fc := NewFilerConf()
assert.False(t, fc.ClearReadOnly(prefix), "no rule to clear")
// locked by quota enforcement, then quota removed: still clearable
fc.ApplyBucketQuotaReadOnly(prefix, 150, 100)
assert.True(t, fc.ClearReadOnly(prefix))
assert.False(t, fc.MatchStorageRule(prefix).ReadOnly)
assert.False(t, fc.ClearReadOnly(prefix), "already writable")
// clearing the flag keeps the rule's other settings
fc = NewFilerConf()
fc.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: prefix, Ttl: "7d", ReadOnly: true})
assert.True(t, fc.ClearReadOnly(prefix))
rule := fc.MatchStorageRule(prefix)
assert.False(t, rule.ReadOnly)
assert.Equal(t, "7d", rule.Ttl)
}
+4
View File
@@ -7,6 +7,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -63,6 +64,9 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
if isDeleteCollection {
collectionName := entry.Name()
f.DoDeleteCollection(collectionName)
// drop bucket-labeled series held by this process; the S3 gateway
// only cleans its own registry
stats.DeleteBucketMetrics(collectionName)
}
return nil
+2 -1
View File
@@ -90,7 +90,8 @@ func (f *Filer) maybeLazyFetchFromRemote(ctx context.Context, p util.FullPath) (
Mode: 0644,
FileSize: uint64(remoteEntry.RemoteSize),
},
Remote: remoteEntry,
Extended: MergeRemoteContentEncoding(remoteEntry, nil),
Remote: remoteEntry,
}
persistBaseCtx, cancelPersist := context.WithTimeout(context.Background(), 30*time.Second)
+3 -1
View File
@@ -113,6 +113,7 @@ func (f *Filer) maybeLazyListFromRemote(ctx context.Context, p util.FullPath) {
existingEntry.Attr.Mtime = time.Unix(remoteEntry.RemoteMtime, 0)
}
existingEntry.Attr.FileSize = uint64(remoteEntry.RemoteSize)
existingEntry.Extended = MergeRemoteContentEncoding(remoteEntry, existingEntry.Extended)
}
if saveErr := f.Store.UpdateEntry(persistCtx, existingEntry); saveErr != nil {
glog.Warningf("maybeLazyListFromRemote: update %s: %v", childPath, saveErr)
@@ -146,7 +147,8 @@ func (f *Filer) maybeLazyListFromRemote(ctx context.Context, p util.FullPath) {
Uid: OS_UID,
Gid: OS_GID,
},
Remote: remoteEntry,
Extended: MergeRemoteContentEncoding(remoteEntry, nil),
Remote: remoteEntry,
}
if remoteEntry != nil {
entry.Attr.FileSize = uint64(remoteEntry.RemoteSize)
+9 -5
View File
@@ -24,6 +24,7 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
)
// --- minimal FilerStore stub ---
@@ -304,7 +305,7 @@ func registerStubMaker(t *testing.T, storageType string, client remote_storage.R
func TestMaybeLazyFetchFromRemote_HitsRemoteAndPersists(t *testing.T) {
const storageType = "stub_lazy_hit"
stub := &stubRemoteClient{
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 1234},
statResult: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 1234, RemoteContentEncoding: proto.String("zstd")},
}
defer registerStubMaker(t, storageType, stub)()
@@ -331,6 +332,7 @@ func TestMaybeLazyFetchFromRemote_HitsRemoteAndPersists(t *testing.T) {
stored, sErr := store.FindEntry(context.Background(), "/buckets/mybucket/file.txt")
require.NoError(t, sErr)
assert.Equal(t, int64(1234), stored.Remote.RemoteSize)
assert.Equal(t, []byte("zstd"), stored.Extended["Content-Encoding"])
}
func TestMaybeLazyFetchFromRemote_NotUnderMount(t *testing.T) {
@@ -849,10 +851,11 @@ func TestMaybeLazyListFromRemote_PopulatesStoreFromRemote(t *testing.T) {
return err
}
if err := visitFn("/", "file.txt", false, &filer_pb.RemoteEntry{
RemoteMtime: 1700000000,
RemoteSize: 42,
RemoteETag: "abc",
StorageName: "myliststore",
RemoteMtime: 1700000000,
RemoteSize: 42,
RemoteETag: "abc",
StorageName: "myliststore",
RemoteContentEncoding: proto.String("gzip"),
}); err != nil {
return err
}
@@ -882,6 +885,7 @@ func TestMaybeLazyListFromRemote_PopulatesStoreFromRemote(t *testing.T) {
require.NotNil(t, fileEntry, "file.txt should be persisted")
assert.Equal(t, uint64(42), fileEntry.FileSize)
assert.NotNil(t, fileEntry.Remote)
assert.Equal(t, []byte("gzip"), fileEntry.Extended["Content-Encoding"])
// Check that the subdirectory was persisted
dirEntry := store.getEntry("/buckets/mybucket/subdir")
+3 -5
View File
@@ -11,13 +11,11 @@ import (
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
)
type LogFileEntry struct {
@@ -518,7 +516,7 @@ func (iter *LogFileIterator) getNext() (logEntry *filer_pb.LogEntry, err error)
return nil, fmt.Errorf("entry data %d bytes, expected %d bytes", n, size)
}
logEntry = &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
if err = logEntry.UnmarshalVT(entryData); err != nil {
return
}
if logEntry.TsNs <= iter.startTsNs {
+31
View File
@@ -0,0 +1,31 @@
package filer
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestDetectBucket(t *testing.T) {
tests := []struct {
name string
fullPath string
bucketsPath string
want string
}{
{"object in bucket", "/buckets/mybucket/a/b.txt", "/buckets", "mybucket"},
{"bucket root", "/buckets/mybucket", "/buckets", "mybucket"},
{"not under buckets path", "/other/path/x", "/buckets", ""},
{"buckets path itself", "/buckets", "/buckets", ""},
{"custom buckets path", "/data/buckets/mybucket/x", "/data/buckets", "mybucket"},
{"nested object", "/buckets/b/deep/nested/key", "/buckets", "b"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &Filer{DirBucketsPath: tt.bucketsPath}
if got := f.DetectBucket(util.FullPath(tt.fullPath)); got != tt.want {
t.Errorf("DetectBucket(%q) with buckets path %q = %q, want %q", tt.fullPath, tt.bucketsPath, got, tt.want)
}
})
}
}
+5 -7
View File
@@ -8,13 +8,11 @@ import (
"sync"
"time"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
const (
@@ -201,10 +199,10 @@ func loadLogFileEntries(masterClient *wdclient.MasterClient, chunk *filer_pb.Fil
// decodeLogRecords parses size-prefixed LogEntry records. A buffer that stops
// mid-record, or whose size prefix is garbage (also the symptom of starting
// mid-record), reports errLogChunkIncomplete with the cleanly decoded prefix.
// Since proto.Unmarshal is permissive enough to accept misaligned bytes,
// Since UnmarshalVT is permissive enough to accept misaligned bytes,
// records must also satisfy the writer's invariants: never empty, a positive
// timestamp, and strictly increasing within one flushed buffer.
// proto.Unmarshal copies all bytes, so the entries do not alias data.
// UnmarshalVT copies all bytes, so the entries do not alias data.
func decodeLogRecords(data []byte) (entries []*filer_pb.LogEntry, cacheable bool, err error) {
var lastTsNs int64
for pos := 0; pos < len(data); {
@@ -220,7 +218,7 @@ func decodeLogRecords(data []byte) (entries []*filer_pb.LogEntry, cacheable bool
return entries, false, errLogChunkIncomplete
}
logEntry := &filer_pb.LogEntry{}
if unmarshalErr := proto.Unmarshal(data[pos+4:pos+4+size], logEntry); unmarshalErr != nil {
if unmarshalErr := logEntry.UnmarshalVT(data[pos+4 : pos+4+size]); unmarshalErr != nil {
return entries, false, errLogChunkIncomplete
}
if logEntry.TsNs <= lastTsNs {
+20
View File
@@ -12,6 +12,26 @@ func (entry *Entry) IsInRemoteOnly() bool {
return len(entry.GetChunks()) == 0 && entry.Remote != nil && entry.Remote.RemoteSize > 0
}
// MergeRemoteContentEncoding stamps the remote object's Content-Encoding into the
// entry extended attributes so HTTP and S3 reads return the header. An unset
// remote value (a listing that does not report encodings) leaves the attribute
// alone; an authoritatively empty one removes it.
func MergeRemoteContentEncoding(remoteEntry *filer_pb.RemoteEntry, extended map[string][]byte) map[string][]byte {
if remoteEntry == nil || remoteEntry.RemoteContentEncoding == nil {
return extended
}
encoding := *remoteEntry.RemoteContentEncoding
if encoding == "" {
delete(extended, "Content-Encoding")
return extended
}
if extended == nil {
extended = make(map[string][]byte)
}
extended["Content-Encoding"] = []byte(encoding)
return extended
}
func MapFullPathToRemoteStorageLocation(localMountedDir util.FullPath, remoteMountedLocation *remote_pb.RemoteStorageLocation, fp util.FullPath) *remote_pb.RemoteStorageLocation {
remoteLocation := &remote_pb.RemoteStorageLocation{
Name: remoteMountedLocation.Name,
+34
View File
@@ -0,0 +1,34 @@
package filer
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
)
func TestMergeRemoteContentEncoding(t *testing.T) {
merged := MergeRemoteContentEncoding(&filer_pb.RemoteEntry{RemoteContentEncoding: proto.String("zstd")}, nil)
assert.Equal(t, []byte("zstd"), merged["Content-Encoding"])
// existing keys are preserved, the encoding is overwritten from remote
merged = MergeRemoteContentEncoding(&filer_pb.RemoteEntry{RemoteContentEncoding: proto.String("gzip")}, map[string][]byte{
"Content-Encoding": []byte("zstd"),
"x-amz-meta-foo": []byte("bar"),
})
assert.Equal(t, []byte("gzip"), merged["Content-Encoding"])
assert.Equal(t, []byte("bar"), merged["x-amz-meta-foo"])
// an unreported encoding (S3 listings) leaves a locally set value alone
local := map[string][]byte{"Content-Encoding": []byte("zstd")}
merged = MergeRemoteContentEncoding(&filer_pb.RemoteEntry{}, local)
assert.Equal(t, []byte("zstd"), merged["Content-Encoding"])
// an authoritatively empty one removes it
merged = MergeRemoteContentEncoding(&filer_pb.RemoteEntry{RemoteContentEncoding: proto.String("")}, local)
assert.NotContains(t, merged, "Content-Encoding")
assert.Nil(t, MergeRemoteContentEncoding(nil, nil))
assert.Nil(t, MergeRemoteContentEncoding(&filer_pb.RemoteEntry{RemoteContentEncoding: proto.String("")}, nil))
}
+4
View File
@@ -22,6 +22,7 @@ import (
. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
@@ -117,6 +118,9 @@ func NewIamApiServerWithStore(router *mux.Router, option *IamServerOption, expli
}
func (iama *IamApiServer) registerRouter(router *mux.Router) {
// SigV4 recomputes the canonical query from the parsed query, so raw ';'
// pairs that Go would drop must be recovered before verification.
router.Use(util_http.EscapeSemicolonsInQuery)
// API Router
apiRouter := router.PathPrefix("/").Subrouter()
apiRouter.Use(request_id.Middleware)
+26 -3
View File
@@ -13,6 +13,7 @@ import (
type ChunkedDirtyPages struct {
fh *FileHandle
writeWaitGroup sync.WaitGroup
lastErrLock sync.Mutex
lastErr error
collection string
replication string
@@ -40,6 +41,12 @@ func newMemoryChunkPages(fh *FileHandle, chunkSize int64) *ChunkedDirtyPages {
}
func (pages *ChunkedDirtyPages) AddPage(offset int64, data []byte, isSequential bool, tsNs int64) error {
// A failed chunk upload already dropped its data, so this handle can never
// flush cleanly. Reject further writes so the writer fails fast instead of
// pushing the rest of the file through a pipeline that cannot persist it.
if err := pages.LastError(); err != nil {
return err
}
pages.hasWrites = true
glog.V(4).Infof("%v memory AddPage [%d, %d)", pages.fh.fh, offset, offset+int64(len(data)))
@@ -53,12 +60,28 @@ func (pages *ChunkedDirtyPages) FlushData() error {
return nil
}
pages.uploadPipeline.FlushAll()
if pages.lastErr != nil {
return fmt.Errorf("flush data: %v", pages.lastErr)
if err := pages.LastError(); err != nil {
return fmt.Errorf("flush data: %w", err)
}
return nil
}
// LastError returns the first chunk upload failure on this handle. It is
// sticky: the failed chunk's data is gone, so the handle stays poisoned.
func (pages *ChunkedDirtyPages) LastError() error {
pages.lastErrLock.Lock()
defer pages.lastErrLock.Unlock()
return pages.lastErr
}
func (pages *ChunkedDirtyPages) setLastError(err error) {
pages.lastErrLock.Lock()
defer pages.lastErrLock.Unlock()
if pages.lastErr == nil {
pages.lastErr = err
}
}
func (pages *ChunkedDirtyPages) ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64) {
if !pages.hasWrites {
return
@@ -75,7 +98,7 @@ func (pages *ChunkedDirtyPages) saveChunkedFileIntervalToStorage(reader io.Reade
chunk, err := pages.fh.wfs.saveDataAsChunk(fileFullPath)(reader, fileName, offset, modifiedTsNs, uint64(size))
if err != nil {
glog.V(0).Infof("%v saveToStorage [%d,%d): %v", fileFullPath, offset, offset+size, err)
pages.lastErr = err
pages.setLastError(err)
return
}
pages.fh.AddChunks([]*filer_pb.FileChunk{chunk})
+31
View File
@@ -0,0 +1,31 @@
package mount
import (
"errors"
"testing"
)
// Once a chunk upload fails its data is gone, so the handle must reject
// further writes instead of buffering the rest of the file — against a full
// cluster that turned cp into an hours-long crawl that only errored at close.
func TestChunkedDirtyPagesFailWritesAfterUploadError(t *testing.T) {
fh := &FileHandle{wfs: &WFS{option: &Option{}}}
pages := newMemoryChunkPages(fh, 1024)
defer pages.Destroy()
pages.hasWrites = true
uploadErr := errors.New("assign volume failure: no writable volumes")
pages.setLastError(uploadErr)
if err := pages.AddPage(0, []byte("x"), true, 1); !errors.Is(err, uploadErr) {
t.Fatalf("AddPage after upload failure = %v, want sticky %v", err, uploadErr)
}
if err := pages.FlushData(); !errors.Is(err, uploadErr) {
t.Fatalf("FlushData after upload failure = %v, want wrapped %v", err, uploadErr)
}
// First failure wins; later errors must not mask the root cause.
pages.setLastError(errors.New("later error"))
if err := pages.LastError(); !errors.Is(err, uploadErr) {
t.Fatalf("LastError = %v, want first error %v", err, uploadErr)
}
}
+22
View File
@@ -48,6 +48,28 @@ func grpcErrorToFuseStatus(err error) fuse.Status {
return fuse.EIO
}
// isStorageFullError reports whether a chunk upload failed because the cluster
// has no writable volume left (disks full and volume growth failed). The
// master's message reaches the mount as plain text inside
// AssignVolumeResponse.Error, so match on text rather than a status code.
func isStorageFullError(err error) bool {
if err == nil {
return false
}
errStr := strings.ToLower(err.Error())
return strings.Contains(errStr, "no writable volumes") ||
strings.Contains(errStr, "no free volumes")
}
// writeErrorToFuseStatus maps a dirty-page write/flush failure to the status
// returned to the kernel: ENOSPC when the cluster is out of space, EIO otherwise.
func writeErrorToFuseStatus(err error) fuse.Status {
if isStorageFullError(err) {
return fuse.Status(syscall.ENOSPC)
}
return fuse.EIO
}
// isRetryableFilerError reports whether a filer RPC error looks transient
// enough to retry. It takes a conservative whitelist approach: only errors
// that clearly describe a permanent application-level failure
+35
View File
@@ -44,6 +44,41 @@ func TestGrpcErrorToFuseStatusDropsCanceledThroughPercentV(t *testing.T) {
}
}
// A full cluster must surface as ENOSPC so cp/rsync abort with "No space left
// on device" instead of a generic I/O error. The master's message reaches the
// mount stringified inside AssignVolumeResponse.Error, in one of two shapes:
// the load-shedding gRPC status text or the topology's plain error text.
func TestWriteErrorToFuseStatus(t *testing.T) {
cases := []struct {
name string
err error
want fuse.Status
}{
{
"assign shed during growth",
errors.New("upload data: filerGrpcAddress assign volume: assign volume failure count:1: assign volume: rpc error: code = ResourceExhausted desc = no writable volumes for replication:000 collection:, volume growth in progress"),
fuse.Status(syscall.ENOSPC),
},
{
"no free volumes left",
errors.New("flush data: upload data: assign volume: No writable volumes available for collection: replication:000 ttl: and no free volumes left for {replication:000}"),
fuse.Status(syscall.ENOSPC),
},
{
"unrelated upload failure",
errors.New("upload data: put http://volume:8080/3,0144: connection reset by peer"),
fuse.EIO,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := writeErrorToFuseStatus(tc.err); got != tc.want {
t.Fatalf("writeErrorToFuseStatus(%v) = %v, want %v", tc.err, got, tc.want)
}
})
}
}
func TestIsRetryableFilerError(t *testing.T) {
cases := []struct {
name string
+1 -1
View File
@@ -186,7 +186,7 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
fhOut.dirtyPages.writerPattern.IsSequentialMode(),
nowUnixNano); err != nil {
glog.Errorf("AddPage error: %v", err)
return 0, fuse.EIO
return 0, writeErrorToFuseStatus(err)
}
// Accumulate for the next loop iteration
+1 -1
View File
@@ -161,7 +161,7 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
if !isOverQuota {
if err := fh.dirtyPages.FlushData(); err != nil {
glog.Errorf("%v doFlush: %v", fileFullPath, err)
return fuse.EIO
return writeErrorToFuseStatus(err)
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
if err := fh.dirtyPages.AddPage(offset, data, fh.dirtyPages.writerPattern.IsSequentialMode(), tsNs); err != nil {
glog.Errorf("AddPage error: %v", err)
return 0, fuse.EIO
return 0, writeErrorToFuseStatus(err)
}
written = uint32(len(data))
+1 -1
View File
@@ -5,7 +5,7 @@ all: gen
gen:
protoc master.proto --go_out=./master_pb --go-grpc_out=./master_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc volume_server.proto --go_out=./volume_server_pb --go-grpc_out=./volume_server_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc filer.proto --go_out=./filer_pb --go-grpc_out=./filer_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc filer.proto --go_out=./filer_pb --go-grpc_out=./filer_pb --go-vtproto_out=./filer_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative --go-vtproto_opt=paths=source_relative,features=marshal+unmarshal+size
protoc remote.proto --go_out=./remote_pb --go-grpc_out=./remote_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc iam.proto --go_out=./iam_pb --go-grpc_out=./iam_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
protoc mount.proto --go_out=./mount_pb --go-grpc_out=./mount_pb --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative
+3
View File
@@ -143,6 +143,9 @@ message RemoteEntry {
string remote_e_tag = 3;
int64 remote_mtime = 4;
int64 remote_size = 5;
// unset when the remote listing does not report encodings (S3);
// empty when the remote object authoritatively has none
optional string remote_content_encoding = 6;
}
message Entry {
string name = 1;
+17 -4
View File
@@ -552,8 +552,11 @@ type RemoteEntry struct {
RemoteETag string `protobuf:"bytes,3,opt,name=remote_e_tag,json=remoteETag,proto3" json:"remote_e_tag,omitempty"`
RemoteMtime int64 `protobuf:"varint,4,opt,name=remote_mtime,json=remoteMtime,proto3" json:"remote_mtime,omitempty"`
RemoteSize int64 `protobuf:"varint,5,opt,name=remote_size,json=remoteSize,proto3" json:"remote_size,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// unset when the remote listing does not report encodings (S3);
// empty when the remote object authoritatively has none
RemoteContentEncoding *string `protobuf:"bytes,6,opt,name=remote_content_encoding,json=remoteContentEncoding,proto3,oneof" json:"remote_content_encoding,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RemoteEntry) Reset() {
@@ -621,6 +624,13 @@ func (x *RemoteEntry) GetRemoteSize() int64 {
return 0
}
func (x *RemoteEntry) GetRemoteContentEncoding() string {
if x != nil && x.RemoteContentEncoding != nil {
return *x.RemoteContentEncoding
}
return ""
}
type Entry struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
@@ -6818,7 +6828,7 @@ const file_filer_proto_rawDesc = "" +
"\x0esnapshot_ts_ns\x18\x06 \x01(\x03R\fsnapshotTsNs\"b\n" +
"\x13ListEntriesResponse\x12%\n" +
"\x05entry\x18\x01 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x12$\n" +
"\x0esnapshot_ts_ns\x18\x02 \x01(\x03R\fsnapshotTsNs\"\xc8\x01\n" +
"\x0esnapshot_ts_ns\x18\x02 \x01(\x03R\fsnapshotTsNs\"\xa1\x02\n" +
"\vRemoteEntry\x12!\n" +
"\fstorage_name\x18\x01 \x01(\tR\vstorageName\x120\n" +
"\x15last_local_sync_ts_ns\x18\x02 \x01(\x03R\x11lastLocalSyncTsNs\x12 \n" +
@@ -6826,7 +6836,9 @@ const file_filer_proto_rawDesc = "" +
"remoteETag\x12!\n" +
"\fremote_mtime\x18\x04 \x01(\x03R\vremoteMtime\x12\x1f\n" +
"\vremote_size\x18\x05 \x01(\x03R\n" +
"remoteSize\"\x89\x04\n" +
"remoteSize\x12;\n" +
"\x17remote_content_encoding\x18\x06 \x01(\tH\x00R\x15remoteContentEncoding\x88\x01\x01B\x1a\n" +
"\x18_remote_content_encoding\"\x89\x04\n" +
"\x05Entry\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12!\n" +
"\fis_directory\x18\x02 \x01(\bR\visDirectory\x12+\n" +
@@ -7719,6 +7731,7 @@ func file_filer_proto_init() {
if File_filer_proto != nil {
return
}
file_filer_proto_msgTypes[4].OneofWrappers = []any{}
file_filer_proto_msgTypes[84].OneofWrappers = []any{
(*StreamMutateEntryRequest_CreateRequest)(nil),
(*StreamMutateEntryRequest_UpdateRequest)(nil),
File diff suppressed because it is too large. Load diff
+265
View File
@@ -0,0 +1,265 @@
package filer_pb
import (
"fmt"
"testing"
"google.golang.org/protobuf/proto"
)
// sampleResponse builds a metadata event exercising the fields touched on the
// hot subscribe path: nested entries, a repeated chunk list, a map, and byte
// fields.
func sampleResponse() *SubscribeMetadataResponse {
entry := func(name string) *Entry {
return &Entry{
Name: name,
IsDirectory: false,
Chunks: []*FileChunk{
{
FileId: "3,01637037d6",
Offset: 0,
Size: 1234,
ModifiedTsNs: 111,
ETag: "abc",
Fid: &FileId{VolumeId: 3, FileKey: 0x1637037, Cookie: 0xd6},
CipherKey: []byte{1, 2, 3, 4},
},
},
Attributes: &FuseAttributes{
FileSize: 1234, Mtime: 222, FileMode: 0644, Uid: 1000, Gid: 1000,
GroupName: []string{"staff", "wheel"}, Md5: []byte{9, 8, 7},
},
Extended: map[string][]byte{
"foo": []byte("bar"),
"baz": []byte("qux"),
"k3": []byte("v3"),
},
Content: []byte("hello"),
}
}
return &SubscribeMetadataResponse{
Directory: "/buckets/test/dir",
EventNotification: &EventNotification{
OldEntry: entry("old.txt"),
NewEntry: entry("new.txt"),
DeleteChunks: true,
NewParentPath: "/buckets/test/dir2",
IsFromOtherCluster: true,
Signatures: []int32{101, 202, 303},
},
TsNs: 1234567890,
}
}
// eventWithChunks models a real create/update event: a file split into n chunks,
// each a nested FileChunk+FileId message. n scales the number of nested messages
// the decoder must allocate, which is where vtproto's edge over reflection grows.
func eventWithChunks(n int) *SubscribeMetadataResponse {
chunks := make([]*FileChunk, n)
for i := 0; i < n; i++ {
chunks[i] = &FileChunk{
FileId: fmt.Sprintf("%d,%08x%04x", i%64, i*7919, i%251),
Offset: int64(i) * 8 << 20,
Size: 8 << 20,
ModifiedTsNs: 1700000000000000000 + int64(i),
ETag: fmt.Sprintf("etag-%d", i),
Fid: &FileId{VolumeId: uint32(i%64 + 1), FileKey: uint64(i * 7919), Cookie: uint32(i % 251)},
}
}
return &SubscribeMetadataResponse{
Directory: "/buckets/data/2026/07/15",
EventNotification: &EventNotification{
NewEntry: &Entry{
Name: "object.bin",
Chunks: chunks,
Attributes: &FuseAttributes{FileSize: uint64(n) * 8 << 20, Mtime: 1700000000, FileMode: 0644, Uid: 1000, Gid: 1000},
},
Signatures: []int32{12345},
},
TsNs: 1700000000000000000,
}
}
// TestVTWireCompatibility guards that the vtproto-generated MarshalVT/UnmarshalVT
// stay wire-compatible with the reflection-based proto path in both directions,
// so adopting VT on the metadata hot paths cannot silently corrupt events.
func TestVTWireCompatibility(t *testing.T) {
orig := sampleResponse()
// vt marshal -> proto unmarshal
vtBytes, err := orig.MarshalVT()
if err != nil {
t.Fatalf("MarshalVT: %v", err)
}
var fromVT SubscribeMetadataResponse
if err := proto.Unmarshal(vtBytes, &fromVT); err != nil {
t.Fatalf("proto.Unmarshal(vtBytes): %v", err)
}
if !proto.Equal(orig, &fromVT) {
t.Fatalf("proto.Unmarshal(MarshalVT) diverged from original")
}
// proto marshal -> vt unmarshal
protoBytes, err := proto.Marshal(orig)
if err != nil {
t.Fatalf("proto.Marshal: %v", err)
}
var fromProto SubscribeMetadataResponse
if err := fromProto.UnmarshalVT(protoBytes); err != nil {
t.Fatalf("UnmarshalVT(protoBytes): %v", err)
}
if !proto.Equal(orig, &fromProto) {
t.Fatalf("UnmarshalVT(proto.Marshal) diverged from original")
}
// MarshalToSizedBufferVT into a pre-sized slice matches MarshalVT, the write
// path used by the log buffer.
sized := make([]byte, orig.SizeVT())
if _, err := orig.MarshalToSizedBufferVT(sized); err != nil {
t.Fatalf("MarshalToSizedBufferVT: %v", err)
}
var fromSized SubscribeMetadataResponse
if err := fromSized.UnmarshalVT(sized); err != nil {
t.Fatalf("UnmarshalVT(sized): %v", err)
}
if !proto.Equal(orig, &fromSized) {
t.Fatalf("MarshalToSizedBufferVT diverged from original")
}
// LogEntry carrying a marshaled event, mirroring the log buffer write path.
le := &LogEntry{TsNs: 7, PartitionKeyHash: 9, Data: vtBytes, Key: []byte("k"), Offset: 42}
leBytes, err := le.MarshalVT()
if err != nil {
t.Fatalf("LogEntry.MarshalVT: %v", err)
}
var leDecoded LogEntry
if err := proto.Unmarshal(leBytes, &leDecoded); err != nil {
t.Fatalf("proto.Unmarshal(LogEntry): %v", err)
}
if !proto.Equal(le, &leDecoded) {
t.Fatalf("LogEntry vt/proto roundtrip diverged")
}
}
// TestUTF8Validation documents the deliberate UTF-8 difference between the two
// decoders. UnmarshalVT skips proto3's UTF-8 validation for string fields, so
// the metadata delivery paths keep decoding SubscribeMetadataResponse with
// proto.Unmarshal; only LogEntry (bytes-only) decodes use UnmarshalVT.
func TestUTF8Validation(t *testing.T) {
// SubscribeMetadataResponse{Directory: "\xff"}: field 1 (string), wire type 2,
// length 1, byte 0xff.
malformed := []byte{0x0a, 0x01, 0xff}
var viaProto SubscribeMetadataResponse
if err := proto.Unmarshal(malformed, &viaProto); err == nil {
t.Fatal("proto.Unmarshal accepted invalid UTF-8 in a string field; expected rejection")
}
var viaVT SubscribeMetadataResponse
if err := viaVT.UnmarshalVT(malformed); err != nil {
t.Fatalf("UnmarshalVT rejected invalid UTF-8: %v", err)
}
if viaVT.Directory != "\xff" {
t.Fatalf("UnmarshalVT Directory = %q, want \\xff", viaVT.Directory)
}
// LogEntry carries only bytes fields, so the decoders agree on arbitrary bytes;
// that is why the log entry decode paths can use UnmarshalVT.
// LogEntry{Data: "\xff"}: field 3 (bytes), wire type 2, length 1, byte 0xff.
leBytes := []byte{0x1a, 0x01, 0xff}
var leProto LogEntry
if err := proto.Unmarshal(leBytes, &leProto); err != nil {
t.Fatalf("proto.Unmarshal LogEntry: %v", err)
}
var leVT LogEntry
if err := leVT.UnmarshalVT(leBytes); err != nil {
t.Fatalf("UnmarshalVT LogEntry: %v", err)
}
if !proto.Equal(&leProto, &leVT) {
t.Fatal("LogEntry proto/VT decode of a bytes field diverged")
}
}
var chunkCounts = []int{1, 8, 32, 128}
// BenchmarkUnmarshal is the decode hot path: each subscriber decodes every
// delivered event, so this cost is paid once per (event, subscriber).
func BenchmarkUnmarshal(b *testing.B) {
for _, n := range chunkCounts {
data, _ := proto.Marshal(eventWithChunks(n))
b.Run(fmt.Sprintf("proto/chunks=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var m SubscribeMetadataResponse
if err := proto.Unmarshal(data, &m); err != nil {
b.Fatal(err)
}
}
})
b.Run(fmt.Sprintf("vt/chunks=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var m SubscribeMetadataResponse
if err := m.UnmarshalVT(data); err != nil {
b.Fatal(err)
}
}
})
}
}
// BenchmarkMarshal is the encode path: each metadata write marshals one LogEntry
// payload.
func BenchmarkMarshal(b *testing.B) {
for _, n := range chunkCounts {
ev := eventWithChunks(n)
b.Run(fmt.Sprintf("proto/chunks=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if _, err := proto.Marshal(ev); err != nil {
b.Fatal(err)
}
}
})
b.Run(fmt.Sprintf("vt/chunks=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if _, err := ev.MarshalVT(); err != nil {
b.Fatal(err)
}
}
})
}
}
// BenchmarkMarshalIntoBuffer mirrors the log buffer write path: marshal into a
// reused destination buffer. proto.Marshal must allocate a fresh slice and copy;
// SizeVT + MarshalToSizedBufferVT writes straight into the destination.
func BenchmarkMarshalIntoBuffer(b *testing.B) {
for _, n := range chunkCounts {
ev := eventWithChunks(n)
dst := make([]byte, 0, ev.SizeVT()*2)
b.Run(fmt.Sprintf("proto+copy/chunks=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
data, err := proto.Marshal(ev)
if err != nil {
b.Fatal(err)
}
dst = dst[:len(data)]
copy(dst, data)
}
})
b.Run(fmt.Sprintf("vt-sized/chunks=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
size := ev.SizeVT()
dst = dst[:size]
if _, err := ev.MarshalToSizedBufferVT(dst); err != nil {
b.Fatal(err)
}
}
})
}
}
+3 -1
View File
@@ -236,6 +236,8 @@ func readFilerFilesToChannel(
func processOneLogEntry(logEntry *filer_pb.LogEntry, filter PathFilter, processEventFn ProcessMetadataFunc) (int64, error) {
event := &filer_pb.SubscribeMetadataResponse{}
// proto.Unmarshal (not UnmarshalVT) validates UTF-8 in string fields, so
// malformed metadata is skipped here instead of reaching path filtering.
if err := proto.Unmarshal(logEntry.Data, event); err != nil {
glog.Errorf("unmarshal log entry: %v", err)
return 0, nil // skip corrupt entries
@@ -329,7 +331,7 @@ func streamLogFileEntries(newReader LogFileReaderFn, chunks []*filer_pb.FileChun
}
logEntry := &filer_pb.LogEntry{}
if err := proto.Unmarshal(entryData, logEntry); err != nil {
if err := logEntry.UnmarshalVT(entryData); err != nil {
return err
}
+26
View File
@@ -449,3 +449,29 @@ func TestReadLogFileRefsSingleFilerNotFoundSkips(t *testing.T) {
t.Fatalf("expected %d events after skipping one file, got %d", want, count)
}
}
// TestProcessOneLogEntrySkipsInvalidUTF8 guards that an event whose string field
// is not valid UTF-8 is rejected by proto.Unmarshal and never reaches path
// filtering or the consumer. UnmarshalVT would accept it, so the decode here
// must stay on proto.Unmarshal.
func TestProcessOneLogEntrySkipsInvalidUTF8(t *testing.T) {
// SubscribeMetadataResponse{Directory: "\xff"}: field 1 (string), wire type 2,
// length 1, byte 0xff — a syntactically valid message with an invalid-UTF-8
// string, which proto3 forbids.
logEntry := &filer_pb.LogEntry{Data: []byte{0x0a, 0x01, 0xff}}
called := false
tsNs, err := processOneLogEntry(logEntry, PathFilter{PathPrefix: "/"}, func(resp *filer_pb.SubscribeMetadataResponse) error {
called = true
return nil
})
if err != nil {
t.Fatalf("processOneLogEntry err = %v, want nil (corrupt entries are skipped)", err)
}
if called {
t.Fatal("consumer was invoked for a malformed (invalid UTF-8) event; validation was bypassed")
}
if tsNs != 0 {
t.Fatalf("tsNs = %d, want 0 for a skipped entry", tsNs)
}
}
+11
View File
@@ -45,6 +45,8 @@ service Seaweed {
}
rpc ReleaseAdminToken (ReleaseAdminTokenRequest) returns (ReleaseAdminTokenResponse) {
}
rpc GetAdminLockStatus (GetAdminLockStatusRequest) returns (GetAdminLockStatusResponse) {
}
rpc Ping (PingRequest) returns (PingResponse) {
}
rpc RaftListClusterServers (RaftListClusterServersRequest) returns (RaftListClusterServersResponse) {
@@ -464,6 +466,15 @@ message ReleaseAdminTokenRequest {
message ReleaseAdminTokenResponse {
}
message GetAdminLockStatusRequest {
string lock_name = 1;
}
message GetAdminLockStatusResponse {
bool is_locked = 1;
string client_name = 2;
string message = 3;
}
message PingRequest {
string target = 1; // default to ping itself
string target_type = 2;
+238 -122
View File
@@ -3597,6 +3597,110 @@ func (*ReleaseAdminTokenResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{51}
}
type GetAdminLockStatusRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
LockName string `protobuf:"bytes,1,opt,name=lock_name,json=lockName,proto3" json:"lock_name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetAdminLockStatusRequest) Reset() {
*x = GetAdminLockStatusRequest{}
mi := &file_master_proto_msgTypes[52]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetAdminLockStatusRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetAdminLockStatusRequest) ProtoMessage() {}
func (x *GetAdminLockStatusRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[52]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetAdminLockStatusRequest.ProtoReflect.Descriptor instead.
func (*GetAdminLockStatusRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{52}
}
func (x *GetAdminLockStatusRequest) GetLockName() string {
if x != nil {
return x.LockName
}
return ""
}
type GetAdminLockStatusResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
IsLocked bool `protobuf:"varint,1,opt,name=is_locked,json=isLocked,proto3" json:"is_locked,omitempty"`
ClientName string `protobuf:"bytes,2,opt,name=client_name,json=clientName,proto3" json:"client_name,omitempty"`
Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetAdminLockStatusResponse) Reset() {
*x = GetAdminLockStatusResponse{}
mi := &file_master_proto_msgTypes[53]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetAdminLockStatusResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetAdminLockStatusResponse) ProtoMessage() {}
func (x *GetAdminLockStatusResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[53]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetAdminLockStatusResponse.ProtoReflect.Descriptor instead.
func (*GetAdminLockStatusResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{53}
}
func (x *GetAdminLockStatusResponse) GetIsLocked() bool {
if x != nil {
return x.IsLocked
}
return false
}
func (x *GetAdminLockStatusResponse) GetClientName() string {
if x != nil {
return x.ClientName
}
return ""
}
func (x *GetAdminLockStatusResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
type PingRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Target string `protobuf:"bytes,1,opt,name=target,proto3" json:"target,omitempty"` // default to ping itself
@@ -3607,7 +3711,7 @@ type PingRequest struct {
func (x *PingRequest) Reset() {
*x = PingRequest{}
mi := &file_master_proto_msgTypes[52]
mi := &file_master_proto_msgTypes[54]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3619,7 +3723,7 @@ func (x *PingRequest) String() string {
func (*PingRequest) ProtoMessage() {}
func (x *PingRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[52]
mi := &file_master_proto_msgTypes[54]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3632,7 +3736,7 @@ func (x *PingRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use PingRequest.ProtoReflect.Descriptor instead.
func (*PingRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{52}
return file_master_proto_rawDescGZIP(), []int{54}
}
func (x *PingRequest) GetTarget() string {
@@ -3660,7 +3764,7 @@ type PingResponse struct {
func (x *PingResponse) Reset() {
*x = PingResponse{}
mi := &file_master_proto_msgTypes[53]
mi := &file_master_proto_msgTypes[55]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3672,7 +3776,7 @@ func (x *PingResponse) String() string {
func (*PingResponse) ProtoMessage() {}
func (x *PingResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[53]
mi := &file_master_proto_msgTypes[55]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3685,7 +3789,7 @@ func (x *PingResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use PingResponse.ProtoReflect.Descriptor instead.
func (*PingResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{53}
return file_master_proto_rawDescGZIP(), []int{55}
}
func (x *PingResponse) GetStartTimeNs() int64 {
@@ -3720,7 +3824,7 @@ type RaftAddServerRequest struct {
func (x *RaftAddServerRequest) Reset() {
*x = RaftAddServerRequest{}
mi := &file_master_proto_msgTypes[54]
mi := &file_master_proto_msgTypes[56]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3732,7 +3836,7 @@ func (x *RaftAddServerRequest) String() string {
func (*RaftAddServerRequest) ProtoMessage() {}
func (x *RaftAddServerRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[54]
mi := &file_master_proto_msgTypes[56]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3745,7 +3849,7 @@ func (x *RaftAddServerRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftAddServerRequest.ProtoReflect.Descriptor instead.
func (*RaftAddServerRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{54}
return file_master_proto_rawDescGZIP(), []int{56}
}
func (x *RaftAddServerRequest) GetId() string {
@@ -3777,7 +3881,7 @@ type RaftAddServerResponse struct {
func (x *RaftAddServerResponse) Reset() {
*x = RaftAddServerResponse{}
mi := &file_master_proto_msgTypes[55]
mi := &file_master_proto_msgTypes[57]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3789,7 +3893,7 @@ func (x *RaftAddServerResponse) String() string {
func (*RaftAddServerResponse) ProtoMessage() {}
func (x *RaftAddServerResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[55]
mi := &file_master_proto_msgTypes[57]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3802,7 +3906,7 @@ func (x *RaftAddServerResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftAddServerResponse.ProtoReflect.Descriptor instead.
func (*RaftAddServerResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{55}
return file_master_proto_rawDescGZIP(), []int{57}
}
type RaftRemoveServerRequest struct {
@@ -3815,7 +3919,7 @@ type RaftRemoveServerRequest struct {
func (x *RaftRemoveServerRequest) Reset() {
*x = RaftRemoveServerRequest{}
mi := &file_master_proto_msgTypes[56]
mi := &file_master_proto_msgTypes[58]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3827,7 +3931,7 @@ func (x *RaftRemoveServerRequest) String() string {
func (*RaftRemoveServerRequest) ProtoMessage() {}
func (x *RaftRemoveServerRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[56]
mi := &file_master_proto_msgTypes[58]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3840,7 +3944,7 @@ func (x *RaftRemoveServerRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftRemoveServerRequest.ProtoReflect.Descriptor instead.
func (*RaftRemoveServerRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{56}
return file_master_proto_rawDescGZIP(), []int{58}
}
func (x *RaftRemoveServerRequest) GetId() string {
@@ -3865,7 +3969,7 @@ type RaftRemoveServerResponse struct {
func (x *RaftRemoveServerResponse) Reset() {
*x = RaftRemoveServerResponse{}
mi := &file_master_proto_msgTypes[57]
mi := &file_master_proto_msgTypes[59]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3877,7 +3981,7 @@ func (x *RaftRemoveServerResponse) String() string {
func (*RaftRemoveServerResponse) ProtoMessage() {}
func (x *RaftRemoveServerResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[57]
mi := &file_master_proto_msgTypes[59]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3890,7 +3994,7 @@ func (x *RaftRemoveServerResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftRemoveServerResponse.ProtoReflect.Descriptor instead.
func (*RaftRemoveServerResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{57}
return file_master_proto_rawDescGZIP(), []int{59}
}
type RaftListClusterServersRequest struct {
@@ -3901,7 +4005,7 @@ type RaftListClusterServersRequest struct {
func (x *RaftListClusterServersRequest) Reset() {
*x = RaftListClusterServersRequest{}
mi := &file_master_proto_msgTypes[58]
mi := &file_master_proto_msgTypes[60]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3913,7 +4017,7 @@ func (x *RaftListClusterServersRequest) String() string {
func (*RaftListClusterServersRequest) ProtoMessage() {}
func (x *RaftListClusterServersRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[58]
mi := &file_master_proto_msgTypes[60]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3926,7 +4030,7 @@ func (x *RaftListClusterServersRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftListClusterServersRequest.ProtoReflect.Descriptor instead.
func (*RaftListClusterServersRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{58}
return file_master_proto_rawDescGZIP(), []int{60}
}
type RaftListClusterServersResponse struct {
@@ -3938,7 +4042,7 @@ type RaftListClusterServersResponse struct {
func (x *RaftListClusterServersResponse) Reset() {
*x = RaftListClusterServersResponse{}
mi := &file_master_proto_msgTypes[59]
mi := &file_master_proto_msgTypes[61]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3950,7 +4054,7 @@ func (x *RaftListClusterServersResponse) String() string {
func (*RaftListClusterServersResponse) ProtoMessage() {}
func (x *RaftListClusterServersResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[59]
mi := &file_master_proto_msgTypes[61]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3963,7 +4067,7 @@ func (x *RaftListClusterServersResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftListClusterServersResponse.ProtoReflect.Descriptor instead.
func (*RaftListClusterServersResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{59}
return file_master_proto_rawDescGZIP(), []int{61}
}
func (x *RaftListClusterServersResponse) GetClusterServers() []*RaftListClusterServersResponse_ClusterServers {
@@ -3983,7 +4087,7 @@ type RaftLeadershipTransferRequest struct {
func (x *RaftLeadershipTransferRequest) Reset() {
*x = RaftLeadershipTransferRequest{}
mi := &file_master_proto_msgTypes[60]
mi := &file_master_proto_msgTypes[62]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3995,7 +4099,7 @@ func (x *RaftLeadershipTransferRequest) String() string {
func (*RaftLeadershipTransferRequest) ProtoMessage() {}
func (x *RaftLeadershipTransferRequest) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[60]
mi := &file_master_proto_msgTypes[62]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4008,7 +4112,7 @@ func (x *RaftLeadershipTransferRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftLeadershipTransferRequest.ProtoReflect.Descriptor instead.
func (*RaftLeadershipTransferRequest) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{60}
return file_master_proto_rawDescGZIP(), []int{62}
}
func (x *RaftLeadershipTransferRequest) GetTargetId() string {
@@ -4035,7 +4139,7 @@ type RaftLeadershipTransferResponse struct {
func (x *RaftLeadershipTransferResponse) Reset() {
*x = RaftLeadershipTransferResponse{}
mi := &file_master_proto_msgTypes[61]
mi := &file_master_proto_msgTypes[63]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4047,7 +4151,7 @@ func (x *RaftLeadershipTransferResponse) String() string {
func (*RaftLeadershipTransferResponse) ProtoMessage() {}
func (x *RaftLeadershipTransferResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[61]
mi := &file_master_proto_msgTypes[63]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4060,7 +4164,7 @@ func (x *RaftLeadershipTransferResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RaftLeadershipTransferResponse.ProtoReflect.Descriptor instead.
func (*RaftLeadershipTransferResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{61}
return file_master_proto_rawDescGZIP(), []int{63}
}
func (x *RaftLeadershipTransferResponse) GetPreviousLeader() string {
@@ -4085,7 +4189,7 @@ type VolumeGrowResponse struct {
func (x *VolumeGrowResponse) Reset() {
*x = VolumeGrowResponse{}
mi := &file_master_proto_msgTypes[62]
mi := &file_master_proto_msgTypes[64]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4097,7 +4201,7 @@ func (x *VolumeGrowResponse) String() string {
func (*VolumeGrowResponse) ProtoMessage() {}
func (x *VolumeGrowResponse) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[62]
mi := &file_master_proto_msgTypes[64]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4110,7 +4214,7 @@ func (x *VolumeGrowResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use VolumeGrowResponse.ProtoReflect.Descriptor instead.
func (*VolumeGrowResponse) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{62}
return file_master_proto_rawDescGZIP(), []int{64}
}
type SuperBlockExtra_ErasureCoding struct {
@@ -4124,7 +4228,7 @@ type SuperBlockExtra_ErasureCoding struct {
func (x *SuperBlockExtra_ErasureCoding) Reset() {
*x = SuperBlockExtra_ErasureCoding{}
mi := &file_master_proto_msgTypes[67]
mi := &file_master_proto_msgTypes[69]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4136,7 +4240,7 @@ func (x *SuperBlockExtra_ErasureCoding) String() string {
func (*SuperBlockExtra_ErasureCoding) ProtoMessage() {}
func (x *SuperBlockExtra_ErasureCoding) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[67]
mi := &file_master_proto_msgTypes[69]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4185,7 +4289,7 @@ type LookupVolumeResponse_VolumeIdLocation struct {
func (x *LookupVolumeResponse_VolumeIdLocation) Reset() {
*x = LookupVolumeResponse_VolumeIdLocation{}
mi := &file_master_proto_msgTypes[68]
mi := &file_master_proto_msgTypes[70]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4197,7 +4301,7 @@ func (x *LookupVolumeResponse_VolumeIdLocation) String() string {
func (*LookupVolumeResponse_VolumeIdLocation) ProtoMessage() {}
func (x *LookupVolumeResponse_VolumeIdLocation) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[68]
mi := &file_master_proto_msgTypes[70]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4251,7 +4355,7 @@ type LookupEcVolumeResponse_EcShardIdLocation struct {
func (x *LookupEcVolumeResponse_EcShardIdLocation) Reset() {
*x = LookupEcVolumeResponse_EcShardIdLocation{}
mi := &file_master_proto_msgTypes[74]
mi := &file_master_proto_msgTypes[76]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4263,7 +4367,7 @@ func (x *LookupEcVolumeResponse_EcShardIdLocation) String() string {
func (*LookupEcVolumeResponse_EcShardIdLocation) ProtoMessage() {}
func (x *LookupEcVolumeResponse_EcShardIdLocation) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[74]
mi := &file_master_proto_msgTypes[76]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4306,7 +4410,7 @@ type ListClusterNodesResponse_ClusterNode struct {
func (x *ListClusterNodesResponse_ClusterNode) Reset() {
*x = ListClusterNodesResponse_ClusterNode{}
mi := &file_master_proto_msgTypes[75]
mi := &file_master_proto_msgTypes[77]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4318,7 +4422,7 @@ func (x *ListClusterNodesResponse_ClusterNode) String() string {
func (*ListClusterNodesResponse_ClusterNode) ProtoMessage() {}
func (x *ListClusterNodesResponse_ClusterNode) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[75]
mi := &file_master_proto_msgTypes[77]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4381,7 +4485,7 @@ type RaftListClusterServersResponse_ClusterServers struct {
func (x *RaftListClusterServersResponse_ClusterServers) Reset() {
*x = RaftListClusterServersResponse_ClusterServers{}
mi := &file_master_proto_msgTypes[76]
mi := &file_master_proto_msgTypes[78]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -4393,7 +4497,7 @@ func (x *RaftListClusterServersResponse_ClusterServers) String() string {
func (*RaftListClusterServersResponse_ClusterServers) ProtoMessage() {}
func (x *RaftListClusterServersResponse_ClusterServers) ProtoReflect() protoreflect.Message {
mi := &file_master_proto_msgTypes[76]
mi := &file_master_proto_msgTypes[78]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -4406,7 +4510,7 @@ func (x *RaftListClusterServersResponse_ClusterServers) ProtoReflect() protorefl
// Deprecated: Use RaftListClusterServersResponse_ClusterServers.ProtoReflect.Descriptor instead.
func (*RaftListClusterServersResponse_ClusterServers) Descriptor() ([]byte, []int) {
return file_master_proto_rawDescGZIP(), []int{59, 0}
return file_master_proto_rawDescGZIP(), []int{61, 0}
}
func (x *RaftListClusterServersResponse_ClusterServers) GetId() string {
@@ -4806,7 +4910,14 @@ const file_master_proto_rawDesc = "" +
"\x0eprevious_token\x18\x01 \x01(\x03R\rpreviousToken\x12,\n" +
"\x12previous_lock_time\x18\x02 \x01(\x03R\x10previousLockTime\x12\x1b\n" +
"\tlock_name\x18\x03 \x01(\tR\blockName\"\x1b\n" +
"\x19ReleaseAdminTokenResponse\"F\n" +
"\x19ReleaseAdminTokenResponse\"8\n" +
"\x19GetAdminLockStatusRequest\x12\x1b\n" +
"\tlock_name\x18\x01 \x01(\tR\blockName\"t\n" +
"\x1aGetAdminLockStatusResponse\x12\x1b\n" +
"\tis_locked\x18\x01 \x01(\bR\bisLocked\x12\x1f\n" +
"\vclient_name\x18\x02 \x01(\tR\n" +
"clientName\x12\x18\n" +
"\amessage\x18\x03 \x01(\tR\amessage\"F\n" +
"\vPingRequest\x12\x16\n" +
"\x06target\x18\x01 \x01(\tR\x06target\x12\x1f\n" +
"\vtarget_type\x18\x02 \x01(\tR\n" +
@@ -4840,7 +4951,7 @@ const file_master_proto_rawDesc = "" +
"\x0fprevious_leader\x18\x01 \x01(\tR\x0epreviousLeader\x12\x1d\n" +
"\n" +
"new_leader\x18\x02 \x01(\tR\tnewLeader\"\x14\n" +
"\x12VolumeGrowResponse2\xc6\x10\n" +
"\x12VolumeGrowResponse2\xab\x11\n" +
"\aSeaweed\x12I\n" +
"\rSendHeartbeat\x12\x14.master_pb.Heartbeat\x1a\x1c.master_pb.HeartbeatResponse\"\x00(\x010\x01\x12X\n" +
"\rKeepConnected\x12\x1f.master_pb.KeepConnectedRequest\x1a .master_pb.KeepConnectedResponse\"\x00(\x010\x01\x12Q\n" +
@@ -4861,7 +4972,8 @@ const file_master_proto_rawDesc = "" +
"\x16GetMasterConfiguration\x12(.master_pb.GetMasterConfigurationRequest\x1a).master_pb.GetMasterConfigurationResponse\"\x00\x12]\n" +
"\x10ListClusterNodes\x12\".master_pb.ListClusterNodesRequest\x1a#.master_pb.ListClusterNodesResponse\"\x00\x12Z\n" +
"\x0fLeaseAdminToken\x12!.master_pb.LeaseAdminTokenRequest\x1a\".master_pb.LeaseAdminTokenResponse\"\x00\x12`\n" +
"\x11ReleaseAdminToken\x12#.master_pb.ReleaseAdminTokenRequest\x1a$.master_pb.ReleaseAdminTokenResponse\"\x00\x129\n" +
"\x11ReleaseAdminToken\x12#.master_pb.ReleaseAdminTokenRequest\x1a$.master_pb.ReleaseAdminTokenResponse\"\x00\x12c\n" +
"\x12GetAdminLockStatus\x12$.master_pb.GetAdminLockStatusRequest\x1a%.master_pb.GetAdminLockStatusResponse\"\x00\x129\n" +
"\x04Ping\x12\x16.master_pb.PingRequest\x1a\x17.master_pb.PingResponse\"\x00\x12o\n" +
"\x16RaftListClusterServers\x12(.master_pb.RaftListClusterServersRequest\x1a).master_pb.RaftListClusterServersResponse\"\x00\x12T\n" +
"\rRaftAddServer\x12\x1f.master_pb.RaftAddServerRequest\x1a .master_pb.RaftAddServerResponse\"\x00\x12]\n" +
@@ -4882,7 +4994,7 @@ func file_master_proto_rawDescGZIP() []byte {
return file_master_proto_rawDescData
}
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 77)
var file_master_proto_msgTypes = make([]protoimpl.MessageInfo, 79)
var file_master_proto_goTypes = []any{
(*DiskTag)(nil), // 0: master_pb.DiskTag
(*Heartbeat)(nil), // 1: master_pb.Heartbeat
@@ -4936,32 +5048,34 @@ var file_master_proto_goTypes = []any{
(*LeaseAdminTokenResponse)(nil), // 49: master_pb.LeaseAdminTokenResponse
(*ReleaseAdminTokenRequest)(nil), // 50: master_pb.ReleaseAdminTokenRequest
(*ReleaseAdminTokenResponse)(nil), // 51: master_pb.ReleaseAdminTokenResponse
(*PingRequest)(nil), // 52: master_pb.PingRequest
(*PingResponse)(nil), // 53: master_pb.PingResponse
(*RaftAddServerRequest)(nil), // 54: master_pb.RaftAddServerRequest
(*RaftAddServerResponse)(nil), // 55: master_pb.RaftAddServerResponse
(*RaftRemoveServerRequest)(nil), // 56: master_pb.RaftRemoveServerRequest
(*RaftRemoveServerResponse)(nil), // 57: master_pb.RaftRemoveServerResponse
(*RaftListClusterServersRequest)(nil), // 58: master_pb.RaftListClusterServersRequest
(*RaftListClusterServersResponse)(nil), // 59: master_pb.RaftListClusterServersResponse
(*RaftLeadershipTransferRequest)(nil), // 60: master_pb.RaftLeadershipTransferRequest
(*RaftLeadershipTransferResponse)(nil), // 61: master_pb.RaftLeadershipTransferResponse
(*VolumeGrowResponse)(nil), // 62: master_pb.VolumeGrowResponse
nil, // 63: master_pb.Heartbeat.MaxVolumeCountsEntry
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
(*GetAdminLockStatusRequest)(nil), // 52: master_pb.GetAdminLockStatusRequest
(*GetAdminLockStatusResponse)(nil), // 53: master_pb.GetAdminLockStatusResponse
(*PingRequest)(nil), // 54: master_pb.PingRequest
(*PingResponse)(nil), // 55: master_pb.PingResponse
(*RaftAddServerRequest)(nil), // 56: master_pb.RaftAddServerRequest
(*RaftAddServerResponse)(nil), // 57: master_pb.RaftAddServerResponse
(*RaftRemoveServerRequest)(nil), // 58: master_pb.RaftRemoveServerRequest
(*RaftRemoveServerResponse)(nil), // 59: master_pb.RaftRemoveServerResponse
(*RaftListClusterServersRequest)(nil), // 60: master_pb.RaftListClusterServersRequest
(*RaftListClusterServersResponse)(nil), // 61: master_pb.RaftListClusterServersResponse
(*RaftLeadershipTransferRequest)(nil), // 62: master_pb.RaftLeadershipTransferRequest
(*RaftLeadershipTransferResponse)(nil), // 63: master_pb.RaftLeadershipTransferResponse
(*VolumeGrowResponse)(nil), // 64: master_pb.VolumeGrowResponse
nil, // 65: master_pb.Heartbeat.MaxVolumeCountsEntry
nil, // 66: master_pb.Heartbeat.DiskTotalBytesEntry
nil, // 67: master_pb.Heartbeat.DiskFreeBytesEntry
nil, // 68: master_pb.StorageBackend.PropertiesEntry
(*SuperBlockExtra_ErasureCoding)(nil), // 69: master_pb.SuperBlockExtra.ErasureCoding
(*LookupVolumeResponse_VolumeIdLocation)(nil), // 70: master_pb.LookupVolumeResponse.VolumeIdLocation
nil, // 71: master_pb.DiskInfo.MaxVolumeCountByDiskEntry
nil, // 72: master_pb.DataNodeInfo.DiskInfosEntry
nil, // 73: master_pb.RackInfo.DiskInfosEntry
nil, // 74: master_pb.DataCenterInfo.DiskInfosEntry
nil, // 75: master_pb.TopologyInfo.DiskInfosEntry
(*LookupEcVolumeResponse_EcShardIdLocation)(nil), // 76: master_pb.LookupEcVolumeResponse.EcShardIdLocation
(*ListClusterNodesResponse_ClusterNode)(nil), // 77: master_pb.ListClusterNodesResponse.ClusterNode
(*RaftListClusterServersResponse_ClusterServers)(nil), // 78: master_pb.RaftListClusterServersResponse.ClusterServers
(*volume_server_pb.VolumeServerState)(nil), // 79: volume_server_pb.VolumeServerState
}
var file_master_proto_depIdxs = []int32{
3, // 0: master_pb.Heartbeat.volumes:type_name -> master_pb.VolumeInformationMessage
@@ -4970,36 +5084,36 @@ var file_master_proto_depIdxs = []int32{
5, // 3: master_pb.Heartbeat.ec_shards:type_name -> master_pb.VolumeEcShardInformationMessage
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
77, // 7: master_pb.Heartbeat.state:type_name -> volume_server_pb.VolumeServerState
65, // 6: master_pb.Heartbeat.max_volume_counts:type_name -> master_pb.Heartbeat.MaxVolumeCountsEntry
79, // 7: master_pb.Heartbeat.state:type_name -> volume_server_pb.VolumeServerState
0, // 8: master_pb.Heartbeat.disk_tags:type_name -> master_pb.DiskTag
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
66, // 9: master_pb.Heartbeat.disk_total_bytes:type_name -> master_pb.Heartbeat.DiskTotalBytesEntry
67, // 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
68, // 12: master_pb.StorageBackend.properties:type_name -> master_pb.StorageBackend.PropertiesEntry
69, // 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
70, // 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
71, // 23: master_pb.DiskInfo.max_volume_count_by_disk:type_name -> master_pb.DiskInfo.MaxVolumeCountByDiskEntry
72, // 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
73, // 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
74, // 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
75, // 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
76, // 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
77, // 34: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode
78, // 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
@@ -5024,38 +5138,40 @@ var file_master_proto_depIdxs = []int32{
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
52, // 60: master_pb.Seaweed.GetAdminLockStatus:input_type -> master_pb.GetAdminLockStatusRequest
54, // 61: master_pb.Seaweed.Ping:input_type -> master_pb.PingRequest
60, // 62: master_pb.Seaweed.RaftListClusterServers:input_type -> master_pb.RaftListClusterServersRequest
56, // 63: master_pb.Seaweed.RaftAddServer:input_type -> master_pb.RaftAddServerRequest
58, // 64: master_pb.Seaweed.RaftRemoveServer:input_type -> master_pb.RaftRemoveServerRequest
62, // 65: master_pb.Seaweed.RaftLeadershipTransfer:input_type -> master_pb.RaftLeadershipTransferRequest
18, // 66: master_pb.Seaweed.VolumeGrow:input_type -> master_pb.VolumeGrowRequest
2, // 67: master_pb.Seaweed.SendHeartbeat:output_type -> master_pb.HeartbeatResponse
12, // 68: master_pb.Seaweed.KeepConnected:output_type -> master_pb.KeepConnectedResponse
15, // 69: master_pb.Seaweed.LookupVolume:output_type -> master_pb.LookupVolumeResponse
19, // 70: master_pb.Seaweed.Assign:output_type -> master_pb.AssignResponse
19, // 71: master_pb.Seaweed.StreamAssign:output_type -> master_pb.AssignResponse
21, // 72: master_pb.Seaweed.Statistics:output_type -> master_pb.StatisticsResponse
24, // 73: master_pb.Seaweed.CollectionList:output_type -> master_pb.CollectionListResponse
26, // 74: master_pb.Seaweed.CollectionDelete:output_type -> master_pb.CollectionDeleteResponse
33, // 75: master_pb.Seaweed.VolumeList:output_type -> master_pb.VolumeListResponse
35, // 76: master_pb.Seaweed.LookupEcVolume:output_type -> master_pb.LookupEcVolumeResponse
37, // 77: master_pb.Seaweed.VacuumVolume:output_type -> master_pb.VacuumVolumeResponse
39, // 78: master_pb.Seaweed.DisableVacuum:output_type -> master_pb.DisableVacuumResponse
41, // 79: master_pb.Seaweed.EnableVacuum:output_type -> master_pb.EnableVacuumResponse
43, // 80: master_pb.Seaweed.VolumeMarkReadonly:output_type -> master_pb.VolumeMarkReadonlyResponse
45, // 81: master_pb.Seaweed.GetMasterConfiguration:output_type -> master_pb.GetMasterConfigurationResponse
47, // 82: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse
49, // 83: master_pb.Seaweed.LeaseAdminToken:output_type -> master_pb.LeaseAdminTokenResponse
51, // 84: master_pb.Seaweed.ReleaseAdminToken:output_type -> master_pb.ReleaseAdminTokenResponse
53, // 85: master_pb.Seaweed.GetAdminLockStatus:output_type -> master_pb.GetAdminLockStatusResponse
55, // 86: master_pb.Seaweed.Ping:output_type -> master_pb.PingResponse
61, // 87: master_pb.Seaweed.RaftListClusterServers:output_type -> master_pb.RaftListClusterServersResponse
57, // 88: master_pb.Seaweed.RaftAddServer:output_type -> master_pb.RaftAddServerResponse
59, // 89: master_pb.Seaweed.RaftRemoveServer:output_type -> master_pb.RaftRemoveServerResponse
63, // 90: master_pb.Seaweed.RaftLeadershipTransfer:output_type -> master_pb.RaftLeadershipTransferResponse
64, // 91: master_pb.Seaweed.VolumeGrow:output_type -> master_pb.VolumeGrowResponse
67, // [67:92] is the sub-list for method output_type
42, // [42:67] 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
@@ -5072,7 +5188,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: 77,
NumMessages: 79,
NumExtensions: 0,
NumServices: 1,
},
+65 -27
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v6.33.4
// - protoc-gen-go-grpc v1.6.2
// - protoc v7.35.0
// source: master.proto
package master_pb
@@ -37,6 +37,7 @@ const (
Seaweed_ListClusterNodes_FullMethodName = "/master_pb.Seaweed/ListClusterNodes"
Seaweed_LeaseAdminToken_FullMethodName = "/master_pb.Seaweed/LeaseAdminToken"
Seaweed_ReleaseAdminToken_FullMethodName = "/master_pb.Seaweed/ReleaseAdminToken"
Seaweed_GetAdminLockStatus_FullMethodName = "/master_pb.Seaweed/GetAdminLockStatus"
Seaweed_Ping_FullMethodName = "/master_pb.Seaweed/Ping"
Seaweed_RaftListClusterServers_FullMethodName = "/master_pb.Seaweed/RaftListClusterServers"
Seaweed_RaftAddServer_FullMethodName = "/master_pb.Seaweed/RaftAddServer"
@@ -67,6 +68,7 @@ type SeaweedClient interface {
ListClusterNodes(ctx context.Context, in *ListClusterNodesRequest, opts ...grpc.CallOption) (*ListClusterNodesResponse, error)
LeaseAdminToken(ctx context.Context, in *LeaseAdminTokenRequest, opts ...grpc.CallOption) (*LeaseAdminTokenResponse, error)
ReleaseAdminToken(ctx context.Context, in *ReleaseAdminTokenRequest, opts ...grpc.CallOption) (*ReleaseAdminTokenResponse, error)
GetAdminLockStatus(ctx context.Context, in *GetAdminLockStatusRequest, opts ...grpc.CallOption) (*GetAdminLockStatusResponse, error)
Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
RaftListClusterServers(ctx context.Context, in *RaftListClusterServersRequest, opts ...grpc.CallOption) (*RaftListClusterServersResponse, error)
RaftAddServer(ctx context.Context, in *RaftAddServerRequest, opts ...grpc.CallOption) (*RaftAddServerResponse, error)
@@ -272,6 +274,16 @@ func (c *seaweedClient) ReleaseAdminToken(ctx context.Context, in *ReleaseAdminT
return out, nil
}
func (c *seaweedClient) GetAdminLockStatus(ctx context.Context, in *GetAdminLockStatusRequest, opts ...grpc.CallOption) (*GetAdminLockStatusResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetAdminLockStatusResponse)
err := c.cc.Invoke(ctx, Seaweed_GetAdminLockStatus_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *seaweedClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(PingResponse)
@@ -354,6 +366,7 @@ type SeaweedServer interface {
ListClusterNodes(context.Context, *ListClusterNodesRequest) (*ListClusterNodesResponse, error)
LeaseAdminToken(context.Context, *LeaseAdminTokenRequest) (*LeaseAdminTokenResponse, error)
ReleaseAdminToken(context.Context, *ReleaseAdminTokenRequest) (*ReleaseAdminTokenResponse, error)
GetAdminLockStatus(context.Context, *GetAdminLockStatusRequest) (*GetAdminLockStatusResponse, error)
Ping(context.Context, *PingRequest) (*PingResponse, error)
RaftListClusterServers(context.Context, *RaftListClusterServersRequest) (*RaftListClusterServersResponse, error)
RaftAddServer(context.Context, *RaftAddServerRequest) (*RaftAddServerResponse, error)
@@ -371,76 +384,79 @@ type SeaweedServer interface {
type UnimplementedSeaweedServer struct{}
func (UnimplementedSeaweedServer) SendHeartbeat(grpc.BidiStreamingServer[Heartbeat, HeartbeatResponse]) error {
return status.Errorf(codes.Unimplemented, "method SendHeartbeat not implemented")
return status.Error(codes.Unimplemented, "method SendHeartbeat not implemented")
}
func (UnimplementedSeaweedServer) KeepConnected(grpc.BidiStreamingServer[KeepConnectedRequest, KeepConnectedResponse]) error {
return status.Errorf(codes.Unimplemented, "method KeepConnected not implemented")
return status.Error(codes.Unimplemented, "method KeepConnected not implemented")
}
func (UnimplementedSeaweedServer) LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method LookupVolume not implemented")
return nil, status.Error(codes.Unimplemented, "method LookupVolume not implemented")
}
func (UnimplementedSeaweedServer) Assign(context.Context, *AssignRequest) (*AssignResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Assign not implemented")
return nil, status.Error(codes.Unimplemented, "method Assign not implemented")
}
func (UnimplementedSeaweedServer) StreamAssign(grpc.BidiStreamingServer[AssignRequest, AssignResponse]) error {
return status.Errorf(codes.Unimplemented, "method StreamAssign not implemented")
return status.Error(codes.Unimplemented, "method StreamAssign not implemented")
}
func (UnimplementedSeaweedServer) Statistics(context.Context, *StatisticsRequest) (*StatisticsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Statistics not implemented")
return nil, status.Error(codes.Unimplemented, "method Statistics not implemented")
}
func (UnimplementedSeaweedServer) CollectionList(context.Context, *CollectionListRequest) (*CollectionListResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CollectionList not implemented")
return nil, status.Error(codes.Unimplemented, "method CollectionList not implemented")
}
func (UnimplementedSeaweedServer) CollectionDelete(context.Context, *CollectionDeleteRequest) (*CollectionDeleteResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CollectionDelete not implemented")
return nil, status.Error(codes.Unimplemented, "method CollectionDelete not implemented")
}
func (UnimplementedSeaweedServer) VolumeList(context.Context, *VolumeListRequest) (*VolumeListResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method VolumeList not implemented")
return nil, status.Error(codes.Unimplemented, "method VolumeList not implemented")
}
func (UnimplementedSeaweedServer) LookupEcVolume(context.Context, *LookupEcVolumeRequest) (*LookupEcVolumeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method LookupEcVolume not implemented")
return nil, status.Error(codes.Unimplemented, "method LookupEcVolume not implemented")
}
func (UnimplementedSeaweedServer) VacuumVolume(context.Context, *VacuumVolumeRequest) (*VacuumVolumeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolume not implemented")
return nil, status.Error(codes.Unimplemented, "method VacuumVolume not implemented")
}
func (UnimplementedSeaweedServer) DisableVacuum(context.Context, *DisableVacuumRequest) (*DisableVacuumResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method DisableVacuum not implemented")
return nil, status.Error(codes.Unimplemented, "method DisableVacuum not implemented")
}
func (UnimplementedSeaweedServer) EnableVacuum(context.Context, *EnableVacuumRequest) (*EnableVacuumResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method EnableVacuum not implemented")
return nil, status.Error(codes.Unimplemented, "method EnableVacuum not implemented")
}
func (UnimplementedSeaweedServer) VolumeMarkReadonly(context.Context, *VolumeMarkReadonlyRequest) (*VolumeMarkReadonlyResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method VolumeMarkReadonly not implemented")
return nil, status.Error(codes.Unimplemented, "method VolumeMarkReadonly not implemented")
}
func (UnimplementedSeaweedServer) GetMasterConfiguration(context.Context, *GetMasterConfigurationRequest) (*GetMasterConfigurationResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetMasterConfiguration not implemented")
return nil, status.Error(codes.Unimplemented, "method GetMasterConfiguration not implemented")
}
func (UnimplementedSeaweedServer) ListClusterNodes(context.Context, *ListClusterNodesRequest) (*ListClusterNodesResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListClusterNodes not implemented")
return nil, status.Error(codes.Unimplemented, "method ListClusterNodes not implemented")
}
func (UnimplementedSeaweedServer) LeaseAdminToken(context.Context, *LeaseAdminTokenRequest) (*LeaseAdminTokenResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method LeaseAdminToken not implemented")
return nil, status.Error(codes.Unimplemented, "method LeaseAdminToken not implemented")
}
func (UnimplementedSeaweedServer) ReleaseAdminToken(context.Context, *ReleaseAdminTokenRequest) (*ReleaseAdminTokenResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReleaseAdminToken not implemented")
return nil, status.Error(codes.Unimplemented, "method ReleaseAdminToken not implemented")
}
func (UnimplementedSeaweedServer) GetAdminLockStatus(context.Context, *GetAdminLockStatusRequest) (*GetAdminLockStatusResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetAdminLockStatus not implemented")
}
func (UnimplementedSeaweedServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
}
func (UnimplementedSeaweedServer) RaftListClusterServers(context.Context, *RaftListClusterServersRequest) (*RaftListClusterServersResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RaftListClusterServers not implemented")
return nil, status.Error(codes.Unimplemented, "method RaftListClusterServers not implemented")
}
func (UnimplementedSeaweedServer) RaftAddServer(context.Context, *RaftAddServerRequest) (*RaftAddServerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RaftAddServer not implemented")
return nil, status.Error(codes.Unimplemented, "method RaftAddServer not implemented")
}
func (UnimplementedSeaweedServer) RaftRemoveServer(context.Context, *RaftRemoveServerRequest) (*RaftRemoveServerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RaftRemoveServer not implemented")
return nil, status.Error(codes.Unimplemented, "method RaftRemoveServer not implemented")
}
func (UnimplementedSeaweedServer) RaftLeadershipTransfer(context.Context, *RaftLeadershipTransferRequest) (*RaftLeadershipTransferResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RaftLeadershipTransfer not implemented")
return nil, status.Error(codes.Unimplemented, "method RaftLeadershipTransfer not implemented")
}
func (UnimplementedSeaweedServer) VolumeGrow(context.Context, *VolumeGrowRequest) (*VolumeGrowResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method VolumeGrow not implemented")
return nil, status.Error(codes.Unimplemented, "method VolumeGrow not implemented")
}
func (UnimplementedSeaweedServer) mustEmbedUnimplementedSeaweedServer() {}
func (UnimplementedSeaweedServer) testEmbeddedByValue() {}
@@ -453,7 +469,7 @@ type UnsafeSeaweedServer interface {
}
func RegisterSeaweedServer(s grpc.ServiceRegistrar, srv SeaweedServer) {
// If the following call pancis, it indicates UnimplementedSeaweedServer was
// If the following call panics, it indicates UnimplementedSeaweedServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
@@ -754,6 +770,24 @@ func _Seaweed_ReleaseAdminToken_Handler(srv interface{}, ctx context.Context, de
return interceptor(ctx, in, info, handler)
}
func _Seaweed_GetAdminLockStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetAdminLockStatusRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SeaweedServer).GetAdminLockStatus(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Seaweed_GetAdminLockStatus_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SeaweedServer).GetAdminLockStatus(ctx, req.(*GetAdminLockStatusRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Seaweed_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PingRequest)
if err := dec(in); err != nil {
@@ -929,6 +963,10 @@ var Seaweed_ServiceDesc = grpc.ServiceDesc{
MethodName: "ReleaseAdminToken",
Handler: _Seaweed_ReleaseAdminToken_Handler,
},
{
MethodName: "GetAdminLockStatus",
Handler: _Seaweed_GetAdminLockStatus_Handler,
},
{
MethodName: "Ping",
Handler: _Seaweed_Ping_Handler,
@@ -190,6 +190,7 @@ func (az *azureRemoteStorageClient) ListDirectory(ctx context.Context, loc *remo
if blobItem.Properties.ETag != nil {
remoteEntry.RemoteETag = string(*blobItem.Properties.ETag)
}
remoteEntry.RemoteContentEncoding = remoteContentEncoding(blobItem.Properties.ContentEncoding)
}
if err = visitFn(dir, name, false, remoteEntry); err != nil {
@@ -224,9 +225,20 @@ func (az *azureRemoteStorageClient) StatFile(loc *remote_pb.RemoteStorageLocatio
if resp.ETag != nil {
remoteEntry.RemoteETag = string(*resp.ETag)
}
remoteEntry.RemoteContentEncoding = remoteContentEncoding(resp.ContentEncoding)
return remoteEntry, nil
}
// blob properties report no Content-Encoding as nil; the remote entry records
// that authoritatively as empty
func remoteContentEncoding(encoding *string) *string {
if encoding == nil {
empty := ""
return &empty
}
return encoding
}
func (az *azureRemoteStorageClient) Traverse(loc *remote_pb.RemoteStorageLocation, visitFn remote_storage.VisitFunc) (err error) {
pathKey := loc.Path[1:]
@@ -263,6 +275,7 @@ func (az *azureRemoteStorageClient) Traverse(loc *remote_pb.RemoteStorageLocatio
if blobItem.Properties.ETag != nil {
remoteEntry.RemoteETag = string(*blobItem.Properties.ETag)
}
remoteEntry.RemoteContentEncoding = remoteContentEncoding(blobItem.Properties.ContentEncoding)
}
err = visitFn(dir, name, false, remoteEntry)
@@ -379,6 +392,9 @@ func (az *azureRemoteStorageClient) WriteFile(loc *remote_pb.RemoteStorageLocati
if entry.Attributes != nil && entry.Attributes.Mime != "" {
httpHeaders.BlobContentType = &entry.Attributes.Mime
}
if contentEncoding := remote_storage.EntryContentEncoding(entry); contentEncoding != "" {
httpHeaders.BlobContentEncoding = &contentEncoding
}
_, err = blobClient.UploadStream(context.Background(), reader, &blockblob.UploadStreamOptions{
BlockSize: defaultBlockSize,
@@ -424,7 +440,27 @@ func (az *azureRemoteStorageClient) UpdateFileMetadata(loc *remote_pb.RemoteStor
key := loc.Path[1:]
blobClient := az.client.ServiceClient().NewContainerClient(loc.Bucket).NewBlobClient(key)
_, err = blobClient.SetMetadata(context.Background(), metadata, nil)
if !reflect.DeepEqual(toMetadata(oldEntry.Extended), metadata) {
if _, err = blobClient.SetMetadata(context.Background(), metadata, nil); err != nil {
return err
}
}
if encoding := remote_storage.EntryContentEncoding(newEntry); encoding != remote_storage.EntryContentEncoding(oldEntry) {
// SetHTTPHeaders replaces the whole header set, so carry the rest over
props, getErr := blobClient.GetProperties(context.Background(), nil)
if getErr != nil {
return fmt.Errorf("azure get properties %s%s: %w", loc.Bucket, loc.Path, getErr)
}
httpHeaders := blob.ParseHTTPHeaders(props)
httpHeaders.BlobContentEncoding = nil
if encoding != "" {
httpHeaders.BlobContentEncoding = &encoding
}
if _, err = blobClient.SetHTTPHeaders(context.Background(), httpHeaders, nil); err != nil {
return fmt.Errorf("azure set http headers %s%s: %w", loc.Bucket, loc.Path, err)
}
}
return
}
+30 -28
View File
@@ -20,6 +20,7 @@ import (
"golang.org/x/oauth2/google"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/protobuf/proto"
)
func init() {
@@ -96,6 +97,16 @@ type gcsRemoteStorageClient struct {
var _ = remote_storage.RemoteStorageClient(&gcsRemoteStorageClient{})
func (gcs *gcsRemoteStorageClient) toRemoteEntry(attr *storage.ObjectAttrs) *filer_pb.RemoteEntry {
return &filer_pb.RemoteEntry{
StorageName: gcs.conf.Name,
RemoteMtime: attr.Updated.Unix(),
RemoteSize: attr.Size,
RemoteETag: attr.Etag,
RemoteContentEncoding: proto.String(attr.ContentEncoding),
}
}
func (gcs *gcsRemoteStorageClient) Traverse(loc *remote_pb.RemoteStorageLocation, visitFn remote_storage.VisitFunc) (err error) {
pathKey := loc.Path[1:]
@@ -119,12 +130,7 @@ func (gcs *gcsRemoteStorageClient) Traverse(loc *remote_pb.RemoteStorageLocation
key := objectAttr.Name
key = "/" + key
dir, name := util.FullPath(key).DirAndName()
err = visitFn(dir, name, false, &filer_pb.RemoteEntry{
RemoteMtime: objectAttr.Updated.Unix(),
RemoteSize: objectAttr.Size,
RemoteETag: objectAttr.Etag,
StorageName: gcs.conf.Name,
})
err = visitFn(dir, name, false, gcs.toRemoteEntry(objectAttr))
}
return
}
@@ -165,12 +171,7 @@ func (gcs *gcsRemoteStorageClient) ListDirectory(ctx context.Context, loc *remot
continue // skip directory markers
}
dir, name := util.FullPath(key).DirAndName()
if err = visitFn(dir, name, false, &filer_pb.RemoteEntry{
RemoteMtime: objectAttr.Updated.Unix(),
RemoteSize: objectAttr.Size,
RemoteETag: objectAttr.Etag,
StorageName: gcs.conf.Name,
}); err != nil {
if err = visitFn(dir, name, false, gcs.toRemoteEntry(objectAttr)); err != nil {
return err
}
}
@@ -188,18 +189,15 @@ func (gcs *gcsRemoteStorageClient) StatFile(loc *remote_pb.RemoteStorageLocation
}
return nil, fmt.Errorf("stat gcs %s%s: %w", loc.Bucket, loc.Path, err)
}
return &filer_pb.RemoteEntry{
StorageName: gcs.conf.Name,
RemoteMtime: attr.Updated.Unix(),
RemoteSize: attr.Size,
RemoteETag: attr.Etag,
}, nil
return gcs.toRemoteEntry(attr), nil
}
func (gcs *gcsRemoteStorageClient) ReadFile(loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (data []byte, err error) {
key := loc.Path[1:]
rangeReader, readErr := gcs.client.Bucket(loc.Bucket).Object(key).NewRangeReader(context.Background(), offset, size)
// read the stored bytes: decompressive transcoding of gzip-encoded objects
// breaks range reads and returns sizes that disagree with RemoteSize
rangeReader, readErr := gcs.client.Bucket(loc.Bucket).Object(key).ReadCompressed(true).NewRangeReader(context.Background(), offset, size)
if readErr != nil {
return nil, readErr
}
@@ -214,7 +212,7 @@ func (gcs *gcsRemoteStorageClient) ReadFile(loc *remote_pb.RemoteStorageLocation
func (gcs *gcsRemoteStorageClient) ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (reader io.ReadCloser, err error) {
key := loc.Path[1:]
return gcs.client.Bucket(loc.Bucket).Object(key).NewRangeReader(ctx, offset, size)
return gcs.client.Bucket(loc.Bucket).Object(key).ReadCompressed(true).NewRangeReader(ctx, offset, size)
}
func (gcs *gcsRemoteStorageClient) WriteDirectory(loc *remote_pb.RemoteStorageLocation, entry *filer_pb.Entry) (err error) {
@@ -235,6 +233,7 @@ func (gcs *gcsRemoteStorageClient) WriteFile(loc *remote_pb.RemoteStorageLocatio
if entry.Attributes != nil && entry.Attributes.Mime != "" {
wc.ContentType = entry.Attributes.Mime
}
wc.ContentEncoding = remote_storage.EntryContentEncoding(entry)
if _, err = io.Copy(wc, reader); err != nil {
return nil, fmt.Errorf("upload to gcs %s/%s%s: %v", loc.Name, loc.Bucket, loc.Path, err)
}
@@ -266,18 +265,21 @@ func (gcs *gcsRemoteStorageClient) UpdateFileMetadata(loc *remote_pb.RemoteStora
if reflect.DeepEqual(oldEntry.Extended, newEntry.Extended) {
return nil
}
metadata := toMetadata(newEntry.Extended)
key := loc.Path[1:]
if len(metadata) > 0 {
_, err = gcs.client.Bucket(loc.Bucket).Object(key).Update(context.Background(), storage.ObjectAttrsToUpdate{
Metadata: metadata,
})
attrsToUpdate := storage.ObjectAttrsToUpdate{}
if metadata := toMetadata(newEntry.Extended); len(metadata) > 0 {
attrsToUpdate.Metadata = metadata
} else {
// no way to delete the metadata yet
}
if encoding := remote_storage.EntryContentEncoding(newEntry); encoding != remote_storage.EntryContentEncoding(oldEntry) {
attrsToUpdate.ContentEncoding = encoding // empty clears the header
}
if attrsToUpdate.Metadata == nil && attrsToUpdate.ContentEncoding == nil {
return nil
}
key := loc.Path[1:]
_, err = gcs.client.Bucket(loc.Bucket).Object(key).Update(context.Background(), attrsToUpdate)
return
}
func (gcs *gcsRemoteStorageClient) DeleteFile(loc *remote_pb.RemoteStorageLocation) (err error) {
+9
View File
@@ -66,6 +66,15 @@ func FormatLocation(loc *remote_pb.RemoteStorageLocation) string {
type VisitFunc func(dir string, name string, isDirectory bool, remoteEntry *filer_pb.RemoteEntry) error
// EntryContentEncoding returns the Content-Encoding stored in the entry
// extended attributes, for clients to set on uploaded remote objects.
func EntryContentEncoding(entry *filer_pb.Entry) string {
if entry == nil {
return ""
}
return string(entry.Extended["Content-Encoding"])
}
type Bucket struct {
Name string
CreatedAt time.Time
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
@@ -18,6 +19,7 @@ import (
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
@@ -224,6 +226,8 @@ func (s *s3RemoteStorageClient) StatFile(loc *remote_pb.RemoteStorageLocation) (
if resp.ETag != nil {
remoteEntry.RemoteETag = *resp.ETag
}
// a HeadObject response is authoritative: no header means no encoding
remoteEntry.RemoteContentEncoding = aws.String(aws.StringValue(resp.ContentEncoding))
return remoteEntry, nil
}
@@ -323,6 +327,9 @@ func (s *s3RemoteStorageClient) WriteFile(loc *remote_pb.RemoteStorageLocation,
if entry.Attributes != nil && entry.Attributes.Mime != "" {
uploadInput.ContentType = aws.String(entry.Attributes.Mime)
}
if contentEncoding := remote_storage.EntryContentEncoding(entry); contentEncoding != "" {
uploadInput.ContentEncoding = aws.String(contentEncoding)
}
if s.conf.S3StorageClass != "" {
uploadInput.StorageClass = aws.String(s.conf.S3StorageClass)
}
@@ -353,10 +360,65 @@ func (s *s3RemoteStorageClient) readFileRemoteEntry(loc *remote_pb.RemoteStorage
return s.StatFile(loc)
}
// the largest object a single CopyObject call accepts
const s3CopyObjectSizeLimit = 5 * 1024 * 1024 * 1024
func (s *s3RemoteStorageClient) UpdateFileMetadata(loc *remote_pb.RemoteStorageLocation, oldEntry *filer_pb.Entry, newEntry *filer_pb.Entry) (err error) {
if reflect.DeepEqual(oldEntry.Extended, newEntry.Extended) {
return nil
}
// Content-Encoding is S3 system metadata, changeable without a content
// rewrite only through an in-place copy
if encoding := remote_storage.EntryContentEncoding(newEntry); encoding != remote_storage.EntryContentEncoding(oldEntry) {
key := loc.Path[1:]
if fileSize := int64(filer.FileSize(newEntry)); fileSize > s3CopyObjectSizeLimit {
glog.Warningf("s3 %s/%s: applying the Content-Encoding change needs an object copy, but %d bytes exceeds the copy limit; it will apply on the next content write", loc.Bucket, key, fileSize)
} else {
// the replace directive drops everything not resent, so read the
// object's current metadata and carry it over
headOut, headErr := s.conn.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(loc.Bucket),
Key: aws.String(key),
})
if headErr != nil {
return fmt.Errorf("stat %s/%s before metadata copy: %w", loc.Bucket, key, headErr)
}
copyInput := &s3.CopyObjectInput{
Bucket: aws.String(loc.Bucket),
Key: aws.String(key),
CopySource: aws.String(url.PathEscape(loc.Bucket + "/" + key)),
MetadataDirective: aws.String(s3.MetadataDirectiveReplace),
Metadata: headOut.Metadata,
ContentType: headOut.ContentType,
CacheControl: headOut.CacheControl,
ContentDisposition: headOut.ContentDisposition,
ContentLanguage: headOut.ContentLanguage,
WebsiteRedirectLocation: headOut.WebsiteRedirectLocation,
ServerSideEncryption: headOut.ServerSideEncryption,
SSEKMSKeyId: headOut.SSEKMSKeyId,
StorageClass: headOut.StorageClass,
}
if headOut.Expires != nil {
if expires, parseErr := http.ParseTime(*headOut.Expires); parseErr == nil {
copyInput.Expires = aws.Time(expires)
}
}
if encoding != "" {
copyInput.ContentEncoding = aws.String(encoding)
}
if newEntry.Attributes != nil && newEntry.Attributes.Mime != "" {
copyInput.ContentType = aws.String(newEntry.Attributes.Mime)
}
if s.conf.S3StorageClass != "" {
copyInput.StorageClass = aws.String(s.conf.S3StorageClass)
}
if _, err = s.conn.CopyObject(copyInput); err != nil {
return fmt.Errorf("update content encoding of %s/%s: %w", loc.Bucket, key, err)
}
}
}
tagging := toTagging(newEntry.Extended)
if len(tagging.TagSet) > 0 {
_, err = s.conn.PutObjectTagging(&s3.PutObjectTaggingInput{
+75 -7
View File
@@ -26,6 +26,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/replication/source"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
@@ -139,7 +140,19 @@ func (fs *FilerSink) replicateOneChunk(sourceChunk *filer_pb.FileChunk, path str
}
func (fs *FilerSink) replicateOneManifestChunk(ctx context.Context, sourceChunk *filer_pb.FileChunk, path string, sourceMtimeNs int64) (*filer_pb.FileChunk, error) {
resolvedChunks, err := filer.ResolveOneChunkManifest(ctx, fs.filerSource.LookupFileId, sourceChunk)
// LookupFileId can transiently fail during a write burst (volume not yet
// registered). Retry like the data-chunk path does; the gate stops on
// supersession or, when that cannot be checked, after a few attempts.
var resolvedChunks []*filer_pb.FileChunk
resolveName := fmt.Sprintf("resolve manifest %s", sourceChunk.GetFileIdString())
err := util.RetryUntil(resolveName, func() error {
rc, e := filer.ResolveOneChunkManifest(ctx, fs.filerSource.LookupFileId, sourceChunk)
if e != nil {
return e
}
resolvedChunks = rc
return nil
}, fs.manifestResolveRetryGate(path, sourceMtimeNs, sourceChunk.GetFileIdString()))
if err != nil {
return nil, fmt.Errorf("resolve manifest %s: %w", sourceChunk.GetFileIdString(), err)
}
@@ -178,6 +191,56 @@ func (fs *FilerSink) replicateOneManifestChunk(ctx context.Context, sourceChunk
}, nil
}
// maxUnverifiableResolveAttempts bounds manifest-resolve retries when
// supersession cannot be checked for the target path.
const maxUnverifiableResolveAttempts = 3
// manifestResolveRetryGate decides whether a failing manifest resolve keeps
// retrying: stop when the source superseded the replayed version (the caller
// skips it as lossless), stop immediately on non-transient errors (e.g. corrupt
// manifest data) so the configured metadata error policy applies, and stop
// after a few attempts when supersession cannot be checked at all (incremental
// dated target keys don't map back to a source path) — propagating lets
// filer.backup decide with the event's real source key instead of spinning
// here forever.
func (fs *FilerSink) manifestResolveRetryGate(path string, sourceMtimeNs int64, chunkName string) func(error) bool {
_, canCheckSupersession := fs.targetPathToSourcePath(path)
attempts := 0
return func(resolveErr error) (shouldContinue bool) {
if fs.hasSourceNewerVersion(path, sourceMtimeNs) {
glog.V(1).Infof("skip retrying stale source manifest %s for %s: %v", chunkName, path, resolveErr)
return false
}
if !isTransientResolveError(resolveErr) {
glog.V(0).Infof("resolve manifest %s for %s: non-transient error, propagating: %v", chunkName, path, resolveErr)
return false
}
attempts++
if !canCheckSupersession && attempts >= maxUnverifiableResolveAttempts {
glog.V(0).Infof("resolve manifest %s for %s: supersession unverifiable, propagating after %d attempts: %v", chunkName, path, attempts, resolveErr)
return false
}
glog.V(0).Infof("resolve manifest %s for %s: %v", chunkName, path, resolveErr)
return true
}
}
// isTransientResolveError reports whether a manifest resolve failure belongs to
// the classes that clear on their own during a write burst — volume-lookup
// races and network interruptions. Anything else (corrupt manifest data, bad
// file ids) is permanent and must propagate rather than retry forever.
func isTransientResolveError(err error) bool {
if err == nil {
return false
}
if isRetryableNetworkError(err) {
return true
}
errStr := err.Error()
return strings.Contains(errStr, "LookupFileId") ||
(strings.Contains(errStr, "volume id") && strings.Contains(errStr, "not found"))
}
func (fs *FilerSink) uploadManifestChunk(path string, sourceMtimeNs int64, sourceFileId string, manifestData []byte) (fileId string, err error) {
uploader, err := fs.getUploader()
if err != nil {
@@ -440,17 +503,22 @@ func validateReplicatedReadSize(sourceChunk *filer_pb.FileChunk, readSize int) e
// version being replayed is stale. The lookup runs regardless of sourceMtimeNs so
// a deleted source is detected even when the replayed mtime is epoch/unset.
func (fs *FilerSink) hasSourceNewerVersion(targetPath string, sourceMtimeNs int64) bool {
if fs.filerSource == nil {
return false
}
sourcePath, ok := fs.targetPathToSourcePath(targetPath)
if !ok {
return false
}
return SourceSupersedes(context.Background(), fs.filerSource, sourcePath, sourceMtimeNs)
}
sourceEntry, err := filer_pb.GetEntry(context.Background(), fs.filerSource, sourcePath)
return sourceSupersedes(sourcePath, sourceEntry, err, sourceMtimeNs)
// SourceSupersedes reports whether the live source's entry at sourcePath has
// moved past the replayed version (mtimeNs) — deleted or strictly newer — so
// skipping it is lossless. Exported for filer.backup's non-filer-sink decision.
func SourceSupersedes(ctx context.Context, filerSource *source.FilerSource, sourcePath util.FullPath, mtimeNs int64) bool {
if filerSource == nil {
return false
}
sourceEntry, err := filer_pb.GetEntry(ctx, filerSource, sourcePath)
return sourceSupersedes(sourcePath, sourceEntry, err, mtimeNs)
}
// sourceSupersedes reports whether the replayed version (sourceMtimeNs) is stale:
@@ -384,3 +384,44 @@ func TestSourceSupersedesEpochMtime(t *testing.T) {
t.Fatal("epoch-mtime live source must not be reported superseded")
}
}
// An incremental sink's dated target keys cannot be mapped back to a source
// path, so supersession is unverifiable: the gate must stop after the bounded
// attempts and propagate instead of spinning forever.
func TestManifestResolveRetryGateUnverifiableSupersessionBounded(t *testing.T) {
fs := &FilerSink{isIncremental: true, dir: "/backup"}
gate := fs.manifestResolveRetryGate("/backup/2026-07-10/buckets/x/f.pt", 123, "3,01abc")
resolveErr := errors.New("LookupFileId volume id 3: not found")
for i := 1; i < maxUnverifiableResolveAttempts; i++ {
if !gate(resolveErr) {
t.Fatalf("attempt %d: gate must keep retrying before the bound", i)
}
}
if gate(resolveErr) {
t.Error("gate must propagate once the bound is reached with supersession unverifiable")
}
}
// Non-transient resolve errors (corrupt manifest data, bad file ids) must
// propagate immediately — before any attempt counting or supersession
// mapping — so the configured metadata error policy applies, instead of
// retrying until the source is superseded.
func TestManifestResolveRetryGateNonTransientPropagates(t *testing.T) {
fs := &FilerSink{dir: "/backup"}
gate := fs.manifestResolveRetryGate("/backup/buckets/x/f.pt", 123, "3,01abc")
permanentErrs := []error{
errors.New("fail to unmarshal manifest 3,01abc: proto: cannot parse invalid wire-format data"),
errors.New("invalid fileId abc"),
}
for _, err := range permanentErrs {
if gate(err) {
t.Errorf("non-transient error must propagate immediately: %v", err)
}
}
if !gate(errors.New("LookupFileId volume id 3: not found")) {
t.Error("transient lookup race must keep retrying on the first attempt")
}
if isTransientResolveError(nil) {
t.Error("isTransientResolveError(nil) must be false")
}
}
+21 -6
View File
@@ -260,8 +260,7 @@ func (fs *FilerSink) CreateEntry(key string, entry *filer_pb.Entry, signatures [
if errors.Is(err, errChunkSizeMismatch) {
return fs.onCorruptChunk(key, entry, err)
}
glog.Warningf("replicate entry chunks %s: %v", key, err)
return nil
return fs.onReplicateChunkError(key, entry, err)
}
// glog.V(4).Infof("replicated %s %+v ===> %+v", key, entry.GetChunks(), replicatedChunks)
@@ -339,8 +338,7 @@ func (fs *FilerSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParent
if errors.Is(err, errChunkSizeMismatch) {
return true, fs.onCorruptChunk(targetKey, newEntry, err)
}
glog.Warningf("replicate entry chunks %s: %v", key, err)
return true, nil
return true, fs.onReplicateChunkError(targetKey, newEntry, err)
}
existingEntry.Chunks = replicatedChunks
existingEntry.Attributes = newEntry.Attributes
@@ -368,8 +366,7 @@ func (fs *FilerSink) UpdateEntry(key string, oldEntry *filer_pb.Entry, newParent
if errors.Is(err, errChunkSizeMismatch) {
return true, fs.onCorruptChunk(targetKey, newEntry, err)
}
glog.Warningf("replicate entry chunks %s: %v", key, err)
return true, nil
return true, fs.onReplicateChunkError(targetKey, newEntry, err)
}
existingEntry.Chunks = append(existingEntry.GetChunks(), replicatedChunks...)
existingEntry.Attributes = newEntry.Attributes
@@ -426,6 +423,11 @@ func getEntryMtimeNs(entry *filer_pb.Entry) int64 {
return entry.Attributes.Mtime*int64(1e9) + int64(entry.Attributes.MtimeNs)
}
// EntryMtimeNs exposes getEntryMtimeNs for filer.backup's supersession check.
func EntryMtimeNs(entry *filer_pb.Entry) int64 {
return getEntryMtimeNs(entry)
}
// onCorruptChunk handles a permanent chunk size-mismatch (fetched source bytes
// disagree with source metadata). If the source already holds a newer version the
// event is a stale replay whose chunk was overwritten and GC'd — skip it (lossless:
@@ -440,6 +442,19 @@ func (fs *FilerSink) onCorruptChunk(key string, entry *filer_pb.Entry, err error
return err
}
// onReplicateChunkError handles a non-size-mismatch replicateChunks failure.
// Skip (return nil) only when the live source has moved past this version —
// deleted or strictly-newer mtime — so a later event carries the current
// content and the skip is lossless. Otherwise propagate so the offset stays
// put and the event is retried; returning nil would silently drop the file.
func (fs *FilerSink) onReplicateChunkError(key string, entry *filer_pb.Entry, err error) error {
if fs.hasSourceNewerVersion(key, getEntryMtimeNs(entry)) {
glog.Warningf("skip stale entry %s, source superseded during replicate: %v", key, err)
return nil
}
return fmt.Errorf("replicate entry chunks %s: %w", key, err)
}
// updateAction decides how UpdateEntry reconciles an incoming source version with
// the destination's current entry.
type updateAction int
@@ -109,6 +109,28 @@ func TestOnCorruptChunkRefusesWhenSupersessionUnconfirmed(t *testing.T) {
}
}
// onReplicateChunkError must NOT swallow a transient/partial replicate failure
// (a volume-id lookup race or unretried manifest-chunk resolve during a write
// burst) when it cannot confirm the source has moved on. Here filerSource is
// nil, so hasSourceNewerVersion is always false — the "supersession unconfirmed"
// case. Returning nil would let the metadata subscription advance its offset
// past an event whose file was never written, silently dropping it (the
// filer.backup partial-landing bug). It must propagate so the offset stays put
// and the event is reprocessed. Genuine source-404 (gone/superseded) skipping is
// covered by TestSourceSupersedes, which gates the return-nil branch.
func TestOnReplicateChunkErrorPropagatesWhenSupersessionUnconfirmed(t *testing.T) {
fs := &FilerSink{} // filerSource nil => hasSourceNewerVersion always false
sentinel := errors.New("replicate manifest data chunks 7,02def: volume id 7 not found")
got := fs.onReplicateChunkError("/buckets/x/model.pt",
&filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{Mtime: 5, MtimeNs: 200}},
sentinel)
if !errors.Is(got, sentinel) {
t.Fatalf("expected the transient replicate error to be propagated (not swallowed), got %v", got)
}
}
// chooseUpdateAction decides skip vs repair vs normal. A destination left
// truncated by an earlier failed replication can carry a newer mtime (the
// source preserved an old mtime while the partial copy was written recently),
@@ -0,0 +1,45 @@
package s3api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// A presigned URL that signs content-type carries
// X-Amz-SignedHeaders=content-type%3Bhost. Some clients and proxies decode
// the %3B into a raw ';', which RFC 3986 permits in a query string and AWS
// accepts, but Go's url.ParseQuery drops the whole pair — verification then
// fails with MissingFields. The router middleware re-encodes the ';' so the
// parameter survives.
func TestPresignedPutSignedContentTypeWithRawSemicolon(t *testing.T) {
iam := newTestIAM()
req, err := newTestRequest(http.MethodPut, "http://127.0.0.1:9000/bucket/key.png", 0, nil)
if err != nil {
t.Fatalf("newTestRequest: %v", err)
}
req.Header.Set("Content-Type", "image/png")
if err := preSignV4WithHeaders(iam, req, "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 600, []string{"host", "content-type"}); err != nil {
t.Fatalf("preSignV4WithHeaders: %v", err)
}
req.URL.RawQuery = strings.ReplaceAll(req.URL.RawQuery, "%3B", ";")
if _, errCode := iam.reqSignatureV4Verify(req); errCode == s3err.ErrNone {
t.Fatal("raw-semicolon query unexpectedly verified without normalization")
}
errCode := s3err.ErrInternalError
handler := util_http.EscapeSemicolonsInQuery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, errCode = iam.reqSignatureV4Verify(r)
}))
handler.ServeHTTP(httptest.NewRecorder(), req)
if errCode != s3err.ErrNone {
t.Fatalf("expected ErrNone through semicolon-normalizing middleware, got %v", errCode)
}
}
@@ -0,0 +1,150 @@
package s3api
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
"github.com/seaweedfs/seaweedfs/weed/iam/oidc"
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A raw OIDC token sent as Authorization: Bearer must clear the same role
// trust-policy gate as AssumeRoleWithWebIdentity. The provider's role mapping
// alone must not mint a principal for a role whose trust policy rejects the
// token's federated provider.
func TestOIDCBearerEnforcesRoleTrustPolicy(t *testing.T) {
ctx := context.Background()
key, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
jwks := map[string]interface{}{
"keys": []map[string]interface{}{{
"kty": "RSA",
"kid": "bearer-test-key",
"use": "sig",
"alg": "RS256",
"n": base64.RawURLEncoding.EncodeToString(key.PublicKey.N.Bytes()),
"e": "AQAB",
}},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/jwks" {
json.NewEncoder(w).Encode(jwks)
}
}))
defer server.Close()
provider := oidc.NewOIDCProvider("test-oidc")
require.NoError(t, provider.Initialize(&oidc.OIDCConfig{
Issuer: server.URL,
ClientID: "test-client",
JWKSUri: server.URL + "/jwks",
RoleMapping: &providers.RoleMapping{
Rules: []providers.MappingRule{
{Claim: "groups", Value: "denied-group", Role: "arn:aws:iam::role/BearerDeniedRole"},
{Claim: "groups", Value: "trusted-group", Role: "arn:aws:iam::role/BearerTrustedRole"},
},
},
}))
iamManager := integration.NewIAMManager()
require.NoError(t, iamManager.Initialize(&integration.IAMConfig{
STS: &sts.STSConfig{
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
Issuer: "test-sts",
SigningKey: []byte("test-signing-key-32-characters-long"),
},
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
}, func() string { return "localhost:8888" }))
require.NoError(t, iamManager.RegisterIdentityProvider(provider))
require.NoError(t, iamManager.CreatePolicy(ctx, "", "BearerTestPolicy", &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Action: []string{"s3:*"},
Resource: []string{"arn:aws:s3:::*", "arn:aws:s3:::*/*"},
}},
}))
trustPolicy := func(federatedProvider string) *policy.PolicyDocument {
return &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{{
Effect: "Allow",
Principal: map[string]interface{}{"Federated": federatedProvider},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
}},
}
}
// trusts a different federated provider than the one issuing the token
require.NoError(t, iamManager.CreateRole(ctx, "", "BearerDeniedRole", &integration.RoleDefinition{
RoleName: "BearerDeniedRole",
TrustPolicy: trustPolicy("other-provider"),
AttachedPolicies: []string{"BearerTestPolicy"},
}))
require.NoError(t, iamManager.CreateRole(ctx, "", "BearerTrustedRole", &integration.RoleDefinition{
RoleName: "BearerTrustedRole",
TrustPolicy: trustPolicy("test-oidc"),
AttachedPolicies: []string{"BearerTestPolicy"},
}))
signJWT := func(groups ...string) string {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iss": server.URL,
"sub": "bearer-user",
"aud": "test-client",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
"groups": groups,
})
token.Header["kid"] = "bearer-test-key"
signed, err := token.SignedString(key)
require.NoError(t, err)
return signed
}
s3iam := NewS3IAMIntegration(iamManager, "localhost:8888")
authenticate := func(token string) (*IAMIdentity, s3err.ErrorCode) {
req := httptest.NewRequest("GET", "/test-bucket/test-object", http.NoBody)
req.Header.Set("Authorization", "Bearer "+token)
return s3iam.AuthenticateJWT(ctx, req)
}
deniedToken := signJWT("denied-group")
// negative control: STS refuses to issue a session for this token and role
_, err = iamManager.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
RoleArn: "arn:aws:iam::role/BearerDeniedRole",
WebIdentityToken: deniedToken,
RoleSessionName: "trust-policy-check",
})
require.ErrorContains(t, err, "trust policy")
// the direct bearer path must reject the same token
identity, errCode := authenticate(deniedToken)
assert.Equal(t, s3err.ErrAccessDenied, errCode)
assert.Nil(t, identity)
// a role whose trust policy trusts the issuing provider still works
identity, errCode = authenticate(signJWT("trusted-group"))
require.Equal(t, s3err.ErrNone, errCode)
assert.Equal(t, "arn:aws:iam::role/BearerTrustedRole", identity.Principal)
}
+7
View File
@@ -143,6 +143,13 @@ func (s3iam *S3IAMIntegration) AuthenticateJWT(ctx context.Context, r *http.Requ
return nil, s3err.ErrAccessDenied
}
// Same trust-policy gate as AssumeRoleWithWebIdentity: the role mapping
// alone must not grant a role that STS would refuse for this token.
if err := s3iam.iamManager.ValidateTrustPolicyForWebIdentity(ctx, identity.RoleArn, sessionToken, nil); err != nil {
glog.V(3).Infof("OIDC bearer token rejected by trust policy of role %s: %v", identity.RoleArn, err)
return nil, s3err.ErrAccessDenied
}
// Create claims map and populate with standard claims and attributes
claims := make(map[string]interface{}, len(identity.Attributes)+5)
@@ -24,14 +24,14 @@ func TestClassifyCopySourceError(t *testing.T) {
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},
{"nil entry", nil, nil, s3err.ErrNoSuchKey},
{"directory entry", &filer_pb.Entry{IsDirectory: true}, nil, s3err.ErrNoSuchKey},
{"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},
{"not found sentinel", nil, filer_pb.ErrNotFound, s3err.ErrNoSuchKey},
{"wrapped not found", nil, fmt.Errorf("read %s: %w", "o", filer_pb.ErrNotFound), s3err.ErrNoSuchKey},
{"grpc not found", nil, status.Error(codes.NotFound, "no entry"), s3err.ErrNoSuchKey},
{"invalid version id", nil, errInvalidVersionID, s3err.ErrNoSuchKey},
{"delete marker error", nil, ErrDeleteMarker, s3err.ErrNoSuchKey},
{"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.
+7
View File
@@ -25,6 +25,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/stats"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -1189,6 +1190,12 @@ func (s3a *S3ApiServer) createLookupFileIdFunction() func(context.Context, strin
// streamFromVolumeServersWithSSE handles streaming with inline SSE decryption
func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType string, bucket, object, versionId string) error {
if entry.RemoteEntry != nil && entry.RemoteEntry.RemoteSize > 0 {
// inline content is served locally without chunks
hit := !entry.IsInRemoteOnly() || len(entry.Content) > 0
stats.RecordRemoteCacheRead(stats.RemoteCacheSourceS3, bucket, hit)
}
// If not encrypted, use fast path without decryption
if sseType == "" || sseType == "None" {
return s3a.streamFromVolumeServers(w, r, entry, sseType, bucket, object, versionId)
+25 -29
View File
@@ -10,6 +10,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// GetObjectAclHandler Get object ACL
@@ -268,35 +269,7 @@ func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Reque
return
}
// Calculate the correct directory for ACL update
var updateDirectory string
if versioningConfigured {
if versionId != "" && versionId != "null" {
// Versioned object - update the specific version file in .versions directory
updateDirectory = s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
} else {
// Latest version in versioned bucket - could be null version or versioned object
// Extract version ID from the entry to determine where it's stored
var actualVersionId string
if entry.Extended != nil {
if versionIdBytes, exists := entry.Extended[s3_constants.ExtVersionIdKey]; exists {
actualVersionId = string(versionIdBytes)
}
}
if actualVersionId == "null" || actualVersionId == "" {
// Null version (pre-versioning object) - stored as regular file
updateDirectory = s3a.bucketDir(bucket)
} else {
// Versioned object - stored in .versions directory
updateDirectory = s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
}
} else {
// Non-versioned object - stored as regular file
updateDirectory = s3a.bucketDir(bucket)
}
updateDirectory := s3a.objectMetadataUpdateDirectory(bucket, object, versioningConfigured, versionId, entry)
// Update the object with new ACL metadata
err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
@@ -320,3 +293,26 @@ func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Reque
glog.V(3).Infof("PutObjectAclHandler: Successfully updated ACL for %s/%s by user %s", bucket, object, amzAccountId)
writeSuccessResponseEmpty(w, r)
}
// objectMetadataUpdateDirectory returns the filer directory holding the entry an in-place
// metadata update (ACL or tags) must target. A regular object lives under its full key's
// parent directory, so a nested key must not fall back to the bucket root, which would
// rewrite a different object sharing the same basename.
func (s3a *S3ApiServer) objectMetadataUpdateDirectory(bucket, object string, versioningConfigured bool, versionId string, entry *filer_pb.Entry) string {
if versioningConfigured {
if versionId != "" && versionId != "null" {
return s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
var actualVersionId string
if entry.Extended != nil {
if versionIdBytes, exists := entry.Extended[s3_constants.ExtVersionIdKey]; exists {
actualVersionId = string(versionIdBytes)
}
}
if actualVersionId != "null" && actualVersionId != "" {
return s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
}
dir, _ := util.NewFullPath(s3a.bucketDir(bucket), object).DirAndName()
return dir
}
@@ -0,0 +1,49 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// TestObjectMetadataUpdateDirectory guards against a metadata-update scope bypass shared by
// PutObjectAcl and Put/DeleteObjectTagging: a nested object key must resolve to its own
// parent directory, not the bucket root, otherwise updating the ACL or tags of
// allowed/protected.txt would rewrite a different protected.txt at the bucket root.
func TestObjectMetadataUpdateDirectory(t *testing.T) {
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
const bucket = "target-bucket"
bucketDir := "/buckets/target-bucket"
versioned := func(id string) *filer_pb.Entry {
return &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte(id)}}
}
tests := []struct {
name string
object string
versioningConfigured bool
versionId string
entry *filer_pb.Entry
want string
}{
{"non-versioned nested key", "allowed/protected.txt", false, "", &filer_pb.Entry{}, bucketDir + "/allowed"},
{"non-versioned root key", "protected.txt", false, "", &filer_pb.Entry{}, bucketDir},
{"non-versioned deep key", "a/b/c/protected.txt", false, "", &filer_pb.Entry{}, bucketDir + "/a/b/c"},
{"null version nested key", "allowed/protected.txt", true, "", versioned("null"), bucketDir + "/allowed"},
{"explicit null version nested key", "allowed/protected.txt", true, "null", versioned("null"), bucketDir + "/allowed"},
{"empty version nested key", "allowed/protected.txt", true, "", &filer_pb.Entry{}, bucketDir + "/allowed"},
{"specific version nested key", "allowed/protected.txt", true, "v1", versioned("v1"), bucketDir + "/allowed/protected.txt" + s3_constants.VersionsFolder},
{"latest versioned nested key", "allowed/protected.txt", true, "", versioned("v1"), bucketDir + "/allowed/protected.txt" + s3_constants.VersionsFolder},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := s3a.objectMetadataUpdateDirectory(bucket, tt.object, tt.versioningConfigured, tt.versionId, tt.entry)
if got != tt.want {
t.Errorf("objectMetadataUpdateDirectory(%q) = %q, want %q", tt.object, got, tt.want)
}
})
}
}
+13 -14
View File
@@ -69,16 +69,14 @@ 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.
// classifyCopySourceError maps a copy-source lookup to an S3 error: a missing
// or directory source is NoSuchKey like AWS, 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
return s3err.ErrNoSuchKey
}
// 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
}
@@ -86,7 +84,7 @@ func classifyCopySourceError(entry *filer_pb.Entry, err error) s3err.ErrorCode {
}
if errors.Is(err, filer_pb.ErrNotFound) || status.Code(err) == codes.NotFound ||
errors.Is(err, errInvalidVersionID) || errors.Is(err, ErrDeleteMarker) {
return s3err.ErrInvalidCopySource
return s3err.ErrNoSuchKey
}
if isTransientFilerError(err) {
return s3err.ErrServiceUnavailable
@@ -171,10 +169,10 @@ 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)
// Only a missing bucket is the client's fault; a store error must stay
// retryable, matching the destination-bucket lookup.
// A missing source bucket is NoSuchBucket like AWS; a store error must
// stay retryable, matching the destination-bucket lookup.
if errors.Is(err, filer_pb.ErrNotFound) {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
return
}
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
@@ -369,7 +367,8 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
// to preserve the encryption header filtering. Fixes GitHub #7562.
processedMetadata, tagErr := processMetadataBytes(r.Header, dstEntry.Extended, replaceMeta, replaceTagging)
if tagErr != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
glog.Errorf("CopyObjectHandler ValidateTags error %s: %v", r.URL, tagErr)
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidTag)
return
}
@@ -870,10 +869,10 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
srcVersioningState, err := s3a.getVersioningState(srcBucket)
if err != nil {
glog.Errorf("Error checking versioning state for source bucket %s: %v", srcBucket, err)
// Only a missing bucket is the client's fault; a store error must stay
// retryable, matching the destination-bucket lookup.
// A missing source bucket is NoSuchBucket like AWS; a store error must
// stay retryable, matching the destination-bucket lookup.
if errors.Is(err, filer_pb.ErrNotFound) {
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
return
}
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
+8 -58
View File
@@ -199,35 +199,10 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
return
}
// For versioned objects, determine the correct directory based on the version
var updateDirectory string
if versionId != "" {
// Specific version requested
if versionId == "null" {
// Null version (pre-versioning object) - stored as regular file
updateDirectory = s3a.bucketDir(bucket)
} else {
// Versioned object - stored in .versions directory
updateDirectory = s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
} else {
// Latest version in versioned bucket - could be null version or versioned object
// Extract version ID from the entry to determine where it's stored
var actualVersionId string
if entry.Extended != nil {
if versionIdBytes, exists := entry.Extended[s3_constants.ExtVersionIdKey]; exists {
actualVersionId = string(versionIdBytes)
}
}
if actualVersionId == "null" || actualVersionId == "" {
// Null version (pre-versioning object) - stored as regular file
updateDirectory = s3a.bucketDir(bucket)
} else {
// Versioned object - stored in .versions directory
updateDirectory = s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
}
// For versioned objects, resolve the directory holding the entry to update. A null
// version lives under its full key's parent directory, so a nested key must not fall
// back to the bucket root and rewrite a different object sharing the same basename.
updateDirectory := s3a.objectMetadataUpdateDirectory(bucket, object, versioningConfigured, versionId, entry)
// Remove old tags and add new ones
for k := range entry.Extended {
@@ -343,35 +318,10 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
return
}
// For versioned objects, determine the correct directory based on the version
var updateDirectory string
if versionId != "" {
// Specific version requested
if versionId == "null" {
// Null version (pre-versioning object) - stored as regular file
updateDirectory = s3a.bucketDir(bucket)
} else {
// Versioned object - stored in .versions directory
updateDirectory = s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
} else {
// Latest version in versioned bucket - could be null version or versioned object
// Extract version ID from the entry to determine where it's stored
var actualVersionId string
if entry.Extended != nil {
if versionIdBytes, exists := entry.Extended[s3_constants.ExtVersionIdKey]; exists {
actualVersionId = string(versionIdBytes)
}
}
if actualVersionId == "null" || actualVersionId == "" {
// Null version (pre-versioning object) - stored as regular file
updateDirectory = s3a.bucketDir(bucket)
} else {
// Versioned object - stored in .versions directory
updateDirectory = s3a.bucketDir(bucket) + "/" + object + s3_constants.VersionsFolder
}
}
// For versioned objects, resolve the directory holding the entry to update. A null
// version lives under its full key's parent directory, so a nested key must not fall
// back to the bucket root and rewrite a different object sharing the same basename.
updateDirectory := s3a.objectMetadataUpdateDirectory(bucket, object, versioningConfigured, versionId, entry)
// Remove all tags
hasDeletion := false
+2
View File
@@ -724,6 +724,8 @@ func (s3a *S3ApiServer) UnifiedPostHandler(w http.ResponseWriter, r *http.Reques
}
func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
// runs before subrouter matching so Queries() matchers see the fixed query
router.Use(util_http.EscapeSemicolonsInQuery)
// API Router
apiRouter := router.PathPrefix("/").Subrouter()
apiRouter.Use(request_id.Middleware)
@@ -515,6 +515,9 @@ func eachLogEntryFn(req *filer_pb.SubscribeMetadataRequest, sender metadataStrea
}
}
event := &filer_pb.SubscribeMetadataResponse{}
// proto.Unmarshal (not UnmarshalVT) validates UTF-8 in string fields, so
// malformed metadata is rejected here instead of reaching path filtering
// and subscribers.
if err := proto.Unmarshal(logEntry.Data, event); err != nil {
glog.Errorf("unexpected unmarshal filer_pb.SubscribeMetadataResponse: %v", err)
return false, fmt.Errorf("unexpected unmarshal filer_pb.SubscribeMetadataResponse: %w", err)
+41 -26
View File
@@ -221,58 +221,53 @@ func (fs *FilerServer) maybeCheckJwtAuthorization(r *http.Request, isWrite bool)
// checkJwtAuthorization verifies the request carries a valid filer JWT for the
// requested access level and, for prefix-restricted tokens, that every path in
// scopedPaths falls within the token's AllowedPrefixes. Callers whose write
// target is not r.URL.Path — the TUS handler, whose URL points at the /.tus
// route — pass the resolved filer path(s) here instead.
// scopedPaths falls within AllowedPrefixes.
func (fs *FilerServer) checkJwtAuthorization(r *http.Request, isWrite bool, scopedPaths []string) bool {
claims, ok := fs.authenticateFilerJwt(r, isWrite)
if !ok {
return false
}
return authorizeFilerJwtPaths(r, claims, scopedPaths)
}
// authenticateFilerJwt verifies the JWT signature and method claims. A nil claims
// with ok true means authentication is disabled for this access level. Splitting
// authentication from path authorization lets a handler load an indirect resource
// (the TUS session target) only after the caller's credential is verified.
func (fs *FilerServer) authenticateFilerJwt(r *http.Request, isWrite bool) (*security.SeaweedFilerClaims, bool) {
var signingKey security.SigningKey
if isWrite {
signingKey = fs.filerGuard.SigningKey()
if len(signingKey) == 0 {
return true
}
} else {
signingKey = fs.filerGuard.ReadSigningKey()
if len(signingKey) == 0 {
return true
}
}
if len(signingKey) == 0 {
return nil, true
}
tokenStr := security.GetJwt(r)
if tokenStr == "" {
glog.V(1).Infof("missing jwt from %s", r.RemoteAddr)
return false
return nil, false
}
token, err := security.DecodeJwt(signingKey, tokenStr, &security.SeaweedFilerClaims{})
if err != nil {
glog.V(1).Infof("jwt verification error from %s: %v", r.RemoteAddr, err)
return false
return nil, false
}
if !token.Valid {
glog.V(1).Infof("jwt invalid from %s: %v", r.RemoteAddr, tokenStr)
return false
return nil, false
}
claims, ok := token.Claims.(*security.SeaweedFilerClaims)
if !ok {
glog.V(1).Infof("jwt claims not of type *SeaweedFilerClaims from %s", r.RemoteAddr)
return false
return nil, false
}
if len(claims.AllowedPrefixes) > 0 {
// Copy and move name their source via a query parameter, not r.URL.Path.
// Scope every path the request reads or relocates, or a prefix-restricted
// token could reach data outside its allowed subtree.
for _, p := range scopedPaths {
if !anyComponentPrefixMatches(claims.AllowedPrefixes, p) {
glog.V(1).Infof("jwt path not allowed from %s: %v", r.RemoteAddr, p)
return false
}
}
}
if len(claims.AllowedMethods) > 0 {
hasMethod := false
for _, method := range claims.AllowedMethods {
@@ -283,10 +278,30 @@ func (fs *FilerServer) checkJwtAuthorization(r *http.Request, isWrite bool, scop
}
if !hasMethod {
glog.V(1).Infof("jwt method not allowed from %s: %v", r.RemoteAddr, r.Method)
return false
return nil, false
}
}
return claims, true
}
// authorizeFilerJwtPaths checks the resource scope after authentication. A
// prefix-restricted token must name at least one resource path; an empty list
// fails closed, so a caller that cannot resolve its target never falls open.
func authorizeFilerJwtPaths(r *http.Request, claims *security.SeaweedFilerClaims, scopedPaths []string) bool {
if claims == nil || len(claims.AllowedPrefixes) == 0 {
return true
}
if len(scopedPaths) == 0 {
glog.V(1).Infof("jwt resource path missing from %s", r.RemoteAddr)
return false
}
for _, p := range scopedPaths {
if !anyComponentPrefixMatches(claims.AllowedPrefixes, p) {
glog.V(1).Infof("jwt path not allowed from %s: %v", r.RemoteAddr, p)
return false
}
}
return true
}
@@ -193,6 +193,12 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
return
}
if entry.Remote != nil && entry.Remote.RemoteSize > 0 {
// inline content is served locally without chunks
hit := !entry.IsInRemoteOnly() || len(entry.Content) > 0
stats.RecordRemoteCacheRead(stats.RemoteCacheSourceFiler, fs.filer.DetectBucket(entry.FullPath), hit)
}
ProcessRangeRequest(r, w, totalSize, mimeType, func(offset int64, size int64) (filer.DoStreamContent, error) {
if offset+size <= int64(len(entry.Content)) {
return func(writer io.Writer) error {
+82 -52
View File
@@ -17,6 +17,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -28,10 +29,9 @@ func (fs *FilerServer) tusHandler(w http.ResponseWriter, r *http.Request) {
// OPTIONS is capability discovery only and carries no data, so it is left
// unauthenticated like the main filer OPTIONS handler. Every other TUS method
// mutates or reads the filer namespace and must pass the same JWT check the
// rest of the filer API enforces: the TUS routes are otherwise only wrapped by
// filerGuard.WhiteList, which is a no-op for the filer, so without this they
// bypass jwt.filer_signing entirely.
// authenticates the credential first, then authorizes the server-stored
// TargetPath below, once routing has resolved which resource it acts on.
var claims *security.SeaweedFilerClaims
if r.Method != http.MethodOptions {
tusVersion := r.Header.Get("Tus-Resumable")
if tusVersion != TusVersion {
@@ -39,7 +39,8 @@ func (fs *FilerServer) tusHandler(w http.ResponseWriter, r *http.Request) {
return
}
if !fs.checkTusJwtAuthorization(r) {
var authenticated bool
if claims, authenticated = fs.authenticateFilerJwt(r, r.Method != http.MethodHead); !authenticated {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
@@ -53,18 +54,51 @@ func (fs *FilerServer) tusHandler(w http.ResponseWriter, r *http.Request) {
// Check if this is an upload location (contains upload ID after {tusPrefix}/.uploads/)
uploadsPrefix := tusPrefix + "/.uploads/"
if strings.HasPrefix(reqPath, uploadsPrefix) {
// Session ids this server mints are canonical UUIDs. Rejecting aliases
// (a trailing path or any non-canonical spelling) keeps one URL bound to
// one stored authorization resource.
uploadID := strings.TrimPrefix(reqPath, uploadsPrefix)
uploadID = strings.Split(uploadID, "/")[0] // Get just the ID, not any trailing path
if !isCanonicalTusUploadID(uploadID) {
writeTusSessionNotFound(w, r.Method)
return
}
switch r.Method {
case http.MethodHead, http.MethodPatch, http.MethodDelete:
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
ctx := r.Context()
if r.Method == http.MethodPatch {
ctx = context.WithoutCancel(ctx)
}
session, err := fs.readTusSessionInfo(ctx, uploadID)
if err != nil {
// A transient filer error resolves to "not found"; log it so it is
// distinguishable from a genuinely missing session.
glog.V(1).Infof("TUS session %s not resolved: %v", uploadID, err)
writeTusSessionNotFound(w, r.Method)
return
}
if !authorizeFilerJwtPaths(r, claims, []string{session.TargetPath}) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
if err := fs.loadTusSessionChunks(ctx, session); err != nil {
glog.Errorf("Failed to load TUS session %s chunks: %v", uploadID, err)
writeTusSessionNotFound(w, r.Method)
return
}
switch r.Method {
case http.MethodHead:
fs.tusHeadHandler(w, r, uploadID)
fs.tusHeadHandler(w, session)
case http.MethodPatch:
fs.tusPatchHandler(w, r, uploadID)
fs.tusPatchHandler(w, r, session)
case http.MethodDelete:
fs.tusDeleteHandler(w, r, uploadID)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
fs.tusDeleteHandler(w, r, session)
}
return
}
@@ -74,28 +108,31 @@ func (fs *FilerServer) tusHandler(w http.ResponseWriter, r *http.Request) {
case http.MethodOptions:
fs.tusOptionsHandler(w, r)
case http.MethodPost:
if !authorizeFilerJwtPaths(r, claims, []string{fs.tusTargetPath(r)}) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
fs.tusCreateHandler(w, r)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// checkTusJwtAuthorization enforces filer JWT authorization for a TUS request.
// HEAD reads the current offset (read access); POST/PATCH/DELETE mutate the
// namespace (write access). Only creation (POST) names a new target path, taken
// from the request URL, so prefix-restricted tokens are scoped against that
// resolved filer path rather than the /.tus route. HEAD/PATCH/DELETE act on an
// existing session addressed by an unguessable id, whose target was already
// scope-checked at creation, so no further path scoping is applied to them.
func (fs *FilerServer) checkTusJwtAuthorization(r *http.Request) bool {
isWrite := r.Method != http.MethodHead
var scopedPaths []string
if r.Method == http.MethodPost {
if target := fs.tusTargetPath(r); target != "" && target != "/" {
scopedPaths = append(scopedPaths, target)
}
// writeTusSessionNotFound answers a request whose session cannot be resolved.
// DELETE is idempotent and returns 204 for a missing session; other verbs 404.
func writeTusSessionNotFound(w http.ResponseWriter, method string) {
if method == http.MethodDelete {
w.WriteHeader(http.StatusNoContent)
return
}
return fs.checkJwtAuthorization(r, isWrite, scopedPaths)
http.Error(w, "Upload not found", http.StatusNotFound)
}
// isCanonicalTusUploadID reports whether uploadID is a canonical UUID, the only
// form this server mints, so an aliased or crafted id cannot address a session.
func isCanonicalTusUploadID(uploadID string) bool {
id, err := uuid.Parse(uploadID)
return err == nil && id.String() == uploadID
}
// tusTargetPath resolves the filer path a TUS create request targets from the
@@ -107,7 +144,17 @@ func (fs *FilerServer) tusTargetPath(r *http.Request) string {
if target != "" && !strings.HasPrefix(target, "/") {
target = "/" + target
}
return target
return canonicalTusTargetPath(target)
}
// canonicalTusTargetPath normalises an absolute filer target, or returns "" when
// the input is empty or not absolute, so authorization and the final write agree
// on one path.
func canonicalTusTargetPath(target string) string {
if target == "" || !strings.HasPrefix(target, "/") {
return ""
}
return path.Clean(target)
}
// writeTusCompleteError maps a completeTusUpload failure to the same HTTP status
@@ -220,9 +267,8 @@ func (fs *FilerServer) tusCreateHandler(w http.ResponseWriter, r *http.Request)
// Check if upload is complete
if bytesWritten == session.Size {
// Refresh session to get updated chunks
session, err = fs.getTusSession(ctx, uploadID)
if err != nil {
// Ensure the pinned session still exists, then refresh its chunks.
if err = fs.refreshTusSessionChunks(ctx, session); err != nil {
glog.Errorf("Failed to get updated TUS session: %v", err)
http.Error(w, "Failed to complete upload", http.StatusInternalServerError)
return
@@ -242,15 +288,7 @@ func (fs *FilerServer) tusCreateHandler(w http.ResponseWriter, r *http.Request)
}
// tusHeadHandler handles HEAD requests to get current upload offset
func (fs *FilerServer) tusHeadHandler(w http.ResponseWriter, r *http.Request, uploadID string) {
ctx := r.Context()
session, err := fs.getTusSession(ctx, uploadID)
if err != nil {
http.Error(w, "Upload not found", http.StatusNotFound)
return
}
func (fs *FilerServer) tusHeadHandler(w http.ResponseWriter, session *TusSession) {
w.Header().Set("Upload-Offset", strconv.FormatInt(session.Offset, 10))
w.Header().Set("Upload-Length", strconv.FormatInt(session.Size, 10))
w.Header().Set("Cache-Control", "no-store")
@@ -258,7 +296,7 @@ func (fs *FilerServer) tusHeadHandler(w http.ResponseWriter, r *http.Request, up
}
// tusPatchHandler handles PATCH requests to upload data
func (fs *FilerServer) tusPatchHandler(w http.ResponseWriter, r *http.Request, uploadID string) {
func (fs *FilerServer) tusPatchHandler(w http.ResponseWriter, r *http.Request, session *TusSession) {
// Use a context that ignores cancellation from the request context.
// The filer's connection has an inactivity timeout: after the request body is fully read,
// internal operations (assigning file IDs, uploading to volume servers, completing uploads)
@@ -272,13 +310,6 @@ func (fs *FilerServer) tusPatchHandler(w http.ResponseWriter, r *http.Request, u
return
}
// Get current session
session, err := fs.getTusSession(ctx, uploadID)
if err != nil {
http.Error(w, "Upload not found", http.StatusNotFound)
return
}
// Validate Upload-Offset header
uploadOffsetStr := r.Header.Get("Upload-Offset")
if uploadOffsetStr == "" {
@@ -319,9 +350,8 @@ func (fs *FilerServer) tusPatchHandler(w http.ResponseWriter, r *http.Request, u
// Check if upload is complete
if newOffset == session.Size {
// Refresh session to get updated chunks
session, err = fs.getTusSession(ctx, uploadID)
if err != nil {
// Ensure the authorized session still exists, then refresh its chunks.
if err = fs.refreshTusSessionChunks(ctx, session); err != nil {
glog.Errorf("Failed to get updated TUS session: %v", err)
http.Error(w, "Failed to complete upload", http.StatusInternalServerError)
return
@@ -339,10 +369,10 @@ func (fs *FilerServer) tusPatchHandler(w http.ResponseWriter, r *http.Request, u
}
// tusDeleteHandler handles DELETE requests to cancel uploads
func (fs *FilerServer) tusDeleteHandler(w http.ResponseWriter, r *http.Request, uploadID string) {
func (fs *FilerServer) tusDeleteHandler(w http.ResponseWriter, r *http.Request, session *TusSession) {
ctx := r.Context()
if err := fs.deleteTusSession(ctx, uploadID); err != nil {
if err := fs.deleteTusSession(ctx, session.ID); err != nil {
glog.Errorf("Failed to delete TUS session: %v", err)
http.Error(w, "Failed to delete upload", http.StatusInternalServerError)
return
+114
View File
@@ -0,0 +1,114 @@
package weed_server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// TestFilerServer_tusHandler_CrossPrefixSessionHijack reproduces
// GHSA-99q7-x53r-6j4g: a prefix-restricted token acting on another tenant's TUS
// session (HEAD/PATCH/DELETE) must be scoped against the session's stored
// TargetPath, not authorized on signature and method alone. The victim's session
// must survive a denied mutation.
func TestFilerServer_tusHandler_CrossPrefixSessionHijack(t *testing.T) {
tests := []struct {
name string
method string
prefix string
expectStatus int
expectExists bool
}{
{"cross-prefix HEAD denied", http.MethodHead, "/buckets/allowed", http.StatusUnauthorized, true},
{"matching-prefix HEAD allowed", http.MethodHead, "/buckets/secret", http.StatusOK, true},
{"cross-prefix PATCH denied", http.MethodPatch, "/buckets/allowed", http.StatusUnauthorized, true},
{"matching-prefix PATCH allowed", http.MethodPatch, "/buckets/secret", http.StatusNoContent, true},
{"cross-prefix DELETE denied", http.MethodDelete, "/buckets/allowed", http.StatusUnauthorized, true},
{"matching-prefix DELETE allowed", http.MethodDelete, "/buckets/secret", http.StatusNoContent, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fs, store := newTusTestServer(t, map[string]string{tusTestUploadID: "/buckets/secret/victim.bin"})
signingKey := tusTestWriteKey
if tt.method == http.MethodHead {
signingKey = tusTestReadKey
}
token := signFilerToken(t, signingKey, []string{tt.prefix}, nil)
req := httptest.NewRequest(tt.method, "/.tus/.uploads/"+tusTestUploadID, http.NoBody)
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Tus-Resumable", TusVersion)
if tt.method == http.MethodPatch {
req.Header.Set("Content-Type", "application/offset+octet-stream")
req.Header.Set("Upload-Offset", "0")
}
rec := httptest.NewRecorder()
fs.tusHandler(rec, req)
if rec.Code != tt.expectStatus {
t.Fatalf("%s status = %d, want %d; body=%q", tt.method, rec.Code, tt.expectStatus, rec.Body.String())
}
_, err := store.FindEntry(context.Background(), util.FullPath(fs.tusSessionInfoPath(tusTestUploadID)))
if tt.expectExists && err != nil {
t.Fatalf("session removed after %s: %v", tt.method, err)
}
if !tt.expectExists && err == nil {
t.Fatalf("session still present after authorized %s", tt.method)
}
})
}
}
// TestFilerServer_tusHandler_RejectsAliasesAndInvalidMetadata covers the routing
// and metadata guards: a non-canonical or aliased upload id is rejected before
// any lookup, and a session whose stored id, target or size is unusable resolves
// to "not found" rather than being authorized or acted upon.
func TestFilerServer_tusHandler_RejectsAliasesAndInvalidMetadata(t *testing.T) {
tests := []struct {
name string
routeID string
stored TusSession
}{
{"trailing path alias", tusTestUploadID + "/extra", TusSession{ID: tusTestUploadID, TargetPath: "/buckets/secret/victim.bin", Size: 1}},
{"non-canonical route id", "not-a-uuid", TusSession{ID: tusTestUploadID, TargetPath: "/buckets/secret/victim.bin", Size: 1}},
{"stored id mismatch", tusTestUploadID, TusSession{ID: "00000000-0000-0000-0000-000000000000", TargetPath: "/buckets/secret/victim.bin", Size: 1}},
{"empty stored target", tusTestUploadID, TusSession{ID: tusTestUploadID, TargetPath: "", Size: 1}},
{"root stored target", tusTestUploadID, TusSession{ID: tusTestUploadID, TargetPath: "/", Size: 1}},
{"relative stored target", tusTestUploadID, TusSession{ID: tusTestUploadID, TargetPath: "buckets/secret/x.bin", Size: 1}},
{"oversize stored size", tusTestUploadID, TusSession{ID: tusTestUploadID, TargetPath: "/buckets/secret/victim.bin", Size: TusMaxSize + 1}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fs, store := newTusTestServer(t, nil)
data, err := json.Marshal(&tt.stored)
if err != nil {
t.Fatalf("marshal session: %v", err)
}
if err := store.InsertEntry(context.Background(), &filer.Entry{
FullPath: util.FullPath(fs.tusSessionInfoPath(tusTestUploadID)),
Content: data,
}); err != nil {
t.Fatalf("seed session: %v", err)
}
req := httptest.NewRequest(http.MethodHead, "/.tus/.uploads/"+tt.routeID, nil)
req.Header.Set("Authorization", "Bearer "+signFilerToken(t, tusTestReadKey, nil, nil))
req.Header.Set("Tus-Resumable", TusVersion)
rec := httptest.NewRecorder()
fs.tusHandler(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("HEAD %s = %d, want %d; body=%q", tt.routeID, rec.Code, http.StatusNotFound, rec.Body.String())
}
})
}
}
+132 -31
View File
@@ -1,13 +1,24 @@
package weed_server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
)
const (
tusTestWriteKey = "write-secret"
tusTestReadKey = "read-secret"
tusTestUploadID = "9f6f0d4b-6556-48f6-b953-0d8fca1966f1"
)
// signFilerToken builds a signed filer JWT for tests.
@@ -27,46 +38,79 @@ func signFilerToken(t *testing.T, signingKey string, allowedPrefixes, allowedMet
return str
}
func TestFilerServer_checkTusJwtAuthorization(t *testing.T) {
const writeKey = "write-secret"
const readKey = "read-secret"
// newTusTestServer builds a FilerServer backed by an in-memory store seeded with
// TUS sessions (uploadID -> stored TargetPath), so the handler can resolve a
// session's target the way production does. The store is returned so a test can
// mutate or inspect the seeded session.
func newTusTestServer(t *testing.T, sessions map[string]string) (*FilerServer, *renameTestStore) {
t.Helper()
store := newRenameTestStore()
fs := &FilerServer{
filerGuard: security.NewGuard(nil, writeKey, 0, readKey, 0),
filer: newRenameTestFiler(store),
filerGuard: security.NewGuard(nil, tusTestWriteKey, 0, tusTestReadKey, 0),
option: &FilerOption{TusBasePath: "/.tus"},
}
for uploadID, targetPath := range sessions {
seedTusSession(t, fs, store, TusSession{ID: uploadID, TargetPath: targetPath, Size: 1})
}
return fs, store
}
// seedTusSession writes a session directory and its .info metadata into the store.
func seedTusSession(t *testing.T, fs *FilerServer, store *renameTestStore, session TusSession) {
t.Helper()
data, err := json.Marshal(&session)
if err != nil {
t.Fatalf("marshal session %s: %v", session.ID, err)
}
dir := &filer.Entry{FullPath: util.FullPath(fs.tusSessionPath(session.ID)), Attr: filer.Attr{Mode: os.ModeDir | 0755}}
info := &filer.Entry{FullPath: util.FullPath(fs.tusSessionInfoPath(session.ID)), Content: data}
for _, entry := range []*filer.Entry{dir, info} {
if err := store.InsertEntry(context.Background(), entry); err != nil {
t.Fatalf("seed session %s: %v", session.ID, err)
}
}
}
func TestFilerServer_checkJwtAuthorization(t *testing.T) {
fs := &FilerServer{
filerGuard: security.NewGuard(nil, tusTestWriteKey, 0, tusTestReadKey, 0),
option: &FilerOption{TusBasePath: "/.tus"},
}
victim := []string{"/buckets/secret/victim.bin"}
uploadPath := "/.tus/.uploads/" + tusTestUploadID
tests := []struct {
name string
method string
path string
token string
scopedPaths []string
expectAuthorized bool
}{
// The advisory: with a filer signing key configured, an unauthenticated
// TUS request must be rejected the same as a normal filer write.
{"create without token denied", http.MethodPost, "/.tus/buckets/secret/owned.txt", "", false},
{"patch without token denied", http.MethodPatch, "/.tus/.uploads/abc", "", false},
{"delete without token denied", http.MethodDelete, "/.tus/.uploads/abc", "", false},
{"head without token denied", http.MethodHead, "/.tus/.uploads/abc", "", false},
// With a filer signing key configured, an unauthenticated request is denied.
{"post without token denied", http.MethodPost, "/.tus/buckets/secret/owned.txt", "", []string{"/buckets/secret/owned.txt"}, false},
{"patch without token denied", http.MethodPatch, uploadPath, "", victim, false},
{"head without token denied", http.MethodHead, uploadPath, "", victim, false},
// A valid token for the right access level is accepted.
{"create with write token allowed", http.MethodPost, "/.tus/buckets/data/ok.txt", signFilerToken(t, writeKey, nil, nil), true},
{"patch with write token allowed", http.MethodPatch, "/.tus/.uploads/abc", signFilerToken(t, writeKey, nil, nil), true},
{"head with read token allowed", http.MethodHead, "/.tus/.uploads/abc", signFilerToken(t, readKey, nil, nil), true},
{"post write token allowed", http.MethodPost, "/.tus/buckets/data/ok.txt", signFilerToken(t, tusTestWriteKey, nil, nil), []string{"/buckets/data/ok.txt"}, true},
{"head read token allowed", http.MethodHead, uploadPath, signFilerToken(t, tusTestReadKey, nil, nil), victim, true},
// HEAD is a read, so a write-only token must not authorize it and a read
// token must not authorize a write.
{"head with write token denied", http.MethodHead, "/.tus/.uploads/abc", signFilerToken(t, writeKey, nil, nil), false},
{"create with read token denied", http.MethodPost, "/.tus/buckets/data/ok.txt", signFilerToken(t, readKey, nil, nil), false},
// HEAD is a read, so a write token must not authorize it, nor a read token a write.
{"head write token denied", http.MethodHead, uploadPath, signFilerToken(t, tusTestWriteKey, nil, nil), victim, false},
{"post read token denied", http.MethodPost, "/.tus/buckets/data/ok.txt", signFilerToken(t, tusTestReadKey, nil, nil), []string{"/buckets/data/ok.txt"}, false},
// Prefix-restricted tokens are scoped against the resolved target path
// (URL minus the /.tus prefix), not the /.tus route.
{"create within allowed prefix", http.MethodPost, "/.tus/buckets/allowed/ok.txt", signFilerToken(t, writeKey, []string{"/buckets/allowed"}, nil), true},
{"create outside allowed prefix denied", http.MethodPost, "/.tus/buckets/secret/owned.txt", signFilerToken(t, writeKey, []string{"/buckets/allowed"}, nil), false},
// Prefix-restricted tokens are scoped against the resolved target path.
{"within allowed prefix", http.MethodPost, "/.tus/buckets/allowed/ok.txt", signFilerToken(t, tusTestWriteKey, []string{"/buckets/allowed"}, nil), []string{"/buckets/allowed/ok.txt"}, true},
{"outside allowed prefix denied", http.MethodPost, "/.tus/buckets/secret/owned.txt", signFilerToken(t, tusTestWriteKey, []string{"/buckets/allowed"}, nil), []string{"/buckets/secret/owned.txt"}, false},
// Fail closed: a prefix-restricted token with no resolved resource is denied.
{"restricted token without resource denied", http.MethodPatch, uploadPath, signFilerToken(t, tusTestWriteKey, []string{"/buckets/allowed"}, nil), nil, false},
// Method-restricted tokens are checked against the actual HTTP method.
{"patch with matching method allowed", http.MethodPatch, "/.tus/.uploads/abc", signFilerToken(t, writeKey, nil, []string{"POST", "PATCH", "DELETE"}), true},
{"patch outside allowed methods denied", http.MethodPatch, "/.tus/.uploads/abc", signFilerToken(t, writeKey, nil, []string{"POST"}), false},
{"matching method allowed", http.MethodPatch, uploadPath, signFilerToken(t, tusTestWriteKey, nil, []string{"POST", "PATCH", "DELETE"}), victim, true},
{"method not allowed denied", http.MethodPatch, uploadPath, signFilerToken(t, tusTestWriteKey, nil, []string{"POST"}), victim, false},
}
for _, tt := range tests {
@@ -75,21 +119,18 @@ func TestFilerServer_checkTusJwtAuthorization(t *testing.T) {
if tt.token != "" {
req.Header.Set("Authorization", "Bearer "+tt.token)
}
if got := fs.checkTusJwtAuthorization(req); got != tt.expectAuthorized {
t.Errorf("checkTusJwtAuthorization(%s %s) = %v, want %v", tt.method, tt.path, got, tt.expectAuthorized)
if got := fs.checkJwtAuthorization(req, tt.method != http.MethodHead, tt.scopedPaths); got != tt.expectAuthorized {
t.Errorf("checkJwtAuthorization(%s %s) = %v, want %v", tt.method, tt.path, got, tt.expectAuthorized)
}
})
}
}
// TestFilerServer_tusHandler_UnauthenticatedRejected exercises the full handler
// entry point: OPTIONS discovery stays open, but an unauthenticated write is
// rejected with 401 before any session is created.
// entry point: OPTIONS discovery stays open, but an unauthenticated request is
// rejected with 401 before any session is created or looked up.
func TestFilerServer_tusHandler_UnauthenticatedRejected(t *testing.T) {
fs := &FilerServer{
filerGuard: security.NewGuard(nil, "write-secret", 0, "read-secret", 0),
option: &FilerOption{TusBasePath: "/.tus"},
}
fs, _ := newTusTestServer(t, map[string]string{tusTestUploadID: "/buckets/secret/victim.bin"})
// OPTIONS is capability discovery and must not require a token.
optionsReq := httptest.NewRequest(http.MethodOptions, "/.tus/buckets/secret/owned.txt", nil)
@@ -108,4 +149,64 @@ func TestFilerServer_tusHandler_UnauthenticatedRejected(t *testing.T) {
if postRec.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated POST = %d, want %d", postRec.Code, http.StatusUnauthorized)
}
// A missing credential is rejected before the upload id triggers a metadata
// lookup, so an existing session is not an unauthenticated resource oracle.
headReq := httptest.NewRequest(http.MethodHead, "/.tus/.uploads/"+tusTestUploadID, nil)
headReq.Header.Set("Tus-Resumable", TusVersion)
headRec := httptest.NewRecorder()
fs.tusHandler(headRec, headReq)
if headRec.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated HEAD = %d, want %d", headRec.Code, http.StatusUnauthorized)
}
}
// TestFilerServer_refreshTusSessionChunks_RevalidatesPinnedSession verifies a
// pinned session cannot complete after it is deleted or its target is replaced
// between authorization and completion.
func TestFilerServer_refreshTusSessionChunks_RevalidatesPinnedSession(t *testing.T) {
pin := func(t *testing.T) (*FilerServer, *renameTestStore, *TusSession) {
t.Helper()
fs, store := newTusTestServer(t, nil)
seedTusSession(t, fs, store, TusSession{
ID: tusTestUploadID,
TargetPath: "/buckets/secret/victim.bin",
Size: 1,
CreatedAt: time.Unix(1700000000, 123),
})
session, err := fs.readTusSessionInfo(context.Background(), tusTestUploadID)
if err != nil {
t.Fatalf("pin session: %v", err)
}
return fs, store, session
}
t.Run("deleted before completion", func(t *testing.T) {
fs, store, session := pin(t)
if err := store.DeleteEntry(context.Background(), util.FullPath(fs.tusSessionInfoPath(tusTestUploadID))); err != nil {
t.Fatalf("delete session info: %v", err)
}
if err := fs.refreshTusSessionChunks(context.Background(), session); err == nil {
t.Fatal("refresh succeeded after the session was deleted")
}
})
t.Run("replaced before completion", func(t *testing.T) {
fs, store, session := pin(t)
replaced := *session
replaced.TargetPath = "/buckets/other/replacement.bin"
data, err := json.Marshal(&replaced)
if err != nil {
t.Fatalf("marshal replacement: %v", err)
}
if err := store.InsertEntry(context.Background(), &filer.Entry{
FullPath: util.FullPath(fs.tusSessionInfoPath(tusTestUploadID)),
Content: data,
}); err != nil {
t.Fatalf("replace session info: %v", err)
}
if err := fs.refreshTusSessionChunks(context.Background(), session); err == nil {
t.Fatal("refresh succeeded after the session target was replaced")
}
})
}
+57 -6
View File
@@ -181,13 +181,19 @@ func (fs *FilerServer) saveTusSession(ctx context.Context, session *TusSession)
return nil
}
// getTusSession retrieves a TUS session by upload ID, including chunks from directory listing
func (fs *FilerServer) getTusSession(ctx context.Context, uploadID string) (*TusSession, error) {
// readTusSessionInfo reads and validates a session's immutable .info metadata
// without listing its chunks, the cheap lookup the authorization check needs for
// the stored TargetPath. It rejects a metadata file whose id, target or size is
// unusable so a corrupt or replaced session cannot be authorized or completed.
func (fs *FilerServer) readTusSessionInfo(ctx context.Context, uploadID string) (*TusSession, error) {
if !isCanonicalTusUploadID(uploadID) {
return nil, fmt.Errorf("invalid TUS upload id: %q", uploadID)
}
infoPath := util.FullPath(fs.tusSessionInfoPath(uploadID))
entry, err := fs.filer.FindEntry(ctx, infoPath)
if err != nil {
if err == filer_pb.ErrNotFound {
return nil, fmt.Errorf("TUS upload session not found: %s", uploadID)
return nil, fmt.Errorf("TUS upload session not found: %s: %w", uploadID, filer_pb.ErrNotFound)
}
return nil, fmt.Errorf("find session: %w", err)
}
@@ -196,9 +202,39 @@ func (fs *FilerServer) getTusSession(ctx context.Context, uploadID string) (*Tus
if err := json.Unmarshal(entry.Content, &session); err != nil {
return nil, fmt.Errorf("unmarshal session: %w", err)
}
if session.ID != uploadID {
return nil, fmt.Errorf("TUS session id mismatch: got %q, want %q", session.ID, uploadID)
}
target := canonicalTusTargetPath(session.TargetPath)
if target == "" || target == "/" {
return nil, fmt.Errorf("invalid TUS target path: %q", session.TargetPath)
}
if session.Size < 0 || session.Size > TusMaxSize {
return nil, fmt.Errorf("invalid TUS upload size: %d", session.Size)
}
// Pin authorization and every later operation to the same canonical path.
session.TargetPath = target
return &session, nil
}
// getTusSession retrieves a validated TUS session by upload ID, including its
// chunks and current offset.
func (fs *FilerServer) getTusSession(ctx context.Context, uploadID string) (*TusSession, error) {
session, err := fs.readTusSessionInfo(ctx, uploadID)
if err != nil {
return nil, err
}
if err := fs.loadTusSessionChunks(ctx, session); err != nil {
return nil, err
}
return session, nil
}
// loadTusSessionChunks refreshes a session's chunks and offset from its session
// directory, leaving the immutable .info metadata untouched.
func (fs *FilerServer) loadTusSessionChunks(ctx context.Context, session *TusSession) error {
// Load chunks from directory listing with pagination (atomic read, no race condition)
sessionDirPath := util.FullPath(fs.tusSessionPath(uploadID))
sessionDirPath := util.FullPath(fs.tusSessionPath(session.ID))
session.Chunks = nil
session.Offset = 0
@@ -207,7 +243,7 @@ func (fs *FilerServer) getTusSession(ctx context.Context, uploadID string) (*Tus
for {
entries, hasMore, err := fs.filer.ListDirectoryEntries(ctx, sessionDirPath, lastFileName, false, int64(pageSize), "", "", "")
if err != nil {
return nil, fmt.Errorf("list session directory: %w", err)
return fmt.Errorf("list session directory: %w", err)
}
for _, e := range entries {
@@ -248,7 +284,22 @@ func (fs *FilerServer) getTusSession(ctx context.Context, uploadID string) (*Tus
session.Offset = contiguousEnd
}
return &session, nil
return nil
}
// refreshTusSessionChunks verifies the pinned session still exists and still
// identifies the same upload before refreshing its chunk state, so a PATCH
// cannot complete after a concurrent DELETE or metadata replacement and land at
// a TargetPath other than the one that was authorized.
func (fs *FilerServer) refreshTusSessionChunks(ctx context.Context, session *TusSession) error {
stored, err := fs.readTusSessionInfo(ctx, session.ID)
if err != nil {
return err
}
if stored.TargetPath != session.TargetPath || stored.Size != session.Size || !stored.CreatedAt.Equal(session.CreatedAt) {
return fmt.Errorf("TUS session identity changed: %s", session.ID)
}
return fs.loadTusSessionChunks(ctx, session)
}
// saveTusChunk stores the chunk info as a separate file entry
+19
View File
@@ -154,12 +154,31 @@ func (ms *MasterServer) LeaseAdminToken(ctx context.Context, req *master_pb.Leas
func (ms *MasterServer) ReleaseAdminToken(ctx context.Context, req *master_pb.ReleaseAdminTokenRequest) (*master_pb.ReleaseAdminTokenResponse, error) {
resp := &master_pb.ReleaseAdminTokenResponse{}
// a follower holds no lock state; answering success here would fake a
// release while the leader keeps the lock until it expires
if !ms.Topo.IsLeader() {
return resp, raft.NotLeaderError
}
if ms.adminLocks.isValidToken(req.LockName, time.Unix(0, req.PreviousLockTime), req.PreviousToken) {
ms.adminLocks.deleteLock(req.LockName)
}
return resp, nil
}
func (ms *MasterServer) GetAdminLockStatus(ctx context.Context, req *master_pb.GetAdminLockStatusRequest) (*master_pb.GetAdminLockStatusResponse, error) {
resp := &master_pb.GetAdminLockStatusResponse{}
if !ms.Topo.IsLeader() {
return resp, raft.NotLeaderError
}
// isLocked reports the last holder even after the lease expired
if clientName, message, isLocked := ms.adminLocks.isLocked(req.LockName); isLocked {
resp.IsLocked = true
resp.ClientName = clientName
resp.Message = message
}
return resp, nil
}
// isKnownPingTarget reports whether target is a peer that the master has
// learned about as part of cluster membership. Restricting Ping to known
// peers avoids turning the RPC into a generic outbound dialer. The lookups
+13 -4
View File
@@ -106,10 +106,11 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest
vl.SetLastGrowCount(req.WritableVolumeCount)
var (
lastErr error
maxTimeout = time.Second * 10
startTime = time.Now()
initiatedGrow bool
lastErr error
maxTimeout = time.Second * 10
startTime = time.Now()
initiatedGrow bool
repickedAfterGrow bool
)
for time.Now().Sub(startTime) < maxTimeout {
@@ -145,6 +146,14 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest
// Unavailable: clients retry it (assign_file_id.go) without
// invalidating the shared master connection.
if initiatedGrow != vl.HasGrowRequest() {
// The failed pick above may predate the growth concluding, so
// re-pick once before shedding: growth registers its volumes
// before clearing the flag, and shedding here would bounce the
// client off a volume that just landed.
if initiatedGrow && !repickedAfterGrow {
repickedAfterGrow = true
continue
}
return nil, status.Errorf(codes.ResourceExhausted, "no writable volumes for %s, volume growth in progress", option.String())
}
}
+3 -14
View File
@@ -204,20 +204,9 @@ func (ms *MasterServer) Statistics(ctx context.Context, req *master_pb.Statistic
return nil, raft.NotLeaderError
}
if req.Replication == "" {
req.Replication = ms.option.DefaultReplicaPlacement
}
replicaPlacement, err := super_block.NewReplicaPlacementFromString(req.Replication)
if err != nil {
return nil, err
}
ttl, err := needle.ReadTTL(req.Ttl)
if err != nil {
return nil, err
}
volumeLayout := ms.Topo.GetVolumeLayout(req.Collection, replicaPlacement, ttl, types.ToDiskType(req.DiskType))
stats := volumeLayout.Stats()
// an empty collection means all collections, and a named collection covers
// all its layouts, so used size matches the topology-wide total size below
stats := ms.Topo.CollectionVolumeStats(req.Collection)
totalSize := ms.Topo.GetDiskUsages().GetMaxVolumeCount() * int64(ms.option.VolumeSizeLimitMB) * 1024 * 1024
resp := &master_pb.StatisticsResponse{
TotalSize: uint64(totalSize),
+11 -4
View File
@@ -158,10 +158,11 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request)
vl := ms.Topo.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType)
var (
lastErr error
maxTimeout = time.Second * 10
startTime = time.Now()
initiatedGrow bool
lastErr error
maxTimeout = time.Second * 10
startTime = time.Now()
initiatedGrow bool
repickedAfterGrow bool
)
if !ms.Topo.DataCenterExists(option.DataCenter) {
@@ -195,6 +196,12 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request)
// See Assign: only the initiator waits, and only while the
// growth it triggered is still pending.
if initiatedGrow != vl.HasGrowRequest() {
// See Assign: re-pick once after the growth concludes before
// shedding — the failed pick may predate the conclusion.
if initiatedGrow && !repickedAfterGrow {
repickedAfterGrow = true
continue
}
w.Header().Set("Retry-After", "1")
writeJsonQuiet(w, r, http.StatusServiceUnavailable, operation.AssignResult{
Error: fmt.Sprintf("no writable volumes for %s, volume growth in progress", option.String()),
+12 -3
View File
@@ -35,7 +35,6 @@ func (vs *VolumeServer) BatchDelete(ctx context.Context, req *volume_server_pb.B
n := new(needle.Needle)
volumeId, _ := needle.NewVolumeId(vid)
ecVolume, isEcVolume := vs.store.FindEcVolume(volumeId)
if req.SkipCookieCheck {
n.Id, _, err = needle.ParseNeedleIdCookie(id_cookie)
if err != nil {
@@ -46,7 +45,17 @@ func (vs *VolumeServer) BatchDelete(ctx context.Context, req *volume_server_pb.B
continue
}
} else {
n.ParsePath(id_cookie)
if err := n.ParsePath(id_cookie); err != nil {
resp.Results = append(resp.Results, &volume_server_pb.DeleteResult{
FileId: fid,
Status: http.StatusBadRequest,
Error: err.Error()})
continue
}
}
ecVolume, isEcVolume := vs.store.FindEcVolume(volumeId)
if !req.SkipCookieCheck {
cookie := n.Cookie
if !isEcVolume {
if _, err := vs.store.ReadVolumeNeedle(volumeId, n, nil, nil); err != nil {
@@ -73,7 +82,7 @@ func (vs *VolumeServer) BatchDelete(ctx context.Context, req *volume_server_pb.B
Status: http.StatusBadRequest,
Error: "File Random Cookie does not match.",
})
break
continue
}
}
+7 -2
View File
@@ -74,9 +74,15 @@ func (vs *VolumeServer) VolumeCopy(req *volume_server_pb.VolumeCopyRequest, stre
if req.DiskType != "" {
diskType = req.DiskType
}
hasRemoteDatFile = volFileInfoResp.VolumeInfo != nil && len(volFileInfoResp.VolumeInfo.Files) > 0
// a remote-backed volume only lands its .idx/.vif locally; the .dat stays in the tier
neededSpace := volFileInfoResp.DatFileSize
if hasRemoteDatFile {
neededSpace = volFileInfoResp.IdxFileSize
}
location := vs.store.FindFreeLocation(func(location *storage.DiskLocation) bool {
return location.DiskType == types.ToDiskType(diskType) &&
location.AvailableSpace.Load() > volFileInfoResp.DatFileSize
location.AvailableSpace.Load() > neededSpace
})
if location == nil {
return fmt.Errorf("%s %s", util.ErrVolumeNoSpaceLeft, types.ToDiskType(diskType).ReadableString())
@@ -84,7 +90,6 @@ func (vs *VolumeServer) VolumeCopy(req *volume_server_pb.VolumeCopyRequest, stre
dataBaseFileName = storage.VolumeFileName(location.Directory, volFileInfoResp.Collection, int(req.VolumeId))
indexBaseFileName = storage.VolumeFileName(location.IdxDirectory, volFileInfoResp.Collection, int(req.VolumeId))
hasRemoteDatFile = volFileInfoResp.VolumeInfo != nil && len(volFileInfoResp.VolumeInfo.Files) > 0
// The .note marks the copy as in-progress; a leftover note fails the
// volume load on restart, so a write failure must abort the copy.
@@ -85,3 +85,67 @@ func TestEcShardDeleteKeepsSharedIndexWhileSiblingHasShards(t *testing.T) {
del(7, 12)
require.False(t, util.FileExists(base0+".ecx"), "shared .ecx must be removed once no shard remains node-wide")
}
// Same protection for the idx-base bitrot sidecar: with one -dir.idx shared by
// every disk, emptying one disk must not sweep <idx>/<volume>.ecsum while a
// sibling disk still holds shards; it goes when the last sibling is emptied.
func TestEcShardDeleteKeepsSharedIdxSidecarWhileSiblingHasShards(t *testing.T) {
tempDir := t.TempDir()
dir0 := filepath.Join(tempDir, "disk0")
dir1 := filepath.Join(tempDir, "disk1")
idxDir := filepath.Join(tempDir, "idx")
for _, d := range []string{dir0, dir1, idxDir} {
require.NoError(t, os.MkdirAll(d, 0o755))
}
const collection = "ec-shared-idx-sidecar"
vid := needle.VolumeId(78)
store := storage.NewStore(nil, "localhost", 8080, 18080, "http://localhost:8080", "store-id",
[]string{dir0, dir1}, []int32{100, 100}, []util.MinFreeSpace{{}, {}}, idxDir,
storage.NeedleMapInMemory, []types.DiskType{types.HardDriveType, types.HardDriveType}, nil, 3, stats.DefaultDiskIOProbeConfig())
done := make(chan struct{})
go func() {
for {
select {
case <-store.NewEcShardsChan:
case <-store.NewVolumesChan:
case <-store.DeletedVolumesChan:
case <-store.DeletedEcShardsChan:
case <-store.StateUpdateChan:
case <-done:
return
}
}
}()
t.Cleanup(func() {
store.Close()
close(done)
})
plant := func(dir string, ids ...int) {
base := erasure_coding.EcShardFileName(collection, dir, int(vid))
for _, id := range ids {
require.NoError(t, os.WriteFile(base+erasure_coding.ToExt(id), []byte("s"), 0o644))
}
}
plant(dir0, 0)
plant(dir1, 7)
idxSidecar := erasure_coding.EcShardFileName(collection, idxDir, int(vid)) + erasure_coding.BitrotSidecarExt
require.NoError(t, os.WriteFile(idxSidecar, []byte("x"), 0o644))
vs := &VolumeServer{store: store}
del := func(ids ...uint32) {
_, err := vs.VolumeEcShardsDelete(context.Background(), &volume_server_pb.VolumeEcShardsDeleteRequest{
VolumeId: uint32(vid),
Collection: collection,
ShardIds: ids,
})
require.NoError(t, err)
}
del(0)
require.True(t, util.FileExists(idxSidecar), "shared idx sidecar must survive while a sibling disk holds shards")
del(7)
require.False(t, util.FileExists(idxSidecar), "shared idx sidecar must be removed once no shard remains node-wide")
}
+18 -3
View File
@@ -471,7 +471,7 @@ func (vs *VolumeServer) VolumeEcShardsDelete(ctx context.Context, req *volume_se
// Pass 1: delete the requested shard files (and any now-orphaned per-disk bitrot
// sidecars) on every disk.
for diskId, location := range vs.store.Locations {
if err := deleteEcShardIdsForEachLocation(bName, location, req.ShardIds); err != nil {
if err := deleteEcShardIdsForEachLocation(bName, location, vs.store.Locations, req.ShardIds); err != nil {
glog.Errorf("deleteEcShards from disk_id:%d %s %s.%v: %v", diskId, location.Directory, bName, req.ShardIds, err)
return nil, err
}
@@ -508,7 +508,7 @@ func (vs *VolumeServer) VolumeEcShardsDelete(ctx context.Context, req *volume_se
return &volume_server_pb.VolumeEcShardsDeleteResponse{}, nil
}
func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocation, shardIds []uint32) error {
func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocation, locations []*storage.DiskLocation, shardIds []uint32) error {
found := false
@@ -546,7 +546,7 @@ func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocatio
if err := removeBitrotSidecars(dataBaseFilename); err != nil {
return err
}
if location.IdxDirectory != location.Directory {
if location.IdxDirectory != location.Directory && !idxSidecarInUse(bName, location.IdxDirectory, locations) {
if err := removeBitrotSidecars(indexBaseFilename); err != nil {
return err
}
@@ -556,6 +556,21 @@ func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocatio
return nil
}
// One -dir.idx serves every disk, so the idx-base sidecar is shared: it stays
// while any disk using that idx directory still holds shards of this volume.
// A status error counts as in-use so a transient failure never strips it early.
func idxSidecarInUse(bName string, idxDirectory string, locations []*storage.DiskLocation) bool {
for _, other := range locations {
if other.IdxDirectory != idxDirectory {
continue
}
if _, _, count, err := checkEcVolumeStatus(bName, other); err != nil || count > 0 {
return true
}
}
return false
}
// removeEcSharedIndexFiles removes the shared .ecx/.ecj index (and the .vif when no
// .idx is present) for an EC volume on one disk. The caller invokes it only after
// the whole node's shards for the volume are gone, so a sibling disk's shards are
@@ -143,7 +143,7 @@ func TestDeleteEcShardsWithoutLocalEcx(t *testing.T) {
}
location := &storage.DiskLocation{Directory: dataDir, IdxDirectory: idxDir}
if err := deleteEcShardIdsForEachLocation(baseName, location, []uint32{3, 11}); err != nil {
if err := deleteEcShardIdsForEachLocation(baseName, location, []*storage.DiskLocation{location}, []uint32{3, 11}); err != nil {
t.Fatalf("deleteEcShardIdsForEachLocation: %v", err)
}
for _, f := range orphans {
+4 -1
View File
@@ -21,7 +21,10 @@ func (vs *VolumeServer) Query(req *volume_server_pb.QueryRequest, stream volume_
n := new(needle.Needle)
volumeId, _ := needle.NewVolumeId(vid)
n.ParsePath(id_cookie)
if err := n.ParsePath(id_cookie); err != nil {
glog.V(0).Infof("volume query failed to parse fid %s: %v", fid, err)
return err
}
cookie := n.Cookie
if _, err := vs.store.ReadVolumeNeedle(volumeId, n, nil, nil); err != nil {
+4 -1
View File
@@ -83,7 +83,10 @@ func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
n := new(needle.Needle)
vid, fid, _, _, _ := parseURLPath(r.URL.Path)
volumeId, _ := needle.NewVolumeId(vid)
n.ParsePath(fid)
if err := n.ParsePath(fid); err != nil {
writeJsonError(w, r, http.StatusBadRequest, err)
return
}
if !vs.maybeCheckJwtAuthorization(r, vid, fid, true) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
@@ -0,0 +1,45 @@
package weed_server
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
const overflowingNeedleDeltaFid = "1,ffffffffffffffff00000000_1"
func TestDeleteHandlerRejectsOverflowingNeedleDelta(t *testing.T) {
req := httptest.NewRequest(http.MethodDelete, "/"+overflowingNeedleDeltaFid, nil)
resp := httptest.NewRecorder()
(&VolumeServer{}).DeleteHandler(resp, req)
if resp.Code != http.StatusBadRequest {
t.Fatalf("DeleteHandler returned status %d, want %d", resp.Code, http.StatusBadRequest)
}
}
func TestBatchDeleteRejectsOverflowingNeedleDelta(t *testing.T) {
resp, err := (&VolumeServer{}).BatchDelete(context.Background(), &volume_server_pb.BatchDeleteRequest{
FileIds: []string{overflowingNeedleDeltaFid},
})
if err != nil {
t.Fatalf("BatchDelete returned error: %v", err)
}
if len(resp.Results) != 1 || resp.Results[0].Status != http.StatusBadRequest {
t.Fatalf("BatchDelete returned results %+v, want one bad request", resp.Results)
}
}
func TestQueryRejectsOverflowingNeedleDelta(t *testing.T) {
err := (&VolumeServer{}).Query(&volume_server_pb.QueryRequest{
FromFileIds: []string{overflowingNeedleDeltaFid},
}, nil)
if err == nil || !strings.Contains(err.Error(), "overflows needle id") {
t.Fatalf("Query returned error %v, want needle id overflow", err)
}
}
+19 -4
View File
@@ -114,9 +114,23 @@ func (fs *SftpServer) CheckFilePermission(path string, perm string) error {
return os.ErrPermission
}
// pathWithin reports whether candidate is base itself or a descendant of base,
// on path-component boundaries so /a does not match /a-sibling.
func pathWithin(base, candidate string) bool {
base = stdpath.Clean(base)
candidate = stdpath.Clean(candidate)
if base == "/" {
return strings.HasPrefix(candidate, "/")
}
return candidate == base || strings.HasPrefix(candidate, base+"/")
}
// isPathInHomeDirectory checks if a path is in the user's home directory
func isPathInHomeDirectory(user *user.User, path string) bool {
return strings.HasPrefix(path, user.HomeDir)
if user.HomeDir == "" {
return true
}
return pathWithin(user.HomeDir, path)
}
// HasUnixPermission checks if the user has the required Unix permission
@@ -182,9 +196,10 @@ func HasExplicitPermission(user *user.User, filepath, requiredPerm string, isDir
var perms []string
for p, userPerms := range user.Permissions {
// Check if the path is either the permission path exactly or is under that path
if strings.HasPrefix(filepath, p) && len(p) > len(bestMatch) {
bestMatch = p
// The path must be the permission path exactly or under that path
cleaned := stdpath.Clean(p)
if pathWithin(cleaned, filepath) && len(cleaned) > len(bestMatch) {
bestMatch = cleaned
perms = userPerms
}
}
+64
View File
@@ -0,0 +1,64 @@
package sftpd
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
)
func TestPathWithin(t *testing.T) {
tests := []struct {
base string
candidate string
want bool
}{
{"/tenants/alice", "/tenants/alice", true},
{"/tenants/alice", "/tenants/alice/file.txt", true},
{"/tenants/alice", "/tenants/alice/sub/dir", true},
{"/tenants/alice", "/tenants/alice-archive", false},
{"/tenants/alice", "/tenants/alice-archive/secret.txt", false},
{"/tenants/alice", "/tenants/alice2", false},
{"/tenants/alice", "/tenants", false},
{"/tenants/alice/", "/tenants/alice/file.txt", true},
{"/tenants/alice", "/tenants/alice/../alice-archive", false},
{"/tenants/alice", "/tenants/alice/..", false},
{"/", "/", true},
{"/", "/anything", true},
}
for _, tt := range tests {
if got := pathWithin(tt.base, tt.candidate); got != tt.want {
t.Errorf("pathWithin(%q, %q) = %v, want %v", tt.base, tt.candidate, got, tt.want)
}
}
}
func TestHasExplicitPermissionSiblingPrefix(t *testing.T) {
u := &user.User{
Username: "scoped",
HomeDir: "/",
Permissions: map[string][]string{
"/tenants/alice": {"read", "write", "list"},
},
}
if !HasExplicitPermission(u, "/tenants/alice/file.txt", PermRead, false) {
t.Error("expected read permission under /tenants/alice")
}
if HasExplicitPermission(u, "/tenants/alice-archive/secret.txt", PermRead, false) {
t.Error("ACL for /tenants/alice must not grant read on sibling /tenants/alice-archive")
}
if HasExplicitPermission(u, "/tenants/alice-archive/secret.txt", PermWrite, false) {
t.Error("ACL for /tenants/alice must not grant write on sibling /tenants/alice-archive")
}
}
func TestIsPathInHomeDirectorySiblingPrefix(t *testing.T) {
u := &user.User{Username: "alice", HomeDir: "/tenants/alice"}
if !isPathInHomeDirectory(u, "/tenants/alice/file.txt") {
t.Error("expected /tenants/alice/file.txt to be within home /tenants/alice")
}
if isPathInHomeDirectory(u, "/tenants/alice-archive/secret.txt") {
t.Error("home /tenants/alice must not match sibling /tenants/alice-archive")
}
}
+33 -28
View File
@@ -47,39 +47,31 @@ func (c *commandClusterPs) Do(args []string, commandEnv *CommandEnv, writer io.W
return nil
}
var filerNodes []*master_pb.ListClusterNodesResponse_ClusterNode
var mqBrokerNodes []*master_pb.ListClusterNodesResponse_ClusterNode
// get the list of filers
err = commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.FilerType,
FilerGroup: *commandEnv.option.FilerGroup,
listClusterNodes := func(clientType string) ([]*master_pb.ListClusterNodesResponse_ClusterNode, error) {
var nodes []*master_pb.ListClusterNodesResponse_ClusterNode
err := commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: clientType,
FilerGroup: *commandEnv.option.FilerGroup,
})
if err != nil {
return err
}
nodes = resp.ClusterNodes
return nil
})
if err != nil {
return err
}
return nodes, err
}
filerNodes = resp.ClusterNodes
return err
})
filerNodes, err := listClusterNodes(cluster.FilerType)
if err != nil {
return
}
// get the list of message queue brokers
err = commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
ClientType: cluster.BrokerType,
FilerGroup: *commandEnv.option.FilerGroup,
})
if err != nil {
return err
}
mqBrokerNodes = resp.ClusterNodes
return err
})
mqBrokerNodes, err := listClusterNodes(cluster.BrokerType)
if err != nil {
return
}
s3Nodes, err := listClusterNodes(cluster.S3Type)
if err != nil {
return
}
@@ -97,6 +89,19 @@ func (c *commandClusterPs) Do(args []string, commandEnv *CommandEnv, writer io.W
}
}
if len(s3Nodes) > 0 {
fmt.Fprintf(writer, "* s3 servers %d\n", len(s3Nodes))
for _, node := range s3Nodes {
fmt.Fprintf(writer, " * %s (%v)\n", node.Address, node.Version)
if node.DataCenter != "" {
fmt.Fprintf(writer, " DataCenter: %v\n", node.DataCenter)
}
if node.Rack != "" {
fmt.Fprintf(writer, " Rack: %v\n", node.Rack)
}
}
}
filerSignatures := make(map[*master_pb.ListClusterNodesResponse_ClusterNode]int32)
fmt.Fprintf(writer, "* filers %d\n", len(filerNodes))
for _, node := range filerNodes {
+15 -1
View File
@@ -53,6 +53,9 @@ type ClusterStatusPrinter struct {
maxParallelization int
locked bool
lockHeld bool
lockHolder string
lockMessage string
collections []string
topology *master_pb.TopologyInfo
volumeSizeLimitMb uint64
@@ -91,12 +94,17 @@ func (c *commandClusterStatus) Do(args []string, commandEnv *CommandEnv, writer
return err
}
lockHolder, lockMessage, lockHeld := commandEnv.shellLockHolder()
sp := &ClusterStatusPrinter{
writer: writer,
humanize: *humanize,
maxParallelization: *maxParallelization,
locked: commandEnv.isLocked(),
lockHeld: lockHeld,
lockHolder: lockHolder,
lockMessage: lockMessage,
collections: collections,
topology: topology,
volumeSizeLimitMb: volumeSizeLimitMb,
@@ -339,8 +347,14 @@ func (sp *ClusterStatusPrinter) printClusterInfo() {
}
status := "unlocked"
if sp.locked {
if sp.lockHeld || sp.locked {
status = "LOCKED"
if sp.lockHolder != "" {
status += " by " + sp.lockHolder
}
if sp.lockMessage != "" {
status += " (" + sp.lockMessage + ")"
}
}
sp.write("cluster:")
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more