Compare commits

...
Author SHA1 Message Date
Chris Lu 223bc86c92 fix(ec): reject oversized bitrot payload before narrowing to u32
save_bitrot_sidecar writes payload.len() into the header as a u32; guard against
a payload > 1 GiB (which would silently truncate the length field), mirroring
Go's SaveBitrotSidecar maxBitrotPayloadSize check. Never triggers for a real
sidecar (a few KB).

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 20:20:19 -07:00
Chris Lu 9bc216b9eb style(ec): align bitrot comments and test setup for merge-cleanliness
Match the shared bitrot code (write_ec_files, encode_one_batch, checksum_scrub,
the encode sidecar test) to the canonical wording/layout so the volume-server
Rust port stays line-aligned across trees, keeping periodic merges conflict-free.
No behavior change.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 19:48:13 -07:00
Chris Lu 4d6fc8047e feat(ec): remove the .ecsum sidecars when destroying an EC volume
remove_ec_volume_files now clears <base>.ecsum (and any versioned .ecsum.v<N>)
from the data and idx dirs, so a vid reuse can't load a stale sidecar. Mirrors
Go's removeBitrotSidecars.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 19:36:38 -07:00
Chris Lu 11c277765c feat(ec): copy the .ecsum sidecar during VolumeEcShardsCopy
Honor copy_ecsum_file: when set, copy the generation-0 .ecsum alongside the
shards so protection travels with them, mirroring Go's non-2PC copy path.
Tolerant of a missing source (empty stream) — the 0-byte file is dropped so
mount sees no sidecar (protection off) rather than a truncated/invalid one.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 19:36:38 -07:00
Chris Lu d810dbd03d feat(scrub): dispatch EC CHECKSUM (mode 4) to checksum_scrub
Accept VolumeScrubMode.CHECKSUM=4 and route it to EcVolume::checksum_scrub,
accumulating blocks scanned + mismatched shards into the scrub response, plus the
CHECKSUM scrub-mode metric label. Read-only bitrot verification over local shards.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 19:26:04 -07:00
Chris Lu dfba9e1575 feat(ec): load the .ecsum at mount + EcVolume::checksum_scrub
EcVolume now loads and validates its generation-0 .ecsum sidecar at mount,
caching the parsed protection + BitrotStatus (Off/On/Invalid), and exposes
bitrot_protection() mirroring Go's EcVolume.BitrotProtection(). checksum_scrub()
verifies every locally-held shard's raw bytes against the sidecar block CRCs —
the only path that exercises cold parity shards — reporting mismatched shards
without mutating anything; a wholesale mismatch beyond parity is flagged as a
suspect sidecar rather than mass shard corruption. Mirrors Go's ChecksumScrub.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 19:26:04 -07:00
Chris Lu fc68dee933 feat(ec): write the .ecsum bitrot sidecar during EC encode
write_ec_files now feeds each shard's bytes through a per-shard
ShardChecksumBuilder as it writes them, then persists the generation-0 sidecar
(<base>.ecsum) alongside the shards — mirroring weed's WriteEcFiles +
SaveBitrotSidecar. Best-effort: a failed sidecar write leaves the generation
unprotected rather than failing the encode. A test confirms the produced sidecar
validates and its per-block CRCs match every on-disk shard.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 18:58:49 -07:00
Chris Lu 4bd0b0c5a6 test(ec): pin .ecsum sidecar bytes for cross-binary interop
Deterministic EcBitrotProtection -> exact on-disk bytes, asserted against a
canonical constant on BOTH sides (this test and ec_bitrot.rs), so a format drift
in either binary fails its own suite rather than silently desyncing a Go-written
.ecsum from a Rust-written one.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 10:41:28 -07:00
Chris Lu ddab5ac403 feat(ec): port the .ecsum bitrot checksum module
ec_bitrot.rs mirrors weed/storage/erasure_coding/ec_bitrot.go: the .ecsum sidecar
format (14-byte big-endian ECSU header + CRC32C over a prost-serialized
EcBitrotProtection payload), the per-shard per-block CRC32C producer
(ShardChecksumBuilder), save/load with payload self-integrity, manifest
validation, status resolution, and verify_shard_file_blocks for the CHECKSUM
scrub. A byte-exact test pins the serialized bytes against the Go reference's
identical constant so a format drift in either binary fails loudly.

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

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 10:41:28 -07:00
Chris Lu 3e558c15e9 proto: add EC bitrot checksum messages + CHECKSUM scrub mode
Mirror weed/pb/volume_server.proto byte-for-byte (field numbers + types) so the
.ecsum sidecar payload is wire-identical across the Go and Rust binaries:
EcBitrotProtection / EcShardChecksums / ChecksumAlgorithm, VolumeScrubMode.CHECKSUM=4,
and VolumeEcShardsCopyRequest.copy_ecsum_file. No code uses them yet — the .ecsum
format, producer, mount-load, copy, and scrub land in following commits.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 03:52:13 -07:00
Chris Lu d18b85ef61 feat(scrub): EC FULL scrub — distributed local+remote needle walk (#10149)
* feat(ec): add scrub_ec_volume_distributed (FULL EC scrub, local+remote)

Ports Go's Store.ScrubEcVolume: walk the raw .ecx, verify every needle across
local AND remote shards without decoding (report faults, don't heal), with the
#10130 deleted-needle size-mismatch suppression gated on a force flag. Reuses
the read path's lock-drop + no-reconstruct read_remote_ec_shard_interval so no
!Send store guard is held across an .await.

Walks the unmasked index (scrub_snapshot_under_lock locates from the raw
(offset, size), not locate_needle) so logically-deleted-but-present needles are
still byte-verified, matching Go. Refreshes shard locations once up front and
hard-fails on a master-lookup error rather than retrying per needle.

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

* feat(scrub): dispatch EC FULL (mode 2) to the distributed needle walk

FULL ran a local-only Reed-Solomon parity check; route it to the per-needle
local+remote walk instead, mirroring Go. The handler collects vids under a brief
lock then releases it: FULL self-locks per needle (it awaits remote reads),
INDEX/LOCAL re-acquire a brief lock. verify_ec_shards is retained but no longer
wired to a mode.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 03:29:46 -07:00
Chris Lu 53087cb237 admin: remove non-functional EC repair button from UI (#10150)
The EC volumes, EC shards, and collection details pages each rendered a
repair (wrench) button for incomplete EC volumes. Its handler POSTed to a
/repair endpoint that the admin server never registers, so every click
returned "404 page not found" (the collection details page only had a
placeholder handler).

Remove the buttons and their JavaScript handlers, and regenerate the
templ output. Manual EC shard recovery remains available from weed shell
via ec.rebuild.
2026-06-30 02:38:13 -07:00
Lisandro Pin cac83bb4a8 Fix scrubbing of deleted needles on EC volumes. (#10130)
EC volumes do not propagate deletions to all shard indexes, so it is possible
to run scrubbing on a volume where a deleted needle is still present in the
index, or a needle deleted from the index is still present on the volume.
On either scenario, scrubbing will fail due to size mismatch errors.

This PR reworks the scrubbing logic so needle size mismatches are
ignored in such scenarios.

Scrubbing can still be forced to check deleted needles (f.ex. to discover
index inconsistencies); this option will be exposed in RPCs and `weed shell`
on a follow-up PR.
2026-06-30 02:05:14 -07:00
Chris Lu acbb6f7550 fix(scrub): don't flag offset-0 logical tombstones in volume scrub (#10148)
* fix(scrub): don't flag offset-0 logical tombstones in volume scrub

A remote-tier delete records a tombstone at .idx offset 0 with no physical .dat
bytes. Full scrub double-flagged a healthy remote-tiered volume with deletes:
scrubVolumeData counted the tombstone's GetActualSize(-1)=32 toward totalRead
(want > physical .dat), and CheckIndexFile treated it as occupying [0,31] and
flagged the first live needle as overlapping. Skip offset-0 logical tombstones
from both the size reconcile and the overlap check; they are still counted for
the index-size check. Local deletes (offset != 0) are unaffected.

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

* fix(scrub): mirror offset-0 logical tombstone handling into Rust

Same fix as the Go volume_checking.go + idx/check.go change: Volume::scrub skips
offset-0 logical tombstones from total_read, and check_index_file excludes them
from the overlap check (still counted for the index-size check).

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 02:01:14 -07:00
Chris Lu c9f2ef9ef7 fix(ec): suppress deleted-needle size mismatch in EC LOCAL scrub (#10147)
* fix(ec): suppress deleted-needle size mismatch in EC LOCAL scrub

EcVolume.ScrubLocal reassembles each fully-local needle and ReadBytes-checks
it, but appended every error unconditionally. A needle the .ecx still reports
live while its reassembled on-disk header carries size 0 (delete state
disagrees between index and header) is not corruption — the LOCAL twin of the
#10130 fix for the FULL path. Suppress the ErrorSizeMismatch in that case;
genuine (non-zero) size mismatches and CRC/tail errors are still reported.

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

* fix(ec): mirror EC LOCAL scrub deleted-needle suppression into Rust

Same suppression as the Go EcVolume.ScrubLocal change: a NeedleError::SizeMismatch
whose on-disk header size is 0 against a live index entry is a delete-state
disagreement, not corruption.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 01:58:57 -07:00
Chris Lu 473f7b2367 feat(scrub): EC LOCAL needle walk (split from FULL) (#10144)
* feat(ec): extract locate_ec_shard_needle_interval

Mirrors Go's EcVolume.LocateEcShardNeedleInterval; reused by locate_needle
and the upcoming local scrub walk.

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

* feat(ec): add EcVolumeShard::to_ec_shard_info

Mirrors Go's ToEcShardInfo.

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

* feat(ec): add EcVolume::scrub_local

Walk the .ecx and verify each needle against the locally-held shards,
reading interval-by-interval (reusing one chunk buffer); CRC-check only
fully-local needles, report short/unreadable local shards, and abort the
scan on a structural size mismatch. Mirrors Go's EcVolume.ScrubLocal.

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

* feat(scrub): dispatch EC LOCAL (mode 3) to scrub_local

Splits the mode 2|3 arm: FULL (2) keeps the Reed-Solomon parity check;
LOCAL (3) now runs the per-needle local-shard walk.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 01:22:46 -07:00
Chris Lu dccc015a1f fix(scrub): walk the on-disk .idx in Volume::scrub (source-of-truth parity) (#10143)
* refactor(scrub): extract open_index_for_scrub shared by scrub_index

Mirrors Go's openIndex, shared by ScrubIndex and the upcoming Scrub rewrite.

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

* fix(scrub): walk the on-disk .idx in Volume::scrub

scrub walked the deduped in-memory map, so total_read undercounted the
physical .dat on any volume with overwrites or deletes and the size
reconcile falsely flagged healthy volumes broken. Walk every .idx row
instead (matching Go's scrubVolumeData): count all rows, CRC-verify live
needles, skip deleted, and reconcile against the .dat. Holds one data-file
read lock and reads via the unlocked path, like Go's Scrub.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 01:17:28 -07:00
adriandadri 1df7a0e653 fix(volume [rust] + ec): search sibling disk locations when rebuilding missing EC shards + .ecx files (#10145)
* fix(volume [rust] + ec): search sibling disk locations when rebuilding missing EC shards

* fix(volume [rust] + ec): apply sibling-disk shard lookup to .ecx rebuild as well

* fix(volume [rust] + ec): include rebuild_dir in .ecx rebuild's shard search dirs

---------

Co-authored-by: adri <adri@digitalunited.net>
2026-06-30 00:07:44 -07:00
Chris Lu 72009c607b fix(scrub): align Rust INDEX scrub to Go's idx.CheckIndexFile (#10142)
* feat(idx): add check_index_file mirroring Go idx.CheckIndexFile

Index-only structural check: walk the on-disk index, sort by (offset, size),
flag overlapping needles, and verify the file is a whole number of entries.
No data-file reads.

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

* refactor(ec): use idx::check_index_file in EcVolume::scrub_index

Drops the inline walk/sort/overlap copy. Walks a private fd so the structural
scan never moves the shared ecx_file cursor (read positionally elsewhere).

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

* fix(scrub): make Volume::scrub_index an index-only check on the on-disk .idx

INDEX mode walked the deduped in-memory map and read .dat headers — more
than the cheap-INDEX contract allows, yet missing Go's overlap and
size-multiple structural checks. Route it through idx::check_index_file so
it matches Go's Volume.ScrubIndex and the INDEX<LOCAL<FULL cost tiering holds.
Ports openIndex's zero-size-index guard (a populated .dat with an empty .idx
is corruption) and takes the data-file read lock for a consistent snapshot.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-30 00:00:24 -07:00
Chris Lu 0e293c9b0a docs(scrub): correct backwards FULL/LOCAL mode comments in Rust (#10141)
docs(scrub): correct backwards FULL(2)/LOCAL(3) mode comments

The proto enum is FULL=2, LOCAL=3; two comments had them swapped.

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-29 23:59:11 -07:00
Chris Lu 270ac332ff fix(ec): honor wide EC ratios in Rust read_ec_shard_config (#10140)
* fix(ec): cap EcShardConfig at MAX_SHARD_COUNT, not TOTAL_SHARDS_COUNT

read_ec_shard_config rejected any .vif ratio summing past 14 shards and
silently fell back to 10/4, so wider EC volumes ran against the wrong
shard set. Match Go's MaxShardCount(32) bound.

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

* docs(ec): correct stale 0..14 shard-count comments

Claude-Session: https://claude.ai/code/session_015EE9Sc9EvNp8BCVva4RKdo
2026-06-29 23:58:38 -07:00
jk2lx 96f93d8e3b fix(rust-volume): parse master lookup when publicUrl is omitted (#10128)
Master /dir/lookup JSON omits publicUrl when empty (Go json omitempty).
The Rust volume server required the field, so serde failed with "lookup
parse failed: error decoding response body" and cross-DC replicated writes
failed.

Default publicUrl to empty, fall back to url for peer filtering, and
normalize addresses with to_http_address before excluding the local peer
(so host:port.grpcPort forms do not match self incorrectly).
2026-06-29 14:03:58 -07:00
Chris Lu 9752286fd4 test(seaweed-volume): cover type=replicate fan-out writes on the Rust volume server (#10139)
* test(seaweed-volume): cover type=replicate fan-out writes

A holder must accept a replicated copy and store it locally without
re-replicating. Covers raw and multipart bodies, and a multi-copy
volume where re-replication would otherwise reach the master.

* test(seaweed-volume): use port 0 for the dead-master address

Connecting to port 0 is refused at the socket layer immediately, so the
plain-write fan-out path fails fast instead of risking a connect-timeout
hang where port 1 is filtered.
2026-06-29 13:55:48 -07:00
b55a608ae0 feat: add collection pattern to delete empty volumes (#10129)
* feat: add collection pattern to delete empty volumes

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

* shell: match collection pattern with wildcard matcher

Use wildcard.MatchesWildcard in the shared collection-pattern helper,
matching command_volume_fix_replication's matchCollectionPattern. The
flag only advertises '*' and '?', which is exactly what the matcher
supports.

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-29 12:43:19 -07:00
dependabot[bot] cb95b45282 build(deps): bump github.com/redis/go-redis/v9 from 9.20.0 to 9.21.0 (#10136)
Bumps [github.com/redis/go-redis/v9](https://github.com/redis/go-redis) from 9.20.0 to 9.21.0.
- [Release notes](https://github.com/redis/go-redis/releases)
- [Changelog](https://github.com/redis/go-redis/blob/master/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/go-redis/compare/v9.20.0...v9.21.0)

---
updated-dependencies:
- dependency-name: github.com/redis/go-redis/v9
  dependency-version: 9.21.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-06-29 11:35:11 -07:00
dependabot[bot] 2acae706d2 build(deps): bump gocloud.dev/pubsub/natspubsub from 0.45.0 to 0.46.0 (#10135)
Bumps [gocloud.dev/pubsub/natspubsub](https://github.com/google/go-cloud) from 0.45.0 to 0.46.0.
- [Release notes](https://github.com/google/go-cloud/releases)
- [Commits](https://github.com/google/go-cloud/compare/v0.45.0...v0.46.0)

---
updated-dependencies:
- dependency-name: gocloud.dev/pubsub/natspubsub
  dependency-version: 0.46.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-06-29 11:35:02 -07:00
dependabot[bot] 6de556a9e3 build(deps): bump github.com/jackc/pgx/v5 from 5.9.2 to 5.10.0 (#10134)
Bumps [github.com/jackc/pgx/v5](https://github.com/jackc/pgx) from 5.9.2 to 5.10.0.
- [Changelog](https://github.com/jackc/pgx/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jackc/pgx/compare/v5.9.2...v5.10.0)

---
updated-dependencies:
- dependency-name: github.com/jackc/pgx/v5
  dependency-version: 5.10.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-06-29 11:34:54 -07:00
dependabot[bot] 9bc8260532 build(deps): bump golang.org/x/term from 0.43.0 to 0.44.0 (#10133)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.43.0 to 0.44.0.
- [Commits](https://github.com/golang/term/compare/v0.43.0...v0.44.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  dependency-version: 0.44.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-06-29 11:34:45 -07:00
dependabot[bot] 990b168766 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azidentity from 1.13.1 to 1.14.0 (#10132)
build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azidentity

Bumps [github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://github.com/Azure/azure-sdk-for-go) from 1.13.1 to 1.14.0.
- [Release notes](https://github.com/Azure/azure-sdk-for-go/releases)
- [Commits](https://github.com/Azure/azure-sdk-for-go/compare/sdk/azidentity/v1.13.1...sdk/azcore/v1.14.0)

---
updated-dependencies:
- dependency-name: github.com/Azure/azure-sdk-for-go/sdk/azidentity
  dependency-version: 1.14.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-06-29 11:34:37 -07:00
dependabot[bot] e2c649d56f build(deps): bump actions/cache from 5 to 6 (#10131)
Bumps [actions/cache](https://github.com/actions/cache) from 5 to 6.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-29 11:34:28 -07:00
7y-9andCodex 1e42dd77ca fix: avoid duplicate volume.list parent headers (#10126)
Co-authored-by: Codex <noreply@openai.com>
2026-06-29 11:31:45 -07:00
github-actions[bot] c06a2dca87 4.37 2026-06-29 06:45:55 +00:00
Chris Lu 5797fb24ec s3: support AWS object form for bucket policy Principal, add NotPrincipal (#10125)
* s3: support AWS object form for bucket policy Principal, add NotPrincipal

Bucket policy statements only accepted a bare string or array of strings for
the Principal element, so the AWS-documented object form was rejected:

    "Principal": { "AWS": "arn:aws:iam::123456789012:root" }
    "Principal": { "AWS": ["arn:...", "999999999999"] }

Add a PolicyPrincipal type that parses the bare string, the bare array
(retained for backward compatibility), and the object form keyed by AWS,
Service, Federated or CanonicalUser (each value a string or array). All keyed
values are flattened for principal matching, and the original JSON is preserved
so PutBucketPolicy/GetBucketPolicy returns the exact shape submitted - keeping
infrastructure-as-code tools (Terraform, Ansible) idempotent.

Also add NotPrincipal support (a statement applies to every principal except the
ones named), compiled and evaluated in both policy evaluators, and reject
statements that specify both Principal and NotPrincipal.

* s3: address review - validate principal object form, honor dynamic NotPrincipal

- Reject unsupported Principal object keys (only AWS/Service/Federated/
  CanonicalUser) and empty values, so a form like {"AWS":[]} no longer compiles
  to zero matchers and silently relies on the match-all fallback.
- Detect both Principal and NotPrincipal by field presence, not by flattened
  length, so a present-but-empty field is still rejected.
- Honor dynamic (policy-variable) NotPrincipal/Principal patterns in the
  compiled evaluator; previously a NotPrincipal made only of variables was
  treated as absent and its exclusion bypassed.
- Add regression tests for the object-form validation and dynamic NotPrincipal.
2026-06-27 22:36:26 -07:00
d0db94c34a feat(metrics): Add EC rebuild/reconstruct Prometheus metrics (#10124)
* Review comment removed unnecessary success and failure count

* fix: use Gather.Gather() with seeded counter for EC rebuild registration test

- Restore Gather.Gather() to verify MustRegister calls as requested in review
- Seed VolumeServerECRebuildCounter before gathering because CounterVec
  only appears after at least one label value is observed
- Use correct fully-qualified metric names (SeaweedFS_volumeServer_*)

* fix: remove preflight checkEcVolumeStatus failure from ec_rebuild_total counter

ec_rebuild_total should only reflect actual rebuild execution failures
(from RebuildEcFiles / RebuildEcxFile), not scan/precheck failures in
the volume status loop. The error is still returned to the caller;
only the misleading counter increment was removed.

* Review comment removed unnecessary observe

* label EC rebuild duration histogram by result

Without a result label, fast failures pull down the success-latency
quantiles shown on the EC Rebuild Duration panel. Make the histogram a
HistogramVec keyed by result, record success/failure through one
recordEcRebuild helper, and split the Grafana quantiles by (le, result).

* reset EC rebuild metric vecs in registration test

The HistogramVec needs a child before Gather emits it, so the test must
observe once; reset both vecs in cleanup so that sample doesn't leak into
other tests.

---------

Co-authored-by: Ubuntu User <ubuntu@example.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-27 22:01:36 -07:00
Chris Lu 57ffef8543 fix(admin): skip task state files with no task data on load
An empty or truncated tasks/*.pb file unmarshals into a TaskStateFile
with a nil Task, and protobufToMaintenanceTask dereferenced it
immediately, panicking the whole admin process on startup. Guard the
nil case so the loader logs a warning and skips the bad file.
2026-06-26 17:36:42 -07:00
Chris Lu f643893891 fix(master): shed assign load when volume growth is already in flight (#10121)
Under a herd of concurrent assigns with no writable volume, Assign spun
PickForWrite for the full 10s timeout, pinning a goroutine per request and
starving the master of the cycles it needs to process growth and answer
heartbeats. When growth is the relevant remedy and already in flight, stop
spinning: if free space exists, shed with a fast retryable error so clients
back off and retry once growth lands; if the cluster is out of space, fail fast
with the real out-of-space error instead of masking it as retryable.

The gRPC shed uses ResourceExhausted, not Unavailable: operation.Assign retries
it, but the client connection layer doesn't treat it as a dead channel, so a
per-request shed across a herd doesn't tear down the shared master connection
and cancel every other in-flight assign. The HTTP dirAssignHandler sheds with
503 + Retry-After.
2026-06-26 14:23:40 -07:00
81ed379884 volume server: route VolumeMarkReadonly to raft leader (#10120)
* volume server: route VolumeMarkReadonly to raft leader

After a master raft election, volume servers may still heartbeat a follower
while admin paths such as weed shell volume.mark call notifyMasterVolumeReadonly
via vs.GetMaster(). Followers reject VolumeMarkReadonly with NotLeader, which
breaks tiering and other mark-readonly workflows until the heartbeat loop
reconnects.

Resolve the leader through GetMasterConfiguration on configured -master peers
(same Leader field filer/master clients already use) before calling
VolumeMarkReadonly. When the leader differs from the heartbeat peer, update
currentMaster so the heartbeat loop converges faster.

Adds operation.LookupRaftLeaderMaster with unit tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: address review feedback on volume.mark raft leader routing

Do not update currentMaster during leader lookup — heartbeat owns that
field and uses stream GetLeader() to reconnect. Try the heartbeat peer
first and only resolve the raft leader after a NotLeader rejection.
Add ctx.Err() early exit and quieter logging for context cancellation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(operation): thread the lookup timeout ctx into connection invalidation

The 5s timeout drove only the RPC; WithMasterServerClient saw the
unbounded outer ctx, so a self-inflicted timeout (slow GetMasterConfiguration
during an election) was treated as a stale channel and tore down the shared
master connection. Pass the timeout ctx into the helper so its own expiry
leaves ctx.Err() set and spares the connection.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-26 14:22:57 -07:00
Chris Lu 7c3c5ed2a4 fix(filer.sync.verify): sort listings client-side before merge (#10117)
* fix(filer.sync.verify): sort listings client-side before merge

The merge walks both filers' directory listings in lockstep and needs
them in the same byte order. A filer before 4.32 with a locale SQL
collation lists case-insensitively while a 4.32+ peer lists byte-ordered,
so comparing two such clusters returns the same names in a different
order and the merge desyncs into spurious MISSING / ONLY_IN_B.

Buffer and sort each directory client-side so both sides agree on order
regardless of filer version or store backend. Trades the streaming
source's O(buffer) memory for O(directory) per side, fine for a one-shot
verify CLI; both sides still load concurrently.

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

* fix(filer.sync.verify): surface listing errors before merging

A listing that fails mid-stream leaves a partial, unsorted buffer. Now
that both sides are fully buffered anyway, check each side's error right
after the loads finish and before the merge, so partial entries can't
emit spurious MISSING / ONLY_IN_B before the error aborts the run.

Claude-Session: https://claude.ai/code/session_01BKsBdKYFNCEjeHLjJfumPF
2026-06-26 10:27:18 -07:00
qzhelloandChris Lu 378f9a64ff fix: apply collectionPattern during detection in volume.fix.replication (#10115)
* fix(shell): correct volume.list -writable filter unit and comparison

* fix(shell): correct volume.list -writable filter unit and comparison

* chore(shell): fix typo in EC shard helper param names

* fix(shell): use exact match for volume.balance -racks/-nodes filter

The old strings.Contains-based filter quietly included any id that was a
  substring of the user-supplied flag value (e.g. -racks=rack10 also matched
  rack1). Replace it with an exact-match set parsed from the comma-separated
  flag value, and add regression tests for both -racks and -nodes paths.

  Also fix a small typo in the "remote storage" error returned by
  maybeMoveOneVolume.

* fix(shell): use exact match for volume.balance -racks/-nodes filter

The old strings.Contains-based filter quietly included any id that was a
  substring of the user-supplied flag value (e.g. -racks=rack10 also matched
  rack1). Replace it with an exact-match set parsed from the comma-separated
  flag value, and add regression tests for both -racks and -nodes paths.

  Also fix a small typo in the "remote storage" error returned by
  maybeMoveOneVolume.

* refactor(shell): drop nil sentinel in splitCSVSet, use len() in callers

* fix: apply collectionPattern during detection in volume.fix.replication

* use existing wildcard.MatchesWildcard for collection matching

It returns a plain bool, so drop the up-front filepath.Match validation
and the path/filepath import that only existed to handle its error.

* trim verbose comments to terse one-liners

* drop redundant per-path collection guards

Detection already filters by replicas[0].info.Collection. The repair guard
re-checked pickOneReplicaToCopyFrom's collection (a different replica), so a
mixed-collection volume could pass detection yet be skipped in repair without
decrementing the counter, spinning the -apply loop. deleteOneVolume keeps its
collectionIsMismatch safety.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-26 00:48:29 -07:00
Chris Lu f475d60fcf mount: move directory cache state to a side map to shrink InodeEntry (152 to 32 bytes) (#10114)
mount: move directory cache state to a side map to shrink InodeEntry

The mount keeps an InodeEntry alive for every inode the kernel references.
On a mount that is almost entirely regular files, each entry carried the full
directory readdir-cache bookkeeping (four time.Time fields plus counters),
bloating it to 152 bytes whether or not the inode was a directory.

Move that state into a dirState held in a side map keyed by inode, and drop the
isDirectory bool: an inode is a directory iff it has a dirState. InodeEntry is
now just paths + nlookup at 32 bytes, landing in a smaller Go allocator size
class; on a mount with tens of millions of cached file inodes that is several GB
less resident heap. As a side effect the readdir-cache scan helpers iterate only
directories instead of every inode.
2026-06-25 19:17:32 -07:00
Chris Lu c2668fbc64 fix(volume): make tier-down crash-safe and serve from local (Rust) (#10113)
* fix(volume): fsync .vif and downloaded tier .dat (Rust)

save_volume_info wrote the .vif with a plain write and no fsync, and the
tier download never synced the .dat it wrote. Either could be lost on a
crash before the tier-down path acts on them. fsync both, matching the Go
volume server's util.WriteFile and DownloadFile.

* fix(volume): swap to local before deleting remote on tier-down (Rust)

The tier-down path deleted the shared remote object before trimming the
.vif, so a crash in between left the volume's .vif pointing at a deleted
object. It also dropped the remote backend only on the delete path and
never opened the downloaded local .dat, so reads broke until reload and a
keep-remote download kept serving from the slow remote object.

Trim the .vif and swap to the local .dat on both paths, bracketed by
directory fsyncs, before removing the remote object; gate only the object
removal on keep_remote_dat_file. Matches the Go volume server's crash-safe
ordering.
2026-06-25 12:29:21 -07:00
Chris Lu 66620a1ab8 fix(volume): serve reads from remote after tier upload (Rust) (#10112)
After VolumeTierMoveDatToRemote uploaded the .dat, the volume closed its
local backend but never opened the remote one, leaving both dat_file and
remote_dat_file empty. The needle read path has no lazy reopen, so reads
returned "dat file not open" until the volume reloaded.

Switch to the remote backend right after saving the .vif, the same as the
Go volume server's LoadRemoteFile, so the volume keeps serving from remote
storage immediately after tiering.
2026-06-25 10:55:52 -07:00
Chris Lu 2c2df751f5 Perf CI: benchmark the Rust volume server and report memory usage (#10111)
* ci: add per-process memory sampler for perf jobs

Samples VmRSS once a second into a CSV and records peak VmHWM per process
on stop. Linux only; reads /proc/<pid>/status.

* ci: run perf benchmarks on the Rust volume server and report memory

Matrix the throughput and S3 jobs over go/rust volume servers, using a
standalone master (plus filer for S3) and swapping only the volume binary
so the two are directly comparable. Sample peak RSS in every job and surface
it per impl in the run summary.

* ci: harden mem sampler arg handling and peak fallback

Guard against missing args under set -u, and fall back to the max RSS
sampled when a process exits before VmHWM can be read.
2026-06-25 10:52:23 -07:00
Chris Lu 2efc0e1656 ec: recover EC shards whose .ecx index lives only on a peer server (#10108)
* ec: recover EC shards whose .ecx index lives only on a peer server

A volume server that boots with EC shard files on disk but no .ecx index
on any local disk cannot mount the shards, so the master never learns
about them. ec.rebuild works off master-registered shards, so it sees the
volume as short and gives up even though the shard data is intact.

Add an operator-triggered recovery: VolumeEcShardsMount gains a
recover_missing_index flag that makes the volume server fetch the missing
.ecx (plus .ecj/.vif) from a peer holding it and mount the on-disk shards.
ec.rebuild runs this across the cluster before planning, so orphaned
shards register and the rebuild sees the true shard set.

.ecx is an immutable encode-time index, identical on every holder. .ecj
is a per-holder deletion journal that differs across holders, so the
recovered node adopts the source peer's deletion view, like a balanced or
rebuilt shard does.

* ec: mirror missing-index recovery into the Rust volume server

Port the #10104 recovery to seaweed-volume so the Rust volume server
self-heals the same layout: EC shards on disk with the .ecx index only on
a peer. Adds collect_ec_volumes_missing_index / mount_recovered_ec_shards
to the store, recover_missing_ec_indexes (master LookupEcVolume + peer
CopyFile fetch + mount) to the server, and the recover_missing_index flag
on VolumeEcShardsMount.

.ecx is the immutable encode-time index, identical on every holder. .ecj
is a per-holder deletion journal, so the recovered node adopts the source
peer's deletion view, matching the Go path.
2026-06-25 10:38:14 -07:00
130a5dffc3 fix (Volume [Rust]): stream copy_file and volume_incremental_copy instead of buffering the whole file in memory (#10110)
* fix(volume): stream copy_file from disk instead of buffering whole file

copy_file pushed every 2MB chunk into a Vec and only then returned tokio_stream::iter(results), so serving a near-limit volume as a copy source (e.g. during volume.fix.replication) held the entire .dat resident and could OOM the process. Stream chunks through a bounded mpsc channel from a spawn_blocking reader instead; caps memory at ~16MB per transfer with backpressure.

* fix(volume): stream volume_incremental_copy from disk instead of buffering

Same buffering pattern as copy_file: every 2MB chunk was pushed into a Vec and only then returned via tokio_stream::iter, holding the entire delta resident. Stream the byte range from an owned file handle through a bounded mpsc channel, mirroring the copy_file fix.

* test(volume): cover streaming copy_file and volume_incremental_copy

Adds a multi-chunk .dat fixture and tests asserting both handlers stream in 2MB chunks (multiple messages), reassemble byte-for-byte, carry modified_ts_ns only on the first copy_file message, and honor stop_offset.

* address review: use u64 byte counters; stream local incremental copy without holding the store lock

- copy_file/volume_incremental_copy: track remaining bytes and offsets as u64 instead of casting uint64 stop_offset/dat_size through i64 (CodeRabbit).
- volume_incremental_copy: for local volumes open the .dat and stream directly with no lock held; only remote/tiered volumes take the per-chunk read_dat_slice path, so a remote S3 read is never performed while holding the store read lock (Gemini).

* volume (Rust): stream tiered incremental copy off the store lock, open .dat under it

Capture the reader for volume_incremental_copy while the volume lookup is still
under the store read lock: an open File for local volumes, a cloned remote
backend handle for tiered ones. Then drop the lock and stream with none held.
Opening under the lock pins the reader to the volume that exists now, so a
concurrent delete/recreate can't stream from the wrong file, and a slow S3
fetch for a tiered .dat no longer blocks store writers (the remote path
previously re-took the store lock per chunk).

Use a non-uniform copy-test payload so chunk reassembly catches duplicated or
reordered chunks a repeated byte would hide.

* volume (Rust): return empty when incremental-copy start offset is past the .dat

A corrupt needle index could locate an offset beyond the captured .dat size,
underflowing the dat_size - start_offset subtraction (panic in debug, wrap in
release). Guard it up front like the other empty-delta early returns.

---------

Co-authored-by: adri <adri@digitalunited.net>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-25 10:25:42 -07:00
Chris Lu c01cea8786 docker release: run all platform jobs in one wave, cache rocksdb compile
Drop max-parallel so the 13 per-platform builds run together instead of two
waves of 8 (rocksdb was queuing behind the cap and starting ~8 min late).

Keep cache-to mode=max for rocksdb: its RocksDB static_lib compile is
sha-independent, so it caches across releases and stops being the ~16-min
long-pole that gates the merge fan-in. go-build variants stay mode=min.
2026-06-25 01:13:32 -07:00
Chris Lu 3f68b19500 docker release: per-platform builds on native runners, drop mode=max cache (#10109)
docker release: build per-platform on native runners, drop mode=max cache

The build job built every platform of a variant on one runner, so 2-4 Go
cross-compiles fought over a single 2-vCPU box and arm64 ran in an emulated
context. Split the matrix to one platform per job on a native runner
(amd64/386 on ubuntu-latest, arm64/arm-v7 on ubuntu-24.04-arm); only arm/v7
still needs QEMU, and only for its final apk stage. Each job pushes by
digest, and a new merge job assembles the multi-arch tag with imagetools
and mirrors it to Docker Hub.

cache-to mode=max -> mode=min: BRANCH=sha cache-busts the heavy go-build
layer every release, so writing all intermediate layers to the gha backend
spent 3-11 min per variant on a cache the next release's sha can never hit.
2026-06-25 00:37:33 -07:00
jay d2795de186 fix(admin): volume TTL in dashboard (#10107)
fix: admin dashboard ttl display

Signed-off-by: jayl1e <jayl1e@outlook.com>
2026-06-24 23:42:10 -07:00
Chris Lu a88acaf061 Add performance CI (profiling, throughput, S3 read/write) (#10105)
* test: add self-contained S3 read/write load tool

Concurrent PUT/GET against the S3 gateway, reporting requests/sec,
transfer rate, and latency percentiles. Built on the aws-sdk-go-v2
client the S3 tests already use, so no extra benchmark binary is needed.

* ci: add performance workflow

Three parallel jobs: cpu/heap pprof of the server under write load,
native throughput via weed benchmark plus the Go micro-benchmarks, and
an S3 read/write benchmark against the gateway. Runs on push to master
and manual dispatch with tunable duration, object count, size, and
concurrency.
2026-06-24 22:44:03 -07:00
86 changed files with 7887 additions and 1430 deletions

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ jobs:
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
+1 -1
View File
@@ -97,7 +97,7 @@ jobs:
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
+118 -84
View File
@@ -33,6 +33,7 @@ permissions:
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.release_tag || github.ref_name }}
IMAGE: ghcr.io/chrislusf/seaweedfs
# Limit concurrent builds to avoid rate limits
concurrency:
@@ -79,7 +80,7 @@ jobs:
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
@@ -113,57 +114,42 @@ jobs:
weed-volume-large-disk-${{ matrix.arch }}
weed-volume-normal-${{ matrix.arch }}
# ── Build Docker containers ─────────────────────────────────────────
# One job per (variant, platform) on a native runner, pushed by digest;
# the merge job stitches the digests into one multi-arch tag.
build:
needs: [build-rust-binaries]
runs-on: ubuntu-latest
runs-on: ${{ matrix.runner }}
strategy:
# All variants at once: pulls hit mirror.gcr.io and pushes go to GHCR only,
# so docker.io limits don't apply. Watch the 10 GB gha cache budget.
max-parallel: 5
fail-fast: false
matrix:
include:
# Normal volume - multi-arch
- variant: normal
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/386
dockerfile: ./docker/Dockerfile.go_build
build_args: ""
tag_suffix: ""
rust_variant: normal
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/arm/v7, arch: armv7, runner: ubuntu-latest, qemu: true }
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/386, arch: i386, runner: ubuntu-latest, qemu: false }
# Large disk - multi-arch
- variant: large_disk
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/386
dockerfile: ./docker/Dockerfile.go_build
build_args: TAGS=5BytesOffset
tag_suffix: _large_disk
rust_variant: large-disk
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/arm/v7, arch: armv7, runner: ubuntu-latest, qemu: true }
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/386, arch: i386, runner: ubuntu-latest, qemu: false }
# Full tags - multi-arch
- variant: full
platforms: linux/amd64,linux/arm64
dockerfile: ./docker/Dockerfile.go_build
build_args: TAGS=elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb
tag_suffix: _full
rust_variant: normal
- { variant: full, tag_suffix: _full, dockerfile: ./docker/Dockerfile.go_build, build_args: "TAGS=elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb", rust_variant: normal, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
- { variant: full, tag_suffix: _full, dockerfile: ./docker/Dockerfile.go_build, build_args: "TAGS=elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb", rust_variant: normal, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
# Large disk + full tags - multi-arch
- variant: large_disk_full
platforms: linux/amd64,linux/arm64
dockerfile: ./docker/Dockerfile.go_build
build_args: TAGS=5BytesOffset,elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb
tag_suffix: _large_disk_full
rust_variant: large-disk
- { variant: large_disk_full, tag_suffix: _large_disk_full, dockerfile: ./docker/Dockerfile.go_build, build_args: "TAGS=5BytesOffset,elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb", rust_variant: large-disk, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
- { variant: large_disk_full, tag_suffix: _large_disk_full, dockerfile: ./docker/Dockerfile.go_build, build_args: "TAGS=5BytesOffset,elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb", rust_variant: large-disk, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
# RocksDB large disk - amd64 only
- variant: rocksdb
platforms: linux/amd64
dockerfile: ./docker/Dockerfile.rocksdb_large
build_args: ""
tag_suffix: _large_disk_rocksdb
rust_variant: large-disk
- { variant: rocksdb, tag_suffix: _large_disk_rocksdb, dockerfile: ./docker/Dockerfile.rocksdb_large, build_args: "", rust_variant: large-disk, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
steps:
- name: Skip unselected variant
if: github.event_name == 'workflow_dispatch' && github.event.inputs.variant != 'all' && github.event.inputs.variant != matrix.variant
run: echo "Skipping ${{ matrix.variant }} (${{ matrix.platform }})" && exit 0
- name: Checkout
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: actions/checkout@v7
@@ -192,36 +178,31 @@ jobs:
- name: Free Disk Space
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
run: |
echo "Available disk space before cleanup:"
df -h
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/*
sudo docker system prune -af --volumes
[ -d ~/.cache/go-build ] && rm -rf ~/.cache/go-build || true
[ -d /go/pkg ] && rm -rf /go/pkg || true
echo "Available disk space after cleanup:"
df -h
- name: Docker meta
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
id: docker_meta
uses: docker/metadata-action@v6
with:
images: |
chrislusf/seaweedfs
ghcr.io/chrislusf/seaweedfs
images: ${{ env.IMAGE }}
tags: type=raw,value=${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
flavor: latest=false
labels: |
org.opencontainers.image.title=seaweedfs
org.opencontainers.image.description=SeaweedFS is a distributed storage system for blobs, objects, files, and data lake, to store and serve billions of files fast!
org.opencontainers.image.vendor=Chris Lu
- name: Set up QEMU
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && contains(matrix.platforms, 'arm')
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && matrix.qemu
uses: docker/setup-qemu-action@v4.1.0
- name: Create BuildKit config
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
run: |
@@ -229,54 +210,113 @@ jobs:
[registry."docker.io"]
mirrors = ["https://mirror.gcr.io"]
EOF
- name: Set up Docker Buildx
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/setup-buildx-action@v4
with:
buildkitd-config: /tmp/buildkitd.toml
- name: Login to Docker Hub
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && github.event_name != 'pull_request'
uses: docker/login-action@v4.2.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && github.event_name != 'pull_request'
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/login-action@v4.2.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
password: ${{ secrets.GHCR_TOKEN }}
- name: Build and push ${{ matrix.variant }}
- name: Build and push ${{ matrix.variant }} (${{ matrix.platform }})
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
id: build
uses: docker/build-push-action@v7
env:
DOCKER_BUILDKIT: 1
with:
context: ./docker
push: ${{ github.event_name != 'pull_request' }}
file: ${{ matrix.dockerfile }}
platforms: ${{ matrix.platforms }}
# Push to GHCR to avoid Docker Hub rate limits on pulls
tags: |
ghcr.io/chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
platforms: ${{ matrix.platform }}
labels: ${{ steps.docker_meta.outputs.labels }}
cache-from: type=gha,scope=${{ matrix.variant }}
cache-to: type=gha,mode=max,scope=${{ matrix.variant }}
# Flat single-platform manifest so imagetools create assembles cleanly.
provenance: false
outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha,scope=${{ matrix.variant }}-${{ matrix.arch }}
# max only for rocksdb: its RocksDB compile is sha-independent and worth
# keeping; go-build layers are sha-busted every release, so min elsewhere.
cache-to: type=gha,mode=${{ matrix.variant == 'rocksdb' && 'max' || 'min' }},scope=${{ matrix.variant }}-${{ matrix.arch }}
build-args: |
${{ matrix.build_args }}
BUILDKIT_INLINE_CACHE=1
BRANCH=${{ github.sha }}
${{ matrix.variant == 'rocksdb' && format('ROCKSDB_VERSION={0}', github.event.inputs.rocksdb_version || 'v10.10.1') || '' }}
# Copy GHCR -> Docker Hub here, per variant, so it overlaps with the other
# variants still building instead of waiting on the whole matrix.
- name: Export digest
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: actions/upload-artifact@v7
with:
name: digest-${{ matrix.variant }}-${{ matrix.arch }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
# Assemble each variant's per-platform digests into one tag, then mirror to Docker Hub.
merge:
needs: [build]
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- { variant: normal, tag_suffix: "" }
- { variant: large_disk, tag_suffix: _large_disk }
- { variant: full, tag_suffix: _full }
- { variant: large_disk_full, tag_suffix: _large_disk_full }
- { variant: rocksdb, tag_suffix: _large_disk_rocksdb }
steps:
- name: Download digests
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: actions/download-artifact@v8
with:
pattern: digest-${{ matrix.variant }}-*
merge-multiple: true
path: /tmp/digests
- name: Set up Docker Buildx
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/setup-buildx-action@v4
- name: Login to GHCR
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/login-action@v4.2.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
password: ${{ secrets.GHCR_TOKEN }}
- name: Create multi-arch tag on GHCR
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
working-directory: /tmp/digests
run: |
docker buildx imagetools create \
-t ${{ env.IMAGE }}:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }} \
$(printf '${{ env.IMAGE }}@sha256:%s ' *)
docker buildx imagetools inspect ${{ env.IMAGE }}:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
- name: Login to Docker Hub
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/login-action@v4.2.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Install crane
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && github.event_name != 'pull_request'
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
run: |
cd $(mktemp -d)
curl -sL "https://github.com/google/go-containerregistry/releases/latest/download/go-containerregistry_Linux_x86_64.tar.gz" | tar xz
@@ -284,7 +324,7 @@ jobs:
crane version
- name: Copy ${{ matrix.variant }} to Docker Hub
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && github.event_name != 'pull_request'
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
run: |
retry_with_backoff() {
local max_attempts=5
@@ -310,16 +350,10 @@ jobs:
echo "Copying ${{ matrix.variant }} from GHCR to Docker Hub..."
retry_with_backoff crane copy \
ghcr.io/chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }} \
${{ env.IMAGE }}:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }} \
chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.tag_suffix }}
echo "Copied ${{ matrix.variant }} to Docker Hub"
- name: Clean up build artifacts
if: always() && (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant)
run: |
sudo docker system prune -f
sudo rm -rf /tmp/go-build*
# Report-only trivy scan: uploads fixable HIGH/CRITICAL findings to GitHub
# Security for visibility, but never blocks the release. Releases (including
# `latest`) ship regardless — vulnerabilities are tracked, not gated, since
@@ -327,7 +361,7 @@ jobs:
# CVE, base-image lag).
trivy-scan:
runs-on: ubuntu-latest
needs: [build]
needs: [merge]
if: github.event_name == 'push'
continue-on-error: true
strategy:
@@ -354,7 +388,7 @@ jobs:
# Scan the multi-arch tag on GHCR (already pushed by the build job).
# Trivy scans the runner's native platform; OS packages are identical
# across architectures since they all share the same alpine base.
image-ref: ghcr.io/chrislusf/seaweedfs:${{ env.RELEASE_TAG }}${{ matrix.source_suffix }}
image-ref: ${{ env.IMAGE }}:${{ env.RELEASE_TAG }}${{ matrix.source_suffix }}
scanners: vuln
vuln-type: os,library
severity: HIGH,CRITICAL
@@ -378,7 +412,7 @@ jobs:
# trivy-scan: vuln findings are reported but do not block `latest`.
tag-latest:
runs-on: ubuntu-latest
needs: [build]
needs: [merge]
if: github.event_name == 'push'
strategy:
matrix:
@@ -435,8 +469,8 @@ jobs:
SRC_TAG="${{ env.RELEASE_TAG }}${{ matrix.source_suffix }}"
DST_TAG="${{ matrix.latest_tag }}"
echo "Tagging ghcr.io/chrislusf/seaweedfs:${SRC_TAG} as ${DST_TAG}"
retry_with_backoff crane tag "ghcr.io/chrislusf/seaweedfs:${SRC_TAG}" "${DST_TAG}"
echo "Tagging ${{ env.IMAGE }}:${SRC_TAG} as ${DST_TAG}"
retry_with_backoff crane tag "${{ env.IMAGE }}:${SRC_TAG}" "${DST_TAG}"
echo "Tagging chrislusf/seaweedfs:${SRC_TAG} as ${DST_TAG}"
retry_with_backoff crane tag "chrislusf/seaweedfs:${SRC_TAG}" "${DST_TAG}"
@@ -452,7 +486,7 @@ jobs:
- uses: actions/checkout@v7
- name: Publish Helm charts
uses: stefanprodan/helm-gh-pages@v1.7.0
with:
with:
token: ${{ secrets.GITHUB_TOKEN }}
charts_dir: k8s/charts
target_dir: helm
+1 -1
View File
@@ -52,7 +52,7 @@ jobs:
uses: docker/setup-buildx-action@v4
- name: Cache Docker layers
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-e2e-${{ github.sha }}
+477
View File
@@ -0,0 +1,477 @@
name: "Performance"
on:
push:
branches: [ master ]
paths:
- '**/*.go'
- 'go.mod'
- 'go.sum'
- 'seaweed-volume/**'
- 'test/perf/**'
- '.github/workflows/performance.yml'
workflow_dispatch:
inputs:
profile_duration:
description: "CPU profiling duration in seconds"
required: false
default: "30"
type: string
benchmark_files:
description: "Number of files for the throughput benchmark"
required: false
default: "100000"
type: string
benchmark_concurrency:
description: "Concurrent read/write workers"
required: false
default: "16"
type: string
benchmark_size:
description: "Simulated file size in bytes"
required: false
default: "1024"
type: string
s3_objects:
description: "Number of objects for the S3 benchmark"
required: false
default: "20000"
type: string
s3_size:
description: "S3 object size in bytes"
required: false
default: "4096"
type: string
concurrency:
group: ${{ github.head_ref || github.ref }}/performance
cancel-in-progress: true
permissions:
contents: read
env:
VOL_SIZE_LIMIT: "1024"
jobs:
performance-profile:
name: CPU and Heap Profile
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: 'go.mod'
- name: Build weed
run: go build -o weed_bin ./weed
- name: Start server with profiling enabled
run: |
mkdir -p ./perfdata
./weed_bin -v=1 server -debug -debug.port=6060 -dir=./perfdata \
-s3 -filer -volume.max=0 -master.volumeSizeLimitMB=100 \
-s3.port=8000 -s3.config=./docker/compose/s3.json \
> weed.log 2>&1 &
echo "WEED_PID=$!" >> "$GITHUB_ENV"
for i in $(seq 1 60); do
if curl -sf http://localhost:9333/dir/status >/dev/null 2>&1; then
echo "master is ready"
break
fi
sleep 1
done
# give the volume server a moment to register with the master
sleep 3
- name: Start memory sampler
run: |
bash test/perf/mem_sample.sh mem-profile.csv "server=${WEED_PID}" &
echo "SAMPLER_PID=$!" >> "$GITHUB_ENV"
- name: Capture profiles under load
run: |
DURATION="${{ github.event.inputs.profile_duration || '30' }}"
# drive write load so the sampled profile reflects real work
./weed_bin benchmark -master=localhost:9333 -writeOnly \
-c=16 -n=5000000 -size=1024 > benchmark-load.log 2>&1 &
echo "Sampling CPU profile for ${DURATION}s..."
curl -s "http://localhost:6060/debug/pprof/profile?seconds=${DURATION}" -o cpu.pprof
curl -s "http://localhost:6060/debug/pprof/heap" -o heap.pprof
curl -s "http://localhost:6060/debug/pprof/goroutine?debug=1" -o goroutine.txt
go tool pprof -top -nodecount=50 cpu.pprof > cpu-top.txt 2>/dev/null || true
go tool pprof -top -nodecount=50 -sample_index=inuse_space heap.pprof > heap-top.txt 2>/dev/null || true
- name: Record memory usage
if: always()
run: |
kill -TERM "${SAMPLER_PID}" 2>/dev/null || true
sleep 2
{
echo "## Memory usage (peak RSS)"
echo '```'
if [ -f mem-profile.csv.peak ]; then
awk -F'\t' '{printf "%-10s %8d KB (%.1f MB)\n", $1, $2, $2/1024}' mem-profile.csv.peak
else
echo "no memory samples captured"
fi
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Profile summary
if: always()
run: |
{
echo "## CPU profile (top functions)"
echo '```'
head -45 cpu-top.txt 2>/dev/null || echo "no cpu profile captured"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Stop server
if: always()
run: kill "${WEED_PID}" 2>/dev/null || true
- name: Show server log on failure
if: failure()
run: tail -200 weed.log || true
- name: Upload profiles
if: always()
uses: actions/upload-artifact@v7
with:
name: performance-profile-${{ github.run_number }}
path: |
cpu.pprof
heap.pprof
cpu-top.txt
heap-top.txt
goroutine.txt
mem-profile.csv
mem-profile.csv.peak
weed.log
retention-days: 30
benchmark:
name: Throughput Benchmark (${{ matrix.impl }} volume)
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
impl: [go, rust]
env:
IMPL: ${{ matrix.impl }}
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: 'go.mod'
- name: Install protobuf compiler
if: matrix.impl == 'rust'
run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
- name: Install Rust toolchain
if: matrix.impl == 'rust'
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
if: matrix.impl == 'rust'
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
key: rust-${{ hashFiles('seaweed-volume/Cargo.lock') }}
restore-keys: |
rust-
- name: Build weed
run: go build -o weed_bin ./weed
- name: Build Rust volume server
if: matrix.impl == 'rust'
run: cd seaweed-volume && cargo build --release
- name: Start master and volume server
run: |
mkdir -p ./perfdata/master ./perfdata/vol
./weed_bin -v=1 master -ip=127.0.0.1 -port=9333 \
-mdir=./perfdata/master -peers=none \
-volumeSizeLimitMB="${VOL_SIZE_LIMIT}" -defaultReplication=000 \
> master.log 2>&1 &
echo "MASTER_PID=$!" >> "$GITHUB_ENV"
for i in $(seq 1 60); do
if curl -sf http://localhost:9333/dir/status >/dev/null 2>&1; then
echo "master is ready"
break
fi
sleep 1
done
if [ "${IMPL}" = "rust" ]; then
./seaweed-volume/target/release/weed-volume \
--master 127.0.0.1:9333 --ip 127.0.0.1 --ip.bind 127.0.0.1 \
--port 8080 --dir ./perfdata/vol --max 100 --preStopSeconds 0 \
> volume.log 2>&1 &
else
./weed_bin -v=1 volume -master=127.0.0.1:9333 -ip=127.0.0.1 \
-port=8080 -dir=./perfdata/vol -max=100 \
> volume.log 2>&1 &
fi
echo "VOLUME_PID=$!" >> "$GITHUB_ENV"
for i in $(seq 1 60); do
if curl -sf http://localhost:8080/status >/dev/null 2>&1; then
echo "volume server is ready"
break
fi
sleep 1
done
# let the volume server register with the master via heartbeat
sleep 3
- name: Start memory sampler
run: |
bash test/perf/mem_sample.sh mem-benchmark.csv \
"master=${MASTER_PID}" "volume=${VOLUME_PID}" &
echo "SAMPLER_PID=$!" >> "$GITHUB_ENV"
- name: Run throughput benchmark
run: |
N="${{ github.event.inputs.benchmark_files || '100000' }}"
C="${{ github.event.inputs.benchmark_concurrency || '16' }}"
SIZE="${{ github.event.inputs.benchmark_size || '1024' }}"
./weed_bin benchmark -master=localhost:9333 \
-c="${C}" -n="${N}" -size="${SIZE}" 2>&1 | tee benchmark-results.txt
- name: Run Go micro-benchmarks
if: matrix.impl == 'go'
continue-on-error: true
run: |
go test -run='^$' -bench=. -benchmem -benchtime=10x \
./weed/topology/... ./weed/util/log_buffer/... ./weed/util/buffered_queue/... \
2>&1 | tee go-benchmarks.txt
- name: Record memory usage
if: always()
run: |
kill -TERM "${SAMPLER_PID}" 2>/dev/null || true
sleep 2
{
echo "## Memory usage (peak RSS, ${IMPL} volume)"
echo '```'
if [ -f mem-benchmark.csv.peak ]; then
awk -F'\t' '{printf "%-10s %8d KB (%.1f MB)\n", $1, $2, $2/1024}' mem-benchmark.csv.peak
else
echo "no memory samples captured"
fi
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Benchmark summary
if: always()
run: |
{
echo "## Throughput benchmark (${IMPL} volume)"
echo '```'
grep -E "Concurrency Level|Time taken|Completed requests|Failed requests|Requests per second|Transfer rate" \
benchmark-results.txt 2>/dev/null || echo "no benchmark results captured"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Stop processes
if: always()
run: |
kill "${VOLUME_PID}" "${MASTER_PID}" 2>/dev/null || true
- name: Show logs on failure
if: failure()
run: |
echo "=== master.log ==="; tail -100 master.log 2>/dev/null || true
echo "=== volume.log ==="; tail -200 volume.log 2>/dev/null || true
- name: Upload benchmark results
if: always()
uses: actions/upload-artifact@v7
with:
name: benchmark-results-${{ matrix.impl }}-${{ github.run_number }}
path: |
benchmark-results.txt
go-benchmarks.txt
mem-benchmark.csv
mem-benchmark.csv.peak
master.log
volume.log
retention-days: 7
s3-benchmark:
name: S3 Read/Write Benchmark (${{ matrix.impl }} volume)
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
impl: [go, rust]
env:
IMPL: ${{ matrix.impl }}
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: 'go.mod'
- name: Install protobuf compiler
if: matrix.impl == 'rust'
run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
- name: Install Rust toolchain
if: matrix.impl == 'rust'
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
if: matrix.impl == 'rust'
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
key: rust-${{ hashFiles('seaweed-volume/Cargo.lock') }}
restore-keys: |
rust-
- name: Build weed and S3 load tool
run: |
go build -o weed_bin ./weed
go build -o s3bench ./test/s3/benchmark
- name: Build Rust volume server
if: matrix.impl == 'rust'
run: cd seaweed-volume && cargo build --release
- name: Start cluster with S3 gateway
run: |
mkdir -p ./perfdata/master ./perfdata/vol ./perfdata/filer
./weed_bin -v=1 master -ip=127.0.0.1 -port=9333 \
-mdir=./perfdata/master -peers=none \
-volumeSizeLimitMB="${VOL_SIZE_LIMIT}" -defaultReplication=000 \
> master.log 2>&1 &
echo "MASTER_PID=$!" >> "$GITHUB_ENV"
for i in $(seq 1 60); do
if curl -sf http://localhost:9333/dir/status >/dev/null 2>&1; then
echo "master is ready"
break
fi
sleep 1
done
if [ "${IMPL}" = "rust" ]; then
./seaweed-volume/target/release/weed-volume \
--master 127.0.0.1:9333 --ip 127.0.0.1 --ip.bind 127.0.0.1 \
--port 8080 --dir ./perfdata/vol --max 100 --preStopSeconds 0 \
> volume.log 2>&1 &
else
./weed_bin -v=1 volume -master=127.0.0.1:9333 -ip=127.0.0.1 \
-port=8080 -dir=./perfdata/vol -max=100 \
> volume.log 2>&1 &
fi
echo "VOLUME_PID=$!" >> "$GITHUB_ENV"
for i in $(seq 1 60); do
if curl -sf http://localhost:8080/status >/dev/null 2>&1; then
echo "volume server is ready"
break
fi
sleep 1
done
sleep 3
./weed_bin -v=1 filer -master=127.0.0.1:9333 -ip=127.0.0.1 -port=8888 \
-s3 -s3.port=8000 -s3.config=./docker/compose/s3.json \
> filer.log 2>&1 &
echo "FILER_PID=$!" >> "$GITHUB_ENV"
for i in $(seq 1 30); do
if nc -z localhost 8000 2>/dev/null; then
echo "s3 gateway is ready"
break
fi
sleep 1
done
sleep 2
- name: Start memory sampler
run: |
bash test/perf/mem_sample.sh mem-s3.csv \
"master=${MASTER_PID}" "volume=${VOLUME_PID}" "filer=${FILER_PID}" &
echo "SAMPLER_PID=$!" >> "$GITHUB_ENV"
- name: Run S3 read/write benchmark
run: |
OBJECTS="${{ github.event.inputs.s3_objects || '20000' }}"
C="${{ github.event.inputs.benchmark_concurrency || '16' }}"
SIZE="${{ github.event.inputs.s3_size || '4096' }}"
./s3bench -endpoint=http://localhost:8000 \
-access-key=some_access_key1 -secret-key=some_secret_key1 \
-objects="${OBJECTS}" -size="${SIZE}" -concurrency="${C}" -mode=both \
2>&1 | tee s3-benchmark-results.txt
- name: Record memory usage
if: always()
run: |
kill -TERM "${SAMPLER_PID}" 2>/dev/null || true
sleep 2
{
echo "## Memory usage (peak RSS, ${IMPL} volume)"
echo '```'
if [ -f mem-s3.csv.peak ]; then
awk -F'\t' '{printf "%-10s %8d KB (%.1f MB)\n", $1, $2, $2/1024}' mem-s3.csv.peak
else
echo "no memory samples captured"
fi
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: S3 benchmark summary
if: always()
run: |
{
echo "## S3 read/write benchmark (${IMPL} volume)"
echo '```'
grep -E "results:|Concurrency Level|Time taken|Completed requests|Failed requests|Requests per second|Transfer rate|Latency" \
s3-benchmark-results.txt 2>/dev/null || echo "no S3 benchmark results captured"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Stop processes
if: always()
run: |
kill "${FILER_PID}" "${VOLUME_PID}" "${MASTER_PID}" 2>/dev/null || true
- name: Show logs on failure
if: failure()
run: |
echo "=== master.log ==="; tail -100 master.log 2>/dev/null || true
echo "=== volume.log ==="; tail -200 volume.log 2>/dev/null || true
echo "=== filer.log ==="; tail -200 filer.log 2>/dev/null || true
- name: Upload S3 benchmark results
if: always()
uses: actions/upload-artifact@v7
with:
name: s3-benchmark-results-${{ matrix.impl }}-${{ github.run_number }}
path: |
s3-benchmark-results.txt
mem-s3.csv
mem-s3.csv.peak
master.log
volume.log
filer.log
retention-days: 7
+1 -1
View File
@@ -56,7 +56,7 @@ jobs:
uses: docker/setup-buildx-action@v4
- name: Cache Docker layers
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-postgres-${{ github.sha }}
@@ -43,7 +43,7 @@ jobs:
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
@@ -80,7 +80,7 @@ jobs:
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
@@ -156,7 +156,7 @@ jobs:
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
+2 -2
View File
@@ -48,7 +48,7 @@ jobs:
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
@@ -119,7 +119,7 @@ jobs:
targets: ${{ matrix.target }}
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
+3 -3
View File
@@ -51,7 +51,7 @@ jobs:
echo "OPENSSL_LIB_DIR=/usr/lib/aarch64-linux-gnu" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
@@ -140,7 +140,7 @@ jobs:
targets: ${{ matrix.target }}
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
@@ -218,7 +218,7 @@ jobs:
uses: dtolnay/rust-toolchain@stable
- name: Cache cargo registry and target
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
+1 -1
View File
@@ -588,7 +588,7 @@ jobs:
- name: Restore python:3 image cache
id: python-image
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: /tmp/python3-image.tar
key: python3-image-${{ steps.week.outputs.week }}
@@ -150,7 +150,7 @@ jobs:
- name: Cache Apache Spark
if: false && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
id: cache-spark
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: spark-3.5.0-bin-hadoop3
key: spark-3.5.0-hadoop3
+9 -9
View File
@@ -38,7 +38,7 @@ require (
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/jackc/pgx/v5 v5.9.2
github.com/jackc/pgx/v5 v5.10.0
github.com/jcmturner/gofork v1.7.6 // indirect
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
github.com/jinzhu/copier v0.4.0
@@ -89,14 +89,14 @@ require (
go.mongodb.org/mongo-driver v1.17.9
go.opencensus.io v0.24.0 // indirect
gocloud.dev v0.46.0
gocloud.dev/pubsub/natspubsub v0.45.0
gocloud.dev/pubsub/natspubsub v0.46.0
gocloud.dev/pubsub/rabbitpubsub v0.46.0
golang.org/x/crypto v0.52.0
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
golang.org/x/image v0.41.0
golang.org/x/net v0.55.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sys v0.45.0
golang.org/x/sys v0.46.0
golang.org/x/text v0.37.0 // indirect
golang.org/x/tools v0.45.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
@@ -145,7 +145,7 @@ require (
github.com/rabbitmq/amqp091-go v1.11.0
github.com/rclone/rclone v1.74.3
github.com/rdleal/intervalst v1.5.0
github.com/redis/go-redis/v9 v9.20.0
github.com/redis/go-redis/v9 v9.21.0
github.com/schollz/progressbar/v3 v3.19.0
github.com/seaweedfs/go-fuse/v2 v2.9.3
github.com/shirou/gopsutil/v4 v4.26.5
@@ -292,8 +292,8 @@ require (
cloud.google.com/go/iam v1.7.0 // indirect
cloud.google.com/go/monitoring v1.24.3 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4 // indirect
@@ -420,8 +420,8 @@ require (
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nats-io/nats.go v1.48.0 // indirect
github.com/nats-io/nkeys v0.4.12 // indirect
github.com/nats-io/nats.go v1.49.0 // indirect
github.com/nats-io/nkeys v0.4.15 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/ncw/swift/v2 v2.0.5 // 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.43.0
golang.org/x/term v0.44.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-20260427160629-7cedc36a6bc4 // indirect
+26 -26
View File
@@ -553,12 +553,12 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zum
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1 h1:jHb/wfvRikGdxMXYV3QG/SzUOPYN9KEUUuC0Yd0/vC0=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1/go.mod h1:pzBXCYn05zvYIrwLgtK8Ap8QcjRg+0i76tMQdWN6wOk=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0/go.mod h1:q0+UTSRvShwUCrR/s5HtyInYphN7Wvxb7snFM3u+SLA=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0 h1:m/sWOGCREuSBqg2htVQTBY8nOZpyajYztF0vUvSZTuM=
@@ -683,8 +683,8 @@ github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUS
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op h1:Ucf+QxEKMbPogRO5guBNe5cgd9uZgfoJLOYs8WWhtjM=
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op h1:kpBdlEPbRvff0mDD1gk7o9BhI16b9p5yYAXRlidpqJE=
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/apache/arrow-go/v18 v18.6.0 h1:GX/Jyd3R7mCLiECAwY9FWbbaYblie2WXBSz4Sw8fNpM=
@@ -1379,8 +1379,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
@@ -1591,14 +1591,14 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nats-io/jwt/v2 v2.8.0 h1:K7uzyz50+yGZDO5o772eRE7atlcSEENpL7P+b74JV1g=
github.com/nats-io/jwt/v2 v2.8.0/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA=
github.com/nats-io/nats-server/v2 v2.11.12 h1:jGDXTkcjqQ5fCRstwIxvv1K0RHfftFUoSCT/iIZcqOc=
github.com/nats-io/nats-server/v2 v2.11.12/go.mod h1:5MCp/pqm5SEfsvVZ31ll1088ZTwEUdvRX1Hmh/mTTDg=
github.com/nats-io/nats.go v1.48.0 h1:pSFyXApG+yWU/TgbKCjmm5K4wrHu86231/w84qRVR+U=
github.com/nats-io/nats.go v1.48.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU=
github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg=
github.com/nats-io/nats-server/v2 v2.11.15 h1:StSf9TINInaZtr4oww2+kXmfwa9SkN//g/LwS19/UJ0=
github.com/nats-io/nats-server/v2 v2.11.15/go.mod h1:zwhv8Y0PE3KHyKgznJc/9Xoai638SaJd83zzJ5GJn74=
github.com/nats-io/nats.go v1.49.0 h1:yh/WvY59gXqYpgl33ZI+XoVPKyut/IcEaqtsiuTJpoE=
github.com/nats-io/nats.go v1.49.0/go.mod h1:fDCn3mN5cY8HooHwE2ukiLb4p4G4ImmzvXyJt+tGwdw=
github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=
github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
@@ -1763,8 +1763,8 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5X
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
github.com/rdleal/intervalst v1.5.0/go.mod h1:xO89Z6BC+LQDH+IPQQw/OESt5UADgFD41tYMUINGpxQ=
github.com/redis/go-redis/v9 v9.20.0 h1:WnQYxLkgO2xiXTCJY0ldIiI8dNqCDlQAG+AtaH7a2a0=
github.com/redis/go-redis/v9 v9.20.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E=
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
github.com/redis/rueidis v1.0.71 h1:pODtnAR5GAB7j4ekhldZ29HKOxe4Hph0GTDGk1ayEQY=
github.com/redis/rueidis v1.0.71/go.mod h1:lfdcZzJ1oKGKL37vh9fO3ymwt+0TdjkkUCJxbgpmcgQ=
github.com/redis/rueidis/rueidiscompat v1.0.71 h1:wNZ//kEjMZgBM0KCk7ncOX8KmAgROU2kDdDNpwheG4w=
@@ -2152,8 +2152,8 @@ go.yaml.in/yaml/v4 v4.0.0-rc.4 h1:UP4+v6fFrBIb1l934bDl//mmnoIZEDK0idg1+AIvX5U=
go.yaml.in/yaml/v4 v4.0.0-rc.4/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM=
gocloud.dev/pubsub/natspubsub v0.45.0 h1:kfCupVejeynIQcS1GaIvkY3Nj/acLlM5yPWyxZN8wJ8=
gocloud.dev/pubsub/natspubsub v0.45.0/go.mod h1:WU5SMDWuF7CCr2U8UpbrEONYYFOmvigCAvTpOOpUvYE=
gocloud.dev/pubsub/natspubsub v0.46.0 h1:cTmJnWOmhb3dYRzX7PvNkq2m5mQdBLFFxZbl/21pfjk=
gocloud.dev/pubsub/natspubsub v0.46.0/go.mod h1:hbEEsNt6mGQoonGQi39VOjHfx2f13DOmWouh4hGsfrU=
gocloud.dev/pubsub/rabbitpubsub v0.46.0 h1:uWJ8z/F8xYxoTlBafTweoKvX2V85cwtN+/+nyRRtjZ0=
gocloud.dev/pubsub/rabbitpubsub v0.46.0/go.mod h1:Ef5XHxv17zV9B3U9xoYAqJ8Rutslxt5Emb5e1cScuXc=
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
@@ -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.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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/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.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
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=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.36"
appVersion: "4.37"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.36.0
version: 4.37.0
+214
View File
@@ -4362,6 +4362,220 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "EC Rebuild Duration",
"description": "p50/p95/p99 duration of EC shard rebuild operations",
"type": "timeseries",
"id": 217,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 126
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_volumeServer_ec_rebuild_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, result))",
"range": true,
"refId": "A",
"legendFormat": "p99 {{result}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.95, sum(rate(SeaweedFS_volumeServer_ec_rebuild_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, result))",
"range": true,
"refId": "B",
"legendFormat": "p95 {{result}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.50, sum(rate(SeaweedFS_volumeServer_ec_rebuild_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, result))",
"range": true,
"refId": "C",
"legendFormat": "p50 {{result}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "EC Rebuild Operations",
"description": "Rate of EC shard rebuild operations by result",
"type": "timeseries",
"id": 218,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 126
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (result) (rate(SeaweedFS_volumeServer_ec_rebuild_total{cluster=~\"$cluster\"}[5m]))",
"range": true,
"refId": "A",
"legendFormat": "{{result}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
+26
View File
@@ -442,6 +442,7 @@ message VolumeEcShardsCopyRequest {
bool copy_ecj_file = 6;
bool copy_vif_file = 7;
uint32 disk_id = 8; // Target disk ID for storing EC shards
bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
}
message VolumeEcShardsCopyResponse {
}
@@ -462,6 +463,7 @@ message VolumeEcShardsMountRequest {
string collection = 2;
repeated uint32 shard_ids = 3;
string source_disk_type = 4; // disk type of the source volume, applied to the in-memory EC volume so heartbeats report under it (#9423)
bool recover_missing_index = 5; // first fetch a missing .ecx index from a peer so on-disk shards without a local index become mountable (#10104)
}
message VolumeEcShardsMountResponse {
}
@@ -586,6 +588,29 @@ message EcShardConfig {
uint32 parity_shards = 2; // Number of parity shards (e.g., 4)
int64 encode_ts_ns = 3; // encode time (unix nanos); a read served from a shard of a different encode run is rejected
}
// EcBitrotProtection is the entire content of a bitrot checksum sidecar
// (<base>.ecsum for the legacy generation, <base>.ecsum.v<N> for vacuum
// generation N): per-shard, per-block CRC32C so a CHECKSUM scrub can detect
// silent bit rot in any shard (including parity) without decoding. Field
// numbers and types match weed/pb/volume_server.proto byte-for-byte so the
// serialized sidecar payload is wire-identical across the Go and Rust binaries.
message EcBitrotProtection {
ChecksumAlgorithm algorithm = 1; // CRC32C (Castagnoli)
uint32 block_size = 2; // bytes per checksum block; default 16777216 (16 MiB), a power-of-two multiple of 1 MiB
uint32 generation = 3; // EC vacuum generation these checksums describe (0 = legacy/fresh); must match the sidecar filename version
EcShardConfig ec_shard_config = 4; // data/parity shard counts at encode time
repeated EcShardChecksums shards = 5; // one entry per shard id in the active layout
bytes encode_uuid = 6; // random per-encode identity, for stale-sidecar detection across in-place re-encodes
}
message EcShardChecksums {
uint32 shard_id = 1; // 0..MaxShardCount-1 (custom EC ratios go up to 32)
int64 covered_size = 2; // shard byte length these checksums cover (must equal the on-disk shard length)
bytes block_crc32c = 3; // packed little-endian uint32[] = ceil(covered_size/block_size) entries
}
enum ChecksumAlgorithm {
CHECKSUM_NONE = 0;
CHECKSUM_CRC32C = 1;
}
message OldVersionVolumeInfo {
repeated RemoteFile files = 1;
uint32 version = 2;
@@ -663,6 +688,7 @@ enum VolumeScrubMode {
INDEX = 1;
FULL = 2;
LOCAL = 3;
CHECKSUM = 4; // EC only: verify each local shard's raw bytes against the bitrot checksum sidecar
}
message ScrubVolumeRequest {
@@ -364,6 +364,18 @@ impl S3TierBackend {
.map_err(|e| format!("download task panicked: {}", e))??;
}
// fsync the file so its content is durable before the caller trims the .vif
// and deletes the remote object (matches Go's DownloadFile f.Sync()).
let synced = tokio::fs::OpenOptions::new()
.write(true)
.open(dest_path)
.await
.map_err(|e| format!("failed to open {} for fsync: {}", dest_path, e))?;
synced
.sync_all()
.await
.map_err(|e| format!("failed to fsync {}: {}", dest_path, e))?;
Ok(file_size)
}
File diff suppressed because it is too large. Load diff
+37 -2
View File
@@ -356,12 +356,23 @@ fn parse_url_path(path: &str) -> Option<(VolumeId, NeedleId, Cookie)> {
#[derive(Clone, Debug, Deserialize)]
struct VolumeLocation {
url: String,
#[serde(rename = "publicUrl")]
// Master often omits publicUrl when it matches url (Go json omitempty).
#[serde(rename = "publicUrl", default)]
public_url: String,
#[serde(rename = "grpcPort", default)]
grpc_port: u32,
}
impl VolumeLocation {
fn public_or_url(&self) -> &str {
if self.public_url.is_empty() {
&self.url
} else {
&self.public_url
}
}
}
/// Master /dir/lookup response.
#[derive(Debug, Deserialize)]
struct LookupResult {
@@ -535,9 +546,13 @@ async fn do_replicated_request(
.await
.map_err(|e| format!("lookup volume failed: {}", e))?;
let self_http = to_http_address(&state.self_url);
let remote_locations: Vec<_> = locations
.into_iter()
.filter(|loc| loc.url != state.self_url && loc.public_url != state.self_url)
.filter(|loc| {
to_http_address(&loc.url) != self_http
&& to_http_address(loc.public_or_url()) != self_http
})
.collect();
if remote_locations.is_empty() {
@@ -4022,6 +4037,26 @@ mod tests {
);
}
/// Master /dir/lookup often omits publicUrl when empty (Go `json:"publicUrl,omitempty"`).
/// Replication must still parse locations or every cross-DC write fails.
#[test]
fn test_lookup_result_deserializes_without_public_url() {
let body = r#"{
"volumeOrFileId": "9",
"locations": [
{"url": "volume-a.example:8080", "dataCenter": "dc-a", "grpcPort": 18080},
{"url": "volume-b.example:8080", "dataCenter": "dc-b", "grpcPort": 18080}
]
}"#;
let result: LookupResult = serde_json::from_str(body).expect("parse lookup JSON");
let locations = result.locations.expect("locations");
assert_eq!(locations.len(), 2);
assert_eq!(locations[0].url, "volume-a.example:8080");
assert!(locations[0].public_url.is_empty());
assert_eq!(locations[0].public_or_url(), "volume-a.example:8080");
assert_eq!(locations[0].grpc_port, 18080);
}
/// Regression test for issue #9274.
///
/// SeaweedFS encodes a server's gRPC port by appending `.grpcPort` to
+451 -18
View File
@@ -27,6 +27,7 @@
//! `RwLock` so we do not contend with the Store-level lock at all.
use std::collections::HashMap;
use std::fs;
use std::io;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -37,14 +38,16 @@ use tonic::Request;
use crate::pb::master_pb::{self, seaweed_client::SeaweedClient, LookupEcVolumeRequest};
use crate::pb::volume_server_pb::{
volume_server_client::VolumeServerClient, VolumeEcShardReadRequest,
volume_server_client::VolumeServerClient, CopyFileRequest, VolumeEcShardReadRequest,
};
use crate::server::grpc_client::{build_grpc_endpoint, parse_grpc_address, GRPC_MAX_MESSAGE_SIZE};
use crate::server::request_id::outgoing_request_id_interceptor;
use crate::server::volume_server::VolumeServerState;
use crate::server::volume_server::{to_http_address, VolumeServerState};
use crate::storage::erasure_coding::ec_shard::ShardId;
use crate::storage::needle::needle::{get_actual_size, Needle};
use crate::storage::needle::needle::{get_actual_size, Needle, NeedleError};
use crate::storage::store_ec_reconcile::EcVolumeMissingIndex;
use crate::storage::types::*;
use crate::storage::volume::volume_file_name;
/// One interval's data after Phase A.
enum IntervalResult {
@@ -190,6 +193,188 @@ pub async fn read_ec_shard_needle_distributed(
Ok(Some(n))
}
/// FULL EC scrub: verify every needle's bytes across local AND remote shards,
/// without decoding (so genuine shard faults are reported rather than healed).
/// Mirrors Go's `Store.ScrubEcVolume`. Returns (rows walked, broken shards,
/// errors). `force_deleted_needles_check` disables the benign delete-state
/// size-mismatch suppression.
///
/// Shard locations are refreshed once up front. Each needle is then processed via
/// `scrub_snapshot_under_lock` + lock-drop + no-reconstruct `read_remote_ec_shard_interval`,
/// so no `!Send` store guard is held across an `.await`.
pub async fn scrub_ec_volume_distributed(
state: &Arc<VolumeServerState>,
vid: VolumeId,
force_deleted_needles_check: bool,
) -> (i64, Vec<crate::pb::volume_server_pb::EcShardInfo>, Vec<String>) {
// Phase A — under the Store read lock, run the index scrub and grab the
// paths/scalars + shard-location staleness; release the lock before any await.
let (ecx_path, collection, seed_errs, cached_locations, cache_refreshed_at, data_shards, total_shards) = {
let store = state.store.read().unwrap();
let ecv = match store.find_ec_volume(vid) {
Some(v) => v,
None => {
return (
0,
Vec::new(),
vec![format!("EC volume id {} not found", vid.0)],
)
}
};
// full scan means verifying the index as well
let (_, errs) = ecv.scrub_index();
// Bind to locals so the inner RwLock/Mutex guards drop before the block ends.
let cached_locations = ecv.shard_locations.read().unwrap().clone();
let cache_refreshed_at = *ecv.shard_locations_refresh_time.lock().unwrap();
let data_shards = ecv.data_shards as usize;
let total_shards = (ecv.data_shards + ecv.parity_shards) as usize;
(
ecv.ecx_file_name(),
ecv.collection.clone(),
errs,
cached_locations,
cache_refreshed_at,
data_shards,
total_shards,
)
};
let mut errs = seed_errs;
// Refresh the shard-location cache once up front (mirrors Go's
// cachedLookupEcShardLocations); a failed lookup is a hard error rather than
// a per-needle connect storm against a down master.
if needs_refresh(&cached_locations, cache_refreshed_at, data_shards, total_shards) {
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => write_back_shard_locations(state, vid, fresh),
Err(e) => {
return (
0,
Vec::new(),
vec![format!("failed to locate shard via master grpc: {}", e)],
)
}
}
}
// Walk the .ecx (private fd, no lock) for the row count + live (id, offset, size).
let mut count: i64 = 0;
let mut needles: Vec<(NeedleId, Offset, Size)> = Vec::new();
match fs::File::open(&ecx_path) {
Ok(mut f) => {
if let Err(e) = crate::storage::idx::walk_index_file(&mut f, 0, |id, offset, size| {
count += 1;
if !size.is_tombstone() {
needles.push((id, offset, size));
}
Ok(())
}) {
errs.push(format!("walk ECX file {}: {}", ecx_path, e));
}
}
Err(e) => errs.push(format!("open ECX file {}: {}", ecx_path, e)),
}
// reads for EC chunks can hit the same shard repeatedly, so dedupe broken shards
let mut broken_shards: HashMap<ShardId, crate::pb::volume_server_pb::EcShardInfo> = HashMap::new();
for (id, offset, size) in needles {
// Per-needle snapshot under the lock from the RAW .ecx (offset, size) so
// logically-deleted needles are still verified; lock dropped before await.
let snapshot = match scrub_snapshot_under_lock(state, vid, offset, size) {
Ok(Some(s)) => s,
Ok(None) => continue, // volume gone since the walk
Err(e) => {
errs.push(format!("needle {} on EC volume {}: {}", id.0, vid.0, e));
continue;
}
};
// Read each interval local-then-remote WITHOUT reconstructing: we verify
// the shards are valid, we do not heal them. Locations refreshed above.
let n_intervals = snapshot.intervals.len();
let mut data: Vec<u8> = Vec::with_capacity(snapshot.actual_size);
for (i, res) in snapshot.intervals.iter().enumerate() {
match res {
IntervalResult::Local(buf) => data.extend_from_slice(buf),
IntervalResult::NeedRemote {
shard_id,
shard_offset,
size: ssize,
} => {
let sources = snapshot
.cached_locations
.get(shard_id)
.cloned()
.unwrap_or_default();
match read_remote_ec_shard_interval(
state,
&sources,
vid,
id,
*shard_id,
*shard_offset,
*ssize,
snapshot.encode_ts_ns,
)
.await
{
Ok(buf) => data.extend_from_slice(&buf),
Err(_) => {
errs.push(format!(
"failed to read EC shard {} for needle {} on volume {} (interval {}/{})",
shard_id, id.0, vid.0, i + 1, n_intervals
));
broken_shards.insert(
*shard_id,
crate::pb::volume_server_pb::EcShardInfo {
shard_id: *shard_id as u32,
size: *ssize as i64,
collection: collection.clone(),
volume_id: vid.0,
..Default::default()
},
);
break;
}
}
}
}
}
// Also fires when a chunk read broke out above (data is short).
if data.len() != snapshot.actual_size {
errs.push(format!(
"expected {} bytes for needle {}, got {}",
snapshot.actual_size,
id.0,
data.len()
));
continue;
}
let mut n = Needle::default();
if let Err(e) = n.read_bytes(&data, 0, snapshot.size_for_parse, snapshot.version) {
// A delete-state disagreement between the index and the reassembled
// header (live index vs zero header size) is not corruption.
let delete_state_disagrees = matches!(
&e,
NeedleError::SizeMismatch { found, .. }
if snapshot.size_for_parse.is_deleted() != (found.0 == 0)
);
if !delete_state_disagrees || force_deleted_needles_check {
errs.push(format!("needle {} on EC volume {}: {}", id.0, vid.0, e));
}
}
}
// Mirror Go CmpEcShardInfo: sort by (volume_id, shard_id).
let mut broken: Vec<crate::pb::volume_server_pb::EcShardInfo> =
broken_shards.into_values().collect();
broken.sort_by(|a, b| a.volume_id.cmp(&b.volume_id).then(a.shard_id.cmp(&b.shard_id)));
(count, broken, errs)
}
fn snapshot_under_lock(
state: &Arc<VolumeServerState>,
vid: VolumeId,
@@ -204,11 +389,44 @@ fn snapshot_under_lock(
// Reuse EcVolume::locate_needle for offset/size resolution AND
// the per-needle shard-interval math — it's the same routine the
// local-only read path uses, so we stay byte-identical on the
// shard-size + interval boundaries.
// shard-size + interval boundaries. locate_needle applies the runtime
// delete mask, which is correct for serving reads.
let (offset, size, intervals) = match ecv.locate_needle(needle_id)? {
Some(v) => v,
None => return Ok(None),
};
build_snapshot(ecv, offset, size, &intervals).map(Some)
}
/// Like `snapshot_under_lock`, but locates intervals from the RAW .ecx
/// (offset, size) the FULL-scrub walk supplies — NOT `locate_needle`, which
/// masks runtime-deleted needles. EC deletes are logical (the shard bytes stay
/// until re-encode), so the scrub must still byte-verify them, matching Go's
/// `Store.ScrubEcVolume` which walks the unmasked index.
fn scrub_snapshot_under_lock(
state: &Arc<VolumeServerState>,
vid: VolumeId,
offset: Offset,
size: Size,
) -> io::Result<Option<Snapshot>> {
let store = state.store.read().unwrap();
let ecv = match store.find_ec_volume(vid) {
Some(v) => v,
None => return Ok(None),
};
let intervals = ecv.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
build_snapshot(ecv, offset, size, &intervals).map(Some)
}
/// Read any locally-held shard intervals and assemble the rest as `NeedRemote`,
/// then snapshot the scalars + shard-location cache so the caller can drop the
/// store lock before awaiting remote reads. Shared by the read and scrub paths.
fn build_snapshot(
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
offset: Offset,
size: Size,
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
) -> io::Result<Snapshot> {
if intervals.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
@@ -217,25 +435,16 @@ fn snapshot_under_lock(
}
let actual = get_actual_size(size, ecv.version);
// Phase A.local: for each interval read the local shard if we
// hold it; otherwise fall through to remote. We accumulate the
// results in interval order so the assembly step is just a
// concat.
let mut interval_results = Vec::with_capacity(intervals.len());
for interval in &intervals {
for interval in intervals {
let (shard_id, shard_offset) = interval.to_shard_id_and_offset(ecv.data_shards);
let buf_size = interval.size as usize;
let local = ecv
.shards
.get(shard_id as usize)
.and_then(|s| s.as_ref());
let local = ecv.shards.get(shard_id as usize).and_then(|s| s.as_ref());
match local {
Some(shard) => {
let mut buf = vec![0u8; buf_size];
match shard.read_at(&mut buf, shard_offset as u64) {
Ok(n) if n == buf_size => {
interval_results.push(IntervalResult::Local(buf));
}
Ok(n) if n == buf_size => interval_results.push(IntervalResult::Local(buf)),
_ => interval_results.push(IntervalResult::NeedRemote {
shard_id,
shard_offset,
@@ -254,7 +463,7 @@ fn snapshot_under_lock(
let cached_locations = ecv.shard_locations.read().unwrap().clone();
let cache_refreshed_at = *ecv.shard_locations_refresh_time.lock().unwrap();
Ok(Some(Snapshot {
Ok(Snapshot {
data_shards: ecv.data_shards,
parity_shards: ecv.parity_shards,
version: ecv.version,
@@ -265,7 +474,7 @@ fn snapshot_under_lock(
cached_locations,
cache_refreshed_at,
encode_ts_ns: ecv.encode_ts_ns,
}))
})
}
/// Master `LookupEcVolume` freshness rules — match Go's
@@ -703,3 +912,227 @@ async fn recover_one_remote_ec_shard_interval(
// parse_grpc_address lives in `grpc_client.rs` and is re-exported
// here via the use above so this module shares a single
// HTTP↔gRPC port-translation routine with grpc_server.rs.
// ---------------------------------------------------------------------------
// Missing-index recovery (issue #10104).
//
// Mirrors weed/server/volume_grpc_erasure_coding_recover.go. EC shards whose
// .ecx index lives only on a peer server cannot be mounted locally, so the
// master never learns about them. recover_missing_ec_indexes fetches the index
// from a peer and mounts the on-disk shards. Driven on demand by
// VolumeEcShardsMount(recover_missing_index), so an operator triggers it through
// ec.rebuild rather than a background loop.
// ---------------------------------------------------------------------------
/// Recover EC volumes whose shards sit on this server while the index lives only
/// on a peer. `filter_vid` 0 recovers every orphan on this server (including
/// volumes the master never registered); otherwise just that volume. Returns the
/// number of volumes whose index was recovered.
pub(crate) async fn recover_missing_ec_indexes(
state: &Arc<VolumeServerState>,
filter_vid: u32,
) -> usize {
let missing: Vec<EcVolumeMissingIndex> = {
let store = state.store.read().unwrap();
store
.collect_ec_volumes_missing_index()
.into_iter()
.filter(|m| filter_vid == 0 || m.vid.0 == filter_vid)
.collect()
};
if missing.is_empty() {
return 0;
}
let self_http = to_http_address(&state.self_url).into_owned();
let mut recovered = 0usize;
for m in &missing {
let peers = match cached_lookup_ec_shard_locations(state, m.vid).await {
Ok(map) => {
let mut peers: Vec<String> = Vec::new();
for addrs in map.values() {
for a in addrs {
if to_http_address(a).as_ref() == self_http.as_str() {
continue;
}
if !peers.contains(a) {
peers.push(a.clone());
}
}
}
peers
}
Err(e) => {
tracing::warn!(
volume_id = m.vid.0,
"cannot look up peers to recover missing .ecx: {}",
e
);
continue;
}
};
if peers.is_empty() {
tracing::warn!(
volume_id = m.vid.0,
"shards present locally but .ecx missing and no peer holds it; leaving shards unloaded"
);
continue;
}
if fetch_ec_index_from_peers(state, m, &peers).await {
recovered += 1;
}
}
if recovered > 0 {
state.store.write().unwrap().mount_recovered_ec_shards();
tracing::info!(
"recovered missing EC index for {} volume(s) from peers and mounted their shards",
recovered
);
}
recovered
}
/// Try each peer in turn, copying the `.ecx` (required) and `.ecj` / `.vif`
/// (best-effort) into m's local dirs. The `.ecx` is an immutable encode-time
/// index, identical on every holder, so any peer's copy serves. The `.ecj` is a
/// per-holder deletion journal that differs across holders; the recovered node
/// adopts the source peer's deletion view, like a balanced or rebuilt shard. The
/// first peer with a non-empty `.ecx` wins.
async fn fetch_ec_index_from_peers(
state: &Arc<VolumeServerState>,
m: &EcVolumeMissingIndex,
peers: &[String],
) -> bool {
let idx_base = volume_file_name(&m.idx_dir, &m.collection, m.vid);
let data_base = volume_file_name(&m.data_dir, &m.collection, m.vid);
let ecx_path = format!("{}.ecx", idx_base);
let ecj_path = format!("{}.ecj", idx_base);
let vif_path = format!("{}.vif", data_base);
for peer in peers {
match fetch_ec_index_from_one_peer(state, m, peer, &ecx_path, &ecj_path, &vif_path).await {
Ok(()) => {
tracing::info!(
volume_id = m.vid.0,
peer = %peer,
"fetched missing .ecx into {}",
m.idx_dir
);
return true;
}
Err(e) => {
// Remove any partial .ecx so a later attempt is not blocked by a stub.
let _ = fs::remove_file(&ecx_path);
tracing::debug!(
volume_id = m.vid.0,
peer = %peer,
"fetch missing .ecx failed: {}",
e
);
}
}
}
false
}
async fn fetch_ec_index_from_one_peer(
state: &Arc<VolumeServerState>,
m: &EcVolumeMissingIndex,
peer: &str,
ecx_path: &str,
ecj_path: &str,
vif_path: &str,
) -> io::Result<()> {
let grpc_addr =
parse_grpc_address(peer).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
let channel = build_grpc_endpoint(&grpc_addr, state.outgoing_grpc_tls.as_ref())
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(30))
.connect()
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("connect {}: {}", peer, e)))?;
let mut client = VolumeServerClient::with_interceptor(channel, outgoing_request_id_interceptor)
.max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE)
.max_encoding_message_size(GRPC_MAX_MESSAGE_SIZE);
let copy_req = |ext: &str, ignore_not_found: bool| CopyFileRequest {
volume_id: m.vid.0,
collection: m.collection.clone(),
is_ec_volume: true,
ext: ext.to_string(),
compaction_revision: u32::MAX,
stop_offset: i64::MAX as u64,
ignore_source_file_not_found: ignore_not_found,
..Default::default()
};
// .ecx is mandatory and written in place (create/truncate); a peer without it
// errors and the caller moves on.
let stream = client
.copy_file(copy_req(".ecx", false))
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("copy .ecx: {}", e)))?
.into_inner();
drain_copy_stream(stream, ecx_path, false).await?;
let meta = fs::metadata(ecx_path)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("stat copied .ecx: {}", e)))?;
if meta.is_dir() || meta.len() == 0 {
let _ = fs::remove_file(ecx_path);
return Err(io::Error::new(
io::ErrorKind::Other,
format!("peer {} served an unusable .ecx (size {})", peer, meta.len()),
));
}
// .ecj is the source peer's deletion journal (appended); .vif carries EC
// params. Both are best-effort: a missing .ecj is recreated at mount and a
// missing .vif falls back to default EC parameters. A failed .ecj append
// leaves a partial file, so drop it.
match client.copy_file(copy_req(".ecj", true)).await {
Ok(resp) => {
if let Err(e) = drain_copy_stream(resp.into_inner(), ecj_path, true).await {
tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .ecj: {}", e);
let _ = fs::remove_file(ecj_path);
}
}
Err(e) => tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .ecj: {}", e),
}
match client.copy_file(copy_req(".vif", true)).await {
Ok(resp) => {
if let Err(e) = drain_copy_stream(resp.into_inner(), vif_path, false).await {
tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .vif: {}", e);
}
}
Err(e) => tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .vif: {}", e),
}
Ok(())
}
/// Drain a CopyFile stream into a local file, appending or truncating.
async fn drain_copy_stream(
mut stream: tonic::Streaming<crate::pb::volume_server_pb::CopyFileResponse>,
dest_path: &str,
append: bool,
) -> io::Result<()> {
use std::io::Write;
let mut file = if append {
fs::OpenOptions::new().create(true).append(true).open(dest_path)
} else {
fs::File::create(dest_path)
}
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("create {}: {}", dest_path, e)))?;
while let Some(chunk) = stream
.message()
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("recv {}: {}", dest_path, e)))?
{
file.write_all(&chunk.file_content)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("write {}: {}", dest_path, e)))?;
}
Ok(())
}
@@ -395,6 +395,12 @@ impl DiskLocation {
for i in 0..MAX_SHARD_COUNT {
rm_if_present(format!("{}.ec{:02}", base, i))?;
}
// Remove the bitrot checksum sidecars from both the data and idx dirs.
remove_bitrot_sidecars(&base)?;
if self.idx_directory != self.directory {
remove_bitrot_sidecars(&idx_base)?;
}
Ok(())
}
@@ -1081,6 +1087,49 @@ 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));
@@ -0,0 +1,838 @@
//! EC bitrot detection — checksum sidecar.
//!
//! A per-volume sidecar file stores a CRC32C (Castagnoli) checksum for every
//! fixed-size block of every EC shard, so a scrub (and the reconstruction path)
//! can detect silent disk corruption in any shard — including cold parity shards
//! that are never read during normal serving.
//!
//! The sidecar is OPTIONAL: an absent or generation-mismatched sidecar simply
//! means "feature off" for that generation, so old binaries, JSON-only nodes,
//! and rollback deployments ignore it and degrade gracefully.
//!
//! On-disk layout of `<base>.ecsum` (legacy/generation 0) and `<base>.ecsum.v<N>`:
//!
//! ```text
//! [ magic(4) | format_version(2) | payload_len(4) | payload_crc32c(4) ] [ proto payload ]
//! ```
//!
//! All header fields are BIG-ENDIAN. The header's `payload_crc32c` lets a loader
//! detect corruption of the sidecar itself BEFORE trusting any contents, so a
//! rotted sidecar can never be mistaken for shard corruption. This format is
//! byte-identical to the Go implementation in
//! `weed/storage/erasure_coding/ec_bitrot.go`.
use std::fs::File;
use std::io::{self, Read, Write};
use prost::Message;
use crate::pb::volume_server_pb::{
ChecksumAlgorithm, EcBitrotProtection, EcShardChecksums, EcShardConfig,
};
use crate::storage::erasure_coding::ec_shard::MAX_SHARD_COUNT;
use crate::storage::needle::crc::CRC;
/// Canonical extension for the checksum sidecar. Generation 0 (legacy/fresh
/// encode) uses `<base>.ecsum`; vacuum generation N uses `<base>.ecsum.v<N>`,
/// mirroring the `.vif`/`.ecx` versioned convention.
pub const BITROT_SIDECAR_EXT: &str = ".ecsum";
/// Default checksum granularity (16 MiB). It is a power-of-two multiple of
/// `ERASURE_CODING_SMALL_BLOCK_SIZE` (1 MiB) and keeps the sidecar tiny
/// (~11 KB for a 30 GB volume) while localizing corruption to a 16 MiB region.
pub const DEFAULT_BITROT_BLOCK_SIZE: usize = 16 * 1024 * 1024;
/// Caps the block granularity so a loaded sidecar cannot force a huge
/// scrub/verify scratch buffer. Power-of-two multiple of 1 MiB.
pub const MAX_BITROT_BLOCK_SIZE: u32 = 64 * 1024 * 1024;
/// Magic "ECSU".
pub const BITROT_MAGIC: u32 = 0x4543_5355;
/// On-disk format version.
pub const BITROT_FORMAT_VERSION: u16 = 1;
/// Header size: magic(4) + version(2) + payload_len(4) + payload_crc32c(4).
pub const BITROT_HEADER_SIZE: usize = 14;
/// Resolved protection state of an EC volume's active generation after loading
/// and validating its sidecar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitrotStatus {
/// No sidecar, or a sidecar that does not describe the active generation.
/// The generation is unprotected; this is NOT corruption.
Off,
/// A complete, well-formed, generation-matching sidecar is loaded.
On,
/// A generation-matching sidecar that is malformed, incomplete, or
/// self-integrity-failed. The generation is unprotected pending repair of
/// the sidecar, and an integrity alarm should fire. The rebuild path treats
/// this as fail-closed.
Invalid,
}
impl std::fmt::Display for BitrotStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
BitrotStatus::On => "on",
BitrotStatus::Invalid => "invalid",
BitrotStatus::Off => "off",
};
f.write_str(s)
}
}
/// Error returned by [`load_bitrot_sidecar`]. A self-integrity failure is a
/// sidecar-integrity problem (the caller maps it to [`BitrotStatus::Invalid`]),
/// never a shard-corruption signal.
#[derive(Debug)]
pub enum BitrotLoadError {
/// File missing or other underlying I/O error.
Io(io::Error),
/// File shorter than the fixed header.
TooShort(usize),
/// Header magic did not match.
BadMagic(u32),
/// Header format version is unsupported.
UnsupportedVersion(u16),
/// Header payload_len disagrees with the actual payload length.
LengthMismatch { header: u32, actual: usize },
/// Header payload_crc32c disagrees with the computed CRC32C of the payload.
CrcMismatch { header: u32, computed: u32 },
/// Protobuf payload failed to decode.
Decode(prost::DecodeError),
}
impl std::fmt::Display for BitrotLoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BitrotLoadError::Io(e) => write!(f, "bitrot sidecar io error: {}", e),
BitrotLoadError::TooShort(n) => {
write!(f, "bitrot sidecar too short ({} bytes)", n)
}
BitrotLoadError::BadMagic(m) => write!(f, "bitrot sidecar bad magic {:#x}", m),
BitrotLoadError::UnsupportedVersion(v) => {
write!(f, "bitrot sidecar unsupported format version {}", v)
}
BitrotLoadError::LengthMismatch { header, actual } => write!(
f,
"bitrot sidecar length mismatch: header {}, actual {}",
header, actual
),
BitrotLoadError::CrcMismatch { header, computed } => write!(
f,
"bitrot sidecar self-integrity CRC mismatch: header {:#x}, computed {:#x}",
header, computed
),
BitrotLoadError::Decode(e) => write!(f, "unmarshal bitrot sidecar: {}", e),
}
}
}
impl std::error::Error for BitrotLoadError {}
impl From<io::Error> for BitrotLoadError {
fn from(e: io::Error) -> Self {
BitrotLoadError::Io(e)
}
}
/// Returns the sidecar path for a base file name and EC generation. Generation
/// 0 is the un-suffixed legacy path; generation N>0 is the versioned path,
/// consistent with how `.vif`/`.ecx` are versioned by the 2PC switch.
pub fn bitrot_sidecar_path(base: &str, generation: u32) -> String {
if generation == 0 {
format!("{}{}", base, BITROT_SIDECAR_EXT)
} else {
format!("{}{}.v{}", base, BITROT_SIDECAR_EXT, generation)
}
}
/// 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> {
use rand::RngCore;
let mut b = vec![0u8; 16];
rand::thread_rng().fill_bytes(&mut b);
b
}
/// Reports whether `block_size` is a power of two in [1 MiB, MAX_BITROT_BLOCK_SIZE].
pub fn is_pow2_multiple_of_1mib(block_size: u32) -> bool {
block_size >= (1 << 20) && block_size <= MAX_BITROT_BLOCK_SIZE && block_size.count_ones() == 1
}
/// Returns ceil(covered_size / block_size).
fn expected_block_count(covered_size: i64, block_size: i64) -> usize {
if block_size <= 0 {
return 0;
}
((covered_size + block_size - 1) / block_size) as usize
}
/// Packs a slice of u32 into little-endian bytes.
fn pack_u32_le(vals: &[u32]) -> Vec<u8> {
let mut out = Vec::with_capacity(vals.len() * 4);
for v in vals {
out.extend_from_slice(&v.to_le_bytes());
}
out
}
/// Unpacks little-endian bytes into a Vec<u32>. Trailing bytes (len % 4) are
/// ignored, matching the Go implementation's `len(b)/4` truncation.
fn unpack_u32_le(b: &[u8]) -> Vec<u32> {
let n = b.len() / 4;
let mut out = Vec::with_capacity(n);
for i in 0..n {
out.push(u32::from_le_bytes([
b[i * 4],
b[i * 4 + 1],
b[i * 4 + 2],
b[i * 4 + 3],
]));
}
out
}
/// Accumulates the per-block CRC32C of a single shard's byte stream as it is
/// written. Tolerates arbitrary chunk sizes that cross block boundaries, so it
/// works for both small encode buffers and the larger rebuild buffers.
pub struct ShardChecksumBuilder {
block_size: i64,
cur: CRC,
cur_len: i64,
total: i64,
blocks: Vec<u32>,
}
impl ShardChecksumBuilder {
/// Creates a builder over a given block size in bytes.
pub fn new(block_size: i64) -> Self {
ShardChecksumBuilder {
block_size,
cur: CRC(0),
cur_len: 0,
total: 0,
blocks: Vec::new(),
}
}
/// Feeds a chunk of arbitrary size, splitting it across block boundaries.
pub fn write(&mut self, mut p: &[u8]) {
while !p.is_empty() {
let room = self.block_size - self.cur_len;
let n = (p.len() as i64).min(room) as usize;
self.cur = self.cur.update(&p[..n]);
self.cur_len += n as i64;
self.total += n as i64;
p = &p[n..];
if self.cur_len == self.block_size {
self.blocks.push(self.cur.0);
self.cur = CRC(0);
self.cur_len = 0;
}
}
}
/// Flushes any partial last block and returns the covered size and the
/// packed little-endian u32 CRC array.
pub fn finalize(mut self) -> (i64, Vec<u8>) {
if self.cur_len > 0 {
self.blocks.push(self.cur.0);
self.cur = CRC(0);
self.cur_len = 0;
}
(self.total, pack_u32_le(&self.blocks))
}
}
/// Atomically writes `prot` to `path`, wrapped in the on-disk header with a
/// CRC32C over the serialized payload (temp file + rename).
pub fn save_bitrot_sidecar(path: &str, prot: &EcBitrotProtection) -> io::Result<()> {
let payload = prot.encode_to_vec();
// The header records payload_len as a uint32 and the allocation below adds it
// to a constant. Bound the payload well under any overflow (a real manifest is
// a few KB) so neither the length field nor the buffer can wrap. Mirrors Go's
// SaveBitrotSidecar maxBitrotPayloadSize check.
const MAX_BITROT_PAYLOAD_SIZE: usize = 1 << 30; // 1 GiB, vastly above any real sidecar
if payload.len() > MAX_BITROT_PAYLOAD_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("bitrot sidecar payload too large: {} bytes", payload.len()),
));
}
let mut buf = Vec::with_capacity(BITROT_HEADER_SIZE + payload.len());
buf.extend_from_slice(&BITROT_MAGIC.to_be_bytes());
buf.extend_from_slice(&BITROT_FORMAT_VERSION.to_be_bytes());
buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
buf.extend_from_slice(&CRC::new(&payload).0.to_be_bytes());
buf.extend_from_slice(&payload);
let tmp = format!("{}.tmp", path);
{
let mut f = File::create(&tmp)?;
f.write_all(&buf)?;
f.sync_all()?;
}
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// Reads and self-integrity-checks a sidecar file. Returns the parsed message,
/// or an error if the file is missing, truncated, has a bad magic/version, or
/// fails the payload CRC. A self-integrity failure is a sidecar-integrity
/// problem (caller maps it to [`BitrotStatus::Invalid`]), never a shard
/// corruption signal.
pub fn load_bitrot_sidecar(path: &str) -> Result<EcBitrotProtection, BitrotLoadError> {
let mut data = Vec::new();
File::open(path)?.read_to_end(&mut data)?;
if data.len() < BITROT_HEADER_SIZE {
return Err(BitrotLoadError::TooShort(data.len()));
}
let magic = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
if magic != BITROT_MAGIC {
return Err(BitrotLoadError::BadMagic(magic));
}
let ver = u16::from_be_bytes([data[4], data[5]]);
if ver != BITROT_FORMAT_VERSION {
return Err(BitrotLoadError::UnsupportedVersion(ver));
}
let payload_len = u32::from_be_bytes([data[6], data[7], data[8], data[9]]);
let want_crc = u32::from_be_bytes([data[10], data[11], data[12], data[13]]);
let payload = &data[BITROT_HEADER_SIZE..];
if payload_len as usize != payload.len() {
return Err(BitrotLoadError::LengthMismatch {
header: payload_len,
actual: payload.len(),
});
}
let got = CRC::new(payload).0;
if got != want_crc {
return Err(BitrotLoadError::CrcMismatch {
header: want_crc,
computed: got,
});
}
EcBitrotProtection::decode(payload).map_err(BitrotLoadError::Decode)
}
/// Performs the disk-free manifest/syntax checks that every loader runs:
/// supported algorithm, valid block size, exactly one entry per shard id in the
/// active layout (no duplicates, no out-of-range ids), positive covered_size,
/// and a packed-CRC count consistent with covered_size.
///
/// It does NOT compare covered_size against on-disk shard lengths — that is a
/// per-node physical check done only for locally-held shards.
pub fn validate_manifest(
prot: &EcBitrotProtection,
data_shards: usize,
parity_shards: usize,
) -> Result<(), String> {
if prot.algorithm != ChecksumAlgorithm::ChecksumCrc32c as i32 {
return Err(format!("unsupported checksum algorithm {}", prot.algorithm));
}
if !is_pow2_multiple_of_1mib(prot.block_size) {
return Err(format!(
"invalid block_size {} (must be a power-of-two multiple of 1 MiB, at most {})",
prot.block_size, MAX_BITROT_BLOCK_SIZE
));
}
let bs = prot.block_size as i64;
let total = data_shards + parity_shards;
if total == 0 || total > MAX_SHARD_COUNT {
return Err(format!(
"invalid active layout: data={} parity={}",
data_shards, parity_shards
));
}
if prot.shards.len() != total {
return Err(format!(
"incomplete manifest: {} shard entries, expected {}",
prot.shards.len(),
total
));
}
let mut seen = vec![false; MAX_SHARD_COUNT];
for s in &prot.shards {
if s.shard_id >= total as u32 {
return Err(format!(
"shard id {} out of range [0,{})",
s.shard_id, total
));
}
if seen[s.shard_id as usize] {
return Err(format!("duplicate shard id {}", s.shard_id));
}
seen[s.shard_id as usize] = true;
if s.covered_size <= 0 {
return Err(format!(
"shard {} has non-positive covered_size {}",
s.shard_id, s.covered_size
));
}
let want_count = expected_block_count(s.covered_size, bs);
if s.block_crc32c.len() != want_count * 4 {
return Err(format!(
"shard {} crc count mismatch: {} bytes, expected {} (covered_size={} block_size={})",
s.shard_id,
s.block_crc32c.len(),
want_count * 4,
s.covered_size,
prot.block_size
));
}
}
Ok(())
}
/// Resolves the protection status of a loaded-or-missing sidecar against the
/// active generation and layout. `loaded` is the result of attempting to load
/// the sidecar at the active generation's path.
///
/// - missing sidecar (NotFound) => [`BitrotStatus::Off`]
/// - load/self-integrity failure => [`BitrotStatus::Invalid`]
/// - generation mismatch => [`BitrotStatus::Off`]
/// - manifest validation failure => [`BitrotStatus::Invalid`]
/// - otherwise => [`BitrotStatus::On`]
pub fn resolve_status(
loaded: &Result<EcBitrotProtection, BitrotLoadError>,
active_generation: u32,
data_shards: usize,
parity_shards: usize,
) -> BitrotStatus {
match loaded {
Err(BitrotLoadError::Io(e)) if e.kind() == io::ErrorKind::NotFound => BitrotStatus::Off,
Err(_) => BitrotStatus::Invalid,
Ok(prot) => {
if prot.generation != active_generation {
return BitrotStatus::Off;
}
if validate_manifest(prot, data_shards, parity_shards).is_err() {
return BitrotStatus::Invalid;
}
BitrotStatus::On
}
}
}
/// Returns the [`EcShardChecksums`] entry for a shard id, or `None`.
pub fn shard_checksums(prot: &EcBitrotProtection, shard_id: u32) -> Option<&EcShardChecksums> {
prot.shards.iter().find(|s| s.shard_id == shard_id)
}
/// Reads a shard file at `path` in `block_size` chunks and compares each block's
/// CRC32C against the manifest entry. Returns the list of mismatching block
/// indices (empty == clean), or a fatal `io::Error` for genuine I/O problems.
///
/// A length mismatch (truncation or unexpected trailing bytes) is itself shard
/// corruption: every block index is reported as mismatched so the caller treats
/// the shard as bad. It does not interpret the result — the caller (scrub /
/// rebuild) arbitrates shard-vs-sidecar via Reed-Solomon before acting.
pub fn verify_shard_file_blocks(
path: &str,
entry: &EcShardChecksums,
block_size: i64,
) -> io::Result<Vec<usize>> {
let f = File::open(path)?;
let file_size = f.metadata()?.len() as i64;
let want = unpack_u32_le(&entry.block_crc32c);
if file_size != entry.covered_size {
// Length drift is shard corruption: report every block as mismatched.
return Ok((0..want.len()).collect());
}
let mut mismatched = Vec::new();
let mut buf = vec![0u8; block_size.max(1) as usize];
let mut offset: i64 = 0;
for (i, want_crc) in want.iter().enumerate() {
let to_read = (entry.covered_size - offset).min(block_size);
if to_read <= 0 {
break;
}
let to_read = to_read as usize;
read_full_at(&f, &mut buf[..to_read], offset as u64)?;
if CRC::new(&buf[..to_read]).0 != *want_crc {
mismatched.push(i);
}
offset += to_read as i64;
}
Ok(mismatched)
}
/// Reads exactly `buf.len()` bytes from `f` at `offset`, erroring on early EOF.
fn read_full_at(f: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
let mut total = 0usize;
while total < buf.len() {
#[cfg(unix)]
let n = {
use std::os::unix::fs::FileExt;
f.read_at(&mut buf[total..], offset + total as u64)?
};
#[cfg(not(unix))]
let n = {
use std::io::{Read, Seek, SeekFrom};
let mut fc = f.try_clone()?;
fc.seek(SeekFrom::Start(offset + total as u64))?;
fc.read(&mut buf[total..])?
};
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"short read on shard block",
));
}
total += n;
}
Ok(())
}
/// Builds the `EcShardConfig` proto for the given layout. The bitrot sidecar
/// carries its own top-level encode_uuid, so the nested config leaves it empty.
pub fn ec_shard_config(data_shards: u32, parity_shards: u32) -> EcShardConfig {
EcShardConfig {
data_shards,
parity_shards,
encode_ts_ns: 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Cross-binary byte-exact proof: CANONICAL_HEX equals `canonicalInteropHex`
/// in weed/storage/erasure_coding/ec_bitrot_interop_test.go (the Go reference
/// asserts the same constant). Both binaries port the same format, so a
/// sidecar written by either must be byte-identical; this pins the Rust side
/// of that guarantee. If you change the format, regenerate and update BOTH.
#[test]
fn test_byte_exact_go_interop() {
const CANONICAL_HEX: &str = "45435355000100000039cc1b826a080110808080082204080a10042a0a108080401a04040302012a0c0801108080401a04080706053210000102030405060708090a0b0c0d0e0f";
let prot = EcBitrotProtection {
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
generation: 0,
ec_shard_config: Some(EcShardConfig {
data_shards: 10,
parity_shards: 4,
encode_ts_ns: 0,
}),
shards: vec![
EcShardChecksums {
shard_id: 0,
covered_size: 1024 * 1024,
block_crc32c: pack_u32_le(&[0x0102_0304]),
},
EcShardChecksums {
shard_id: 1,
covered_size: 1024 * 1024,
block_crc32c: pack_u32_le(&[0x0506_0708]),
},
],
encode_uuid: (0..16u8).collect(),
};
let dir = std::env::temp_dir().join(format!("ecsum_interop_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("v1.ecsum");
let path = path.to_str().unwrap();
save_bitrot_sidecar(path, &prot).unwrap();
let bytes = std::fs::read(path).unwrap();
let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
assert_eq!(hex, CANONICAL_HEX, "Rust .ecsum bytes drifted from the Go canonical form");
let _ = std::fs::remove_file(path);
}
#[test]
fn test_sidecar_path_generations() {
assert_eq!(bitrot_sidecar_path("/d/1", 0), "/d/1.ecsum");
assert_eq!(bitrot_sidecar_path("/d/1", 3), "/d/1.ecsum.v3");
}
#[test]
fn test_is_pow2_multiple_of_1mib() {
assert!(is_pow2_multiple_of_1mib(1 << 20)); // 1 MiB
assert!(is_pow2_multiple_of_1mib(16 * 1024 * 1024)); // 16 MiB default
assert!(is_pow2_multiple_of_1mib(1 << 25));
assert!(is_pow2_multiple_of_1mib(MAX_BITROT_BLOCK_SIZE)); // 64 MiB boundary
assert!(!is_pow2_multiple_of_1mib(0));
assert!(!is_pow2_multiple_of_1mib(1 << 19)); // 512 KiB, too small
assert!(!is_pow2_multiple_of_1mib(3 << 20)); // 3 MiB, not pow2
assert!(!is_pow2_multiple_of_1mib(128 * 1024 * 1024)); // pow2 but > MAX_BITROT_BLOCK_SIZE
assert!(!is_pow2_multiple_of_1mib(DEFAULT_BITROT_BLOCK_SIZE as u32 + 1));
}
#[test]
fn test_expected_block_count() {
assert_eq!(expected_block_count(0, 16), 0);
assert_eq!(expected_block_count(1, 16), 1);
assert_eq!(expected_block_count(16, 16), 1);
assert_eq!(expected_block_count(17, 16), 2);
assert_eq!(expected_block_count(32, 16), 2);
assert_eq!(expected_block_count(100, 0), 0);
}
#[test]
fn test_pack_unpack_roundtrip() {
let vals = vec![0x0102_0304u32, 0xdead_beef, 0, u32::MAX];
let packed = pack_u32_le(&vals);
assert_eq!(packed.len(), 16);
// Verify little-endian byte order of the first entry.
assert_eq!(&packed[0..4], &[0x04, 0x03, 0x02, 0x01]);
assert_eq!(unpack_u32_le(&packed), vals);
}
#[test]
fn test_builder_block_boundaries() {
// block_size = 4; feed 10 bytes in chunks that cross boundaries.
let mut b = ShardChecksumBuilder::new(4);
let data = b"0123456789";
b.write(&data[0..3]); // partial block 0
b.write(&data[3..7]); // completes block 0 (idx 3), fills block 1
b.write(&data[7..10]); // partial block 2
let (covered, packed) = b.finalize();
assert_eq!(covered, 10);
let crcs = unpack_u32_le(&packed);
// ceil(10/4) = 3 blocks
assert_eq!(crcs.len(), 3);
// Compare against direct per-block CRCs.
assert_eq!(crcs[0], CRC::new(&data[0..4]).0);
assert_eq!(crcs[1], CRC::new(&data[4..8]).0);
assert_eq!(crcs[2], CRC::new(&data[8..10]).0);
}
#[test]
fn test_builder_exact_block_multiple() {
let mut b = ShardChecksumBuilder::new(4);
b.write(b"01234567"); // exactly 2 blocks, no partial
let (covered, packed) = b.finalize();
assert_eq!(covered, 8);
assert_eq!(unpack_u32_le(&packed).len(), 2);
}
#[test]
fn test_save_load_roundtrip() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp
.path()
.join("vol.ecsum")
.to_str()
.unwrap()
.to_string();
let mut builder = ShardChecksumBuilder::new(DEFAULT_BITROT_BLOCK_SIZE as i64);
builder.write(b"hello world");
let (covered, packed) = builder.finalize();
let prot = EcBitrotProtection {
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
generation: 0,
ec_shard_config: Some(ec_shard_config(10, 4)),
shards: vec![EcShardChecksums {
shard_id: 0,
covered_size: covered,
block_crc32c: packed,
}],
encode_uuid: new_encode_uuid(),
};
save_bitrot_sidecar(&path, &prot).unwrap();
let loaded = load_bitrot_sidecar(&path).unwrap();
assert_eq!(loaded, prot);
}
#[test]
fn test_load_rejects_bad_magic() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("bad.ecsum").to_str().unwrap().to_string();
std::fs::write(&path, vec![0u8; BITROT_HEADER_SIZE + 4]).unwrap();
match load_bitrot_sidecar(&path) {
Err(BitrotLoadError::BadMagic(_)) => {}
other => panic!("expected BadMagic, got {:?}", other),
}
}
#[test]
fn test_load_rejects_corrupted_payload() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp
.path()
.join("corrupt.ecsum")
.to_str()
.unwrap()
.to_string();
let prot = EcBitrotProtection {
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
generation: 0,
ec_shard_config: Some(ec_shard_config(10, 4)),
shards: vec![EcShardChecksums {
shard_id: 0,
covered_size: 5,
block_crc32c: pack_u32_le(&[CRC::new(b"hello").0]),
}],
encode_uuid: vec![0u8; 16],
};
save_bitrot_sidecar(&path, &prot).unwrap();
// Flip a byte in the payload (after the 14-byte header).
let mut data = std::fs::read(&path).unwrap();
let last = data.len() - 1;
data[last] ^= 0xff;
std::fs::write(&path, &data).unwrap();
match load_bitrot_sidecar(&path) {
Err(BitrotLoadError::CrcMismatch { .. }) => {}
other => panic!("expected CrcMismatch, got {:?}", other),
}
}
#[test]
fn test_load_missing_is_notfound() {
let res = load_bitrot_sidecar("/nonexistent/path/x.ecsum");
match res {
Err(BitrotLoadError::Io(e)) => assert_eq!(e.kind(), io::ErrorKind::NotFound),
other => panic!("expected Io(NotFound), got {:?}", other),
}
}
fn good_manifest() -> EcBitrotProtection {
let mut shards = Vec::new();
for id in 0..14u32 {
shards.push(EcShardChecksums {
shard_id: id,
covered_size: 5,
block_crc32c: pack_u32_le(&[CRC::new(b"hello").0]),
});
}
EcBitrotProtection {
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
generation: 0,
ec_shard_config: Some(ec_shard_config(10, 4)),
shards,
encode_uuid: vec![0u8; 16],
}
}
#[test]
fn test_validate_manifest_ok() {
assert!(validate_manifest(&good_manifest(), 10, 4).is_ok());
}
#[test]
fn test_validate_rejects_wrong_algorithm() {
let mut m = good_manifest();
m.algorithm = ChecksumAlgorithm::ChecksumNone as i32;
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_validate_rejects_bad_block_size() {
let mut m = good_manifest();
m.block_size = 3 << 20;
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_validate_rejects_incomplete() {
let mut m = good_manifest();
m.shards.pop();
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_validate_rejects_duplicate_shard_id() {
let mut m = good_manifest();
m.shards[1].shard_id = 0;
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_validate_rejects_out_of_range_id() {
let mut m = good_manifest();
m.shards[13].shard_id = 14;
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_validate_rejects_nonpositive_covered_size() {
let mut m = good_manifest();
m.shards[0].covered_size = 0;
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_validate_rejects_crc_count_mismatch() {
let mut m = good_manifest();
m.shards[0].block_crc32c = vec![0u8; 8]; // 2 entries but covered_size=5 => want 1
assert!(validate_manifest(&m, 10, 4).is_err());
}
#[test]
fn test_resolve_status() {
// Missing => Off.
let notfound: Result<EcBitrotProtection, BitrotLoadError> = Err(BitrotLoadError::Io(
io::Error::new(io::ErrorKind::NotFound, "x"),
));
assert_eq!(resolve_status(&notfound, 0, 10, 4), BitrotStatus::Off);
// Integrity failure => Invalid.
let bad: Result<EcBitrotProtection, BitrotLoadError> =
Err(BitrotLoadError::BadMagic(0));
assert_eq!(resolve_status(&bad, 0, 10, 4), BitrotStatus::Invalid);
// Generation mismatch => Off.
let mut m = good_manifest();
m.generation = 7;
let ok: Result<EcBitrotProtection, BitrotLoadError> = Ok(m);
assert_eq!(resolve_status(&ok, 0, 10, 4), BitrotStatus::Off);
// Matching + valid => On.
let ok2: Result<EcBitrotProtection, BitrotLoadError> = Ok(good_manifest());
assert_eq!(resolve_status(&ok2, 0, 10, 4), BitrotStatus::On);
// Matching generation but invalid manifest => Invalid.
let mut bad_m = good_manifest();
bad_m.shards.pop();
let ok3: Result<EcBitrotProtection, BitrotLoadError> = Ok(bad_m);
assert_eq!(resolve_status(&ok3, 0, 10, 4), BitrotStatus::Invalid);
}
#[test]
fn test_verify_shard_file_blocks() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("s.ec00").to_str().unwrap().to_string();
let block_size: i64 = 4;
let data = b"0123456789"; // 10 bytes, 3 blocks
std::fs::write(&path, data).unwrap();
let mut b = ShardChecksumBuilder::new(block_size);
b.write(data);
let (covered, packed) = b.finalize();
let entry = EcShardChecksums {
shard_id: 0,
covered_size: covered,
block_crc32c: packed,
};
// Clean file => no mismatches.
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
assert!(mm.is_empty());
// Corrupt block index 1 (bytes 4..8).
let mut corrupt = data.to_vec();
corrupt[5] ^= 0xff;
std::fs::write(&path, &corrupt).unwrap();
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
assert_eq!(mm, vec![1]);
// Truncation => all blocks mismatched.
std::fs::write(&path, b"012").unwrap();
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
assert_eq!(mm, vec![0, 1, 2]);
}
}
@@ -10,6 +10,12 @@ use std::io::{Read, Seek, SeekFrom};
use reed_solomon_erasure::galois_8::ReedSolomon;
use crate::pb::volume_server_pb::{
ChecksumAlgorithm, EcBitrotProtection, EcShardChecksums,
};
use crate::storage::erasure_coding::ec_bitrot::{
self, ShardChecksumBuilder, DEFAULT_BITROT_BLOCK_SIZE,
};
use crate::storage::erasure_coding::ec_shard::*;
use crate::storage::idx;
use crate::storage::types::*;
@@ -52,12 +58,21 @@ pub fn write_ec_files(
shard.create()?;
}
// Per-shard bitrot checksum builders: accumulate a CRC32C for every
// DEFAULT_BITROT_BLOCK_SIZE block of each shard's byte stream as it is
// written, so the resulting `.ecsum` sidecar can later detect silent
// corruption in any shard (including cold parity).
let mut builders: Vec<ShardChecksumBuilder> = (0..total_shards)
.map(|_| ShardChecksumBuilder::new(DEFAULT_BITROT_BLOCK_SIZE as i64))
.collect();
// Encode in large blocks, then small blocks
encode_dat_file(
&dat_file,
dat_size,
&rs,
&mut shards,
&mut builders,
data_shards,
parity_shards,
)?;
@@ -67,12 +82,52 @@ pub fn write_ec_files(
shard.close();
}
// Write the generation-0 bitrot sidecar (`<base>.ecsum`). Finalizing each
// builder yields covered_size (== total bytes written to that shard) and
// the packed little-endian CRC32C array.
let mut shard_checksums: Vec<EcShardChecksums> = Vec::with_capacity(total_shards);
for (i, builder) in builders.into_iter().enumerate() {
let (covered_size, packed) = builder.finalize();
shard_checksums.push(EcShardChecksums {
shard_id: i as u32,
covered_size,
block_crc32c: packed,
});
}
let prot = EcBitrotProtection {
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
generation: 0,
ec_shard_config: Some(ec_bitrot::ec_shard_config(
data_shards as u32,
parity_shards as u32,
)),
shards: shard_checksums,
encode_uuid: ec_bitrot::new_encode_uuid(),
};
let sidecar_path = ec_bitrot::bitrot_sidecar_path(&base, 0);
if let Err(e) = ec_bitrot::save_bitrot_sidecar(&sidecar_path, &prot) {
// A failed sidecar must not fail the encode — the shards are already
// written and valid. The volume simply runs with bitrot protection
// off for this generation until the sidecar is regenerated.
tracing::warn!(
volume_id = volume_id.0,
path = %sidecar_path,
error = %e,
"ec encode: failed to write bitrot sidecar; protection off for this generation",
);
}
Ok(())
}
/// Rebuild missing EC shard files from existing shards using Reed-Solomon reconstruct.
///
/// This does not require the `.dat` file, only the existing `.ecXX` shard files.
///
/// `additional_dirs` lists sibling disk locations to search for existing shards when
/// they are not found in `dir`. This is required on multi-disk volume servers where
/// shards for the same volume may be spread across disks.
pub fn rebuild_ec_files(
dir: &str,
collection: &str,
@@ -80,6 +135,7 @@ pub fn rebuild_ec_files(
missing_shard_ids: &[u32],
data_shards: usize,
parity_shards: usize,
additional_dirs: &[&str],
) -> io::Result<()> {
if missing_shard_ids.is_empty() {
return Ok(());
@@ -93,7 +149,9 @@ pub fn rebuild_ec_files(
.map(|i| EcVolumeShard::new(dir, collection, volume_id, i))
.collect();
// Determine the exact shard size from the first available existing shard
// Determine the exact shard size from the first available existing shard.
// When a shard is not found in `dir`, search `additional_dirs` (sibling disks
// on the same volume server) before failing — mirrors Go's findShardFile logic.
let mut shard_size = 0;
for (i, shard) in shards.iter_mut().enumerate() {
if !missing_shard_ids.contains(&(i as u32)) {
@@ -103,10 +161,26 @@ pub fn rebuild_ec_files(
shard_size = size;
}
} else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("missing non-rebuild shard {}", i),
));
// Try sibling disk locations before giving up.
let mut found = false;
for &other_dir in additional_dirs {
let mut alt = EcVolumeShard::new(other_dir, collection, volume_id, i as u8);
if let Ok(_) = alt.open() {
let size = alt.file_size();
if size > shard_size {
shard_size = size;
}
*shard = alt;
found = true;
break;
}
}
if !found {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("missing non-rebuild shard {}", i),
));
}
}
}
}
@@ -185,6 +259,12 @@ pub fn rebuild_ec_files(
}
/// Verify EC shards by computing parity against the existing data and identifying corrupted shards.
///
/// No longer wired to a scrub mode: FULL is now Go's per-needle local+remote walk
/// (`store_ec::scrub_ec_volume_distributed`). Retained as a standalone Reed-Solomon
/// parity check — the only parity/cold-region verification available until the
/// `.ecsum` bitrot CHECKSUM path lands.
#[allow(dead_code)]
pub fn verify_ec_shards(
dir: &str,
collection: &str,
@@ -331,11 +411,16 @@ fn write_sorted_ecx_from_idx(idx_path: &str, ecx_path: &str) -> io::Result<()> {
/// content from the EC data shards, walks through needle headers to extract
/// (needle_id, offset, size) entries, deduplicates them, and writes a sorted
/// .ecx index file.
///
/// `additional_dirs` lists sibling disk locations to search for data shards when
/// they are not found in `dir` — mirrors the same fallback used by rebuild_ec_files,
/// required on multi-disk volume servers where shards may be spread across disks.
pub fn rebuild_ecx_file(
dir: &str,
collection: &str,
volume_id: VolumeId,
data_shards: usize,
additional_dirs: &[&str],
) -> io::Result<()> {
use crate::storage::needle::needle::get_actual_size;
use crate::storage::super_block::SUPER_BLOCK_SIZE;
@@ -343,21 +428,34 @@ pub fn rebuild_ecx_file(
let base = volume_file_name(dir, collection, volume_id);
let ecx_path = format!("{}.ecx", base);
// Open data shards to read logical .dat content
// Open data shards to read logical .dat content. When a shard isn't found
// in `dir`, search `additional_dirs` (sibling disks on the same volume
// server) before giving up.
let mut shards: Vec<EcVolumeShard> = (0..data_shards as u8)
.map(|i| EcVolumeShard::new(dir, collection, volume_id, i))
.collect();
for shard in &mut shards {
for (i, shard) in shards.iter_mut().enumerate() {
if let Err(_) = shard.open() {
// If a data shard is missing, we can't rebuild ecx
for s in &mut shards {
s.close();
let mut found = false;
for &other_dir in additional_dirs {
let mut alt = EcVolumeShard::new(other_dir, collection, volume_id, i as u8);
if alt.open().is_ok() {
*shard = alt;
found = true;
break;
}
}
if !found {
// If a data shard is missing, we can't rebuild ecx
for s in &mut shards {
s.close();
}
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("cannot open data shard for ecx rebuild"),
));
}
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("cannot open data shard for ecx rebuild"),
));
}
}
@@ -490,6 +588,7 @@ fn encode_dat_file(
dat_size: i64,
rs: &ReedSolomon,
shards: &mut [EcVolumeShard],
builders: &mut [ShardChecksumBuilder],
data_shards: usize,
parity_shards: usize,
) -> io::Result<()> {
@@ -507,6 +606,7 @@ fn encode_dat_file(
large_block_size,
rs,
shards,
builders,
data_shards,
parity_shards,
)?;
@@ -526,6 +626,7 @@ fn encode_dat_file(
small_block_size,
rs,
shards,
builders,
data_shards,
parity_shards,
)?;
@@ -543,6 +644,7 @@ fn encode_one_batch(
block_size: usize,
rs: &ReedSolomon,
shards: &mut [EcVolumeShard],
builders: &mut [ShardChecksumBuilder],
data_shards: usize,
parity_shards: usize,
) -> io::Result<()> {
@@ -596,9 +698,11 @@ fn encode_one_batch(
)
})?;
// Write all shard buffers to files
// Write all shard buffers to files and feed the same bytes to each
// shard's bitrot checksum builder, keeping covered_size == on-disk length.
for (i, buf) in buffers.iter().enumerate() {
shards[i].write_all(buf)?;
builders[i].write(buf);
}
Ok(())
@@ -666,6 +770,84 @@ mod tests {
assert!(std::path::Path::new(&ecx_path).exists());
}
fn make_volume_with_needles(n: u64) -> TempDir {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = Volume::new(
dir,
dir,
"",
VolumeId(1),
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap();
for i in 1..=n {
// Larger payloads so encoded shards span multiple bitrot blocks
// would require huge data; small payloads are fine for correctness.
let data = format!("test data for needle {} {}", i, "x".repeat(64));
let mut needle = 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 needle, true).unwrap();
}
v.sync_to_disk().unwrap();
v.close();
tmp
}
/// Encode-time capture writes a valid generation-0 `.ecsum` sidecar whose
/// recorded checksums match the actual on-disk shards.
#[test]
fn test_encode_writes_valid_bitrot_sidecar() {
use crate::storage::erasure_coding::ec_bitrot;
let tmp = make_volume_with_needles(5);
let dir = tmp.path().to_str().unwrap();
write_ec_files(dir, dir, "", VolumeId(1), 10, 4).unwrap();
let base = format!("{}/1", dir);
let sidecar_path = ec_bitrot::bitrot_sidecar_path(&base, 0);
assert!(
std::path::Path::new(&sidecar_path).exists(),
"generation-0 .ecsum sidecar should exist after encode"
);
let prot = ec_bitrot::load_bitrot_sidecar(&sidecar_path).unwrap();
ec_bitrot::validate_manifest(&prot, 10, 4).unwrap();
assert_eq!(prot.generation, 0);
assert_eq!(prot.shards.len(), 14);
assert_eq!(prot.encode_uuid.len(), 16);
assert_eq!(prot.block_size, ec_bitrot::DEFAULT_BITROT_BLOCK_SIZE as u32);
// Every shard's recorded covered_size must equal its on-disk length and
// its block CRCs must verify clean.
let bs = prot.block_size as i64;
for entry in &prot.shards {
let path = format!("{}.ec{:02}", base, entry.shard_id);
let on_disk = std::fs::metadata(&path).unwrap().len() as i64;
assert_eq!(
entry.covered_size, on_disk,
"covered_size must equal on-disk length for shard {}",
entry.shard_id
);
let mm = ec_bitrot::verify_shard_file_blocks(&path, entry, bs).unwrap();
assert!(
mm.is_empty(),
"shard {} should verify clean, got mismatches {:?}",
entry.shard_id,
mm
);
}
}
// encode_sample_volume writes a small volume and EC-encodes it, returning
// the dir path so a test can drop/truncate shards and rebuild.
fn encode_sample_volume(tmp: &TempDir) -> String {
@@ -717,7 +899,7 @@ mod tests {
// Rebuild a different (genuinely missing) shard.
std::fs::remove_file(format!("{}/1.ec07", dir)).unwrap();
let res = rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4);
let res = rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4, &[]);
assert!(res.is_err(), "truncated input shard must abort the rebuild");
}
@@ -730,7 +912,7 @@ mod tests {
let dropped = format!("{}/1.ec07", dir);
std::fs::remove_file(&dropped).unwrap();
rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4).unwrap();
rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4, &[]).unwrap();
assert!(
std::path::Path::new(&dropped).exists(),
"rebuilt shard .ec07 should exist"
@@ -741,6 +923,124 @@ mod tests {
);
}
// Multi-disk rebuild: shards for the same volume are split across two
// directories (simulating a volume server with two disk locations). The
// shard to rebuild is in the primary dir; some of the input shards needed
// for RS reconstruction exist only in the secondary dir. Passing the
// secondary dir via `additional_dirs` must allow the rebuild to succeed
// where it would previously return "missing non-rebuild shard N".
#[test]
fn test_rebuild_ec_files_multi_disk() {
let tmp_primary = TempDir::new().unwrap();
let tmp_secondary = TempDir::new().unwrap();
let primary = tmp_primary.path().to_str().unwrap().to_string();
let secondary = tmp_secondary.path().to_str().unwrap().to_string();
// Encode into primary dir first (all 14 shards land there).
let dir = encode_sample_volume(&tmp_primary);
assert_eq!(dir, primary);
// Simulate a multi-disk layout: move shards 0, 4, 8 to the secondary
// dir, as if the master had placed them on a different disk.
let moved_shards: &[u8] = &[0, 4, 8];
for &shard_id in moved_shards {
let src = format!("{}/1.ec{:02}", primary, shard_id);
let dst = format!("{}/1.ec{:02}", secondary, shard_id);
std::fs::rename(&src, &dst).unwrap();
}
// Remove shard 7 from primary — this is the shard we want to rebuild.
let missing_path = format!("{}/1.ec07", primary);
std::fs::remove_file(&missing_path).unwrap();
// Without additional_dirs the rebuild must fail: shards 0, 4, 8 are
// not in primary and shard 7 cannot be reconstructed without them.
let res = rebuild_ec_files(&primary, "", VolumeId(1), &[7], 10, 4, &[]);
assert!(
res.is_err(),
"rebuild without additional_dirs must fail when input shards are on another disk"
);
assert!(
!std::path::Path::new(&missing_path).exists(),
"failed rebuild must not leave a partial shard file behind"
);
// With additional_dirs pointing at the secondary, the rebuild must succeed.
rebuild_ec_files(
&primary,
"",
VolumeId(1),
&[7],
10,
4,
&[secondary.as_str()],
)
.unwrap();
assert!(
std::path::Path::new(&missing_path).exists(),
"rebuilt shard .ec07 should exist in primary dir"
);
assert!(
std::fs::metadata(&missing_path).unwrap().len() > 0,
"rebuilt shard must be non-empty"
);
}
// Multi-disk .ecx rebuild: data shards (0-9) needed to reconstruct the
// logical .dat content are split across two directories, as on a
// multi-disk volume server. Passing the secondary dir via
// `additional_dirs` must allow rebuild_ecx_file to find them and
// succeed where it would previously fail with
// "cannot open data shard for ecx rebuild".
#[test]
fn test_rebuild_ecx_file_multi_disk() {
let tmp_primary = TempDir::new().unwrap();
let tmp_secondary = TempDir::new().unwrap();
let primary = tmp_primary.path().to_str().unwrap().to_string();
let secondary = tmp_secondary.path().to_str().unwrap().to_string();
let dir = encode_sample_volume(&tmp_primary);
assert_eq!(dir, primary);
// Move some data shards (0-9) to the secondary dir, simulating a
// multi-disk layout where not all data shards landed on the same disk.
let moved_shards: &[u8] = &[1, 3, 6];
for &shard_id in moved_shards {
let src = format!("{}/1.ec{:02}", primary, shard_id);
let dst = format!("{}/1.ec{:02}", secondary, shard_id);
std::fs::rename(&src, &dst).unwrap();
}
// Delete the existing .ecx to force a rebuild.
let ecx_path = format!("{}/1.ecx", primary);
std::fs::remove_file(&ecx_path).unwrap();
// Without additional_dirs, rebuild must fail: shards 1, 3, 6 are not
// in primary and the full logical .dat content can't be reconstructed.
let res = rebuild_ecx_file(&primary, "", VolumeId(1), 10, &[]);
assert!(
res.is_err(),
"ecx rebuild without additional_dirs must fail when data shards are on another disk"
);
assert!(
!std::path::Path::new(&ecx_path).exists(),
"failed ecx rebuild must not leave a partial .ecx file behind"
);
// With additional_dirs pointing at the secondary, the rebuild must succeed.
rebuild_ecx_file(&primary, "", VolumeId(1), 10, &[secondary.as_str()]).unwrap();
assert!(
std::path::Path::new(&ecx_path).exists(),
"rebuilt .ecx should exist in primary dir"
);
assert!(
std::fs::metadata(&ecx_path).unwrap().len() > 0,
"rebuilt .ecx must be non-empty"
);
}
#[test]
fn test_reed_solomon_basic() {
let data_shards = 10;
@@ -109,6 +109,17 @@ impl EcVolumeShard {
self.ecd_file_size
}
/// Protobuf descriptor for this shard. Mirrors Go's ToEcShardInfo.
pub fn to_ec_shard_info(&self) -> crate::pb::volume_server_pb::EcShardInfo {
crate::pb::volume_server_pb::EcShardInfo {
shard_id: self.shard_id as u32,
size: self.file_size(),
collection: self.collection.clone(),
volume_id: self.volume_id.0,
..Default::default()
}
}
/// Close the shard file.
pub fn close(&mut self) {
if let Some(ref file) = self.ecd_file {
@@ -1,4 +1,4 @@
//! EcVolume: an erasure-coded volume with up to 14 shards.
//! EcVolume: an erasure-coded volume with up to MAX_SHARD_COUNT shards.
//!
//! Each EcVolume has a sorted index (.ecx) and a deletion journal (.ecj).
//! Shards (.ec00-.ec13) may be distributed across multiple servers.
@@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use crate::pb::master_pb;
use crate::storage::erasure_coding::ec_locate;
use crate::storage::erasure_coding::ec_shard::*;
use crate::storage::needle::needle::{get_actual_size, Needle};
use crate::storage::needle::needle::{get_actual_size, Needle, NeedleError};
use crate::storage::types::*;
/// An erasure-coded volume managing its local shards and index.
@@ -22,7 +22,7 @@ pub struct EcVolume {
pub dir: String,
pub dir_idx: String,
pub version: Version,
pub shards: Vec<Option<EcVolumeShard>>, // indexed by ShardId (0..14)
pub shards: Vec<Option<EcVolumeShard>>, // indexed by ShardId (0..MAX_SHARD_COUNT)
pub dat_file_size: i64,
pub data_shards: u32,
pub parity_shards: u32,
@@ -61,6 +61,13 @@ pub struct EcVolume {
/// served from a shard of a different encode run is rejected (server- and
/// client-side); 0 for a pre-feature volume, which is treated leniently.
pub encode_ts_ns: i64,
/// Active-generation EC bitrot checksum sidecar (`<base>.ecsum`), loaded and
/// validated at mount. `None` unless `bitrot_status == On`.
pub(crate) bitrot: Option<crate::pb::volume_server_pb::EcBitrotProtection>,
/// Resolved protection state of the loaded sidecar. Cached alongside `bitrot`
/// so `bitrot_protection()` can return the `Off`/`Invalid` distinction without
/// re-reading, mirroring Go's `EcVolume.bitrotStatus`.
pub(crate) bitrot_status: crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
}
/// Locate the `.vif` for a (collection, vid) by preferring the data dir
@@ -106,7 +113,7 @@ pub fn read_ec_shard_config(
if let Some(ec) = vif_info.ec_shard_config {
if ec.data_shards > 0
&& ec.parity_shards > 0
&& (ec.data_shards + ec.parity_shards) <= TOTAL_SHARDS_COUNT as u32
&& (ec.data_shards + ec.parity_shards) <= MAX_SHARD_COUNT as u32
{
data_shards = ec.data_shards;
parity_shards = ec.parity_shards;
@@ -191,6 +198,8 @@ impl EcVolume {
shard_locations_refresh_time: std::sync::Mutex::new(None),
expire_at_sec,
encode_ts_ns,
bitrot: None,
bitrot_status: crate::storage::erasure_coding::ec_bitrot::BitrotStatus::Off,
};
// Open .ecx file (sorted index) in read/write mode for in-place deletion marking.
@@ -237,9 +246,189 @@ impl EcVolume {
// Seed the in-memory deleted set from the journal.
vol.load_deleted_needles_from_ecj()?;
// Load the generation-0 EC bitrot checksum sidecar (optional; best-effort).
vol.load_active_bitrot_sidecar();
Ok(vol)
}
/// Load the generation-0 checksum sidecar into `self.bitrot`/`self.bitrot_status`.
/// OSS only produces generation-0 (fresh-encode) sidecars, mirroring Go's
/// `loadActiveBitrotSidecar`.
fn load_active_bitrot_sidecar(&mut self) {
self.load_bitrot_for_generation(0);
}
/// Load and validate the sidecar describing `generation`, setting
/// `self.bitrot`/`self.bitrot_status`. Absent or generation/config-mismatched
/// => `Off` (protection off, not corruption); self-integrity or manifest
/// failure => `Invalid` with a warning (protection off pending repair); usable
/// => `On`. Mirrors Go's `loadBitrotForGeneration`.
fn load_bitrot_for_generation(&mut self, generation: u32) {
use crate::storage::erasure_coding::ec_bitrot;
let base = self.base_name();
let path = ec_bitrot::bitrot_sidecar_path(&base, generation);
let loaded = ec_bitrot::load_bitrot_sidecar(&path);
let status = ec_bitrot::resolve_status(
&loaded,
generation,
self.data_shards as usize,
self.parity_shards as usize,
);
self.bitrot = None;
self.bitrot_status = status;
match status {
ec_bitrot::BitrotStatus::On => self.bitrot = loaded.ok(),
ec_bitrot::BitrotStatus::Off => {}
ec_bitrot::BitrotStatus::Invalid => {
tracing::warn!(
volume_id = self.volume_id.0,
path = %path,
generation,
"ec volume: bitrot sidecar present but invalid; protection off pending repair",
);
}
}
}
/// The active-generation bitrot protection AND its status (cached at mount),
/// mirroring Go's `EcVolume.BitrotProtection()`. Preserves the distinction
/// `checksum_scrub` needs: an absent/generation-mismatched sidecar is `Off`
/// (a clean no-op), a present-but-malformed one is `Invalid` (a real integrity
/// error). Returns `Some(prot)` only for `On`.
pub(crate) fn bitrot_protection(
&self,
) -> (
Option<crate::pb::volume_server_pb::EcBitrotProtection>,
crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
) {
(self.bitrot.clone(), self.bitrot_status)
}
/// Read-only EC bitrot checksum scrub of the LOCAL shards of this volume's
/// active generation.
///
/// Loads the active-generation `.ecsum` sidecar and, for each locally-held
/// shard, reads the on-disk shard file in `block_size` chunks and compares
/// each block's CRC32C against the sidecar. Returns
/// `(blocks_scanned, mismatched_shards, errors)`.
///
/// If more than `parity_shards` shards mismatch wholesale (i.e. every block
/// of those shards is wrong — the signature of a stale/wrong sidecar rather
/// than localized disk rot), the result is classified as a suspect sidecar:
/// `mismatched_shards` is cleared and an integrity note is added to `errors`
/// instead. A genuine multi-shard disk failure of that magnitude is
/// already unrecoverable, so treating it as a sidecar-integrity issue avoids
/// raising false shard-corruption alarms.
///
/// This method NEVER deletes or mutates anything — it is purely diagnostic.
pub fn checksum_scrub(&self) -> (u64, Vec<u32>, Vec<String>) {
use crate::storage::erasure_coding::ec_bitrot;
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
let mut errors: Vec<String> = Vec::new();
// Resolve the active-generation protection AND its status, mirroring
// Go's `ChecksumScrub` (`prot, status := ecv.BitrotProtection()`):
// - BitrotOff => sidecars are OPTIONAL; an absent (or generation/
// config-mismatched) sidecar simply means protection is not enabled
// for this generation. Return a CLEAN, EMPTY result — NOT an error —
// so legacy/intentionally-unprotected volumes are never reported
// broken. (Go: `case BitrotOff: return 0, nil, nil`.)
// - BitrotInvalid => the sidecar is PRESENT but malformed/unverifiable
// (self-integrity or manifest failure). That is the only status that
// yields an integrity error here.
// - BitrotOn => scan local shards against it.
let prot = match self.bitrot_protection() {
(_, BitrotStatus::Off) => {
// Unprotected generation: nothing to verify. Not an error.
return (0, Vec::new(), Vec::new());
}
(_, BitrotStatus::Invalid) => {
return (
0,
Vec::new(),
vec![format!(
"EC volume {} bitrot sidecar is malformed/unverifiable (sidecar integrity)",
self.volume_id.0
)],
);
}
(Some(p), BitrotStatus::On) => p,
(None, BitrotStatus::On) => {
// Unreachable: BitrotOn always carries a loaded sidecar. Treat a
// missing payload defensively as protection off (clean no-op).
return (0, Vec::new(), Vec::new());
}
};
let block_size = prot.block_size as i64;
let generation = prot.generation;
let base = self.base_name();
let mut blocks_scanned: u64 = 0;
let mut mismatched_shards: Vec<u32> = Vec::new();
// Track shards whose blocks ALL mismatch (wholesale) to detect a
// stale/wrong sidecar.
let mut wholesale_mismatch = 0usize;
for (i, slot) in self.shards.iter().enumerate() {
if slot.is_none() {
continue; // not local
}
let shard_id = i as u32;
let Some(entry) = ec_bitrot::shard_checksums(&prot, shard_id) else {
errors.push(format!(
"EC volume {} shard {} present but missing from sidecar manifest",
self.volume_id.0, shard_id
));
continue;
};
// Resolve the on-disk shard file path for the active generation,
// mirroring EcVolumeShard::reopen_against_generation's convention.
let path = if generation == 0 {
format!("{}.ec{:02}", base, shard_id)
} else {
format!("{}.ec{:02}.v{}", base, shard_id, generation)
};
let expected_blocks = entry.block_crc32c.len() / 4;
match ec_bitrot::verify_shard_file_blocks(&path, entry, block_size) {
Ok(mismatched) => {
blocks_scanned += expected_blocks as u64;
if !mismatched.is_empty() {
mismatched_shards.push(shard_id);
if expected_blocks > 0 && mismatched.len() == expected_blocks {
wholesale_mismatch += 1;
}
}
}
Err(e) => {
errors.push(format!(
"EC volume {} shard {} scrub read error: {}",
self.volume_id.0, shard_id, e
));
}
}
}
// If more shards mismatch wholesale than parity can mask, the sidecar
// itself is the likely culprit (stale generation / wrong volume), so
// suppress the shard-corruption verdict and flag a sidecar-integrity
// issue instead.
if wholesale_mismatch > self.parity_shards as usize {
errors.push(format!(
"EC volume {}: {} shards mismatch wholesale (> {} parity); suspect stale/wrong sidecar, not shard corruption",
self.volume_id.0, wholesale_mismatch, self.parity_shards
));
mismatched_shards.clear();
}
mismatched_shards.sort_unstable();
(blocks_scanned, mismatched_shards, errors)
}
/// Walk the .ecj journal and populate `deleted_needles`. Called once
/// from `new()` under exclusive ownership of the just-constructed
/// EcVolume, so locking is not strictly required — but we take the
@@ -546,6 +735,26 @@ impl EcVolume {
}
/// Locate the EC shard intervals needed to read a needle.
/// Locate the EC shard intervals covering a needle at `actual_offset` whose
/// index size is `size`. Mirrors Go's EcVolume.LocateEcShardNeedleInterval.
pub fn locate_ec_shard_needle_interval(
&self,
actual_offset: i64,
size: Size,
) -> Vec<ec_locate::Interval> {
// shardSize = datFileSize / DataShards when known, else ecdFileSize - 1
// (shards are padded to the small block size; the -1 avoids an
// off-by-one in the large-block row count).
let shard_size = if self.dat_file_size > 0 {
self.dat_file_size / self.data_shards as i64
} else {
self.shard_file_size() - 1
};
// locate_data wants the on-disk size (header+body+checksum+timestamp+padding).
let actual = get_actual_size(size, self.version);
ec_locate::locate_data(actual_offset, Size(actual as i32), shard_size, self.data_shards)
}
pub fn locate_needle(
&self,
needle_id: NeedleId,
@@ -559,25 +768,7 @@ impl EcVolume {
return Ok(None);
}
// Match Go's LocateEcShardNeedleInterval: shardSize = shard.ecdFileSize - 1
// Shards are usually padded to ErasureCodingSmallBlockSize, so subtract 1
// to avoid off-by-one in large block row count calculation.
// If datFileSize is known, use datFileSize / DataShards instead.
let shard_size = if self.dat_file_size > 0 {
self.dat_file_size / self.data_shards as i64
} else {
self.shard_file_size() - 1
};
// Pass the actual on-disk size (header+body+checksum+timestamp+padding)
// to locate_data, matching Go: types.Size(needle.GetActualSize(size, version))
let actual = get_actual_size(size, self.version);
let intervals = ec_locate::locate_data(
offset.to_actual_offset(),
Size(actual as i32),
shard_size,
self.data_shards,
);
let intervals = self.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
Ok(Some((offset, size, intervals)))
}
@@ -708,97 +899,186 @@ impl EcVolume {
/// Matches Go's `(ev *EcVolume) ScrubIndex()` → `idx.CheckIndexFile()`.
/// Returns (entry_count, errors).
pub fn scrub_index(&self) -> (u64, Vec<String>) {
let ecx_file = match self.ecx_file.as_ref() {
Some(f) => f,
None => {
return (
0,
vec![format!(
"no ECX file associated with EC volume {}",
self.volume_id.0
)],
)
}
};
if self.ecx_file_size == 0 {
if self.ecx_file.is_none() {
return (
0,
vec![format!(
"zero-size ECX file for EC volume {}",
"no ECX file associated with EC volume {}",
self.volume_id.0
)],
);
}
if self.ecx_file_size == 0 {
return (
0,
vec![format!("zero-size ECX file for EC volume {}", self.volume_id.0)],
);
}
let entry_count = self.ecx_file_size as usize / NEEDLE_MAP_ENTRY_SIZE;
let mut entries: Vec<(usize, NeedleId, i64, Size)> = Vec::with_capacity(entry_count);
let mut errs: Vec<String> = Vec::new();
let mut entry_buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
// Walk a private fd so the structural scan never moves the shared
// ecx_file cursor (the cached handle is read positionally elsewhere).
let ecx_path = self.ecx_file_name();
let mut ecx_file = match File::open(&ecx_path) {
Ok(f) => f,
Err(e) => return (0, vec![format!("open ECX file {}: {}", ecx_path, e)]),
};
crate::storage::idx::check_index_file(&mut ecx_file, self.ecx_file_size, self.version)
}
// Walk all entries
for i in 0..entry_count {
let file_offset = (i * NEEDLE_MAP_ENTRY_SIZE) as u64;
#[cfg(unix)]
{
use std::os::unix::fs::FileExt;
if let Err(e) = ecx_file.read_exact_at(&mut entry_buf, file_offset) {
errs.push(format!("read ecx entry {}: {}", i, e));
/// ScrubLocal verifies each needle against the LOCAL shards only; it cannot
/// CRC-check a needle whose intervals span shards held on other servers.
/// Mirrors Go's EcVolume.ScrubLocal. Returns (rows walked, broken shards, errors).
pub fn scrub_local(
&self,
) -> (u64, Vec<crate::pb::volume_server_pb::EcShardInfo>, Vec<String>) {
// Local scan also verifies the index.
let (_, mut errs) = self.scrub_index();
let mut broken_shards: HashSet<ShardId> = HashSet::new();
let mut count: u64 = 0;
let ecx_path = self.ecx_file_name();
let mut ecx_file = match File::open(&ecx_path) {
Ok(f) => f,
Err(e) => {
errs.push(format!("open ECX file {}: {}", ecx_path, e));
return (count, Vec::new(), errs);
}
};
// Reused across every needle/chunk to avoid a per-chunk allocation.
let mut chunk_buf: Vec<u8> = Vec::new();
let walk = crate::storage::idx::walk_index_file(&mut ecx_file, 0, |id, offset, size| {
count += 1;
if size.is_tombstone() {
return Ok(());
}
let locations = self.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
// A needle is verifiable locally only if every shard it spans is local;
// when any is remote, skip the reassembly buffer entirely.
let has_remote_chunks = locations.iter().any(|iv| {
let (sid, _) = iv.to_shard_id_and_offset(self.data_shards);
self.shards.get(sid as usize).and_then(|s| s.as_ref()).is_none()
});
let mut read: i64 = 0;
let mut data: Vec<u8> = if has_remote_chunks {
Vec::new()
} else {
Vec::with_capacity(get_actual_size(size, self.version) as usize)
};
let mut local_shard_ids: Vec<ShardId> = Vec::new();
for (i, iv) in locations.iter().enumerate() {
let (sid, soffset) = iv.to_shard_id_and_offset(self.data_shards);
let ssize = iv.size;
let shard = match self.shards.get(sid as usize).and_then(|s| s.as_ref()) {
Some(s) => s,
None => {
// Shard is not local; we can't verify it without decoding.
read += ssize;
continue;
}
};
local_shard_ids.push(sid);
if soffset + ssize > shard.file_size() {
broken_shards.insert(sid);
errs.push(format!(
"local shard {} for needle {} is too short ({}), cannot read chunk {}/{}",
sid,
id.0,
shard.file_size(),
i + 1,
locations.len()
));
continue;
}
chunk_buf.resize(ssize as usize, 0);
match shard.read_at(&mut chunk_buf, soffset as u64) {
Err(e) => {
broken_shards.insert(sid);
errs.push(format!(
"failed to read chunk {}/{} for needle {} from local shard {} at offset {}: {}",
i + 1,
locations.len(),
id.0,
sid,
soffset,
e
));
continue;
}
Ok(got) if got as i64 != ssize => {
broken_shards.insert(sid);
errs.push(format!(
"expected {} bytes for chunk {}/{} for needle {} from local shard {}, got {}",
ssize,
i + 1,
locations.len(),
id.0,
sid,
got
));
continue;
}
Ok(_) => {}
}
if !has_remote_chunks {
data.extend_from_slice(&chunk_buf);
}
read += ssize;
}
let (key, offset, size) = idx_entry_from_bytes(&entry_buf);
entries.push((i, key, offset.to_actual_offset(), size));
}
// Sort by offset, then size
entries.sort_by(|a, b| a.2.cmp(&b.2).then(a.3 .0.cmp(&b.3 .0)));
local_shard_ids.sort_unstable();
// Check for overlapping needles
for i in 1..entries.len() {
let (idx, id, offset, size) = entries[i];
let (_, last_id, last_offset, last_size) = entries[i - 1];
let actual_size =
crate::storage::needle::needle::get_actual_size(size, self.version);
let end = if actual_size != 0 {
offset + actual_size - 1
} else {
offset
};
let last_actual_size =
crate::storage::needle::needle::get_actual_size(last_size, self.version);
let last_end = if last_actual_size != 0 {
last_offset + last_actual_size - 1
} else {
last_offset
};
if offset <= last_end {
errs.push(format!(
"needle {} (#{}) at [{}-{}] overlaps needle {} at [{}-{}]",
id.0,
idx + 1,
offset,
end,
last_id.0,
last_offset,
last_end
let want = get_actual_size(size, self.version);
if read != want {
// Like Go, returning from the walk callback aborts the scan.
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"expected {} bytes for needle {} on volume {}, got {}",
want, id.0, self.volume_id.0, read
),
));
}
// Only a fully-local needle can be reassembled and CRC-checked.
if !has_remote_chunks {
let mut n = Needle::default();
if let Err(e) = n.read_bytes(&data, 0, size, self.version) {
// A delete-state disagreement between the .ecx index and the reassembled
// on-disk header (live index vs zero header size) is not corruption.
let delete_state_disagrees = matches!(
&e,
NeedleError::SizeMismatch { found, .. } if size.is_deleted() != (found.0 == 0)
);
if !delete_state_disagrees {
errs.push(format!(
"needle {} on volume {}, shards {:?}: {}",
id.0, self.volume_id.0, local_shard_ids, e
));
}
}
}
Ok(())
});
if let Err(e) = walk {
// Go appends the walk/callback error verbatim.
errs.push(e.to_string());
}
// Verify file size matches entry count
let expected_size = entry_count as i64 * NEEDLE_MAP_ENTRY_SIZE as i64;
if expected_size != self.ecx_file_size {
errs.push(format!(
"expected an index file of size {}, got {}",
expected_size, self.ecx_file_size
));
}
let mut broken: Vec<crate::pb::volume_server_pb::EcShardInfo> = broken_shards
.iter()
.filter_map(|sid| self.shards.get(*sid as usize).and_then(|s| s.as_ref()))
.map(|s| s.to_ec_shard_info())
.collect();
broken.sort_by(|a, b| a.shard_id.cmp(&b.shard_id));
(entries.len() as u64, errs)
(count, broken, errs)
}
// ---- Deletion ----
@@ -1160,6 +1440,118 @@ mod tests {
use super::*;
use tempfile::TempDir;
/// Mounting an EC volume loads and validates its generation-0 `.ecsum`
/// sidecar, so `bitrot_protection()` reports `On` with the parsed manifest.
#[test]
fn test_mount_loads_bitrot_sidecar() {
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
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,
"",
VolumeId(1),
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap();
for i in 1..=5 {
let data = format!("test data for 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, "", VolumeId(1), 10, 4)
.unwrap();
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
assert!(
vol.bitrot.is_some(),
"mount should load the generation-0 .ecsum sidecar"
);
let (prot, status) = vol.bitrot_protection();
assert_eq!(status, BitrotStatus::On);
assert_eq!(prot.unwrap().shards.len(), 14);
}
/// CHECKSUM scrub verifies clean shards against the sidecar and flags a shard
/// whose bytes are corrupted after encode.
#[test]
fn test_checksum_scrub_clean_and_detects_corruption() {
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,
"",
VolumeId(1),
NeedleMapKind::InMemory,
None,
None,
0,
Version::current(),
)
.unwrap();
for i in 1..=8 {
let data = format!("test data for needle {} with a bit more length", 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, "", VolumeId(1), 10, 4)
.unwrap();
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
for id in 0..14u8 {
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), id))
.unwrap();
}
// Clean scrub: no mismatches, no errors, blocks scanned > 0.
let (scanned, broken, errs) = vol.checksum_scrub();
assert!(errs.is_empty(), "unexpected scrub errors: {:?}", errs);
assert!(broken.is_empty(), "unexpected mismatches: {:?}", broken);
assert!(scanned > 0, "scrub should scan at least one block");
// Corrupt one byte of shard 3 on disk; re-scrub must report shard 3.
let shard3 = format!("{}/1.ec03", dir);
let mut bytes = std::fs::read(&shard3).unwrap();
assert!(!bytes.is_empty());
bytes[0] ^= 0xFF;
std::fs::write(&shard3, &bytes).unwrap();
let (_, broken2, _) = vol.checksum_scrub();
assert!(
broken2.contains(&3),
"corrupted shard 3 should be flagged, got {:?}",
broken2
);
}
fn write_ecx_file(
dir: &str,
collection: &str,
@@ -1292,10 +1684,11 @@ mod tests {
let dir = tmp.path().to_str().unwrap();
write_ecx_file(dir, "pics", VolumeId(1), &[]);
// data + parity exceeds MAX_SHARD_COUNT, so the config is rejected.
let vif = crate::storage::volume::VifVolumeInfo {
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
data_shards: 10,
parity_shards: 10,
data_shards: 20,
parity_shards: 20,
..Default::default()
}),
..Default::default()
@@ -1311,4 +1704,150 @@ mod tests {
assert_eq!(vol.data_shards, DATA_SHARDS_COUNT as u32);
assert_eq!(vol.parity_shards, PARITY_SHARDS_COUNT as u32);
}
#[test]
fn test_ec_volume_wide_ratio_vif_config() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
write_ecx_file(dir, "pics", VolumeId(1), &[]);
// A wider-than-default ratio within MAX_SHARD_COUNT must load as-is.
let vif = crate::storage::volume::VifVolumeInfo {
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
data_shards: 16,
parity_shards: 4,
..Default::default()
}),
..Default::default()
};
let base = crate::storage::volume::volume_file_name(dir, "pics", VolumeId(1));
std::fs::write(
format!("{}.vif", base),
serde_json::to_string_pretty(&vif).unwrap(),
)
.unwrap();
let vol = EcVolume::new(dir, dir, "pics", VolumeId(1)).unwrap();
assert_eq!(vol.data_shards, 16);
assert_eq!(vol.parity_shards, 4);
}
#[test]
fn test_scrub_local_skips_tombstones() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(-1))];
write_ecx_file(dir, "", VolumeId(1), &entries);
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
let (count, broken, errs) = vol.scrub_local();
assert_eq!(count, 1);
assert!(broken.is_empty(), "{:?}", broken);
assert!(errs.is_empty(), "{:?}", errs);
}
#[test]
fn test_scrub_local_clean_when_no_local_shards() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(100))];
write_ecx_file(dir, "", VolumeId(1), &entries);
// dat_file_size makes the shard-size math well-defined.
let vif = crate::storage::volume::VifVolumeInfo {
dat_file_size: 14000,
..Default::default()
};
let base = crate::storage::volume::volume_file_name(dir, "", VolumeId(1));
std::fs::write(
format!("{}.vif", base),
serde_json::to_string_pretty(&vif).unwrap(),
)
.unwrap();
// No shard files present: nothing to verify locally, so no errors.
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
let (count, broken, errs) = vol.scrub_local();
assert_eq!(count, 1);
assert!(broken.is_empty(), "{:?}", broken);
assert!(errs.is_empty(), "{:?}", errs);
}
#[test]
fn test_scrub_local_suppresses_delete_state_disagreement() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
// Live index entry (size > 0) whose reassembled on-disk header reports size 0
// (deleted-on-shards but live-in-index) — a delete-state disagreement, not corruption.
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(100))];
write_ecx_file(dir, "", VolumeId(1), &entries);
let vif = crate::storage::volume::VifVolumeInfo {
dat_file_size: 14000,
..Default::default()
};
let base = crate::storage::volume::volume_file_name(dir, "", VolumeId(1));
std::fs::write(
format!("{}.vif", base),
serde_json::to_string_pretty(&vif).unwrap(),
)
.unwrap();
// Shard 0 holds the needle's bytes; all-zero so the parsed header size is 0.
let mut shard0 = EcVolumeShard::new(dir, "", VolumeId(1), 0);
shard0.create().unwrap();
shard0.write_all(&[0u8; 256]).unwrap();
shard0.close();
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), 0))
.unwrap();
let (count, broken, errs) = vol.scrub_local();
assert_eq!(count, 1);
assert!(broken.is_empty(), "{:?}", broken);
assert!(
errs.is_empty(),
"delete-state disagreement must be suppressed, got {:?}",
errs
);
}
#[test]
fn test_scrub_local_reports_genuine_size_corruption() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(100))];
write_ecx_file(dir, "", VolumeId(1), &entries);
let vif = crate::storage::volume::VifVolumeInfo {
dat_file_size: 14000,
..Default::default()
};
let base = crate::storage::volume::volume_file_name(dir, "", VolumeId(1));
std::fs::write(
format!("{}.vif", base),
serde_json::to_string_pretty(&vif).unwrap(),
)
.unwrap();
// On-disk header reports a non-zero size (50) that disagrees with the live
// index size (100): genuine corruption, not a delete-state race — must report.
let mut bytes = vec![0u8; 256];
bytes[15] = 50; // header size field (big-endian u32) = 50
let mut shard0 = EcVolumeShard::new(dir, "", VolumeId(1), 0);
shard0.create().unwrap();
shard0.write_all(&bytes).unwrap();
shard0.close();
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), 0))
.unwrap();
let (_count, _broken, errs) = vol.scrub_local();
assert!(
!errs.is_empty(),
"a non-zero size mismatch is genuine corruption and must be reported"
);
}
}
@@ -3,6 +3,7 @@
//! Encodes a volume's .dat file into 10 data + 4 parity shards using
//! Reed-Solomon erasure coding. Can reconstruct from any 10 of 14 shards.
pub mod ec_bitrot;
pub mod ec_decoder;
pub mod ec_encoder;
pub mod ec_locate;
+132
View File
@@ -2,6 +2,7 @@
//!
//! Each entry: NeedleId(8) + Offset(5) + Size(4) = 17 bytes.
use crate::storage::needle::needle::get_actual_size;
use crate::storage::types::*;
use std::io::{self, Read, Seek, SeekFrom};
@@ -36,6 +37,76 @@ where
}
}
/// Verify the integrity of an .idx/.ecx index file: walk every entry, sort by
/// (offset, size), flag overlapping needles, and check the file is a whole
/// number of entries. Mirrors Go's `idx.CheckIndexFile`. No data-file reads.
pub fn check_index_file<R: Read + Seek>(
reader: &mut R,
idx_file_size: i64,
version: Version,
) -> (u64, Vec<String>) {
let mut errs = Vec::new();
// (walk index, id, actual offset, size)
let mut entries: Vec<(usize, NeedleId, i64, Size)> = Vec::new();
let mut i = 0usize;
if let Err(e) = walk_index_file(reader, 0, |id, offset, size| {
entries.push((i, id, offset.to_actual_offset(), size));
i += 1;
Ok(())
}) {
errs.push(format!("walk index file: {}", e));
}
entries.sort_by(|a, b| a.2.cmp(&b.2).then(a.3 .0.cmp(&b.3 .0)));
// Offset-0 logical tombstones (remote-tier deletes) occupy no physical extent,
// so they cannot overlap anything — exclude them from the overlap check. They
// are still counted below for the index-size check.
let physical: Vec<(usize, NeedleId, i64, Size)> = entries
.iter()
.copied()
.filter(|e| !(e.2 == 0 && e.3.is_deleted()))
.collect();
for j in 1..physical.len() {
let (index, id, offset, size) = physical[j];
let (_, last_id, last_offset, last_size) = physical[j - 1];
let end = match get_actual_size(size, version) {
0 => offset,
s => offset + s - 1,
};
let last_end = match get_actual_size(last_size, version) {
0 => last_offset,
s => last_offset + s - 1,
};
if offset <= last_end {
errs.push(format!(
"needle {} (#{}) at [{}-{}] overlaps needle {} at [{}-{}]",
id.0,
index + 1,
offset,
end,
last_id.0,
last_offset,
last_end
));
}
}
let count = entries.len() as u64;
let expected = count as i64 * NEEDLE_MAP_ENTRY_SIZE as i64;
if expected != idx_file_size {
errs.push(format!(
"expected an index file of size {}, got {}",
idx_file_size, expected
));
}
(count, errs)
}
/// Write a single index entry to a writer.
pub fn write_index_entry<W: io::Write>(
writer: &mut W,
@@ -96,6 +167,67 @@ mod tests {
assert_eq!(count, 0);
}
fn idx_bytes(entries: &[(NeedleId, Offset, Size)]) -> Vec<u8> {
let mut data = Vec::new();
for (key, offset, size) in entries {
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_entry_to_bytes(&mut buf, *key, *offset, *size);
data.extend_from_slice(&buf);
}
data
}
#[test]
fn test_check_index_file_clean() {
let data = idx_bytes(&[
(NeedleId(1), Offset::from_actual_offset(0), Size(50)),
(NeedleId(2), Offset::from_actual_offset(100_000), Size(50)),
]);
let size = data.len() as i64;
let (count, errs) = check_index_file(&mut Cursor::new(data), size, Version(3));
assert_eq!(count, 2);
assert!(errs.is_empty(), "{:?}", errs);
}
#[test]
fn test_check_index_file_detects_overlap() {
let data = idx_bytes(&[
(NeedleId(1), Offset::from_actual_offset(0), Size(100)),
(NeedleId(2), Offset::from_actual_offset(8), Size(100)),
]);
let size = data.len() as i64;
let (count, errs) = check_index_file(&mut Cursor::new(data), size, Version(3));
assert_eq!(count, 2);
assert_eq!(errs.len(), 1, "{:?}", errs);
assert!(errs[0].contains("overlaps"), "{:?}", errs);
}
#[test]
fn test_check_index_file_ignores_offset0_tombstone() {
// A live needle near the start plus an offset-0 logical tombstone (remote-tier
// delete) must NOT be flagged as overlapping; the tombstone row still counts.
let data = idx_bytes(&[
(NeedleId(1), Offset::from_actual_offset(8), Size(100)),
(NeedleId(2), Offset::from_actual_offset(0), Size(-1)),
]);
let size = data.len() as i64;
let (count, errs) = check_index_file(&mut Cursor::new(data), size, Version(3));
assert_eq!(count, 2, "tombstone row is still counted: {:?}", errs);
assert!(errs.is_empty(), "offset-0 tombstone must not overlap: {:?}", errs);
}
#[test]
fn test_check_index_file_detects_size_mismatch() {
let data = idx_bytes(&[(NeedleId(1), Offset::from_actual_offset(0), Size(50))]);
let claimed = data.len() as i64 + 5;
let (_count, errs) = check_index_file(&mut Cursor::new(data), claimed, Version(3));
assert!(
errs.iter().any(|e| e.contains("expected an index file")),
"{:?}",
errs
);
}
#[test]
fn test_write_index_entry() {
let mut buf = Vec::new();
@@ -15,16 +15,28 @@
//! sibling disk's index files so it can serve reads and route deletes
//! through a real `.ecx` / `.ecj`.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::fs;
use tracing::{info, warn};
use tracing::{error, info, warn};
use crate::storage::disk_location::{is_ec_shard_extension, parse_collection_volume_id_pub};
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
use crate::storage::store::Store;
use crate::storage::types::VolumeId;
/// An EC volume with shard files on a local disk but no usable `.ecx` on any
/// local disk, so the shards cannot mount. The same-server reconcile/mirror
/// handle a `.ecx` on a sibling disk; this is the cross-server case whose index
/// must be fetched from a peer (issue #10104). Mirrors Go's `EcVolumeMissingIndex`.
#[derive(Clone, Debug)]
pub(crate) struct EcVolumeMissingIndex {
pub collection: String,
pub vid: VolumeId,
pub idx_dir: String,
pub data_dir: String,
}
pub(crate) fn ec_local_ecx_path(dir: &str, collection: &str, vid: VolumeId) -> String {
if collection.is_empty() {
format!("{}/{}.ecx", dir, vid.0)
@@ -420,6 +432,71 @@ impl Store {
}
owners
}
/// Cross-server orphans: EC volumes that have shard files on a local disk but
/// no usable `.ecx` on any local disk. A `.ecx` merely on a sibling disk is
/// excluded (the same-server reconcile/mirror handles it). Scans on-disk shard
/// files, so it surfaces volumes the master never learned about — including
/// those whose every holder is missing its index.
///
/// Mirrors `Store.CollectEcVolumesMissingIndex` in Go.
pub(crate) fn collect_ec_volumes_missing_index(&self) -> Vec<EcVolumeMissingIndex> {
let owners = self.index_ecx_owners();
let mut seen: HashSet<EcKey> = HashSet::new();
let mut missing = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
for (key, _shards) in collect_orphan_ec_shards(loc, loc_idx) {
if owners.contains_key(&key) || !seen.insert(key.clone()) {
continue;
}
missing.push(EcVolumeMissingIndex {
collection: key.collection,
vid: key.vid,
idx_dir: loc.idx_directory.clone(),
data_dir: loc.directory.clone(),
});
}
}
missing
}
/// Mount EC shards that became loadable after a missing `.ecx` was fetched
/// onto a local disk: mirror the index onto every shard-bearing disk, mount
/// the disks that now have a local index, then fall back to the cross-disk
/// virtual mount. Mirrors `Store.MountRecoveredEcShards` in Go.
pub(crate) fn mount_recovered_ec_shards(&mut self) {
self.mirror_ec_metadata_to_shard_disks();
self.load_orphan_ec_shards_with_local_index();
self.reconcile_ec_shards_across_disks();
}
/// Mount on-disk EC shards whose `.ecx` index is now present on the same disk.
/// Unlike `reconcile_ec_shards_across_disks` it needs no sibling disk, so a
/// single-disk store recovers once its index has been fetched from a peer.
fn load_orphan_ec_shards_with_local_index(&mut self) {
let mut work: Vec<(usize, EcKey, Vec<u32>)> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
for (key, shards) in collect_orphan_ec_shards(loc, loc_idx) {
if !loc.has_ecx_file_on_disk(&key.collection, key.vid) {
continue;
}
let ids: Vec<u32> = shards.iter().map(|(_, sid)| *sid).collect();
work.push((loc_idx, key, ids));
}
}
for (loc_idx, key, ids) in work {
let loc_dir = self.locations[loc_idx].directory.clone();
let loc = &mut self.locations[loc_idx];
if let Err(e) = loc.mount_ec_shards(key.vid, &key.collection, &ids, "") {
error!(
volume_id = key.vid.0,
directory = %loc_dir,
"load after index recovery failed: {}",
e,
);
}
}
}
}
#[cfg(test)]
@@ -944,6 +1021,103 @@ mod tests {
}
}
#[test]
fn test_collect_missing_index_recovers_cross_server_orphan() {
// Reproduces issue #10104: shards spread across this server's disks with
// no .ecx anywhere local. collect_ec_volumes_missing_index must surface
// the volume; after the index lands on the orphan disk (as a peer fetch
// would deliver it), mount_recovered_ec_shards mounts all shards.
let tmp = TempDir::new().unwrap();
let dir0 = tmp.path().join("data0");
let dir1 = tmp.path().join("data1");
std::fs::create_dir_all(&dir0).unwrap();
std::fs::create_dir_all(&dir1).unwrap();
let collection = "video-recordings";
let vid = 6190u32;
write_shard(dir0.to_str().unwrap(), collection, vid, 0);
write_shard(dir0.to_str().unwrap(), collection, vid, 5);
write_shard(dir1.to_str().unwrap(), collection, vid, 6);
let mut store = Store::new(NeedleMapKind::InMemory);
for d in [&dir0, &dir1] {
store
.add_location(
d.to_str().unwrap(),
d.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
// Bug state: nothing mounted.
assert!(store.locations[0].find_ec_volume(VolumeId(vid)).is_none());
let missing = store.collect_ec_volumes_missing_index();
let m = missing
.iter()
.find(|m| m.vid == VolumeId(vid) && m.collection == collection)
.expect("cross-server orphan not reported");
// Simulate the peer fetch dropping the index onto the orphan disk.
write_index_files(&m.idx_dir, collection, vid, 10, 4);
store.mount_recovered_ec_shards();
let ev0 = store.locations[0]
.find_ec_volume(VolumeId(vid))
.expect("dir0 not mounted after recovery");
assert!(ev0.has_shard(0) && ev0.has_shard(5), "dir0 shards missing");
let ev1 = store.locations[1]
.find_ec_volume(VolumeId(vid))
.expect("dir1 not mounted after recovery");
assert!(ev1.has_shard(6), "dir1 shard missing");
// Nothing left to recover.
assert!(store
.collect_ec_volumes_missing_index()
.iter()
.all(|m| m.vid != VolumeId(vid)));
}
#[test]
fn test_collect_missing_index_excludes_cross_disk_orphan() {
// A .ecx merely on a sibling disk is the same-server case the reconcile
// already handles; it must not be reported as a cross-server orphan.
let tmp = TempDir::new().unwrap();
let dir0 = tmp.path().join("data0");
let dir1 = tmp.path().join("data1");
std::fs::create_dir_all(&dir0).unwrap();
std::fs::create_dir_all(&dir1).unwrap();
let collection = "mybucket";
let vid = 42u32;
write_shard(dir0.to_str().unwrap(), collection, vid, 3);
write_index_files(dir1.to_str().unwrap(), collection, vid, 10, 4);
let mut store = Store::new(NeedleMapKind::InMemory);
for d in [&dir0, &dir1] {
store
.add_location(
d.to_str().unwrap(),
d.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
assert!(store
.collect_ec_volumes_missing_index()
.iter()
.all(|m| m.vid != VolumeId(vid)));
}
/// Helper: build a 2-disk store where reconcile produces the
/// cross-disk split layout (shards 0/12 on dir0, shard 1 + .ecx
/// on dir1). Mirrors the report-from-the-issue layout that
+236 -108
View File
@@ -455,6 +455,19 @@ pub(crate) struct RemoteDatFile {
}
impl RemoteDatFile {
/// Read up to `size` bytes at `offset`, bounded by the remote file size.
/// Mirrors `Volume::read_dat_slice` for a remote-only backend, but holds no
/// volume/store lock so callers can stream off the store lock entirely.
pub(crate) fn read_slice(&self, offset: u64, size: usize) -> io::Result<Vec<u8>> {
if size == 0 || offset >= self.file_size {
return Ok(Vec::new());
}
let read_len = std::cmp::min(size as u64, self.file_size - offset) as usize;
let mut buf = vec![0u8; read_len];
self.read_exact_at(&mut buf, offset)?;
Ok(buf)
}
pub(crate) fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
let data = self
.backend
@@ -936,7 +949,7 @@ impl Volume {
Ok(())
}
fn load_remote_dat_file(&mut self) -> Result<(), VolumeError> {
pub(crate) fn load_remote_dat_file(&mut self) -> Result<(), VolumeError> {
let (storage_name, storage_key) = self.remote_storage_name_key();
let backend = crate::remote_storage::s3_tier::global_s3_tier_registry()
.read()
@@ -1037,6 +1050,14 @@ impl Volume {
Ok(buf)
}
/// Clone the remote backend handle (cheap: an `Arc` plus key/size) so a
/// caller can stream a tiered `.dat` from S3 after dropping the store lock.
/// Returns `None` for local volumes. `has_remote_file` implies `dat_file`
/// is `None`, so this selects the same backend `read_dat_slice` would.
pub(crate) fn remote_dat_file(&self) -> Option<RemoteDatFile> {
self.remote_dat_file.clone()
}
// ---- SuperBlock I/O ----
fn read_super_block(&mut self) -> Result<(), VolumeError> {
@@ -1945,136 +1966,134 @@ impl Volume {
Ok(())
}
/// Scrub the volume index by verifying each needle map entry against the dat file.
/// For each entry, reads only the 16-byte needle header at the given offset to verify:
/// correct needle ID, correct cookie (non-zero), and valid size.
/// Does NOT read/verify the full needle data or CRC.
/// Returns (files_checked, broken_needles) tuple.
pub fn scrub_index(&self) -> Result<(u64, Vec<String>), VolumeError> {
if self.dat_file.is_none() && self.remote_dat_file.is_none() {
return Err(VolumeError::NotFound);
}
let nm = self.nm_or_not_found()?;
let dat_size = self.dat_file_size().map_err(VolumeError::Io)?;
let mut files_checked: u64 = 0;
let mut broken = Vec::new();
for (needle_id, nv) in nm.iter_entries() {
if nv.offset.is_zero() || nv.size.is_deleted() {
continue;
}
let offset = nv.offset.to_actual_offset();
if offset < 0 || offset as u64 >= dat_size {
broken.push(format!(
"needle {} offset {} out of range (dat_size={})",
needle_id.0, offset, dat_size
));
continue;
}
// Read only the 16-byte needle header to verify ID, cookie, and size
let mut header_buf = [0u8; NEEDLE_HEADER_SIZE];
match self.read_exact_at_backend(&mut header_buf, offset as u64) {
Ok(()) => {
let (cookie, id, size) = Needle::parse_header(&header_buf);
if id != needle_id {
broken.push(format!(
"needle {} header id mismatch: expected {}, got {}",
needle_id.0, needle_id.0, id.0
));
} else if cookie.0 == 0 {
broken.push(format!(
"needle {} has zero cookie at offset {}",
needle_id.0, offset
));
} else if size.0 <= 0 && !nv.size.is_deleted() {
broken.push(format!(
"needle {} has invalid size {} at offset {}",
needle_id.0, size.0, offset
));
}
/// Open the on-disk .idx for scrubbing and apply Go openIndex's zero-size
/// guard: a zero-size index is only legal for a pre-allocated volume whose
/// .dat is superblock-only; an empty index over a populated .dat is
/// corruption. Returns the open file + size, or the messages to report.
fn open_index_for_scrub(&self) -> Result<(File, i64), Vec<String>> {
let idx_path = self.file_name(".idx");
let idx_file =
File::open(&idx_path).map_err(|e| vec![format!("open index file {}: {}", idx_path, e)])?;
let idx_file_size = idx_file
.metadata()
.map_err(|e| vec![format!("stat index file {}: {}", idx_path, e)])?
.len() as i64;
if idx_file_size == 0 {
match self.dat_file_size() {
Ok(dat_size) if dat_size > SUPER_BLOCK_SIZE as u64 => {
return Err(vec![format!(
"zero-size IDX file for volume {} with store size {}",
self.id.0, dat_size
)]);
}
Ok(_) => {}
Err(e) => {
broken.push(format!("needle {} read header error: {}", needle_id.0, e));
return Err(vec![format!(
"stat data file for volume {}: {}",
self.id.0, e
)])
}
}
files_checked += 1;
}
Ok((files_checked, broken))
Ok((idx_file, idx_file_size))
}
/// Scrub the volume by reading and verifying all needles.
/// Returns (files_checked, broken_needles) tuple.
/// Each needle is read from disk and its CRC checksum is verified.
/// Scrub the volume index: verify the on-disk .idx for overlapping needles
/// and a size that is a whole number of entries. Mirrors Go's Volume.ScrubIndex
/// → idx.CheckIndexFile. Index-only; does not read the .dat.
pub fn scrub_index(&self) -> Result<(u64, Vec<String>), VolumeError> {
let _guard = self.data_file_access_control.read_lock();
let (mut idx_file, idx_file_size) = match self.open_index_for_scrub() {
Ok(v) => v,
Err(msgs) => return Ok((0, msgs)),
};
Ok(crate::storage::idx::check_index_file(
&mut idx_file,
idx_file_size,
self.version(),
))
}
/// Scrub the volume: walk the on-disk .idx (every physical row, including
/// superseded and deleted entries), CRC-verify each live needle, and reconcile
/// the .dat size against the needles it indexes. Mirrors Go's Volume.Scrub →
/// scrubVolumeData. Returns (rows_walked, broken_needles).
pub fn scrub(&self) -> Result<(u64, Vec<String>), VolumeError> {
if self.dat_file.is_none() && self.remote_dat_file.is_none() {
// Matches Go's scrubVolumeData: a volume with no data backend can't be
// scrubbed (and a zero dat_size would flag every needle out of range).
if !self.has_data_backend() {
return Err(VolumeError::NotFound);
}
let nm = self.nm_or_not_found()?;
let _guard = self.data_file_access_control.read_lock();
let (mut idx_file, idx_file_size) = match self.open_index_for_scrub() {
Ok(v) => v,
Err(msgs) => return Ok((0, msgs)),
};
let dat_size = self.dat_file_size().map_err(|e| VolumeError::Io(e))?;
let version = self.version();
let dat_size = self.dat_file_size().map_err(VolumeError::Io)?;
let mut files_checked: u64 = 0;
let mut broken = Vec::new();
// Full scrub also runs the index structural check.
let (_, mut broken) =
crate::storage::idx::check_index_file(&mut idx_file, idx_file_size, version);
let mut count: u64 = 0;
let mut total_read: i64 = 0;
for (needle_id, nv) in nm.iter_entries() {
if nv.offset.is_zero() {
continue;
let walk = crate::storage::idx::walk_index_file(&mut idx_file, 0, |needle_id, offset, size| {
count += 1;
// A remote-tier delete records an offset-0 tombstone with no physical
// .dat bytes, so it must not contribute to total_read.
if offset.is_zero() && size.is_deleted() {
return Ok(());
}
// Accumulate actual needle size for ALL entries including deleted ones
// (matches Go: deleted needles still occupy space in the .dat file).
total_read += get_actual_size(nv.size, version);
if nv.size.is_deleted() {
continue;
// Deleted needles still occupy .dat space: count their size, don't read.
total_read += get_actual_size(size, version);
if size.is_deleted() {
return Ok(());
}
let offset = nv.offset.to_actual_offset();
if offset < 0 || offset as u64 >= dat_size {
let actual_offset = offset.to_actual_offset();
if actual_offset < 0 || actual_offset as u64 >= dat_size {
broken.push(format!(
"needle {} offset {} out of range (dat_size={})",
needle_id.0, offset, dat_size
needle_id.0, actual_offset, dat_size
));
continue;
return Ok(());
}
// Read and verify the needle (read_needle_data_at checks CRC via read_bytes/read_tail)
// Lock held above; read directly via the unlocked path (matches Go).
let mut n = Needle {
id: needle_id,
..Needle::default()
};
match self.read_needle_data_at(&mut n, offset, nv.size) {
Ok(_) => {}
Err(e) => {
broken.push(format!("needle {} error: {}", needle_id.0, e));
}
let mut read_option = ReadOption::default();
if let Err(e) =
self.read_needle_data_at_unlocked(&mut n, actual_offset, size, &mut read_option)
{
broken.push(format!(
"failed to read needle {} on volume {}: {}",
needle_id.0, self.id.0, e
));
}
files_checked += 1;
Ok(())
});
if let Err(e) = walk {
broken.push(format!("walk index file: {}", e));
}
// Validate total data size against .dat file size (matches Go's scrubVolumeData)
let expected_size = total_read + SUPER_BLOCK_SIZE as i64;
if (dat_size as i64) < expected_size {
// Reconcile the physical .dat size against the needles read.
let want_size = total_read + SUPER_BLOCK_SIZE as i64;
if (dat_size as i64) < want_size {
broken.push(format!(
"dat file size {} is smaller than expected {} (total_read {} + super_block {})",
dat_size, expected_size, total_read, SUPER_BLOCK_SIZE
"data file for volume {} is smaller ({}) than the {} needles it contains ({})",
self.id.0, dat_size, count, want_size
));
} else if dat_size as i64 != expected_size {
} else if dat_size as i64 != want_size {
broken.push(format!(
"warning: dat file size {} does not match expected {} (total_read {} + super_block {})",
dat_size, expected_size, total_read, SUPER_BLOCK_SIZE
"data file size for volume {} ({}) doesn't match the size for {} needles read ({})",
self.id.0, dat_size, count, want_size
));
}
Ok((files_checked, broken))
Ok((count, broken))
}
/// Scan raw needle entries from the .dat file starting at `from_offset`.
@@ -2204,16 +2223,16 @@ impl Volume {
}
}
/// Close the local .dat file handle (matches Go's v.DataBackend.Close() in LoadRemoteFile).
/// Called after tier-upload when the local file is being replaced by remote storage.
pub fn close_local_dat_backend(&mut self) {
self.dat_file = None;
}
/// Close the remote dat file backend (matches Go's v.DataBackend.Close(); v.DataBackend = nil).
/// Called after tier-download when the remote backend is being replaced by local storage.
pub fn close_remote_dat_backend(&mut self) {
/// Open the local .dat as the data backend, dropping any remote backend, so reads
/// are served from local disk. Mirrors Go's swapToLocalDatBackend after a tier-down.
pub(crate) fn open_local_dat_backend(&mut self) -> Result<(), VolumeError> {
let file = OpenOptions::new()
.read(true)
.write(true)
.open(self.dat_path())?;
self.remote_dat_file = None;
self.dat_file = Some(file);
Ok(())
}
/// Path to .vif file.
@@ -2351,7 +2370,15 @@ impl Volume {
let vif = VifVolumeInfo::from_pb(&self.volume_info);
let content = serde_json::to_string_pretty(&vif)
.map_err(|e| VolumeError::Io(io::Error::new(io::ErrorKind::Other, e.to_string())))?;
fs::write(&self.vif_path(), content)?;
// fsync the .vif so a tiered volume's remote reference is durable before the
// caller acts on it, e.g. deletes the remote object (matches Go util.WriteFile).
let mut f = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(self.vif_path())?;
f.write_all(content.as_bytes())?;
f.sync_all()?;
Ok(())
}
@@ -3885,6 +3912,107 @@ mod tests {
);
}
#[test]
fn test_scrub_overwritten_volume_scrubs_clean() {
// An overwrite/delete appends a second .dat record + .idx row. Walking
// the on-disk .idx (not the deduped map) makes total_read match the
// physical .dat, so a healthy overwritten volume is NOT flagged broken.
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = make_test_volume(dir);
for (id, body) in [(1u64, "first version"), (1, "second version"), (2, "other")] {
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(id as u32),
data: body.as_bytes().to_vec(),
data_size: body.len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true).unwrap();
}
v.sync_to_disk().unwrap();
let (count, broken) = v.scrub().unwrap();
assert!(
broken.is_empty(),
"overwritten volume should scrub clean, got {:?}",
broken
);
assert_eq!(count, 3, "scrub must count every .idx row");
}
#[test]
fn test_scrub_ignores_offset0_tombstone() {
// A remote-tier delete appends an offset-0 tombstone to the .idx with no
// physical .dat bytes; it must not flag the volume (neither the size
// reconcile nor the structural overlap check).
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = make_test_volume(dir);
let data = b"needle data".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.sync_to_disk().unwrap();
// Append an offset-0 logical tombstone to the on-disk .idx.
let mut f = std::fs::OpenOptions::new()
.append(true)
.open(v.file_name(".idx"))
.unwrap();
crate::storage::idx::write_index_entry(&mut f, NeedleId(2), Offset::from_actual_offset(0), Size(-1))
.unwrap();
f.sync_all().unwrap();
drop(f);
let (count, broken) = v.scrub().unwrap();
assert!(
broken.is_empty(),
"offset-0 tombstone must not flag the volume, got {:?}",
broken
);
assert_eq!(count, 2, "both .idx rows are walked");
}
#[test]
fn test_scrub_index_flags_zero_size_idx_with_data() {
// A populated .dat with an empty .idx is corruption — the pre-allocated
// exception only covers a superblock-only .dat.
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let mut v = make_test_volume(dir);
let data = b"needle data".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.sync_to_disk().unwrap();
assert!(v.dat_file_size().unwrap() > SUPER_BLOCK_SIZE as u64);
// Truncate the .idx to zero while the .dat keeps its needle.
std::fs::File::create(v.file_name(".idx")).unwrap();
let (count, broken) = v.scrub_index().unwrap();
assert_eq!(count, 0);
assert!(
broken.iter().any(|e| e.contains("zero-size IDX file")),
"expected zero-size IDX error, got {:?}",
broken
);
}
#[test]
fn test_scrub_healthy_volume() {
// Mirror of Go's TestScrubVolumeData "healthy volume" case: a volume
+158 -2
View File
@@ -38,10 +38,27 @@ fn test_state_with_whitelist(whitelist: Vec<String>) -> (Arc<VolumeServerState>,
fn test_state_with_guard(
whitelist: Vec<String>,
signing_key: Vec<u8>,
) -> (Arc<VolumeServerState>, TempDir) {
build_test_state(whitelist, signing_key, None, String::new())
}
/// Build a test state with volume 1 created using the given replica placement
/// (e.g. "001" for a two-copy volume) and master URL. An empty master URL plus
/// a None placement is the single-copy default used by most tests.
fn build_test_state(
whitelist: Vec<String>,
signing_key: Vec<u8>,
replication: Option<&str>,
master_url: String,
) -> (Arc<VolumeServerState>, TempDir) {
let tmp = TempDir::new().expect("failed to create temp dir");
let dir = tmp.path().to_str().unwrap();
let replica_placement = replication.map(|s| {
seaweed_volume::storage::super_block::ReplicaPlacement::from_string(s)
.expect("invalid replica placement")
});
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
@@ -57,7 +74,7 @@ fn test_state_with_guard(
.add_volume(
VolumeId(1),
"",
None,
replica_placement,
None,
0,
DiskType::HardDrive,
@@ -100,7 +117,7 @@ fn test_state_with_guard(
),
read_mode: seaweed_volume::config::ReadMode::Local,
allow_untrusted_remote_endpoints: false,
master_url: String::new(),
master_url,
master_urls: Vec::new(),
seed_master_set: std::collections::HashSet::new(),
current_master_url: tokio::sync::RwLock::new(String::new()),
@@ -678,3 +695,142 @@ async fn admin_router_serves_volume_ui_static_assets() {
let body = body_bytes(response).await;
assert!(body.len() > 1000);
}
// ============================================================================
// Replicated (fan-out) writes
//
// A chunked S3 upload has the gateway write every replica holder directly with
// `type=replicate` instead of relaying through the primary volume. Each holder
// must accept the copy and store it locally without re-replicating. These tests
// pin that contract on the Rust volume server.
// ============================================================================
/// Raw-body `type=replicate` write is stored and reads back.
#[tokio::test]
async fn replicate_write_raw_body_is_stored() {
let (state, _tmp) = test_state();
let uri = "/1,01637037d6?type=replicate";
let payload = b"fan-out replica bytes";
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri(uri)
.body(Body::from(payload.to_vec()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.uri("/1,01637037d6")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_bytes(response).await, payload);
}
/// Multipart `type=replicate` write (the shape the Go gateway uploader sends)
/// is stored and reads back.
#[tokio::test]
async fn replicate_write_multipart_body_is_stored() {
let (state, _tmp) = test_state();
let boundary = "----replicateboundary";
let payload = b"fan-out replica bytes";
let mut body = Vec::new();
body.extend_from_slice(format!("--{}\r\n", boundary).as_bytes());
body.extend_from_slice(
b"Content-Disposition: form-data; name=\"file\"; filename=\"chunk\"\r\n",
);
body.extend_from_slice(b"Content-Type: application/octet-stream\r\n\r\n");
body.extend_from_slice(payload);
body.extend_from_slice(format!("\r\n--{}--\r\n", boundary).as_bytes());
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/1,01637037d6?type=replicate")
.header(
"Content-Type",
format!("multipart/form-data; boundary={}", boundary),
)
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.uri("/1,01637037d6")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_bytes(response).await, payload);
}
/// On a multi-copy volume, a `type=replicate` write must store locally without
/// re-replicating: it must not contact the master, even an unreachable one.
/// A plain write to the same volume does attempt replication and fails against
/// the dead master, which proves the `type=replicate` flag is what suppresses
/// the fan-out (not a disabled replication path).
#[tokio::test]
async fn replicate_write_does_not_re_replicate() {
// Port 0 is rejected by the socket layer immediately, so a stray lookup
// fails fast instead of hanging on a connect timeout in firewalled CI.
let dead_master = "127.0.0.1:0".to_string();
let (state, _tmp) = build_test_state(Vec::new(), Vec::new(), Some("001"), dead_master);
// type=replicate: stored locally, no master lookup -> 201.
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/1,01637037d6?type=replicate")
.body(Body::from(b"replicated copy".to_vec()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::CREATED,
"replicate write must not depend on the master"
);
// plain write: tries to fan out to the dead master and fails.
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/1,02637037d7")
.body(Body::from(b"primary copy".to_vec()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::INTERNAL_SERVER_ERROR,
"plain write to a multi-copy volume must attempt replication"
);
}
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Sample resident memory of one or more processes once per second.
# Usage: mem_sample.sh <out.csv> <label=pid> [label=pid ...]
#
# Writes a per-second time series to <out.csv> and, on stop, the peak
# resident set (VmHWM) per process to <out.csv>.peak. Stop with SIGTERM/SIGINT;
# if a process already exited, its peak falls back to the max RSS sampled.
# Linux only (reads /proc/<pid>/status).
set -u
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <out.csv> <label=pid> [label=pid ...]" >&2
exit 1
fi
out="$1"; shift
labels=(); pids=(); peaks=()
for arg in "$@"; do
labels+=("${arg%%=*}")
pids+=("${arg#*=}")
peaks+=(0)
done
record_peaks() {
local total=0 i hwm
: > "${out}.peak"
for i in "${!pids[@]}"; do
hwm="$(awk '/^VmHWM:/{print $2}' "/proc/${pids[$i]}/status" 2>/dev/null)"
if [ -z "$hwm" ] || [ "$hwm" -eq 0 ]; then
hwm="${peaks[$i]}"
fi
printf '%s\t%s\n' "${labels[$i]}" "$hwm" >> "${out}.peak"
total=$((total + hwm))
done
printf 'total\t%s\n' "$total" >> "${out}.peak"
exit 0
}
trap record_peaks TERM INT
header="epoch"
for l in "${labels[@]}"; do header+=",${l}_rss_kb"; done
header+=",total_rss_kb"
echo "$header" > "$out"
while true; do
line="$(date +%s)"; total=0
for i in "${!pids[@]}"; do
p="${pids[$i]}"
rss="$(awk '/^VmRSS:/{print $2}' "/proc/$p/status" 2>/dev/null)"
rss="${rss:-0}"
if [ "$rss" -gt "${peaks[$i]}" ]; then
peaks[$i]="$rss"
fi
line+=",${rss}"
total=$((total + rss))
done
echo "${line},${total}" >> "$out"
# Sleep via a background child + wait so a caught signal interrupts promptly.
sleep 1 &
wait $! 2>/dev/null
done
+223
View File
@@ -0,0 +1,223 @@
// Command s3_benchmark drives concurrent PUT and GET load against an S3
// gateway and reports throughput and latency. It is a self-contained load
// generator for the performance CI, using the aws-sdk-go-v2 client the rest
// of the S3 tests already depend on.
package main
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
)
func main() {
endpoint := flag.String("endpoint", "http://localhost:8000", "S3 gateway endpoint")
accessKey := flag.String("access-key", "some_access_key1", "S3 access key")
secretKey := flag.String("secret-key", "some_secret_key1", "S3 secret key")
region := flag.String("region", "us-east-1", "S3 region")
bucket := flag.String("bucket", "perf-benchmark", "bucket to write into")
objects := flag.Int("objects", 10000, "number of objects")
size := flag.Int("size", 1024, "object size in bytes")
concurrency := flag.Int("concurrency", 16, "concurrent workers")
mode := flag.String("mode", "both", "write, read, or both")
flag.Parse()
cfg, err := config.LoadDefaultConfig(context.Background(),
config.WithRegion(*region),
config.WithRetryMaxAttempts(1),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(*accessKey, *secretKey, "")),
)
if err != nil {
fatalf("load aws config: %v", err)
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(*endpoint)
o.UsePathStyle = true
})
if err := ensureBucket(client, *bucket); err != nil {
fatalf("ensure bucket: %v", err)
}
payload := make([]byte, *size)
for i := range payload {
payload[i] = byte(i)
}
doWrite := *mode == "both" || *mode == "write"
doRead := *mode == "both" || *mode == "read"
if doWrite {
report("S3 WRITE", *concurrency, *size, run(*concurrency, *objects, func(key string) error {
_, err := client.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: bucket,
Key: aws.String(key),
Body: bytes.NewReader(payload),
ContentLength: aws.Int64(int64(*size)),
})
return err
}))
}
if doRead {
report("S3 READ", *concurrency, *size, run(*concurrency, *objects, func(key string) error {
out, err := client.GetObject(context.Background(), &s3.GetObjectInput{
Bucket: bucket,
Key: aws.String(key),
})
if err != nil {
return err
}
defer out.Body.Close()
_, err = io.Copy(io.Discard, out.Body)
return err
}))
}
}
type result struct {
completed int64
failed int64
elapsed time.Duration
latencies []time.Duration
firstErr error
}
// run fans `total` keyed operations across `workers` goroutines, timing each.
func run(workers, total int, op func(key string) error) result {
var (
completed, failed, nextKey atomic.Int64
mu sync.Mutex
firstErr error
latencies = make([]time.Duration, 0, total)
wg sync.WaitGroup
)
start := time.Now()
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
local := make([]time.Duration, 0, total/workers+1)
for {
i := nextKey.Add(1) - 1
if i >= int64(total) {
break
}
key := fmt.Sprintf("obj-%d", i)
opStart := time.Now()
err := op(key)
local = append(local, time.Since(opStart))
if err != nil {
failed.Add(1)
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
continue
}
completed.Add(1)
}
mu.Lock()
latencies = append(latencies, local...)
mu.Unlock()
}()
}
wg.Wait()
return result{
completed: completed.Load(),
failed: failed.Load(),
elapsed: time.Since(start),
latencies: latencies,
firstErr: firstErr,
}
}
func report(label string, concurrency, size int, r result) {
secs := r.elapsed.Seconds()
transferred := r.completed * int64(size)
rps := 0.0
kbps := 0.0
if secs > 0 {
rps = float64(r.completed) / secs
kbps = float64(transferred) / 1024 / secs
}
fmt.Printf("\n%s results:\n", label)
fmt.Printf("Concurrency Level: %d\n", concurrency)
fmt.Printf("Time taken for tests: %.3f seconds\n", secs)
fmt.Printf("Completed requests: %d\n", r.completed)
fmt.Printf("Failed requests: %d\n", r.failed)
fmt.Printf("Total transferred: %d bytes\n", transferred)
fmt.Printf("Requests per second: %.2f [#/sec]\n", rps)
fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", kbps)
p := percentiles(r.latencies)
fmt.Printf("Latency (ms): avg=%.2f p50=%.2f p90=%.2f p99=%.2f max=%.2f\n",
ms(p.avg), ms(p.p50), ms(p.p90), ms(p.p99), ms(p.max))
if r.failed > 0 && r.firstErr != nil {
fmt.Printf("First error: %v\n", r.firstErr)
os.Exit(1)
}
}
type latencyStats struct {
avg, p50, p90, p99, max time.Duration
}
func percentiles(d []time.Duration) latencyStats {
if len(d) == 0 {
return latencyStats{}
}
slices.Sort(d)
var sum time.Duration
for _, v := range d {
sum += v
}
at := func(q float64) time.Duration {
idx := int(q * float64(len(d)))
if idx >= len(d) {
idx = len(d) - 1
}
return d[idx]
}
return latencyStats{
avg: sum / time.Duration(len(d)),
p50: at(0.50),
p90: at(0.90),
p99: at(0.99),
max: d[len(d)-1],
}
}
func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
func ensureBucket(client *s3.Client, bucket string) error {
_, err := client.CreateBucket(context.Background(), &s3.CreateBucketInput{Bucket: aws.String(bucket)})
if err == nil {
return nil
}
var owned *types.BucketAlreadyOwnedByYou
var exists *types.BucketAlreadyExists
if errors.As(err, &owned) || errors.As(err, &exists) {
return nil
}
return err
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
}
+4
View File
@@ -1088,6 +1088,10 @@ func (cp *ConfigPersistence) loadTaskStateLocked(taskID string) (*maintenance.Ma
return nil, fmt.Errorf("failed to unmarshal task state protobuf: %w", err)
}
if taskStateFile.Task == nil {
return nil, fmt.Errorf("task state file %s contains no task data", taskID)
}
// Convert protobuf to maintenance task
task := cp.protobufToMaintenanceTask(taskStateFile.Task)
@@ -242,14 +242,6 @@ templ ClusterEcShards(data dash.ClusterEcShardsData) {
title="View EC volume details">
<i class="fas fa-info-circle"></i>
</button>
if !shard.IsComplete {
<button type="button" class="btn btn-sm btn-outline-warning"
onclick="repairVolume(event)"
data-volume-id={ fmt.Sprintf("%d", shard.VolumeID) }
title="Repair missing shards">
<i class="fas fa-wrench"></i>
</button>
}
</div>
</td>
</tr>
@@ -388,32 +380,6 @@ templ ClusterEcShards(data dash.ClusterEcShardsData) {
window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;
}
function repairVolume(event) {
// Get data from the button element (not the icon inside it)
const button = event.target.closest('button');
const volumeId = button.getAttribute('data-volume-id');
showConfirm(`Are you sure you want to repair missing shards for volume ${volumeId}?`, function() {
fetch((window.__BASE_PATH__ || '') + `/api/storage/volumes/${volumeId}/repair`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
showAlert('Repair initiated successfully', 'success');
location.reload();
} else {
showAlert('Failed to initiate repair: ' + data.error, 'error');
}
})
.catch(error => {
showAlert('Error: ' + error.message, 'error');
});
});
}
</script>
}
+126 -149
View File
@@ -479,230 +479,207 @@ func ClusterEcShards(data dash.ClusterEcShardsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "\" title=\"View EC volume details\"><i class=\"fas fa-info-circle\"></i></button> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "\" title=\"View EC volume details\"><i class=\"fas fa-info-circle\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if !shard.IsComplete {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "<button type=\"button\" class=\"btn btn-sm btn-outline-warning\" onclick=\"repairVolume(event)\" data-volume-id=\"")
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "</tbody></table></div><!-- Pagination -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "<nav aria-label=\"EC Shards pagination\"><ul class=\"pagination justify-content-center\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", shard.VolumeID))
templ_7745c5c3_Var16, 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/cluster_ec_shards.templ`, Line: 248, Col: 94}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 259, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "\" title=\"Repair missing shards\"><i class=\"fas fa-wrench\"></i></button>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "</div></td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "<!-- First page -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "</tbody></table></div><!-- Pagination -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "<nav aria-label=\"EC Shards pagination\"><ul class=\"pagination justify-content-center\">")
if data.CurrentPage > 3 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(1)\">1</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 4 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "<!-- Current page and neighbors -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if data.CurrentPage > 1 && data.CurrentPage-1 >= 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, 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/cluster_ec_shards.templ`, Line: 267, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 280, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "<!-- First page -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 3 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(1)\">1</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 4 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "<!-- Current page and neighbors -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage > 1 && data.CurrentPage-1 >= 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, 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/cluster_ec_shards.templ`, Line: 288, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 280, Col: 170}
}
_, 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, 77, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, 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/cluster_ec_shards.templ`, Line: 288, Col: 170}
}
_, 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, 78, "</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "<li class=\"page-item active\"><span class=\"page-link\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "<li class=\"page-item active\"><span class=\"page-link\">")
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", data.CurrentPage))
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 293, Col: 80}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 285, Col: 80}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
_, 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, 80, "</span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage < data.TotalPages && data.CurrentPage+1 <= data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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", data.CurrentPage+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 290, Col: 129}
}
_, 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, 79, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, 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/cluster_ec_shards.templ`, Line: 298, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 290, Col: 170}
}
_, 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, 82, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, 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/cluster_ec_shards.templ`, Line: 298, Col: 170}
}
_, 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, 83, "</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "<!-- Last page -->")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "<!-- Last page -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.CurrentPage < data.TotalPages-2 {
if data.CurrentPage < data.TotalPages-3 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, " <li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, " <li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 302, Col: 126}
}
_, 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, 84, "\">")
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", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 310, Col: 126}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 302, Col: 164}
}
_, 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, 87, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 310, Col: 164}
}
_, 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, 88, "</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if data.CurrentPage < data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, 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/cluster_ec_shards.templ`, Line: 316, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 308, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
_, 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, 90, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
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
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</ul></nav>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "</ul></nav>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "<!-- JavaScript --><script>\n function sortBy(field) {\n const currentSort = \"{data.SortBy}\";\n const currentOrder = \"{data.SortOrder}\";\n let newOrder = 'asc';\n \n if (currentSort === field && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n updateUrl({\n sortBy: field,\n sortOrder: newOrder,\n page: 1\n });\n }\n\n function goToPage(arg) {\n let page;\n if (typeof arg === 'number' || typeof arg === 'string') {\n page = arg;\n } else {\n // Get data from the link element (not any child elements)\n const link = arg.target.closest('a');\n page = link.getAttribute('data-page');\n }\n updateUrl({ page: page });\n }\n\n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n updateUrl({ pageSize: pageSize, page: 1 });\n }\n\n function updateUrl(params) {\n const url = new URL(window.location);\n Object.keys(params).forEach(key => {\n if (params[key]) {\n url.searchParams.set(key, params[key]);\n } else {\n url.searchParams.delete(key);\n }\n });\n window.location.href = url.toString();\n }\n\n function exportEcShards() {\n const url = new URL((window.__BASE_PATH__ || '') + '/api/storage/ec-shards/export', window.location.origin);\n const params = new URLSearchParams(window.location.search);\n params.forEach((value, key) => {\n url.searchParams.set(key, value);\n });\n window.open(url.toString(), '_blank');\n }\n\n function showShardDetails(event) {\n // Get data from the button element (not the icon inside it)\n const button = event.target.closest('button');\n const volumeId = button.getAttribute('data-volume-id');\n \n // Navigate to the EC volume details page\n window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;\n }\n\n function repairVolume(event) {\n // Get data from the button element (not the icon inside it)\n const button = event.target.closest('button');\n const volumeId = button.getAttribute('data-volume-id');\n showConfirm(`Are you sure you want to repair missing shards for volume ${volumeId}?`, function() {\n fetch((window.__BASE_PATH__ || '') + `/api/storage/volumes/${volumeId}/repair`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Repair initiated successfully', 'success');\n location.reload();\n } else {\n showAlert('Failed to initiate repair: ' + data.error, 'error');\n }\n })\n .catch(error => {\n showAlert('Error: ' + error.message, 'error');\n });\n });\n }\n\n </script>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "<!-- JavaScript --><script>\n function sortBy(field) {\n const currentSort = \"{data.SortBy}\";\n const currentOrder = \"{data.SortOrder}\";\n let newOrder = 'asc';\n \n if (currentSort === field && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n updateUrl({\n sortBy: field,\n sortOrder: newOrder,\n page: 1\n });\n }\n\n function goToPage(arg) {\n let page;\n if (typeof arg === 'number' || typeof arg === 'string') {\n page = arg;\n } else {\n // Get data from the link element (not any child elements)\n const link = arg.target.closest('a');\n page = link.getAttribute('data-page');\n }\n updateUrl({ page: page });\n }\n\n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n updateUrl({ pageSize: pageSize, page: 1 });\n }\n\n function updateUrl(params) {\n const url = new URL(window.location);\n Object.keys(params).forEach(key => {\n if (params[key]) {\n url.searchParams.set(key, params[key]);\n } else {\n url.searchParams.delete(key);\n }\n });\n window.location.href = url.toString();\n }\n\n function exportEcShards() {\n const url = new URL((window.__BASE_PATH__ || '') + '/api/storage/ec-shards/export', window.location.origin);\n const params = new URLSearchParams(window.location.search);\n params.forEach((value, key) => {\n url.searchParams.set(key, value);\n });\n window.open(url.toString(), '_blank');\n }\n\n function showShardDetails(event) {\n // Get data from the button element (not the icon inside it)\n const button = event.target.closest('button');\n const volumeId = button.getAttribute('data-volume-id');\n \n // Navigate to the EC volume details page\n window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;\n }\n\n </script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -727,25 +704,25 @@ func displayShardDistribution(shard dash.EcShardWithInfo, allShards []dash.EcSha
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var26 := templ.GetChildren(ctx)
if templ_7745c5c3_Var26 == nil {
templ_7745c5c3_Var26 = templ.NopComponent
templ_7745c5c3_Var25 := templ.GetChildren(ctx)
if templ_7745c5c3_Var25 == nil {
templ_7745c5c3_Var25 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "<div class=\"small\"><i class=\"fas fa-sitemap me-1\"></i> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "<div class=\"small\"><i class=\"fas fa-sitemap me-1\"></i> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(calculateDistributionSummary(shard.VolumeID, allShards))
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(calculateDistributionSummary(shard.VolumeID, allShards))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 424, Col: 65}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 390, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
_, 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, 94, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -770,86 +747,86 @@ func displayVolumeStatus(shard dash.EcShardWithInfo) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var28 := templ.GetChildren(ctx)
if templ_7745c5c3_Var28 == nil {
templ_7745c5c3_Var28 = templ.NopComponent
templ_7745c5c3_Var27 := templ.GetChildren(ctx)
if templ_7745c5c3_Var27 == nil {
templ_7745c5c3_Var27 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
if shard.IsComplete {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Complete</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Complete</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
if len(shard.MissingShards) > 10 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "<span class=\"badge bg-danger\"><i class=\"fas fa-skull me-1\"></i>Critical (")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "<span class=\"badge bg-danger\"><i class=\"fas fa-skull me-1\"></i>Critical (")
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", len(shard.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 400, Col: 129}
}
_, 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, 94, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if len(shard.MissingShards) > 6 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<span class=\"badge bg-warning\"><i class=\"fas fa-exclamation-triangle me-1\"></i>Degraded (")
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", len(shard.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 434, Col: 129}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 402, Col: 145}
}
_, 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, 97, " missing)</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if len(shard.MissingShards) > 6 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "<span class=\"badge bg-warning\"><i class=\"fas fa-exclamation-triangle me-1\"></i>Degraded (")
} else if len(shard.MissingShards) > 2 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "<span class=\"badge bg-warning\"><i class=\"fas fa-info-circle me-1\"></i>Incomplete (")
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", len(shard.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 436, Col: 145}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 404, Col: 138}
}
_, 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, 99, " missing)</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if len(shard.MissingShards) > 2 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, "<span class=\"badge bg-warning\"><i class=\"fas fa-info-circle me-1\"></i>Incomplete (")
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "<span class=\"badge bg-info\"><i class=\"fas fa-info-circle me-1\"></i>Minor Issues (")
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", len(shard.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 438, Col: 138}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 406, Col: 137}
}
_, 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, 101, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 102, "<span class=\"badge bg-info\"><i class=\"fas fa-info-circle me-1\"></i>Minor Issues (")
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", len(shard.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_shards.templ`, Line: 440, Col: 137}
}
_, 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, 103, " missing)</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -241,14 +241,6 @@ templ ClusterEcVolumes(data dash.ClusterEcVolumesData) {
title="View EC volume details">
<i class="fas fa-info-circle"></i>
</button>
if !volume.IsComplete {
<button type="button" class="btn btn-sm btn-outline-warning"
onclick="repairVolume(event)"
data-volume-id={ fmt.Sprintf("%d", volume.VolumeID) }
title="Repair missing shards">
<i class="fas fa-wrench"></i>
</button>
}
</div>
</td>
</tr>
@@ -376,34 +368,6 @@ templ ClusterEcVolumes(data dash.ClusterEcVolumesData) {
window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;
}
function repairVolume(event) {
const volumeId = event.target.closest('button').getAttribute('data-volume-id');
showConfirm(`Are you sure you want to repair missing shards for volume ${volumeId}?`, function() {
fetch((window.__BASE_PATH__ || '') + `/api/storage/ec-volumes/${volumeId}/repair`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
})
.then(data => {
if (data && data.success) {
showAlert('Repair initiated successfully', 'success');
location.reload();
} else {
showAlert('Failed to initiate repair: ' + (data && data.error ? data.error : 'Unknown error'), 'error');
}
})
.catch(error => {
showAlert('Error: ' + error.message, 'error');
});
});
}
</script>
}
+165 -188
View File
@@ -534,243 +534,220 @@ func ClusterEcVolumes(data dash.ClusterEcVolumesData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" title=\"View EC volume details\"><i class=\"fas fa-info-circle\"></i></button> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" title=\"View EC volume details\"><i class=\"fas fa-info-circle\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if !volume.IsComplete {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "<button type=\"button\" class=\"btn btn-sm btn-outline-warning\" onclick=\"repairVolume(event)\" data-volume-id=\"")
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "</tbody></table></div><!-- Pagination -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "<nav aria-label=\"EC Volumes pagination\"><ul class=\"pagination justify-content-center\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"1\"><i class=\"fas fa-angle-double-left\"></i></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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", volume.VolumeID))
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 247, Col: 95}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 263, Col: 122}
}
_, 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, 70, "\" title=\"Repair missing shards\"><i class=\"fas fa-wrench\"></i></button>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "</div></td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "<!-- First page -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "</tbody></table></div><!-- Pagination -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "<nav aria-label=\"EC Volumes pagination\"><ul class=\"pagination justify-content-center\">")
if data.Page > 3 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"1\">1</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 4 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "<!-- Current page neighbors -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"1\"><i class=\"fas fa-angle-double-left\"></i></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 271, Col: 122}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 284, Col: 122}
}
_, 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, 75, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "<!-- First page -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 3 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 77, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"1\">1</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 4 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "<!-- Current page neighbors -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 78, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 292, Col: 122}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 284, Col: 156}
}
_, 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, 81, "\">")
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", data.Page-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 292, Col: 156}
}
_, 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, 82, "</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "<li class=\"page-item active\"><span class=\"page-link\">")
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_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page))
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 297, Col: 73}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 289, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
_, 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, 84, "</span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page < data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 294, Col: 122}
}
_, 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, 83, "\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 302, Col: 122}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 294, Col: 156}
}
_, 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, 86, "\">")
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.Page+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 302, Col: 156}
}
_, 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, 87, "</a></li>")
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, 88, "<!-- Last page -->")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<!-- Last page -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page < data.TotalPages-2 {
if data.Page < data.TotalPages-3 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, " <li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, " <li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 306, Col: 126}
}
_, 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, 88, "\">")
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", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 314, Col: 126}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 306, Col: 164}
}
_, 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, 91, "\">")
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.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 314, Col: 164}
}
_, 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, 92, "</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if data.Page < data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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.Page+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 312, Col: 122}
}
_, 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, 91, "\"><i class=\"fas fa-chevron-right\"></i></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" 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.Page+1))
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 320, Col: 122}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 317, Col: 126}
}
_, 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, 94, "\"><i class=\"fas fa-chevron-right\"></i></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 325, Col: 126}
}
_, 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, 95, "\"><i class=\"fas fa-angle-double-right\"></i></a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "\"><i class=\"fas fa-angle-double-right\"></i></a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "</ul></nav>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "</ul></nav>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "<!-- JavaScript --><script>\n function sortBy(field) {\n const currentSort = new URLSearchParams(window.location.search).get('sort_by');\n const currentOrder = new URLSearchParams(window.location.search).get('sort_order') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === field && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n updateUrl({\n sort_by: field,\n sort_order: newOrder,\n page: 1\n });\n }\n\n function goToPage(event) {\n event.preventDefault();\n const page = event.target.closest('a').getAttribute('data-page');\n updateUrl({ page: page });\n }\n\n function changePageSize(newPageSize) {\n updateUrl({ page_size: newPageSize, page: 1 });\n }\n\n function updateUrl(params) {\n const url = new URL(window.location);\n Object.keys(params).forEach(key => {\n if (params[key] != null) {\n url.searchParams.set(key, params[key]);\n } else {\n url.searchParams.delete(key);\n }\n });\n window.location.href = url.toString();\n }\n\n function showVolumeDetails(event) {\n const volumeId = event.target.closest('button').getAttribute('data-volume-id');\n window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;\n }\n\n function repairVolume(event) {\n const volumeId = event.target.closest('button').getAttribute('data-volume-id');\n showConfirm(`Are you sure you want to repair missing shards for volume ${volumeId}?`, function() {\n fetch((window.__BASE_PATH__ || '') + `/api/storage/ec-volumes/${volumeId}/repair`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => {\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n return response.json();\n })\n .then(data => {\n if (data && data.success) {\n showAlert('Repair initiated successfully', 'success');\n location.reload();\n } else {\n showAlert('Failed to initiate repair: ' + (data && data.error ? data.error : 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n showAlert('Error: ' + error.message, 'error');\n });\n });\n }\n </script>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "<!-- JavaScript --><script>\n function sortBy(field) {\n const currentSort = new URLSearchParams(window.location.search).get('sort_by');\n const currentOrder = new URLSearchParams(window.location.search).get('sort_order') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === field && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n updateUrl({\n sort_by: field,\n sort_order: newOrder,\n page: 1\n });\n }\n\n function goToPage(event) {\n event.preventDefault();\n const page = event.target.closest('a').getAttribute('data-page');\n updateUrl({ page: page });\n }\n\n function changePageSize(newPageSize) {\n updateUrl({ page_size: newPageSize, page: 1 });\n }\n\n function updateUrl(params) {\n const url = new URL(window.location);\n Object.keys(params).forEach(key => {\n if (params[key] != null) {\n url.searchParams.set(key, params[key]);\n } else {\n url.searchParams.delete(key);\n }\n });\n window.location.href = url.toString();\n }\n\n function showVolumeDetails(event) {\n const volumeId = event.target.closest('button').getAttribute('data-volume-id');\n window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;\n }\n\n </script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -795,13 +772,13 @@ func displayShardSizes(shardSizes map[int]int64) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var31 := templ.GetChildren(ctx)
if templ_7745c5c3_Var31 == nil {
templ_7745c5c3_Var31 = templ.NopComponent
templ_7745c5c3_Var30 := templ.GetChildren(ctx)
if templ_7745c5c3_Var30 == nil {
templ_7745c5c3_Var30 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
if len(shardSizes) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "<span class=\"text-muted\">-</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<span class=\"text-muted\">-</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -832,44 +809,44 @@ func renderShardSizesContent(shardSizes map[int]int64) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var32 := templ.GetChildren(ctx)
if templ_7745c5c3_Var32 == nil {
templ_7745c5c3_Var32 = templ.NopComponent
templ_7745c5c3_Var31 := templ.GetChildren(ctx)
if templ_7745c5c3_Var31 == nil {
templ_7745c5c3_Var31 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
if areAllShardSizesSame(shardSizes) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, " <span class=\"text-success\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, " <span class=\"text-success\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(getCommonShardSize(shardSizes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 387, Col: 60}
}
_, 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, 97, "</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, " <div class=\"shard-sizes\" style=\"max-width: 300px;\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(getCommonShardSize(shardSizes))
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(formatIndividualShardSizes(shardSizes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 423, Col: 60}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 391, Col: 43}
}
_, 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, 100, "</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 101, " <div class=\"shard-sizes\" style=\"max-width: 300px;\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(formatIndividualShardSizes(shardSizes))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 427, Col: 43}
}
_, 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, 102, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -1059,25 +1036,25 @@ func displayVolumeDistribution(volume dash.EcVolumeWithShards) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var35 := templ.GetChildren(ctx)
if templ_7745c5c3_Var35 == nil {
templ_7745c5c3_Var35 = templ.NopComponent
templ_7745c5c3_Var34 := templ.GetChildren(ctx)
if templ_7745c5c3_Var34 == nil {
templ_7745c5c3_Var34 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 103, "<div class=\"small\"><i class=\"fas fa-sitemap me-1\"></i> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, "<div class=\"small\"><i class=\"fas fa-sitemap me-1\"></i> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(calculateVolumeDistributionSummary(volume))
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(calculateVolumeDistributionSummary(volume))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 600, Col: 52}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 564, Col: 52}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
_, 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, 104, "</div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 101, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -1107,86 +1084,86 @@ func displayEcVolumeStatus(volume dash.EcVolumeWithShards) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var37 := templ.GetChildren(ctx)
if templ_7745c5c3_Var37 == nil {
templ_7745c5c3_Var37 = templ.NopComponent
templ_7745c5c3_Var36 := templ.GetChildren(ctx)
if templ_7745c5c3_Var36 == nil {
templ_7745c5c3_Var36 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
if volume.IsComplete {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 105, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Complete</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 102, "<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Complete</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
if len(volume.MissingShards) > erasure_coding.DataShardsCount {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 106, " <span class=\"badge bg-danger\"><i class=\"fas fa-skull me-1\"></i>Critical (")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 103, " <span class=\"badge bg-danger\"><i class=\"fas fa-skull me-1\"></i>Critical (")
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", len(volume.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 580, Col: 130}
}
_, 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, 104, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if len(volume.MissingShards) > (erasure_coding.DataShardsCount / 2) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 105, " <span class=\"badge bg-warning\"><i class=\"fas fa-exclamation-triangle me-1\"></i>Degraded (")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(volume.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 616, Col: 130}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 583, Col: 146}
}
_, 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, 107, " missing)</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 106, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if len(volume.MissingShards) > (erasure_coding.DataShardsCount / 2) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 108, " <span class=\"badge bg-warning\"><i class=\"fas fa-exclamation-triangle me-1\"></i>Degraded (")
} else if len(volume.MissingShards) > (erasure_coding.ParityShardsCount / 2) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 107, " <span class=\"badge bg-warning\"><i class=\"fas fa-info-circle me-1\"></i>Incomplete (")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(volume.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 619, Col: 146}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 586, Col: 139}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 109, " missing)</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 108, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if len(volume.MissingShards) > (erasure_coding.ParityShardsCount / 2) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 110, " <span class=\"badge bg-warning\"><i class=\"fas fa-info-circle me-1\"></i>Incomplete (")
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 109, " <span class=\"badge bg-info\"><i class=\"fas fa-info-circle me-1\"></i>Minor Issues (")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(volume.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 622, Col: 139}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 589, Col: 138}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 111, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, " <span class=\"badge bg-info\"><i class=\"fas fa-info-circle me-1\"></i>Minor Issues (")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(volume.MissingShards)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_ec_volumes.templ`, Line: 625, Col: 138}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 113, " missing)</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 110, " missing)</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -250,14 +250,6 @@ templ CollectionDetails(data dash.CollectionDetailsData) {
title="View EC volume details">
<i class="fas fa-info-circle"></i>
</button>
if !ecVolume.IsComplete {
<button type="button" class="btn btn-sm btn-outline-warning"
onclick="repairEcVolume(event)"
data-volume-id={ fmt.Sprintf("%d", ecVolume.VolumeID) }
title="Repair missing shards">
<i class="fas fa-wrench"></i>
</button>
}
</div>
</td>
</tr>
@@ -369,13 +361,5 @@ templ CollectionDetails(data dash.CollectionDetailsData) {
window.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;
}
// Repair EC Volume
function repairEcVolume(event) {
const volumeId = event.target.closest('button').getAttribute('data-volume-id');
showConfirm(`Are you sure you want to repair missing shards for EC volume ${volumeId}?`, function() {
// TODO: Implement repair functionality
showAlert('Repair functionality will be implemented soon.', 'info');
});
}
</script>
}
+59 -82
View File
@@ -427,181 +427,158 @@ func CollectionDetails(data dash.CollectionDetailsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" title=\"View EC volume details\"><i class=\"fas fa-info-circle\"></i></button> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if !ecVolume.IsComplete {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "<button type=\"button\" class=\"btn btn-sm btn-outline-warning\" onclick=\"repairEcVolume(event)\" data-volume-id=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", ecVolume.VolumeID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 256, Col: 64}
}
_, 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, 47, "\" title=\"Repair missing shards\"><i class=\"fas fa-wrench\"></i></button>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "</div></td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" title=\"View EC volume details\"><i class=\"fas fa-info-circle\"></i></button></div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(data.RegularVolumes) == 0 && len(data.EcVolumes) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<tr><td colspan=\"6\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No volumes found for collection \"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "<tr><td colspan=\"6\" class=\"text-center text-muted py-4\"><i class=\"fas fa-info-circle me-2\"></i> No volumes found for collection \"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(data.CollectionName)
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(data.CollectionName)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 271, Col: 60}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 263, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
_, 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, 50, "\"</td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\"</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "</tbody></table></div><!-- Pagination -->")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "</tbody></table></div><!-- Pagination -->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.TotalPages > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "<nav aria-label=\"Collection volumes pagination\"><ul class=\"pagination justify-content-center\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<nav aria-label=\"Collection volumes pagination\"><ul class=\"pagination justify-content-center\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.Page > 1 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"1\">First</a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"1\">First</a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page-1))
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Page-1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 288, Col: 104}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 280, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
_, 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, 54, "\">Previous</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\">Previous</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
for i := 1; i <= data.TotalPages; i++ {
if i == data.Page {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "<li class=\"page-item active\"><span class=\"page-link\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "<li class=\"page-item active\"><span class=\"page-link\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 287, Col: 52}
}
_, 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, 53, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if i <= 3 || i > data.TotalPages-3 || (i >= data.Page-2 && i <= data.Page+2) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 295, Col: 52}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 291, Col: 95}
}
_, 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, 56, "</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if i <= 3 || i > data.TotalPages-3 || (i >= data.Page-2 && i <= data.Page+2) {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "\">")
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", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 299, Col: 95}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 291, Col: 119}
}
_, 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, 58, "\">")
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", i))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 299, Col: 119}
}
_, 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, 59, "</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if i == 4 && data.Page > 6 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else if i == data.TotalPages-3 && data.Page < data.TotalPages-5 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "<li class=\"page-item disabled\"><span class=\"page-link\">...</span></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
}
if data.Page < data.TotalPages {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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", data.Page+1))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 306, Col: 104}
}
_, 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, 60, "\">Next</a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" data-page=\"")
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.Page+1))
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 314, Col: 104}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 309, Col: 108}
}
_, 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, 63, "\">Next</a></li><li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=\"goToPage(event)\" 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.TotalPages))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/collection_details.templ`, Line: 317, Col: 108}
}
_, 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, 64, "\">Last</a></li>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "\">Last</a></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "</ul></nav>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "</ul></nav>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "<script>\n\t\t// Sorting functionality\n\t\tfunction sortBy(field) {\n\t\t\tconst currentSort = new URLSearchParams(window.location.search).get('sort_by');\n\t\t\tconst currentOrder = new URLSearchParams(window.location.search).get('sort_order') || 'asc';\n\t\t\t\n\t\t\tlet newOrder = 'asc';\n\t\t\tif (currentSort === field && currentOrder === 'asc') {\n\t\t\t\tnewOrder = 'desc';\n\t\t\t}\n\t\t\t\n\t\t\tconst url = new URL(window.location);\n\t\t\turl.searchParams.set('sort_by', field);\n\t\t\turl.searchParams.set('sort_order', newOrder);\n\t\t\turl.searchParams.set('page', '1'); // Reset to first page\n\t\t\twindow.location.href = url.toString();\n\t\t}\n\n\t\t// Pagination functionality\n\t\tfunction goToPage(event) {\n\t\t\tevent.preventDefault();\n\t\t\tconst page = event.target.closest('a').getAttribute('data-page');\n\t\t\tconst url = new URL(window.location);\n\t\t\turl.searchParams.set('page', page);\n\t\t\twindow.location.href = url.toString();\n\t\t}\n\n\t\t// Page size functionality\n\t\tfunction changePageSize(newPageSize) {\n\t\t\tconst url = new URL(window.location);\n\t\t\turl.searchParams.set('page_size', newPageSize);\n\t\t\turl.searchParams.set('page', '1'); // Reset to first page when changing page size\n\t\t\twindow.location.href = url.toString();\n\t\t}\n\n\t\t// Volume details\n\t\tfunction showVolumeDetails(event) {\n\t\t\tconst volumeId = event.target.closest('button').getAttribute('data-volume-id');\n\t\t\tconst server = event.target.closest('button').getAttribute('data-server');\n\t\t\twindow.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${server}`;\n\t\t}\n\n\t\t// EC Volume details\n\t\tfunction showEcVolumeDetails(event) {\n\t\t\tconst volumeId = event.target.closest('button').getAttribute('data-volume-id');\n\t\t\twindow.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;\n\t\t}\n\n\t\t// Repair EC Volume\n\t\tfunction repairEcVolume(event) {\n\t\t\tconst volumeId = event.target.closest('button').getAttribute('data-volume-id');\n showConfirm(`Are you sure you want to repair missing shards for EC volume ${volumeId}?`, function() {\n\t\t\t\t// TODO: Implement repair functionality\n\t\t\t\tshowAlert('Repair functionality will be implemented soon.', 'info');\n\t\t\t});\n\t\t}\n\t</script>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "<script>\n\t\t// Sorting functionality\n\t\tfunction sortBy(field) {\n\t\t\tconst currentSort = new URLSearchParams(window.location.search).get('sort_by');\n\t\t\tconst currentOrder = new URLSearchParams(window.location.search).get('sort_order') || 'asc';\n\t\t\t\n\t\t\tlet newOrder = 'asc';\n\t\t\tif (currentSort === field && currentOrder === 'asc') {\n\t\t\t\tnewOrder = 'desc';\n\t\t\t}\n\t\t\t\n\t\t\tconst url = new URL(window.location);\n\t\t\turl.searchParams.set('sort_by', field);\n\t\t\turl.searchParams.set('sort_order', newOrder);\n\t\t\turl.searchParams.set('page', '1'); // Reset to first page\n\t\t\twindow.location.href = url.toString();\n\t\t}\n\n\t\t// Pagination functionality\n\t\tfunction goToPage(event) {\n\t\t\tevent.preventDefault();\n\t\t\tconst page = event.target.closest('a').getAttribute('data-page');\n\t\t\tconst url = new URL(window.location);\n\t\t\turl.searchParams.set('page', page);\n\t\t\twindow.location.href = url.toString();\n\t\t}\n\n\t\t// Page size functionality\n\t\tfunction changePageSize(newPageSize) {\n\t\t\tconst url = new URL(window.location);\n\t\t\turl.searchParams.set('page_size', newPageSize);\n\t\t\turl.searchParams.set('page', '1'); // Reset to first page when changing page size\n\t\t\twindow.location.href = url.toString();\n\t\t}\n\n\t\t// Volume details\n\t\tfunction showVolumeDetails(event) {\n\t\t\tconst volumeId = event.target.closest('button').getAttribute('data-volume-id');\n\t\t\tconst server = event.target.closest('button').getAttribute('data-server');\n\t\t\twindow.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${server}`;\n\t\t}\n\n\t\t// EC Volume details\n\t\tfunction showEcVolumeDetails(event) {\n\t\t\tconst volumeId = event.target.closest('button').getAttribute('data-volume-id');\n\t\t\twindow.location.href = (window.__BASE_PATH__ || '') + `/storage/ec-volumes/${volumeId}`;\n\t\t}\n\n\t</script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+5 -28
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
templ VolumeDetails(data dash.VolumeDetailsData) {
@@ -467,31 +468,7 @@ func formatTimestamp(unixTimestamp int64) string {
return t.Format("2006-01-02 15:04:05")
}
func formatTTL(ttlSeconds uint32) string {
if ttlSeconds == 0 {
return "No TTL"
}
duration := time.Duration(ttlSeconds) * time.Second
// Convert to human readable format
days := int(duration.Hours()) / 24
hours := int(duration.Hours()) % 24
minutes := int(duration.Minutes()) % 60
if days > 0 {
if hours > 0 {
return fmt.Sprintf("%dd %dh", days, hours)
}
return fmt.Sprintf("%d days", days)
} else if hours > 0 {
if minutes > 0 {
return fmt.Sprintf("%dh %dm", hours, minutes)
}
return fmt.Sprintf("%d hours", hours)
} else if minutes > 0 {
return fmt.Sprintf("%d minutes", minutes)
} else {
return fmt.Sprintf("%d seconds", int(duration.Seconds()))
}
}
func formatTTL(ttlEncoded uint32) string {
ttl := needle.LoadTTLFromUint32(ttlEncoded)
return ttl.String()
}
+48 -71
View File
@@ -11,6 +11,7 @@ import templruntime "github.com/a-h/templ/runtime"
import (
"fmt"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"time"
)
@@ -42,7 +43,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var2 templ.SafeURL
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/admin"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 17, Col: 82}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 18, Col: 82}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
@@ -55,7 +56,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var3 templ.SafeURL
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/storage/volumes"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 18, Col: 92}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 19, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
@@ -68,7 +69,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.Id))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 19, Col: 116}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 20, Col: 116}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -81,7 +82,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.Id))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 49, Col: 90}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 50, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -94,7 +95,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var6 templ.SafeURL
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", data.Volume.Server)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 54, Col: 113}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 55, Col: 113}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
@@ -107,7 +108,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.Server)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 55, Col: 59}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 56, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -120,7 +121,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 62, Col: 99}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 63, Col: 99}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -133,7 +134,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.Rack)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 66, Col: 93}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 67, Col: 93}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -151,7 +152,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var10 templ.SafeURL
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/storage/volumes?collection=default"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 74, Col: 103}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 75, Col: 103}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -169,7 +170,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var11 templ.SafeURL
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/storage/volumes?collection=%s", data.Volume.Collection)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 78, Col: 135}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 79, Col: 135}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
@@ -182,7 +183,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.Collection)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 79, Col: 100}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 80, Col: 100}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
@@ -200,7 +201,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%03d", data.Volume.ReplicaPlacement))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 86, Col: 115}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 87, Col: 115}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
@@ -219,7 +220,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.DiskType)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 95, Col: 65}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 96, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
@@ -233,7 +234,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("v%d", data.Volume.Version))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 102, Col: 105}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 103, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
@@ -246,7 +247,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(int64(data.Volume.Size - data.Volume.DeletedByteCount)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 125, Col: 104}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 126, Col: 104}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
@@ -259,7 +260,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(int64(data.Volume.DeletedByteCount)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 133, Col: 85}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 134, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -272,7 +273,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.FileCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 147, Col: 77}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 148, Col: 77}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
@@ -285,7 +286,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.DeleteCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 155, Col: 79}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 156, Col: 79}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -303,7 +304,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%%", float64(data.Volume.Size-data.Volume.DeletedByteCount)/float64(data.Volume.Size)*100))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 170, Col: 144}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 171, Col: 144}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -316,7 +317,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %.1f%%", float64(data.Volume.Size-data.Volume.DeletedByteCount)/float64(data.Volume.Size)*100))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 175, Col: 158}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 176, Col: 158}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
@@ -329,7 +330,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f", float64(data.Volume.Size-data.Volume.DeletedByteCount)/float64(data.Volume.Size)*100))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 176, Col: 157}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 177, Col: 157}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
if templ_7745c5c3_Err != nil {
@@ -373,7 +374,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.CompactRevision))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 216, Col: 84}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 217, Col: 84}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
@@ -387,7 +388,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(formatTimestamp(data.Volume.ModifiedAtSecond))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 225, Col: 86}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 226, Col: 86}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
@@ -411,7 +412,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(formatTTL(data.Volume.Ttl))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 239, Col: 92}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 240, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
@@ -434,7 +435,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.RemoteStorageName)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 253, Col: 99}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 254, Col: 99}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
@@ -452,7 +453,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.RemoteStorageKey)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 260, Col: 138}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 261, Col: 138}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil {
@@ -465,7 +466,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.RemoteStorageKey)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 261, Col: 65}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 262, Col: 65}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil {
@@ -489,7 +490,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ReplicationCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 279, Col: 111}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 280, Col: 111}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil {
@@ -502,7 +503,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var30 templ.SafeURL
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", data.Volume.Server)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 301, Col: 125}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 302, Col: 125}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil {
@@ -515,7 +516,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.Server)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 302, Col: 71}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 303, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil {
@@ -528,7 +529,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 308, Col: 106}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 309, Col: 106}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil {
@@ -541,7 +542,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.Rack)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 309, Col: 100}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 310, Col: 100}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil {
@@ -554,7 +555,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(int64(data.Volume.Size)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 310, Col: 81}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 311, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil {
@@ -567,7 +568,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.FileCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 311, Col: 85}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 312, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil {
@@ -585,7 +586,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var36 templ.SafeURL
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", replica.Server)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 321, Col: 121}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 322, Col: 121}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
if templ_7745c5c3_Err != nil {
@@ -598,7 +599,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var37 string
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(replica.Server)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 322, Col: 67}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 323, Col: 67}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
@@ -611,7 +612,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(replica.DataCenter)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 326, Col: 106}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 327, Col: 106}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil {
@@ -624,7 +625,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(replica.Rack)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 327, Col: 100}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 328, Col: 100}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil {
@@ -637,7 +638,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(int64(replica.Size)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 328, Col: 81}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 329, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil {
@@ -650,7 +651,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", replica.FileCount))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 329, Col: 85}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 330, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
@@ -663,7 +664,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var42 templ.SafeURL
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/storage/volumes/%d/%s", replica.Id, replica.Server)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 332, Col: 139}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 333, Col: 139}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
if templ_7745c5c3_Err != nil {
@@ -686,7 +687,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var43 string
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.Volume.Id))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 360, Col: 81}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 361, Col: 81}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
if templ_7745c5c3_Err != nil {
@@ -699,7 +700,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var44 string
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(data.Volume.Server)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 361, Col: 63}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 362, Col: 63}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
if templ_7745c5c3_Err != nil {
@@ -712,7 +713,7 @@ func VolumeDetails(data dash.VolumeDetailsData) templ.Component {
var templ_7745c5c3_Var45 string
templ_7745c5c3_Var45, 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/volume_details.templ`, Line: 381, Col: 77}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/volume_details.templ`, Line: 382, Col: 77}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
if templ_7745c5c3_Err != nil {
@@ -734,33 +735,9 @@ func formatTimestamp(unixTimestamp int64) string {
return t.Format("2006-01-02 15:04:05")
}
func formatTTL(ttlSeconds uint32) string {
if ttlSeconds == 0 {
return "No TTL"
}
duration := time.Duration(ttlSeconds) * time.Second
// Convert to human readable format
days := int(duration.Hours()) / 24
hours := int(duration.Hours()) % 24
minutes := int(duration.Minutes()) % 60
if days > 0 {
if hours > 0 {
return fmt.Sprintf("%dd %dh", days, hours)
}
return fmt.Sprintf("%d days", days)
} else if hours > 0 {
if minutes > 0 {
return fmt.Sprintf("%dh %dm", hours, minutes)
}
return fmt.Sprintf("%d hours", hours)
} else if minutes > 0 {
return fmt.Sprintf("%d minutes", minutes)
} else {
return fmt.Sprintf("%d seconds", int(duration.Seconds()))
}
func formatTTL(ttlEncoded uint32) string {
ttl := needle.LoadTTLFromUint32(ttlEncoded)
return ttl.String()
}
var _ = templruntime.GeneratedTemplate
+70 -53
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path"
"sort"
"sync"
"sync/atomic"
"time"
@@ -261,59 +262,73 @@ func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
return nil
}
// entryStream is a sorted, streaming view of a single directory's entries.
// A background goroutine pages through the directory via ReadDirAllEntries
// and forwards each entry to a buffered channel; the caller consumes entries
// one at a time through peek/advance. Memory usage is O(channel buffer) —
// independent of directory size — rather than O(total entries).
type entryStream struct {
ch <-chan *filer_pb.Entry
head *filer_pb.Entry
done bool
err error // written before ch is closed; safe to read once done==true
// dirEntries holds one directory's entries buffered and sorted in Go byte
// order, which the merge in compareDirectory requires (it pairs equal names and
// uses eA.Name < eB.Name as the tie-break). The filer's own list order is not
// trusted: since PR #9824 (4.32) a filer forces byte-lexicographic listing
// regardless of SQL collation, while an older filer whose name column uses a
// locale collation lists case-insensitively. Comparing two such clusters yields
// the same name set in a different order, desyncing the merge into spurious
// MISSING / ONLY_IN_B. Sorting both sides client-side makes the order identical
// regardless of filer version or store backend.
//
// The load runs in a background goroutine so both sides of a compareDirectory
// list concurrently; peek/advance block on `ready` until it completes. Memory
// is O(directory size) per side — acceptable for a one-shot verify CLI.
type dirEntries struct {
ready chan struct{} // closed once entries and err are set
entries []*filer_pb.Entry
idx int
err error
}
// newEntryStream starts the background goroutine. It exits when listing
// completes, an error occurs, or ctx is cancelled; the channel is always
// closed before exit so consumers do not block indefinitely.
func newEntryStream(ctx context.Context, client filer_pb.FilerClient, dir string) *entryStream {
ch := make(chan *filer_pb.Entry, 64)
s := &entryStream{ch: ch}
// newDirEntries starts loading the whole directory and sorting it by Name, then
// returns immediately. The goroutine exits when listing completes, errors, or
// ctx is cancelled; it always closes `ready` so consumers never block forever.
func newDirEntries(ctx context.Context, client filer_pb.FilerClient, dir string) *dirEntries {
s := &dirEntries{ready: make(chan struct{})}
go func() {
defer close(ch)
defer close(s.ready)
s.err = filer_pb.ReadDirAllEntries(ctx, client, util.FullPath(dir), "",
func(entry *filer_pb.Entry, isLast bool) error {
select {
case ch <- entry:
return nil
case <-ctx.Done():
return ctx.Err()
default:
}
s.entries = append(s.entries, entry)
return nil
})
if s.err == nil {
sort.Slice(s.entries, func(i, j int) bool {
return s.entries[i].Name < s.entries[j].Name
})
}
}()
return s
}
// wait blocks until the directory has finished loading and sorting. Its close
// of `ready` happens-before the return, so entries and err are then safe to read
// without additional synchronisation.
func (s *dirEntries) wait() { <-s.ready }
// peek returns the next entry without consuming it, or nil at end-of-stream.
func (s *entryStream) peek() *filer_pb.Entry {
if s.done {
// It blocks until the directory has finished loading and sorting.
func (s *dirEntries) peek() *filer_pb.Entry {
s.wait()
if s.idx >= len(s.entries) {
return nil
}
if s.head == nil {
e, ok := <-s.ch
if !ok {
s.done = true
return nil
}
s.head = e
}
return s.head
return s.entries[s.idx]
}
// advance consumes and returns the next entry.
func (s *entryStream) advance() *filer_pb.Entry {
func (s *dirEntries) advance() *filer_pb.Entry {
e := s.peek()
s.head = nil
if e != nil {
s.idx++
}
return e
}
@@ -340,26 +355,38 @@ func compareDirectory(ctx context.Context,
result.dirCount.Add(1)
// A child context ensures that stream goroutines are cancelled and their
// channels are closed if compareDirectory returns early (e.g. on error).
// A child context cancels the load goroutines (and their listing RPCs) if
// compareDirectory returns early, e.g. on error. Both sides load concurrently.
mergeCtx, cancelMerge := context.WithCancel(ctx)
defer cancelMerge()
streamA := newEntryStream(mergeCtx, clientA, dirA)
streamB := newEntryStream(mergeCtx, clientB, dirB)
entriesA := newDirEntries(mergeCtx, clientA, dirA)
entriesB := newDirEntries(mergeCtx, clientB, dirB)
// Both sides are fully buffered before merging; surface any listing error
// here so a failed or cancelled listing can't emit bogus diffs from partial
// data. wait() makes entries/err visible without extra synchronisation.
entriesA.wait()
entriesB.wait()
if err := entriesA.err; err != nil && err != context.Canceled {
return fmt.Errorf("list %s on filer A: %v", dirA, err)
}
if err := entriesB.err; err != nil && err != context.Canceled {
return fmt.Errorf("list %s on filer B: %v", dirB, err)
}
// collect subdirectories for recursive comparison
type dirPair struct{ a, b string }
var subDirs []dirPair
for streamA.peek() != nil || streamB.peek() != nil {
eA := streamA.peek()
eB := streamB.peek()
for entriesA.peek() != nil || entriesB.peek() != nil {
eA := entriesA.peek()
eB := entriesB.peek()
switch {
case eA != nil && (eB == nil || eA.Name < eB.Name):
// entry only in A
entryA := streamA.advance()
entryA := entriesA.advance()
if entryA.IsDirectory {
// Always recurse for missing-in-B directories: a recent
// child write can bump the parent's mtime even though
@@ -375,7 +402,7 @@ func compareDirectory(ctx context.Context,
case eB != nil && (eA == nil || eB.Name < eA.Name):
// entry only in B
entryB := streamB.advance()
entryB := entriesB.advance()
if !isActivePassive {
if isTooRecent(entryB, cutoffTime) {
result.skippedRecent.Add(1)
@@ -386,8 +413,8 @@ func compareDirectory(ctx context.Context,
default:
// same name in both
entryA := streamA.advance()
entryB := streamB.advance()
entryA := entriesA.advance()
entryB := entriesB.advance()
if entryA.IsDirectory && entryB.IsDirectory {
subDirs = append(subDirs, dirPair{
@@ -411,15 +438,6 @@ func compareDirectory(ctx context.Context,
}
}
// Both channels are closed: close happens-before the receive of the zero
// value, so stream.err is visible here without additional synchronisation.
if err := streamA.err; err != nil && err != context.Canceled {
return fmt.Errorf("list %s on filer A: %v", dirA, err)
}
if err := streamB.err; err != nil && err != context.Canceled {
return fmt.Errorf("list %s on filer B: %v", dirB, err)
}
// Release our slot before recursing so children can acquire it. Holding
// it across wg.Wait would deadlock once depth exceeds verifySyncConcurrency.
releaseSlot()
@@ -465,7 +483,6 @@ func compareDirectory(ctx context.Context,
return nil
}
func compareEntries(dir string, entryA, entryB *filer_pb.Entry, result *VerifyResult) {
result.fileCount.Add(1)
+149 -9
View File
@@ -18,10 +18,14 @@ import (
type verifyTestStream struct {
entries []*filer_pb.Entry
idx int
recvErr error // returned after all entries instead of io.EOF, if set
}
func (s *verifyTestStream) Recv() (*filer_pb.ListEntriesResponse, error) {
if s.idx >= len(s.entries) {
if s.recvErr != nil {
return nil, s.recvErr
}
return nil, io.EOF
}
resp := &filer_pb.ListEntriesResponse{Entry: s.entries[s.idx]}
@@ -39,11 +43,12 @@ func (s *verifyTestStream) RecvMsg(_ any) error { return nil }
// verifyTestInnerClient is the SeaweedFilerClient passed to fn inside WithFilerClient.
type verifyTestInnerClient struct {
filer_pb.SeaweedFilerClient // embed for unimplemented RPCs
entriesByDir map[string][]*filer_pb.Entry
entriesByDir map[string][]*filer_pb.Entry
recvErr error // injected listing error, if set
}
func (c *verifyTestInnerClient) ListEntries(_ context.Context, in *filer_pb.ListEntriesRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
return &verifyTestStream{entries: c.entriesByDir[in.Directory]}, nil
return &verifyTestStream{entries: c.entriesByDir[in.Directory], recvErr: c.recvErr}, nil
}
// verifyTestFilerClient implements filer_pb.FilerClient and tracks concurrent
@@ -57,6 +62,8 @@ type verifyTestFilerClient struct {
inFlight atomic.Int64
peakFlight atomic.Int64
delay time.Duration
onList func() // called at the start of each listing, if set
recvErr error // injected listing error, surfaced after entries
}
func (c *verifyTestFilerClient) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error {
@@ -69,10 +76,13 @@ func (c *verifyTestFilerClient) WithFilerClient(_ bool, fn func(filer_pb.Seaweed
break
}
}
if c.onList != nil {
c.onList()
}
if c.delay > 0 {
time.Sleep(c.delay)
}
return fn(&verifyTestInnerClient{entriesByDir: c.entriesByDir})
return fn(&verifyTestInnerClient{entriesByDir: c.entriesByDir, recvErr: c.recvErr})
}
func (c *verifyTestFilerClient) AdjustedUrl(_ *filer_pb.Location) string { return "" }
@@ -422,8 +432,8 @@ func TestVerifySyncMissingDirRecursesEvenWithRecentMtime(t *testing.T) {
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/": {recentDir},
"/subdir": {oldChild},
"/": {recentDir},
"/subdir": {oldChild},
},
}
clientB := &verifyTestFilerClient{
@@ -454,14 +464,14 @@ func TestVerifySyncMissingDirRecursesEvenWithRecentMtime(t *testing.T) {
func TestVerifySyncRootPath(t *testing.T) {
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/": {verifyDirEntry("data")},
"/data": {verifyFileEntry("file.txt", 42)},
"/": {verifyDirEntry("data")},
"/data": {verifyFileEntry("file.txt", 42)},
},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/": {verifyDirEntry("data")},
"/data": {verifyFileEntry("file.txt", 42)},
"/": {verifyDirEntry("data")},
"/data": {verifyFileEntry("file.txt", 42)},
},
}
@@ -531,3 +541,133 @@ func TestVerifySyncNoDeadlockDeepTree(t *testing.T) {
t.Fatal("compareDirectory did not complete within 10s — possible deadlock")
}
}
// TestVerifySyncByteOrderSkew covers a collation skew between two filer
// versions: both return the SAME name set in DIFFERENT order. Filer A (older,
// pre-4.32) lists in locale collation (case-insensitive: lowercase mixes in
// among uppercase); filer B (4.32+, with PR #9824) lists in byte order
// (uppercase before lowercase). The mock returns each side's slice verbatim.
//
// Because compareDirectory sorts both sides client-side before merging, the two
// orders converge and no spurious diffs are reported. Were the sort removed, the
// streaming merge would desync and count 3 false MISSING + 3 false ONLY_IN_B.
func TestVerifySyncByteOrderSkew(t *testing.T) {
// locale order (case-insensitive): lowercase mixes in among uppercase.
localeOrder := []*filer_pb.Entry{
verifyFileEntry("sk-4", 10),
verifyFileEntry("sk-8", 10),
verifyFileEntry("sk-mmsJ", 10),
verifyFileEntry("sk-nFGE", 10),
verifyFileEntry("sk-RH0Z", 10),
verifyFileEntry("sk-Xp", 10),
verifyFileEntry("sk-Z06", 10),
}
// byte order: uppercase (R,X,Z) sort before lowercase (m,n).
byteOrder := []*filer_pb.Entry{
verifyFileEntry("sk-4", 10),
verifyFileEntry("sk-8", 10),
verifyFileEntry("sk-RH0Z", 10),
verifyFileEntry("sk-Xp", 10),
verifyFileEntry("sk-Z06", 10),
verifyFileEntry("sk-mmsJ", 10),
verifyFileEntry("sk-nFGE", 10),
}
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{"/root": localeOrder},
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{"/root": byteOrder},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := result.missingCount.Load(); got != 0 {
t.Errorf("missingCount = %d, want 0", got)
}
if got := result.onlyInB.Load(); got != 0 {
t.Errorf("onlyInB = %d, want 0", got)
}
}
// TestVerifySyncSourcesListConcurrently guards against re-serializing the two
// directory listings: both sides buffer + sort, and their loads must run
// concurrently — not A fully then B. A shared gate releases only once both
// listings are in-flight at the same time; if they were sequential the first
// would block on the gate and time out.
func TestVerifySyncSourcesListConcurrently(t *testing.T) {
var started atomic.Int32
var timedOut atomic.Bool
release := make(chan struct{})
gate := func() {
if started.Add(1) == 2 {
close(release) // both listings reached the gate → proceed
}
select {
case <-release:
case <-time.After(3 * time.Second):
timedOut.Store(true) // only one listing ever in-flight → serialized
}
}
entries := []*filer_pb.Entry{verifyFileEntry("a", 1), verifyFileEntry("b", 1)}
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{"/root": entries},
onList: gate,
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{"/root": entries},
onList: gate,
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
if err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if timedOut.Load() {
t.Fatal("sources listed sequentially: both listings were not in-flight at once")
}
}
// TestVerifySyncListErrorNoBogusDiffs verifies that a listing failure aborts
// with the error and reports no differences. A side whose listing errors keeps
// only a partial, unsorted buffer; the error must be surfaced before the merge
// so those partial entries never produce spurious MISSING / ONLY_IN_B.
func TestVerifySyncListErrorNoBogusDiffs(t *testing.T) {
entries := []*filer_pb.Entry{
verifyFileEntry("a", 1),
verifyFileEntry("b", 1),
verifyFileEntry("c", 1),
}
// A errors mid-listing (partial buffer); B lists cleanly.
clientA := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{"/root": entries},
recvErr: fmt.Errorf("injected list failure"),
}
clientB := &verifyTestFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{"/root": entries},
}
result := &VerifyResult{}
sem := make(chan struct{}, verifySyncConcurrency)
err := compareDirectory(context.Background(), clientA, clientB,
"/root", "/root", false, time.Time{}, sem, result)
if err == nil {
t.Fatal("expected a listing error, got nil")
}
if got := result.missingCount.Load(); got != 0 {
t.Errorf("missingCount = %d, want 0 (no bogus diffs on list error)", got)
}
if got := result.onlyInB.Load(); got != 0 {
t.Errorf("onlyInB = %d, want 0 (no bogus diffs on list error)", got)
}
if got := result.fileCount.Load(); got != 0 {
t.Errorf("fileCount = %d, want 0 (merge must not run on failed listing)", got)
}
}
+110 -104
View File
@@ -15,11 +15,20 @@ type InodeToPath struct {
cacheMetaTtlSec time.Duration
inode2path map[uint64]*InodeEntry
path2inode map[util.FullPath]uint64
// dirStates holds directory-only readdir-cache state, keyed by inode. An
// inode is a directory iff it has an entry here, registered at creation.
dirStates map[uint64]*dirState
}
// InodeEntry exists per inode the kernel references. Directory cache state is
// kept out in dirStates so a file entry stays in the 32-byte size class — the
// dominant cost on a mount with millions of files.
type InodeEntry struct {
paths []util.FullPath
nlookup uint64
isDirectory bool
paths []util.FullPath
nlookup uint64
}
type dirState struct {
isChildrenCached bool
readDirDirect bool
cachedExpiresTime time.Time
@@ -30,12 +39,12 @@ type InodeEntry struct {
subdirCount int32 // tracked in-memory for POSIX directory nlink
}
func (ie *InodeEntry) resetCacheState() {
ie.isChildrenCached = false
ie.readDirDirect = false
ie.cachedExpiresTime = time.Time{}
ie.updateCount = 0
ie.updateWindowStart = time.Time{}
func (d *dirState) resetCacheState() {
d.isChildrenCached = false
d.readDirDirect = false
d.cachedExpiresTime = time.Time{}
d.updateCount = 0
d.updateWindowStart = time.Time{}
}
func (ie *InodeEntry) removeOnePath(p util.FullPath) bool {
@@ -63,14 +72,14 @@ func NewInodeToPath(root util.FullPath, ttlSec int) *InodeToPath {
t := &InodeToPath{
inode2path: make(map[uint64]*InodeEntry),
path2inode: make(map[util.FullPath]uint64),
dirStates: make(map[uint64]*dirState),
cacheMetaTtlSec: time.Second * time.Duration(ttlSec),
}
t.inode2path[1] = &InodeEntry{
paths: []util.FullPath{root},
nlookup: 1,
isDirectory: true,
lastAccess: time.Now(),
paths: []util.FullPath{root},
nlookup: 1,
}
t.dirStates[1] = &dirState{lastAccess: time.Now()}
t.path2inode[root] = 1
return t
@@ -112,17 +121,16 @@ func (i *InodeToPath) Lookup(path util.FullPath, unixTime int64, isDirectory boo
i.inode2path[inode].nlookup++
}
} else {
if !isLookup {
i.inode2path[inode] = &InodeEntry{
paths: []util.FullPath{path},
isDirectory: isDirectory,
}
} else {
i.inode2path[inode] = &InodeEntry{
paths: []util.FullPath{path},
nlookup: 1,
isDirectory: isDirectory,
}
nlookup := uint64(0)
if isLookup {
nlookup = 1
}
i.inode2path[inode] = &InodeEntry{
paths: []util.FullPath{path},
nlookup: nlookup,
}
if isDirectory {
i.dirStates[inode] = &dirState{}
}
}
@@ -198,20 +206,20 @@ func (i *InodeToPath) MarkChildrenCached(fullpath util.FullPath) {
glog.Warningf("MarkChildrenCached not found inode %v", fullpath)
return
}
path, found := i.inode2path[inode]
d, found := i.dirStates[inode]
if !found {
glog.Warningf("MarkChildrenCached inode %d not found in inode2path for %v", inode, fullpath)
glog.Warningf("MarkChildrenCached inode %d not a tracked directory for %v", inode, fullpath)
return
}
path.isChildrenCached = true
path.readDirDirect = false
d.isChildrenCached = true
d.readDirDirect = false
now := time.Now()
path.lastAccess = now
path.lastRefresh = now
path.updateCount = 0
path.updateWindowStart = time.Time{}
d.lastAccess = now
d.lastRefresh = now
d.updateCount = 0
d.updateWindowStart = time.Time{}
if i.cacheMetaTtlSec > 0 {
path.cachedExpiresTime = now.Add(i.cacheMetaTtlSec)
d.cachedExpiresTime = now.Add(i.cacheMetaTtlSec)
}
}
@@ -222,12 +230,12 @@ func (i *InodeToPath) IsChildrenCached(fullpath util.FullPath) bool {
if !found {
return false
}
path, found := i.inode2path[inode]
if !found {
d := i.dirStates[inode]
if d == nil {
return false
}
if path.isChildrenCached {
return path.cachedExpiresTime.IsZero() || time.Now().Before(path.cachedExpiresTime)
if d.isChildrenCached {
return d.cachedExpiresTime.IsZero() || time.Now().Before(d.cachedExpiresTime)
}
return false
}
@@ -245,9 +253,9 @@ func (i *InodeToPath) HasInode(inode uint64) bool {
func (i *InodeToPath) InvalidateAllChildrenCache() {
i.Lock()
defer i.Unlock()
for _, entry := range i.inode2path {
if entry.isDirectory && entry.isChildrenCached {
entry.resetCacheState()
for _, d := range i.dirStates {
if d.isChildrenCached {
d.resetCacheState()
}
}
}
@@ -259,11 +267,9 @@ func (i *InodeToPath) InvalidateChildrenCache(fullpath util.FullPath) {
if !found {
return
}
entry, found := i.inode2path[inode]
if !found {
return
if d := i.dirStates[inode]; d != nil {
d.resetCacheState()
}
entry.resetCacheState()
}
// AdjustSubdirCount adjusts the subdirectory count for a directory inode.
@@ -275,13 +281,13 @@ func (i *InodeToPath) AdjustSubdirCount(dirPath util.FullPath, delta int32) {
if !found {
return
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
d := i.dirStates[inode]
if d == nil {
return
}
entry.subdirCount += delta
if entry.subdirCount < 0 {
entry.subdirCount = 0
d.subdirCount += delta
if d.subdirCount < 0 {
d.subdirCount = 0
}
}
@@ -293,11 +299,11 @@ func (i *InodeToPath) GetSubdirCount(dirPath util.FullPath) int32 {
if !found {
return 0
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
d := i.dirStates[inode]
if d == nil {
return 0
}
return entry.subdirCount
return d.subdirCount
}
// SetSubdirCount sets the subdirectory count for a directory (used after readdir).
@@ -308,11 +314,9 @@ func (i *InodeToPath) SetSubdirCount(dirPath util.FullPath, count int32) {
if !found {
return
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
return
if d := i.dirStates[inode]; d != nil {
d.subdirCount = count
}
entry.subdirCount = count
}
func (i *InodeToPath) TouchDirectory(fullpath util.FullPath) {
@@ -322,11 +326,9 @@ func (i *InodeToPath) TouchDirectory(fullpath util.FullPath) {
if !found {
return
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
return
if d := i.dirStates[inode]; d != nil {
d.lastAccess = time.Now()
}
entry.lastAccess = time.Now()
}
func (i *InodeToPath) MarkDirectoryReadThrough(fullpath util.FullPath, now time.Time) bool {
@@ -336,17 +338,17 @@ func (i *InodeToPath) MarkDirectoryReadThrough(fullpath util.FullPath, now time.
if !found {
return false
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
d := i.dirStates[inode]
if d == nil {
return false
}
entry.isChildrenCached = false
entry.readDirDirect = true
entry.cachedExpiresTime = time.Time{}
entry.lastAccess = now
entry.lastRefresh = time.Time{}
entry.updateCount = 0
entry.updateWindowStart = time.Time{}
d.isChildrenCached = false
d.readDirDirect = true
d.cachedExpiresTime = time.Time{}
d.lastAccess = now
d.lastRefresh = time.Time{}
d.updateCount = 0
d.updateWindowStart = time.Time{}
return true
}
@@ -360,23 +362,23 @@ func (i *InodeToPath) RecordDirectoryUpdate(fullpath util.FullPath, now time.Tim
if !found {
return false
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory || !entry.isChildrenCached {
d := i.dirStates[inode]
if d == nil || !d.isChildrenCached {
return false
}
if entry.updateWindowStart.IsZero() || now.Sub(entry.updateWindowStart) > window {
entry.updateWindowStart = now
entry.updateCount = 0
if d.updateWindowStart.IsZero() || now.Sub(d.updateWindowStart) > window {
d.updateWindowStart = now
d.updateCount = 0
}
entry.updateCount++
if entry.updateCount >= threshold {
entry.isChildrenCached = false
entry.readDirDirect = true
entry.cachedExpiresTime = time.Time{}
entry.lastAccess = now
entry.lastRefresh = time.Time{}
entry.updateCount = 0
entry.updateWindowStart = time.Time{}
d.updateCount++
if d.updateCount >= threshold {
d.isChildrenCached = false
d.readDirDirect = true
d.cachedExpiresTime = time.Time{}
d.lastAccess = now
d.lastRefresh = time.Time{}
d.updateCount = 0
d.updateWindowStart = time.Time{}
return true
}
return false
@@ -389,11 +391,11 @@ func (i *InodeToPath) ShouldReadDirectoryDirect(fullpath util.FullPath) bool {
if !found {
return false
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
d := i.dirStates[inode]
if d == nil {
return false
}
return entry.readDirDirect
return d.readDirDirect
}
func (i *InodeToPath) MarkDirectoryRefreshed(fullpath util.FullPath, now time.Time) {
@@ -403,17 +405,17 @@ func (i *InodeToPath) MarkDirectoryRefreshed(fullpath util.FullPath, now time.Ti
if !found {
return
}
entry, found := i.inode2path[inode]
if !found || !entry.isDirectory {
d := i.dirStates[inode]
if d == nil {
return
}
entry.lastRefresh = now
entry.lastAccess = now
entry.readDirDirect = false
entry.updateCount = 0
entry.updateWindowStart = time.Time{}
d.lastRefresh = now
d.lastAccess = now
d.readDirDirect = false
d.updateCount = 0
d.updateWindowStart = time.Time{}
if i.cacheMetaTtlSec > 0 {
entry.cachedExpiresTime = now.Add(i.cacheMetaTtlSec)
d.cachedExpiresTime = now.Add(i.cacheMetaTtlSec)
}
}
@@ -424,15 +426,17 @@ func (i *InodeToPath) CollectEvictableDirs(now time.Time, idle time.Duration) []
i.Lock()
defer i.Unlock()
var dirs []util.FullPath
for _, entry := range i.inode2path {
if !entry.isDirectory || !entry.isChildrenCached {
for inode, d := range i.dirStates {
if !d.isChildrenCached {
continue
}
if entry.lastAccess.IsZero() || now.Sub(entry.lastAccess) < idle {
if d.lastAccess.IsZero() || now.Sub(d.lastAccess) < idle {
continue
}
entry.resetCacheState()
dirs = append(dirs, entry.paths...)
d.resetCacheState()
if entry, ok := i.inode2path[inode]; ok {
dirs = append(dirs, entry.paths...)
}
}
return dirs
}
@@ -448,9 +452,8 @@ func (i *InodeToPath) AddPath(inode uint64, path util.FullPath) {
ie.nlookup++
} else {
i.inode2path[inode] = &InodeEntry{
paths: []util.FullPath{path},
nlookup: 1,
isDirectory: false,
paths: []util.FullPath{path},
nlookup: 1,
}
}
}
@@ -498,7 +501,9 @@ func (i *InodeToPath) MovePath(sourcePath, targetPath util.FullPath) (sourceInod
entry.paths[i] = targetPath
}
}
entry.resetCacheState()
if d := i.dirStates[sourceInode]; d != nil {
d.resetCacheState()
}
} else {
glog.Errorf("MovePath %s to %s: sourceInode %d not found", sourcePath, targetPath, sourceInode)
}
@@ -520,7 +525,7 @@ func (i *InodeToPath) Forget(inode, nlookup uint64, onForgetDir func(dir util.Fu
}
glog.V(4).Infof("kernel forget: inode %d paths %v nlookup %d", inode, path.paths, path.nlookup)
if path.nlookup == 0 {
if path.isDirectory && onForgetDir != nil {
if _, isDir := i.dirStates[inode]; isDir && onForgetDir != nil {
dirPaths = append([]util.FullPath(nil), path.paths...)
callOnForgetDir = true
}
@@ -528,6 +533,7 @@ func (i *InodeToPath) Forget(inode, nlookup uint64, onForgetDir func(dir util.Fu
delete(i.path2inode, p)
}
delete(i.inode2path, inode)
delete(i.dirStates, inode)
} else {
glog.V(4).Infof("kernel forget but nlookup not zero: inode %d paths %v nlookup %d", inode, path.paths, path.nlookup)
}
+32
View File
@@ -94,6 +94,38 @@ func TestInodeEntry_removeOnePath(t *testing.T) {
}
}
// Only directory inodes carry dirState; files never do. This keeps the file
// InodeEntry in the smaller size class, which is the memory win on large mounts.
func TestOnlyDirectoriesGetDirState(t *testing.T) {
itp := NewInodeToPath(util.FullPath("/"), 60)
file := util.FullPath("/data/file.txt")
fileInode := itp.Lookup(file, time.Now().Unix(), false, false, 0, true)
if _, ok := itp.dirStates[fileInode]; ok {
t.Fatal("file inode must not have a dirState")
}
// dir queries against a file are no-ops and must not register one
itp.GetSubdirCount(file)
itp.IsChildrenCached(file)
itp.ShouldReadDirectoryDirect(file)
itp.MarkChildrenCached(file)
if _, ok := itp.dirStates[fileInode]; ok {
t.Fatal("dir queries on a file inode must not create a dirState")
}
dir := util.FullPath("/data")
dirInode := itp.Lookup(dir, time.Now().Unix(), true, false, 0, true)
if _, ok := itp.dirStates[dirInode]; !ok {
t.Fatal("directory inode should be registered in dirStates at creation")
}
// forgetting the directory drops its dirState
itp.Forget(dirInode, 1, nil)
if _, ok := itp.dirStates[dirInode]; ok {
t.Fatal("forgotten directory must be removed from dirStates")
}
}
func TestRecordDirectoryUpdateSwitchesDirectoryToReadThrough(t *testing.T) {
root := util.FullPath("/")
dir := util.FullPath("/data")
+3 -1
View File
@@ -74,7 +74,9 @@ func Assign(ctx context.Context, masterFn GetMasterFn, grpcDialOption grpc.DialO
return false
}
switch st.Code() {
case codes.Unavailable:
case codes.Unavailable, codes.ResourceExhausted:
// ResourceExhausted: the master is shedding because volume growth
// is in flight; retry so we pick up the new volume once it lands.
return true
case codes.Canceled, codes.DeadlineExceeded:
// A stale cached gRPC channel (e.g., master restart behind
+54
View File
@@ -0,0 +1,54 @@
package operation
import (
"context"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"google.golang.org/grpc"
)
// LookupRaftLeaderMaster returns the current raft leader by querying configured
// master peers. Followers answer GetMasterConfiguration with the leader address;
// topology mutations such as VolumeMarkReadonly must run on that node.
//
// The volume server's heartbeat peer (GetMaster) may still be a follower after an
// election until the heartbeat loop reconnects.
func LookupRaftLeaderMaster(ctx context.Context, masters []pb.ServerAddress, grpcDialOption grpc.DialOption) (pb.ServerAddress, error) {
if len(masters) == 0 {
return "", fmt.Errorf("no master peers configured")
}
var lastErr error
for _, peer := range masters {
if err := ctx.Err(); err != nil {
return "", err
}
// The same timeout ctx drives both the RPC and WithMasterServerClient's
// connection-invalidation decision, so a self-inflicted 5s timeout leaves
// callCtx.Err() != nil and does not poison the shared master connection.
callCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
var leader pb.ServerAddress
err := WithMasterServerClient(callCtx, false, peer, grpcDialOption, func(client master_pb.SeaweedClient) error {
resp, err := client.GetMasterConfiguration(callCtx, &master_pb.GetMasterConfigurationRequest{})
if err != nil {
return err
}
if resp.Leader == "" {
return fmt.Errorf("master %s returned empty leader", peer)
}
leader = pb.ServerAddress(resp.Leader)
return nil
})
cancel()
if err == nil && leader != "" {
return leader, nil
}
lastErr = err
}
if lastErr != nil {
return "", fmt.Errorf("lookup raft leader from %d master peer(s): %w", len(masters), lastErr)
}
return "", fmt.Errorf("lookup raft leader: no leader from %d master peer(s)", len(masters))
}
+99
View File
@@ -0,0 +1,99 @@
package operation
import (
"context"
"errors"
"fmt"
"net"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type fakeLeaderConfigServer struct {
master_pb.UnimplementedSeaweedServer
leader string
}
func (s *fakeLeaderConfigServer) GetMasterConfiguration(_ context.Context, _ *master_pb.GetMasterConfigurationRequest) (*master_pb.GetMasterConfigurationResponse, error) {
return &master_pb.GetMasterConfigurationResponse{Leader: s.leader}, nil
}
func startFakeMasterServer(t *testing.T, srv master_pb.SeaweedServer) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcServer := grpc.NewServer()
master_pb.RegisterSeaweedServer(grpcServer, srv)
go func() { _ = grpcServer.Serve(lis) }()
t.Cleanup(grpcServer.GracefulStop)
_, port, _ := net.SplitHostPort(lis.Addr().String())
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", port))
}
func TestLookupRaftLeaderMasterFromFollower(t *testing.T) {
follower := startFakeMasterServer(t, &fakeLeaderConfigServer{
leader: "leader.example.com:9333.19333",
})
leader, err := LookupRaftLeaderMaster(
context.Background(),
[]pb.ServerAddress{follower},
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
t.Fatalf("lookup: %v", err)
}
if got, want := leader.ToHttpAddress(), "leader.example.com:9333"; got != want {
t.Fatalf("leader = %q, want %q", got, want)
}
}
func TestLookupRaftLeaderMasterTriesNextPeer(t *testing.T) {
down := pb.ServerAddress("127.0.0.1:1")
peer := startFakeMasterServer(t, &fakeLeaderConfigServer{
leader: "leader.example.com:9333.19333",
})
leader, err := LookupRaftLeaderMaster(
context.Background(),
[]pb.ServerAddress{down, peer},
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
t.Fatalf("lookup: %v", err)
}
if got, want := leader.ToHttpAddress(), "leader.example.com:9333"; got != want {
t.Fatalf("leader = %q, want %q", got, want)
}
}
func TestLookupRaftLeaderMasterNoPeers(t *testing.T) {
_, err := LookupRaftLeaderMaster(context.Background(), nil, nil)
if err == nil {
t.Fatal("expected error for empty peers")
}
}
func TestLookupRaftLeaderMasterCanceledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := LookupRaftLeaderMaster(
ctx,
[]pb.ServerAddress{"127.0.0.1:1"},
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err == nil {
t.Fatal("expected error for canceled context")
}
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected context.Canceled, got %v", err)
}
}
+7
View File
@@ -391,6 +391,13 @@ func shouldInvalidateConnection(ctx context.Context, err error) bool {
switch code {
case codes.Unavailable, codes.Aborted, codes.Internal:
return true
case codes.ResourceExhausted:
// Server-side backpressure on a healthy channel (e.g. the master's
// assign shed while volume growth is in flight), not a dead connection.
// Invalidating would Close() the shared conn and cancel every other
// in-flight RPC with "the client connection is closing"; keep it and let
// the caller retry.
return false
case codes.Canceled, codes.DeadlineExceeded:
// Ambiguous: this fires both when a stale cached channel rejects
// RPCs (e.g. a peer restart behind a k8s Service VIP), where we must
+16
View File
@@ -66,6 +66,22 @@ func TestShouldInvalidateConnection_StaleChannelStillInvalidates(t *testing.T) {
}
}
// TestShouldInvalidateConnection_ResourceExhaustedIsPerRequest ensures the
// master's growth-in-progress assign shed (codes.ResourceExhausted) does NOT
// tear down the shared cached ClientConn. The shed fires per-request across a
// herd of concurrent assigns; invalidating on it would cancel every other
// in-flight assign with "the client connection is closing" — the cascade in
// seaweedfs#10118. It is retried by the caller without touching the channel.
func TestShouldInvalidateConnection_ResourceExhaustedIsPerRequest(t *testing.T) {
shed := status.Error(codes.ResourceExhausted, "no writable volumes for x, volume growth in progress")
if shouldInvalidateConnection(context.Background(), shed) {
t.Fatalf("ResourceExhausted shed must not invalidate the shared connection")
}
if shouldInvalidateConnection(nil, shed) {
t.Fatalf("ResourceExhausted shed must not invalidate the shared connection (nil ctx)")
}
}
// TestShouldInvalidateConnection_GenuineInternalStillInvalidates ensures the
// marshal-error carve-out does not swallow real server-side Internal errors,
// which previously caused — and should continue to cause — connection
+1
View File
@@ -464,6 +464,7 @@ message VolumeEcShardsMountRequest {
string collection = 2;
repeated uint32 shard_ids = 3;
string source_disk_type = 4; // disk type of the source volume, applied to the in-memory EC volume so heartbeats report under it (#9423)
bool recover_missing_index = 5; // first fetch a missing .ecx index from a peer so on-disk shards without a local index become mountable (#10104)
}
message VolumeEcShardsMountResponse {
}
+19 -10
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v6.33.4
// protoc v7.35.0
// source: volume_server.proto
package volume_server_pb
@@ -3721,13 +3721,14 @@ func (x *VolumeEcShardsDeleteResponse) GetFullTeardownDone() bool {
}
type VolumeEcShardsMountRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
SourceDiskType string `protobuf:"bytes,4,opt,name=source_disk_type,json=sourceDiskType,proto3" json:"source_disk_type,omitempty"` // disk type of the source volume, applied to the in-memory EC volume so heartbeats report under it (#9423)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
SourceDiskType string `protobuf:"bytes,4,opt,name=source_disk_type,json=sourceDiskType,proto3" json:"source_disk_type,omitempty"` // disk type of the source volume, applied to the in-memory EC volume so heartbeats report under it (#9423)
RecoverMissingIndex bool `protobuf:"varint,5,opt,name=recover_missing_index,json=recoverMissingIndex,proto3" json:"recover_missing_index,omitempty"` // first fetch a missing .ecx index from a peer so on-disk shards without a local index become mountable (#10104)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *VolumeEcShardsMountRequest) Reset() {
@@ -3788,6 +3789,13 @@ func (x *VolumeEcShardsMountRequest) GetSourceDiskType() string {
return ""
}
func (x *VolumeEcShardsMountRequest) GetRecoverMissingIndex() bool {
if x != nil {
return x.RecoverMissingIndex
}
return false
}
type VolumeEcShardsMountResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -7295,14 +7303,15 @@ const file_volume_server_proto_rawDesc = "" +
"\fencode_ts_ns\x18\x05 \x01(\x03R\n" +
"encodeTsNs\"L\n" +
"\x1cVolumeEcShardsDeleteResponse\x12,\n" +
"\x12full_teardown_done\x18\x01 \x01(\bR\x10fullTeardownDone\"\xa0\x01\n" +
"\x12full_teardown_done\x18\x01 \x01(\bR\x10fullTeardownDone\"\xd4\x01\n" +
"\x1aVolumeEcShardsMountRequest\x12\x1b\n" +
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
"\n" +
"collection\x18\x02 \x01(\tR\n" +
"collection\x12\x1b\n" +
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12(\n" +
"\x10source_disk_type\x18\x04 \x01(\tR\x0esourceDiskType\"\x1d\n" +
"\x10source_disk_type\x18\x04 \x01(\tR\x0esourceDiskType\x122\n" +
"\x15recover_missing_index\x18\x05 \x01(\bR\x13recoverMissingIndex\"\x1d\n" +
"\x1bVolumeEcShardsMountResponse\"z\n" +
"\x1cVolumeEcShardsUnmountRequest\x12\x1b\n" +
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1b\n" +
+11
View File
@@ -218,6 +218,17 @@ func (engine *PolicyEngine) evaluateStatement(stmt *CompiledStatement, args *Pol
}
}
// Check NotPrincipal (statement applies to everyone EXCEPT these principals)
if len(stmt.NotPrincipalPatterns) > 0 || len(stmt.DynamicNotPrincipalPatterns) > 0 {
matchedNotPrincipal := engine.matchesPatterns(stmt.NotPrincipalPatterns, args.Principal)
if !matchedNotPrincipal {
matchedNotPrincipal = engine.matchesDynamicPatterns(stmt.DynamicNotPrincipalPatterns, args.Principal, args)
}
if matchedNotPrincipal {
return false
}
}
// Check conditions
if len(stmt.Statement.Condition) > 0 {
condCtx := args.Conditions
+255
View File
@@ -0,0 +1,255 @@
package policy_engine
import (
"encoding/json"
"reflect"
"slices"
"testing"
)
// TestPolicyPrincipalUnmarshal covers every Principal shape AWS documents, plus
// the bare string/array forms SeaweedFS accepts for backward compatibility.
func TestPolicyPrincipalUnmarshal(t *testing.T) {
cases := []struct {
name string
in string
want []string
}{
{"bare wildcard", `"*"`, []string{"*"}},
{"bare arn", `"arn:aws:iam::123456789012:user/alice"`, []string{"arn:aws:iam::123456789012:user/alice"}},
{"bare array", `["arn:aws:iam::123:root","arn:aws:iam::456:root"]`, []string{"arn:aws:iam::123:root", "arn:aws:iam::456:root"}},
{"AWS single", `{"AWS":"arn:aws:iam::123456789012:root"}`, []string{"arn:aws:iam::123456789012:root"}},
{"AWS array", `{"AWS":["arn:aws:iam::123:root","999999999999"]}`, []string{"arn:aws:iam::123:root", "999999999999"}},
{"AWS wildcard", `{"AWS":"*"}`, []string{"*"}},
{"AWS array wildcard (public read)", `{"AWS":["*"]}`, []string{"*"}},
{"service", `{"Service":"s3.amazonaws.com"}`, []string{"s3.amazonaws.com"}},
{"canonical user", `{"CanonicalUser":"79a59df900b949e55d96a1e698fbace"}`, []string{"79a59df900b949e55d96a1e698fbace"}},
// Object keys are flattened in sorted-key order: AWS < CanonicalUser.
{"mixed keys", `{"CanonicalUser":"79a59","AWS":"arn:aws:iam::123:root"}`, []string{"arn:aws:iam::123:root", "79a59"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var p PolicyPrincipal
if err := json.Unmarshal([]byte(c.in), &p); err != nil {
t.Fatalf("unmarshal %s: %v", c.in, err)
}
if got := p.Strings(); !slices.Equal(got, c.want) {
t.Errorf("Strings() = %v, want %v", got, c.want)
}
})
}
}
func TestPolicyPrincipalUnmarshalInvalid(t *testing.T) {
// Includes object-form abuses: unknown key, empty array, empty string -- all
// of which must error rather than compile to zero matchers (which would let
// the match-all fallback silently make an Allow statement public).
for _, in := range []string{`123`, `{}`, `{"AWS":123}`, `{"Foo":"bar"}`, `{"AWS":[]}`, `{"AWS":""}`} {
var p PolicyPrincipal
if err := json.Unmarshal([]byte(in), &p); err == nil {
t.Errorf("expected error unmarshaling %s, got values %v", in, p.Strings())
}
}
}
// TestNotPrincipalDynamicCompiledPath guards the bug where a NotPrincipal made
// only of policy variables (no static matchers) was treated as absent in the
// compiled evaluator, bypassing the exclusion. aws:username is pinned via the
// condition context so the substituted value is independent of the principal.
func TestNotPrincipalDynamicCompiledPath(t *testing.T) {
policyJSON := `{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":"*","Action":"s3:*","Resource":"arn:aws:s3:::b/*"},
{"Effect":"Deny","NotPrincipal":{"AWS":"${aws:username}"},"Action":"s3:*","Resource":"arn:aws:s3:::b/*"}
]}`
doc, err := ParsePolicy(policyJSON)
if err != nil {
t.Fatalf("ParsePolicy: %v", err)
}
compiled, err := CompilePolicy(doc)
if err != nil {
t.Fatalf("CompilePolicy: %v", err)
}
conds := map[string][]string{"aws:username": {"arn:aws:iam::111:user/alice"}}
allowed := func(p string) bool {
allow, _ := compiled.EvaluatePolicy(&PolicyEvaluationArgs{
Action: "s3:GetObject", Resource: "arn:aws:s3:::b/x", Principal: p, Conditions: conds,
})
return allow
}
// alice matches the substituted NotPrincipal -> deny excluded -> allowed.
if !allowed("arn:aws:iam::111:user/alice") {
t.Errorf("alice should be allowed (matched dynamic NotPrincipal)")
}
// bob does not match -> deny applies.
if allowed("arn:aws:iam::111:user/bob") {
t.Errorf("bob should be denied (dynamic NotPrincipal did not match)")
}
}
// TestPolicyPrincipalRoundTrip guards idempotency for IaC tools (Terraform,
// Ansible): GetBucketPolicy must return the same shape PutBucketPolicy received,
// otherwise those tools see perpetual drift (cf. NotResource normalization bug).
func TestPolicyPrincipalRoundTrip(t *testing.T) {
inputs := []string{
`"*"`,
`{"AWS":"arn:aws:iam::123456789012:root"}`,
`{"AWS":["arn:aws:iam::123456789012:root","arn:aws:iam::555555555555:root"]}`,
`{"AWS":["*"]}`,
`["arn:aws:iam::123:root","arn:aws:iam::456:root"]`,
}
for _, in := range inputs {
var p PolicyPrincipal
if err := json.Unmarshal([]byte(in), &p); err != nil {
t.Fatalf("unmarshal %s: %v", in, err)
}
out, err := json.Marshal(&p)
if err != nil {
t.Fatalf("marshal: %v", err)
}
if !jsonSemanticEqual(t, string(out), in) {
t.Errorf("round-trip mismatch: got %s, want %s", out, in)
}
}
}
// TestBucketPolicyAWSObjectPrincipalEndToEnd parses, compiles and evaluates a
// public-read policy written with the AWS object form {"AWS":["*"]} — the
// AWS-documented shape that previously failed to parse.
func TestBucketPolicyAWSObjectPrincipalEndToEnd(t *testing.T) {
policyJSON := `{
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::my-bucket/*"]
}]
}`
doc, err := ParsePolicy(policyJSON)
if err != nil {
t.Fatalf("ParsePolicy: %v", err)
}
compiled, err := CompilePolicy(doc)
if err != nil {
t.Fatalf("CompilePolicy: %v", err)
}
for _, principal := range []string{"arn:aws:iam::123456789012:user/bob", "*"} {
allow, effect := compiled.EvaluatePolicy(&PolicyEvaluationArgs{
Action: "s3:GetObject",
Resource: "arn:aws:s3:::my-bucket/object.txt",
Principal: principal,
})
if !allow || effect != PolicyEffectAllow {
t.Errorf("principal %q: allow=%v effect=%v, want allow", principal, allow, effect)
}
}
}
// TestBucketPolicySpecificAWSPrincipal verifies a named-principal object form
// only matches the named principal.
func TestBucketPolicySpecificAWSPrincipal(t *testing.T) {
policyJSON := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow",` +
`"Principal":{"AWS":"arn:aws:iam::123456789012:user/alice"},` +
`"Action":"s3:*","Resource":"arn:aws:s3:::b/*"}]}`
doc, err := ParsePolicy(policyJSON)
if err != nil {
t.Fatalf("ParsePolicy: %v", err)
}
compiled, err := CompilePolicy(doc)
if err != nil {
t.Fatalf("CompilePolicy: %v", err)
}
args := func(p string) *PolicyEvaluationArgs {
return &PolicyEvaluationArgs{Action: "s3:GetObject", Resource: "arn:aws:s3:::b/x", Principal: p}
}
if allow, _ := compiled.EvaluatePolicy(args("arn:aws:iam::123456789012:user/alice")); !allow {
t.Errorf("alice should be allowed")
}
if allow, _ := compiled.EvaluatePolicy(args("arn:aws:iam::123456789012:user/bob")); allow {
t.Errorf("bob should NOT be allowed")
}
}
// TestBucketPolicyNotPrincipalDeny exercises the common "deny everyone except X"
// pattern through the real bucket-policy evaluator (PolicyEngine). A Deny with
// NotPrincipal applies to every principal NOT named, so the named principal is
// spared and everyone else is denied.
func TestBucketPolicyNotPrincipalDeny(t *testing.T) {
engine := NewPolicyEngine()
policyJSON := `{
"Version": "2012-10-17",
"Statement": [
{"Sid":"AllowAll","Effect":"Allow","Principal":"*","Action":"s3:*","Resource":"arn:aws:s3:::b/*"},
{"Sid":"DenyExceptAlice","Effect":"Deny","NotPrincipal":{"AWS":"arn:aws:iam::123456789012:user/alice"},"Action":"s3:*","Resource":"arn:aws:s3:::b/*"}
]
}`
if err := engine.SetBucketPolicy("b", policyJSON); err != nil {
t.Fatalf("SetBucketPolicy: %v", err)
}
eval := func(p string) PolicyEvaluationResult {
return engine.EvaluatePolicy("b", &PolicyEvaluationArgs{Action: "s3:GetObject", Resource: "arn:aws:s3:::b/x", Principal: p})
}
// alice is excluded from the NotPrincipal deny, so the Allow wins.
if got := eval("arn:aws:iam::123456789012:user/alice"); got != PolicyResultAllow {
t.Errorf("alice: got %v, want Allow", got)
}
// bob is not named in NotPrincipal, so the Deny applies.
if got := eval("arn:aws:iam::123456789012:user/bob"); got != PolicyResultDeny {
t.Errorf("bob: got %v, want Deny", got)
}
}
// TestBucketPolicyNotPrincipalCompiledPath covers the matcher-based evaluator
// (CompiledPolicy). An Allow-all paired with a Deny/NotPrincipal makes the
// "excluded vs denied" difference observable (a lone Deny would yield implicit
// deny for both).
func TestBucketPolicyNotPrincipalCompiledPath(t *testing.T) {
policyJSON := `{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":"*","Action":"s3:*","Resource":"arn:aws:s3:::b/*"},
{"Effect":"Deny","NotPrincipal":{"AWS":["arn:aws:iam::123456789012:user/alice"]},"Action":"s3:*","Resource":"arn:aws:s3:::b/*"}
]}`
doc, err := ParsePolicy(policyJSON)
if err != nil {
t.Fatalf("ParsePolicy: %v", err)
}
compiled, err := CompilePolicy(doc)
if err != nil {
t.Fatalf("CompilePolicy: %v", err)
}
args := func(p string) *PolicyEvaluationArgs {
return &PolicyEvaluationArgs{Action: "s3:GetObject", Resource: "arn:aws:s3:::b/x", Principal: p}
}
// alice is named in NotPrincipal -> deny excluded -> allowed.
if allow, _ := compiled.EvaluatePolicy(args("arn:aws:iam::123456789012:user/alice")); !allow {
t.Errorf("alice should be allowed (excluded from NotPrincipal deny)")
}
// bob is not named -> deny applies.
if allow, effect := compiled.EvaluatePolicy(args("arn:aws:iam::123456789012:user/bob")); allow || effect != PolicyEffectDeny {
t.Errorf("bob should be denied, got allow=%v effect=%v", allow, effect)
}
}
// TestPolicyBothPrincipalAndNotPrincipalRejected verifies AWS's rule that a
// single statement may not contain both Principal and NotPrincipal.
func TestPolicyBothPrincipalAndNotPrincipalRejected(t *testing.T) {
policyJSON := `{"Version":"2012-10-17","Statement":[{"Effect":"Deny",` +
`"Principal":"*","NotPrincipal":{"AWS":"arn:aws:iam::1:user/a"},` +
`"Action":"s3:*","Resource":"arn:aws:s3:::b/*"}]}`
if _, err := ParsePolicy(policyJSON); err == nil {
t.Errorf("expected error when both Principal and NotPrincipal are set")
}
}
func jsonSemanticEqual(t *testing.T, a, b string) bool {
t.Helper()
var av, bv interface{}
if err := json.Unmarshal([]byte(a), &av); err != nil {
t.Fatalf("unmarshal %s: %v", a, err)
}
if err := json.Unmarshal([]byte(b), &bv); err != nil {
t.Fatalf("unmarshal %s: %v", b, err)
}
return reflect.DeepEqual(av, bv)
}
+202 -14
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"regexp"
"slices"
"sort"
"strings"
"time"
@@ -106,6 +107,129 @@ func CloneStringOrStringSlice(value StringOrStringSlice) StringOrStringSlice {
return StringOrStringSlice{values: append([]string(nil), value.values...)}
}
// allowedPrincipalKeys is the set of principal-type keys AWS allows inside the
// Principal/NotPrincipal object form.
var allowedPrincipalKeys = map[string]struct{}{
"AWS": {},
"Service": {},
"Federated": {},
"CanonicalUser": {},
}
// PolicyPrincipal represents the Principal element of a policy statement.
//
// AWS accepts three shapes (see the IAM "Principal" element reference):
//
// "Principal": "*" // all principals (anonymous)
// "Principal": { "AWS": "arn:aws:iam::123:user/x" } // single, keyed by type
// "Principal": { "AWS": ["arn:...", "999999999999"] } // array of values
//
// The object may key on "AWS", "Service", "Federated" or "CanonicalUser", and
// each value is itself a string or an array of strings. For backward
// compatibility SeaweedFS also accepts a bare string or array of strings.
//
// Authorization matches the request principal ARN against the flat set of
// principal values, so every keyed value is flattened into one list. The
// original JSON is preserved so GetBucketPolicy returns the exact shape the
// caller submitted; this keeps PutBucketPolicy/GetBucketPolicy idempotent for
// infrastructure-as-code tools (Terraform, Ansible) that diff the returned
// policy against the submitted one.
type PolicyPrincipal struct {
values []string
raw json.RawMessage
}
// UnmarshalJSON implements json.Unmarshaler for PolicyPrincipal.
func (p *PolicyPrincipal) UnmarshalJSON(data []byte) error {
// Preserve the original encoding for a faithful round-trip on marshal.
p.raw = append(json.RawMessage(nil), data...)
// Bare string, e.g. "*"
var str string
if err := json.Unmarshal(data, &str); err == nil {
p.values = []string{str}
return nil
}
// Bare array of strings (SeaweedFS extension; not standard AWS).
var strs []string
if err := json.Unmarshal(data, &strs); err == nil {
p.values = strs
return nil
}
// AWS object form: {"AWS": <string|[]string>, "Service": ..., "Federated": ...,
// "CanonicalUser": ...}. Each value reuses StringOrStringSlice so it accepts a
// single string or an array. All keyed values are flattened for matching.
var obj map[string]StringOrStringSlice
if err := json.Unmarshal(data, &obj); err == nil && len(obj) > 0 {
// Sort keys so the flattened order is deterministic.
keys := make([]string, 0, len(obj))
for k := range obj {
if _, ok := allowedPrincipalKeys[k]; !ok {
return fmt.Errorf("unsupported Principal type %q (expected AWS, Service, Federated or CanonicalUser)", k)
}
keys = append(keys, k)
}
sort.Strings(keys)
values := make([]string, 0, len(obj))
for _, k := range keys {
v := obj[k]
items := v.Strings()
if len(items) == 0 {
return fmt.Errorf("Principal %q must list at least one value", k)
}
for _, item := range items {
if item == "" {
return fmt.Errorf("Principal %q must not contain empty values", k)
}
}
values = append(values, items...)
}
p.values = values
return nil
}
return fmt.Errorf(`Principal must be a string, an array of strings, or an object such as {"AWS": ["arn:..."]}`)
}
// MarshalJSON implements json.Marshaler for PolicyPrincipal.
func (p PolicyPrincipal) MarshalJSON() ([]byte, error) {
// Echo the original JSON when we parsed it, so the shape is preserved.
if len(p.raw) > 0 {
return p.raw, nil
}
// Programmatically-constructed principals marshal as a bare string/array.
if len(p.values) == 1 {
return json.Marshal(p.values[0])
}
return json.Marshal(p.values)
}
// Strings returns the flattened principal values. Nil-safe for pointer receivers.
func (p *PolicyPrincipal) Strings() []string {
if p == nil {
return nil
}
return p.values
}
// NewPolicyPrincipalPtr builds a *PolicyPrincipal from flat values (no object wrapping).
func NewPolicyPrincipalPtr(values ...string) *PolicyPrincipal {
return &PolicyPrincipal{values: values}
}
// ClonePolicyPrincipal deep-copies a *PolicyPrincipal (nil-safe).
func ClonePolicyPrincipal(p *PolicyPrincipal) *PolicyPrincipal {
if p == nil {
return nil
}
return &PolicyPrincipal{
values: append([]string(nil), p.values...),
raw: append(json.RawMessage(nil), p.raw...),
}
}
// PolicyConditions represents policy conditions with proper typing
type PolicyConditions map[string]map[string]StringOrStringSlice
@@ -148,13 +272,14 @@ func (p *PolicyDocument) UnmarshalJSON(data []byte) error {
// PolicyStatement represents a single policy statement
type PolicyStatement struct {
Sid string `json:"Sid,omitempty"`
Effect PolicyEffect `json:"Effect"`
Principal *StringOrStringSlice `json:"Principal,omitempty"`
Action StringOrStringSlice `json:"Action"`
Resource *StringOrStringSlice `json:"Resource,omitempty"`
NotResource *StringOrStringSlice `json:"NotResource,omitempty"`
Condition PolicyConditions `json:"Condition,omitempty"`
Sid string `json:"Sid,omitempty"`
Effect PolicyEffect `json:"Effect"`
Principal *PolicyPrincipal `json:"Principal,omitempty"`
NotPrincipal *PolicyPrincipal `json:"NotPrincipal,omitempty"`
Action StringOrStringSlice `json:"Action"`
Resource *StringOrStringSlice `json:"Resource,omitempty"`
NotResource *StringOrStringSlice `json:"NotResource,omitempty"`
Condition PolicyConditions `json:"Condition,omitempty"`
}
// PolicyEffect represents Allow or Deny
@@ -212,6 +337,11 @@ type CompiledStatement struct {
DynamicResourcePatterns []string
DynamicPrincipalPatterns []string
// NotPrincipal patterns (principal should NOT match these)
NotPrincipalMatchers []*wildcard.WildcardMatcher
NotPrincipalPatterns []*regexp.Regexp
DynamicNotPrincipalPatterns []string
// NotResource patterns (resource should NOT match these)
NotResourcePatterns []*regexp.Regexp
NotResourceMatchers []*wildcard.WildcardMatcher
@@ -258,6 +388,11 @@ func validateStatement(stmt *PolicyStatement) error {
return fmt.Errorf("statement must specify Resource or NotResource")
}
// AWS does not allow both Principal and NotPrincipal in the same statement.
if stmt.Principal != nil && stmt.NotPrincipal != nil {
return fmt.Errorf("statement cannot specify both Principal and NotPrincipal")
}
return nil
}
@@ -306,11 +441,12 @@ func compileStatement(stmt *PolicyStatement) (*CompiledStatement, error) {
},
}
// Deep clone Principal if present
// Deep clone Principal / NotPrincipal if present
if stmt.Principal != nil {
principalClone := *stmt.Principal
principalClone.values = slices.Clone(stmt.Principal.values)
compiled.Statement.Principal = &principalClone
compiled.Statement.Principal = ClonePolicyPrincipal(stmt.Principal)
}
if stmt.NotPrincipal != nil {
compiled.Statement.NotPrincipal = ClonePolicyPrincipal(stmt.NotPrincipal)
}
// Deep clone Resource/NotResource into the internal statement as well for completeness
@@ -412,6 +548,32 @@ func compileStatement(stmt *PolicyStatement) (*CompiledStatement, error) {
}
}
// Compile NotPrincipal patterns and matchers (principal should NOT match these)
if stmt.NotPrincipal != nil && len(stmt.NotPrincipal.Strings()) > 0 {
for _, notPrincipal := range stmt.NotPrincipal.Strings() {
if notPrincipal == "" {
continue
}
// Check for dynamic variables
if PolicyVariableRegex.MatchString(notPrincipal) {
compiled.DynamicNotPrincipalPatterns = append(compiled.DynamicNotPrincipalPatterns, notPrincipal)
continue
}
pattern, err := compilePattern(notPrincipal)
if err != nil {
return nil, fmt.Errorf("failed to compile NotPrincipal pattern %s: %v", notPrincipal, err)
}
compiled.NotPrincipalPatterns = append(compiled.NotPrincipalPatterns, pattern)
matcher, err := wildcard.NewWildcardMatcher(notPrincipal)
if err != nil {
return nil, fmt.Errorf("failed to create NotPrincipal matcher %s: %v", notPrincipal, err)
}
compiled.NotPrincipalMatchers = append(compiled.NotPrincipalMatchers, matcher)
}
}
// Compile NotResource patterns (resource should NOT match these)
if len(notResStrings) > 0 {
for _, notResource := range notResStrings {
@@ -546,6 +708,23 @@ func (cs *CompiledStatement) MatchesPrincipal(principal string) bool {
return false
}
// matchesPrincipalSet reports whether the request principal matches any static
// matcher or dynamic (policy-variable) pattern in the given set.
func (cs *CompiledStatement) matchesPrincipalSet(args *PolicyEvaluationArgs, matchers []*wildcard.WildcardMatcher, dynamic []string) bool {
for _, matcher := range matchers {
if matcher.Match(args.Principal) {
return true
}
}
for _, pattern := range dynamic {
substituted := SubstituteVariables(pattern, args.Conditions, args.Claims)
if FastMatchesWildcard(substituted, args.Principal) {
return true
}
}
return false
}
// EvaluateStatement evaluates a compiled statement against the given arguments
func (cs *CompiledStatement) EvaluateStatement(args *PolicyEvaluationArgs) bool {
// Check if action matches
@@ -558,9 +737,18 @@ func (cs *CompiledStatement) EvaluateStatement(args *PolicyEvaluationArgs) bool
return false
}
// Check if principal matches
if !cs.MatchesPrincipal(args.Principal) {
return false
// Principal / NotPrincipal (mutually exclusive per AWS): NotPrincipal makes
// the statement apply to everyone EXCEPT the named principals; a plain
// Principal requires a match. Both static matchers and dynamic
// (policy-variable) patterns are honored.
if len(cs.NotPrincipalMatchers) > 0 || len(cs.DynamicNotPrincipalPatterns) > 0 {
if cs.matchesPrincipalSet(args, cs.NotPrincipalMatchers, cs.DynamicNotPrincipalPatterns) {
return false
}
} else if len(cs.PrincipalMatchers) > 0 || len(cs.DynamicPrincipalPatterns) > 0 {
if !cs.matchesPrincipalSet(args, cs.PrincipalMatchers, cs.DynamicPrincipalPatterns) {
return false
}
}
return true
+7 -6
View File
@@ -695,12 +695,13 @@ func cloneBucketPolicy(policyDoc *policy_engine.PolicyDocument) *policy_engine.P
func clonePolicyStatement(statement policy_engine.PolicyStatement) policy_engine.PolicyStatement {
cloned := policy_engine.PolicyStatement{
Sid: statement.Sid,
Effect: statement.Effect,
Action: cloneStringOrStringSlice(statement.Action),
NotResource: cloneStringOrStringSlicePtr(statement.NotResource),
Principal: cloneStringOrStringSlicePtr(statement.Principal),
Resource: cloneStringOrStringSlicePtr(statement.Resource),
Sid: statement.Sid,
Effect: statement.Effect,
Action: cloneStringOrStringSlice(statement.Action),
NotResource: cloneStringOrStringSlicePtr(statement.NotResource),
Principal: policy_engine.ClonePolicyPrincipal(statement.Principal),
NotPrincipal: policy_engine.ClonePolicyPrincipal(statement.NotPrincipal),
Resource: cloneStringOrStringSlicePtr(statement.Resource),
}
if statement.Condition != nil {
cloned.Condition = make(policy_engine.PolicyConditions, len(statement.Condition))
+15 -3
View File
@@ -30,9 +30,10 @@ func (ms *MasterServer) StreamAssign(server master_pb.Seaweed_StreamAssignServer
}
resp, err := ms.Assign(context.Background(), req)
if err != nil {
// Return transient errors (e.g. warmup) as in-band error responses
// instead of killing the stream, so pooled connections survive.
if st, ok := status.FromError(err); ok && st.Code() == codes.Unavailable {
// Return transient errors (warmup, growth-in-progress shed) as in-band
// error responses instead of killing the stream, so pooled connections
// survive.
if st, ok := status.FromError(err); ok && (st.Code() == codes.Unavailable || st.Code() == codes.ResourceExhausted) {
glog.V(1).Infof("StreamAssign transient error: %v", err)
resp = &master_pb.AssignResponse{Error: st.Message()}
} else {
@@ -130,6 +131,17 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest
if (req.DataCenter != "" || req.Rack != "") && strings.Contains(err.Error(), topology.NoWritableVolumes) {
break
}
// Growth is the remedy and already in flight; don't pin a goroutine
// spinning out the timeout under an assign herd.
if shouldGrow && vl.HasGrowRequest() {
if ms.Topo.AvailableSpaceFor(option) <= 0 {
break // out of space: surface the real error, not a retryable shed
}
// ResourceExhausted, not Unavailable: clients retry it (assign_file_id.go)
// but the gRPC layer doesn't treat it as a dead channel, so the shed
// doesn't tear down the shared master connection mid-herd.
return nil, status.Errorf(codes.ResourceExhausted, "no writable volumes for %s, volume growth in progress", option.String())
}
time.Sleep(200 * time.Millisecond)
continue
}
@@ -0,0 +1,97 @@
package weed_server
import (
"context"
"testing"
"time"
"github.com/seaweedfs/raft"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/sequence"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
// leaderRaftServer answers only State(); the embedded nil interface panics if any
// other method is called.
type leaderRaftServer struct {
raft.Server
}
func (leaderRaftServer) State() string { return raft.Leader }
func newLeaderMaster() *MasterServer {
topo := topology.NewTopology("test", sequence.NewMemorySequencer(), 1<<20, 5, false)
topo.RaftServer = leaderRaftServer{}
return &MasterServer{
Topo: topo,
option: &MasterOption{},
volumeGrowthRequestChan: make(chan *topology.VolumeGrowRequest, 1<<6),
}
}
// markGrowthInFlight flags growth on the same VolumeLayout the handler resolves,
// by mirroring its exact lookup.
func markGrowthInFlight(t *testing.T, topo *topology.Topology, req *master_pb.AssignRequest) {
t.Helper()
rp, err := super_block.NewReplicaPlacementFromString(req.Replication)
require.NoError(t, err)
ttl, err := needle.ReadTTL(req.Ttl)
require.NoError(t, err)
topo.GetVolumeLayout(req.Collection, rp, ttl, types.ToDiskType(req.DiskType)).AddGrowRequest()
}
// With free space but no writable volume and growth already in flight, Assign
// sheds with a retryable ResourceExhausted immediately instead of spinning to
// timeout. ResourceExhausted (not Unavailable) so the shed isn't mistaken for a
// dead channel and doesn't tear down the shared master connection.
func TestAssignShedsLoadWhenGrowthInFlight(t *testing.T) {
ms := newLeaderMaster()
// Free volume slots but no writable volume yet, so growth is the remedy.
ms.Topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", 8080, 18080, "127.0.0.1", "dn1", map[string]uint32{"": 100})
req := &master_pb.AssignRequest{Count: 1, Replication: "000"}
markGrowthInFlight(t, ms.Topo, req)
start := time.Now()
resp, err := ms.Assign(context.Background(), req)
elapsed := time.Since(start)
require.Error(t, err)
require.Nil(t, resp)
st, ok := status.FromError(err)
require.True(t, ok)
assert.Equal(t, codes.ResourceExhausted, st.Code())
// Shed immediately rather than spinning out the 10s retry budget.
assert.Less(t, elapsed, 2*time.Second)
// Growth was already pending, so we must not enqueue another grow request.
assert.Len(t, ms.volumeGrowthRequestChan, 0)
}
// Out of space, Assign fails fast with the real error rather than masking it as
// a retryable "growth in progress".
func TestAssignFailsFastWhenOutOfSpace(t *testing.T) {
ms := newLeaderMaster() // no data nodes -> no free space
req := &master_pb.AssignRequest{Count: 1, Replication: "000"}
start := time.Now()
resp, err := ms.Assign(context.Background(), req)
elapsed := time.Since(start)
require.Error(t, err)
require.Nil(t, resp)
if st, ok := status.FromError(err); ok {
assert.NotEqual(t, codes.Unavailable, st.Code())
}
assert.Contains(t, err.Error(), "no free volumes left")
assert.Less(t, elapsed, 2*time.Second)
}
+11
View File
@@ -187,6 +187,17 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request)
if err != nil {
stats.MasterPickForWriteErrorCounter.Inc()
lastErr = err
// See Assign: shed instead of spinning when growth is already in flight.
if shouldGrow && vl.HasGrowRequest() {
if ms.Topo.AvailableSpaceFor(option) <= 0 {
break // out of space: surface the real error (406 below)
}
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()),
})
return
}
time.Sleep(200 * time.Millisecond)
continue
} else {
+23 -4
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"net"
"path/filepath"
"strings"
"time"
"google.golang.org/grpc/codes"
@@ -279,9 +280,27 @@ func (vs *VolumeServer) makeVolumeWritable(ctx context.Context, v *storage.Volum
return nil
}
func isNotLeaderErr(err error) bool {
return err != nil && strings.Contains(err.Error(), "Not current leader")
}
func (vs *VolumeServer) notifyMasterVolumeReadonly(ctx context.Context, v *storage.Volume, isReadOnly bool) error {
if grpcErr := pb.WithMasterClient(context.Background(), false, vs.GetMaster(ctx), vs.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
_, err := client.VolumeMarkReadonly(context.Background(), &master_pb.VolumeMarkReadonlyRequest{
master := vs.GetMaster(ctx)
err := vs.volumeMarkReadonlyOnMaster(ctx, master, v, isReadOnly)
if err != nil && isNotLeaderErr(err) {
leader, lookupErr := vs.lookupRaftLeaderMaster(ctx)
if lookupErr != nil {
return fmt.Errorf("heartbeat master %s rejected mark-readonly and leader lookup failed: %w", master, lookupErr)
}
master = leader
err = vs.volumeMarkReadonlyOnMaster(ctx, master, v, isReadOnly)
}
return err
}
func (vs *VolumeServer) volumeMarkReadonlyOnMaster(ctx context.Context, master pb.ServerAddress, v *storage.Volume, isReadOnly bool) error {
if grpcErr := pb.WithMasterClient(ctx, false, master, vs.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
_, err := client.VolumeMarkReadonly(ctx, &master_pb.VolumeMarkReadonlyRequest{
Ip: vs.store.Ip,
Port: uint32(vs.store.Port),
VolumeId: uint32(v.Id),
@@ -296,8 +315,8 @@ func (vs *VolumeServer) notifyMasterVolumeReadonly(ctx context.Context, v *stora
}
return nil
}); grpcErr != nil {
glog.V(0).Infof("connect to %s: %v", vs.GetMaster(context.Background()), grpcErr)
return fmt.Errorf("grpc VolumeMarkReadonly with master %s: %v", vs.GetMaster(context.Background()), grpcErr)
glog.V(0).Infof("connect to %s: %v", master, grpcErr)
return fmt.Errorf("grpc VolumeMarkReadonly with master %s: %v", master, grpcErr)
}
return nil
}
+46 -10
View File
@@ -1,6 +1,8 @@
package weed_server
import (
"context"
"errors"
"fmt"
"os"
"strings"
@@ -10,14 +12,14 @@ import (
"github.com/seaweedfs/seaweedfs/weed/stats"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"context"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -27,6 +29,40 @@ func (vs *VolumeServer) GetMaster(ctx context.Context) pb.ServerAddress {
return vs.getCurrentMaster()
}
// lookupRaftLeaderMaster resolves the raft leader for topology mutations via
// GetMasterConfiguration on configured peers. It does not update currentMaster;
// the heartbeat loop owns that field and reconnects when the stream reports a
// different leader than the connected peer.
func (vs *VolumeServer) lookupRaftLeaderMaster(ctx context.Context) (pb.ServerAddress, error) {
if ctx == nil {
ctx = context.Background()
}
leader, err := operation.LookupRaftLeaderMaster(ctx, vs.SeedMasterNodes, vs.grpcDialOption)
if err != nil {
if isContextDoneErr(err) {
glog.V(1).Infof("volume server %s:%d: raft leader lookup: %v", vs.store.Ip, vs.store.Port, err)
} else {
glog.V(0).Infof("volume server %s:%d: raft leader lookup: %v", vs.store.Ip, vs.store.Port, err)
}
return "", err
}
current := vs.getCurrentMaster()
if !leader.Equals(current) {
glog.V(1).Infof("volume server %s:%d: raft leader %v (heartbeat peer %v)", vs.store.Ip, vs.store.Port, leader, current)
}
return leader, nil
}
func isContextDoneErr(err error) bool {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return true
}
if st, ok := status.FromError(err); ok {
return st.Code() == codes.Canceled || st.Code() == codes.DeadlineExceeded
}
return false
}
// getCurrentMaster returns vs.currentMaster under a read lock so callers
// (e.g. Ping admission) do not race with the heartbeat goroutine that
// rewrites it on leader changes.
@@ -262,10 +298,10 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp
case first := <-vs.store.NewEcShardsChan:
shards := util.DrainChannel(vs.store.NewEcShardsChan, first)
deltaBeat := &master_pb.Heartbeat{
Ip: ip,
Port: port,
DataCenter: dataCenter,
Rack: rack,
Ip: ip,
Port: port,
DataCenter: dataCenter,
Rack: rack,
NewEcShards: shards,
}
for _, s := range shards {
@@ -295,10 +331,10 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp
case first := <-vs.store.DeletedEcShardsChan:
shards := util.DrainChannel(vs.store.DeletedEcShardsChan, first)
deltaBeat := &master_pb.Heartbeat{
Ip: ip,
Port: port,
DataCenter: dataCenter,
Rack: rack,
Ip: ip,
Port: port,
DataCenter: dataCenter,
Rack: rack,
DeletedEcShards: shards,
}
for _, s := range shards {
@@ -0,0 +1,62 @@
package weed_server
import (
"context"
"fmt"
"net"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func TestLookupRaftLeaderMasterDoesNotUpdateCurrentMaster(t *testing.T) {
follower := startFakeMasterServerForLeaderLookup(t, &fakeLeaderConfigServer{
leader: "leader.example.com:9333.19333",
})
heartbeatPeer := pb.ServerAddress("10.0.0.1:9333")
vs := &VolumeServer{
SeedMasterNodes: []pb.ServerAddress{follower},
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
store: &storage.Store{Ip: "127.0.0.1", Port: 8080},
}
vs.setCurrentMaster(heartbeatPeer)
leader, err := vs.lookupRaftLeaderMaster(context.Background())
if err != nil {
t.Fatalf("lookup: %v", err)
}
if got, want := leader.ToHttpAddress(), "leader.example.com:9333"; got != want {
t.Fatalf("leader = %q, want %q", got, want)
}
if got := vs.getCurrentMaster(); got != heartbeatPeer {
t.Fatalf("currentMaster = %v, want unchanged %v", got, heartbeatPeer)
}
}
type fakeLeaderConfigServer struct {
master_pb.UnimplementedSeaweedServer
leader string
}
func (s *fakeLeaderConfigServer) GetMasterConfiguration(_ context.Context, _ *master_pb.GetMasterConfigurationRequest) (*master_pb.GetMasterConfigurationResponse, error) {
return &master_pb.GetMasterConfigurationResponse{Leader: s.leader}, nil
}
func startFakeMasterServerForLeaderLookup(t *testing.T, srv master_pb.SeaweedServer) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcServer := grpc.NewServer()
master_pb.RegisterSeaweedServer(grpcServer, srv)
go func() { _ = grpcServer.Serve(lis) }()
t.Cleanup(grpcServer.GracefulStop)
_, port, _ := net.SplitHostPort(lis.Addr().String())
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", port))
}
+22 -3
View File
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
@@ -174,6 +175,11 @@ func (vs *VolumeServer) VolumeEcShardsGenerate(ctx context.Context, req *volume_
return &volume_server_pb.VolumeEcShardsGenerateResponse{}, nil
}
func recordEcRebuild(result string, d time.Duration) {
stats.VolumeServerECRebuildHistogram.WithLabelValues(result).Observe(d.Seconds())
stats.VolumeServerECRebuildCounter.WithLabelValues(result).Inc()
}
// VolumeEcShardsRebuild generates the any of the missing .ec00 ~ .ec13 files
func (vs *VolumeServer) VolumeEcShardsRebuild(ctx context.Context, req *volume_server_pb.VolumeEcShardsRebuildRequest) (*volume_server_pb.VolumeEcShardsRebuildResponse, error) {
if err := vs.CheckMaintenanceMode(); err != nil {
@@ -235,21 +241,26 @@ func (vs *VolumeServer) VolumeEcShardsRebuild(ctx context.Context, req *volume_s
// Rebuild missing EC files, searching all disk locations for input shards.
// Present input shards are verified against the bitrot sidecar (when present)
// and corrupt ones are regenerated; unsafe_ignore_sidecar bypasses the guard.
start := time.Now()
dataBaseFileName := path.Join(rebuildDataDir, baseFileName)
if generatedShardIds, err := erasure_coding.RebuildEcFiles(dataBaseFileName, erasure_coding.BackgroundECContext(), req.UnsafeIgnoreSidecar, additionalDirs...); err != nil {
generatedShardIds, err := erasure_coding.RebuildEcFiles(dataBaseFileName, erasure_coding.BackgroundECContext(), req.UnsafeIgnoreSidecar, additionalDirs...)
if err != nil {
recordEcRebuild("failure", time.Since(start))
return nil, fmt.Errorf("RebuildEcFiles %s: %v", dataBaseFileName, err)
} else {
rebuiltShardIds = generatedShardIds
}
rebuiltShardIds = generatedShardIds
indexBaseFileName := path.Join(rebuildLocation.IdxDirectory, baseFileName)
if !util.FileExists(indexBaseFileName+".ecx") && rebuildLocation.IdxDirectory != rebuildLocation.Directory {
indexBaseFileName = path.Join(rebuildLocation.Directory, baseFileName)
}
if err := erasure_coding.RebuildEcxFile(indexBaseFileName); err != nil {
recordEcRebuild("failure", time.Since(start))
return nil, fmt.Errorf("RebuildEcxFile %s: %v", indexBaseFileName, err)
}
recordEcRebuild("success", time.Since(start))
// Opportunistic bitrot backfill: if protection is enabled, no sidecar exists
// yet (a volume encoded before this feature), and this rebuilder can reach
// every shard, compute and write a generation-0 sidecar. The TOFU baseline
@@ -717,6 +728,14 @@ func (vs *VolumeServer) VolumeEcShardsMount(ctx context.Context, req *volume_ser
glog.V(0).Infof("VolumeEcShardsMount: %v", req)
// Fetch a missing .ecx from a peer first so on-disk shards that never had a
// local index can be mounted (issue #10104). Driven on demand by ec.rebuild.
// volume_id 0 recovers every orphan on this server, including volumes the
// master never learned about.
if req.RecoverMissingIndex {
vs.recoverMissingEcIndexes(req.VolumeId)
}
for _, shardId := range req.ShardIds {
err := vs.store.MountEcShards(req.Collection, needle.VolumeId(req.VolumeId), erasure_coding.ShardId(shardId), req.SourceDiskType)
@@ -0,0 +1,168 @@
package weed_server
import (
"context"
"fmt"
"math"
"os"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
)
// ecRecoveryLookupTimeout bounds the master LookupEcVolume call so a slow or
// unresponsive master cannot hang the synchronous recovery RPC.
const ecRecoveryLookupTimeout = time.Minute
// recoverMissingEcIndexes fetches the .ecx / .ecj / .vif index files for EC
// volumes whose shards sit on this server while the index lives only on a peer,
// then mounts the now-recoverable shards. This self-heals the "shards present,
// .ecx missing everywhere local" layout (issue #10104) that the per-disk loader
// and the same-server cross-disk reconcile both leave unmounted, including for
// volumes already broken before the upgrade.
//
// filterVid limits recovery to a single volume id; 0 recovers every orphan on
// this server (used by ec.rebuild to heal volumes the master never learned
// about). It is driven on demand by VolumeEcShardsMount (recover_missing_index),
// so an operator triggers it through ec.rebuild rather than a background loop.
// Returns the number of volumes whose index was recovered.
func (vs *VolumeServer) recoverMissingEcIndexes(filterVid uint32) int {
orphans := vs.store.CollectEcVolumesMissingIndex()
if filterVid != 0 {
filtered := orphans[:0]
for _, m := range orphans {
if uint32(m.VolumeId) == filterVid {
filtered = append(filtered, m)
}
}
orphans = filtered
}
if len(orphans) == 0 {
return 0
}
master := vs.getCurrentMaster()
if master == "" {
glog.Warningf("cannot recover missing EC index without a master connection")
return 0
}
self := pb.NewServerAddress(vs.store.Ip, vs.store.Port, vs.store.GrpcPort)
recovered := 0
for _, m := range orphans {
peers, err := vs.lookupEcVolumePeers(master, uint32(m.VolumeId), self)
if err != nil {
glog.Warningf("ec volume %d: cannot look up peers to recover missing .ecx: %v", m.VolumeId, err)
continue
}
if len(peers) == 0 {
glog.Warningf("ec volume %d: shards present locally but .ecx missing and no peer holds it; leaving shards unloaded", m.VolumeId)
continue
}
if vs.fetchEcIndexFromPeers(peers, m) {
recovered++
}
}
if recovered > 0 {
vs.store.MountRecoveredEcShards()
glog.V(0).Infof("recovered missing EC index for %d volume(s) from peers and mounted their shards", recovered)
}
return recovered
}
// lookupEcVolumePeers asks the master which servers hold shards for vid and
// returns the unique peer addresses, excluding this server itself.
func (vs *VolumeServer) lookupEcVolumePeers(master pb.ServerAddress, vid uint32, self pb.ServerAddress) ([]pb.ServerAddress, error) {
ctx, cancel := context.WithTimeout(context.Background(), ecRecoveryLookupTimeout)
defer cancel()
var peers []pb.ServerAddress
seen := make(map[pb.ServerAddress]bool)
err := operation.WithMasterServerClient(ctx, false, master, vs.grpcDialOption, func(client master_pb.SeaweedClient) error {
resp, err := client.LookupEcVolume(ctx, &master_pb.LookupEcVolumeRequest{VolumeId: vid})
if err != nil {
return err
}
for _, shardIdLocations := range resp.ShardIdLocations {
for _, loc := range shardIdLocations.Locations {
addr := pb.NewServerAddressFromLocation(loc)
if addr.Equals(self) || seen[addr] {
continue
}
seen[addr] = true
peers = append(peers, addr)
}
}
return nil
})
return peers, err
}
// fetchEcIndexFromPeers tries each peer in turn, copying the .ecx (required) and
// the .ecj / .vif (best-effort) for the volume onto the local disk recorded in
// m. The .ecx is an immutable encode-time index, identical on every holder, so
// any peer's copy serves. The .ecj is a per-holder deletion journal that differs
// across holders (a delete is journaled on only one node); the recovered node
// adopts the source peer's deletion view, exactly as a balanced or rebuilt shard
// does — the EC delete model already tolerates that divergence. The first peer
// that yields a non-empty .ecx wins; a peer with no index or a 0-byte stub is
// skipped (the orphan shards are non-empty, so a 0-byte index cannot be theirs).
// A failed copy removes its partial file so a later attempt is not blocked by a
// stub.
func (vs *VolumeServer) fetchEcIndexFromPeers(peers []pb.ServerAddress, m storage.EcVolumeMissingIndex) bool {
idxBaseFileName := storage.VolumeFileName(m.IdxDir, m.Collection, int(m.VolumeId))
dataBaseFileName := storage.VolumeFileName(m.DataDir, m.Collection, int(m.VolumeId))
ecxPath := idxBaseFileName + ".ecx"
ecjPath := idxBaseFileName + ".ecj"
removePartial := func(path string) {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
glog.Warningf("ec volume %d: remove partial %s: %v", m.VolumeId, path, err)
}
}
for _, peer := range peers {
err := operation.WithVolumeServerClient(true, peer, vs.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
// .ecx is mandatory; a peer without it errors and we move on.
if _, err := vs.doCopyFile(client, true, m.Collection, uint32(m.VolumeId), math.MaxUint32, math.MaxInt64, idxBaseFileName, ".ecx", false, false, nil); err != nil {
removePartial(ecxPath)
return err
}
info, statErr := os.Stat(ecxPath)
if statErr != nil {
removePartial(ecxPath)
return fmt.Errorf("stat copied .ecx %s: %w", ecxPath, statErr)
}
if info.IsDir() || info.Size() == 0 {
removePartial(ecxPath)
return fmt.Errorf("peer %s served an unusable .ecx (size %d)", peer, info.Size())
}
// .ecj is the source peer's deletion journal; .vif carries EC params
// and EncodeTsNs. Both are best-effort: a missing .ecj is recreated at
// mount and a missing .vif falls back to default EC parameters. A failed
// .ecj copy is an in-place append, so drop the partial file; the .vif
// copy stages and renames, leaving nothing to clean up.
if _, err := vs.doCopyFile(client, true, m.Collection, uint32(m.VolumeId), math.MaxUint32, math.MaxInt64, idxBaseFileName, ".ecj", true, true, nil); err != nil {
glog.Warningf("ec volume %d: copy .ecj from %s: %v", m.VolumeId, peer, err)
removePartial(ecjPath)
}
if _, err := vs.doCopyFile(client, true, m.Collection, uint32(m.VolumeId), math.MaxUint32, math.MaxInt64, dataBaseFileName, ".vif", false, true, nil); err != nil {
glog.Warningf("ec volume %d: copy .vif from %s: %v", m.VolumeId, peer, err)
}
return nil
})
if err != nil {
glog.V(1).Infof("ec volume %d: fetch missing .ecx from %s failed: %v", m.VolumeId, peer, err)
continue
}
glog.V(0).Infof("ec volume %d: fetched missing .ecx from %s into %s", m.VolumeId, peer, m.IdxDir)
return true
}
return false
}
@@ -0,0 +1,285 @@
package weed_server
import (
"context"
"net"
"os"
"path/filepath"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// fakeMaster serves only LookupEcVolume, returning the configured holders for
// every shard of one volume. Used to drive the receiver's peer discovery.
type fakeMaster struct {
master_pb.UnimplementedSeaweedServer
volumeId uint32
locations []*master_pb.Location
}
func (m *fakeMaster) LookupEcVolume(_ context.Context, req *master_pb.LookupEcVolumeRequest) (*master_pb.LookupEcVolumeResponse, error) {
resp := &master_pb.LookupEcVolumeResponse{VolumeId: req.VolumeId}
if req.VolumeId != m.volumeId {
return resp, nil
}
// Recovery only needs one peer holding the index; report a couple of shards
// pointing at the holder, independent of the EC ratio.
for shardId := 0; shardId < 2; shardId++ {
resp.ShardIdLocations = append(resp.ShardIdLocations, &master_pb.LookupEcVolumeResponse_EcShardIdLocation{
ShardId: uint32(shardId),
Locations: m.locations,
})
}
return resp, nil
}
// serveGrpc registers register(s) on a fresh localhost listener and returns its
// grpc port, stopping the server on test cleanup.
func serveGrpc(t *testing.T, register func(*grpc.Server)) int {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
srv := grpc.NewServer()
register(srv)
go srv.Serve(lis)
t.Cleanup(srv.Stop)
return lis.Addr().(*net.TCPAddr).Port
}
func newRecoverTestStore(t *testing.T, dir string) *storage.Store {
t.Helper()
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("mkdir %s: %v", dir, err)
}
store := storage.NewStore(nil, "localhost", 8080, 18080, "http://localhost:8080", "store-id",
[]string{dir}, []int32{100}, []util.MinFreeSpace{{}}, "",
storage.NeedleMapInMemory, []types.DiskType{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)
})
return store
}
// TestFetchEcIndexFromPeers_CopiesIndexOverGrpc stands up a source volume server
// that holds the .ecx/.ecj/.vif for a volume and verifies the receiver pulls
// them over a real CopyFile gRPC stream into its own disk, the way #10104
// recovery does when the index lives only on a peer.
func TestFetchEcIndexFromPeers_CopiesIndexOverGrpc(t *testing.T) {
const collection = "video-recordings"
vid := needle.VolumeId(6190)
// Source server: has the index files on disk.
srcDir := filepath.Join(t.TempDir(), "src")
srcStore := newRecoverTestStore(t, srcDir)
srcBase := erasure_coding.EcShardFileName(collection, srcDir, int(vid))
ecxBytes := make([]byte, types.NeedleMapEntrySize*3)
for i := range ecxBytes {
ecxBytes[i] = byte(i)
}
if err := os.WriteFile(srcBase+".ecx", ecxBytes, 0o644); err != nil {
t.Fatalf("write source .ecx: %v", err)
}
if err := os.WriteFile(srcBase+".ecj", []byte("journal"), 0o644); err != nil {
t.Fatalf("write source .ecj: %v", err)
}
if err := os.WriteFile(srcBase+".vif", []byte("volinfo"), 0o644); err != nil {
t.Fatalf("write source .vif: %v", err)
}
// Serve the source over a real TCP gRPC listener.
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcServer := grpc.NewServer()
volume_server_pb.RegisterVolumeServerServer(grpcServer, &VolumeServer{store: srcStore})
go grpcServer.Serve(lis)
t.Cleanup(grpcServer.Stop)
grpcPort := lis.Addr().(*net.TCPAddr).Port
peer := pb.NewServerAddress("127.0.0.1", grpcPort-10000, grpcPort)
// Receiver server: empty disk, ready to receive the index.
dstDir := filepath.Join(t.TempDir(), "dst")
dstStore := newRecoverTestStore(t, dstDir)
receiver := &VolumeServer{
store: dstStore,
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
m := storage.EcVolumeMissingIndex{
Collection: collection,
VolumeId: vid,
IdxDir: dstDir,
DataDir: dstDir,
}
if !receiver.fetchEcIndexFromPeers([]pb.ServerAddress{peer}, m) {
t.Fatalf("fetchEcIndexFromPeers returned false; expected a successful copy")
}
dstBase := erasure_coding.EcShardFileName(collection, dstDir, int(vid))
got, err := os.ReadFile(dstBase + ".ecx")
if err != nil {
t.Fatalf("read copied .ecx: %v", err)
}
if len(got) != len(ecxBytes) {
t.Errorf("copied .ecx size = %d, want %d", len(got), len(ecxBytes))
}
if _, err := os.Stat(dstBase + ".ecj"); err != nil {
t.Errorf("copied .ecj missing: %v", err)
}
if _, err := os.Stat(dstBase + ".vif"); err != nil {
t.Errorf("copied .vif missing: %v", err)
}
}
// TestFetchEcIndexFromPeers_SkipsPeerWithoutIndex verifies the receiver moves on
// to the next peer when the first has no .ecx, and reports failure when no peer
// can serve a usable index.
func TestFetchEcIndexFromPeers_SkipsPeerWithoutIndex(t *testing.T) {
const collection = "video-recordings"
vid := needle.VolumeId(6191)
// Source server with NO index files for this volume.
srcDir := filepath.Join(t.TempDir(), "src")
srcStore := newRecoverTestStore(t, srcDir)
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcServer := grpc.NewServer()
volume_server_pb.RegisterVolumeServerServer(grpcServer, &VolumeServer{store: srcStore})
go grpcServer.Serve(lis)
t.Cleanup(grpcServer.Stop)
grpcPort := lis.Addr().(*net.TCPAddr).Port
peer := pb.NewServerAddress("127.0.0.1", grpcPort-10000, grpcPort)
dstDir := filepath.Join(t.TempDir(), "dst")
dstStore := newRecoverTestStore(t, dstDir)
receiver := &VolumeServer{
store: dstStore,
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
m := storage.EcVolumeMissingIndex{Collection: collection, VolumeId: vid, IdxDir: dstDir, DataDir: dstDir}
if receiver.fetchEcIndexFromPeers([]pb.ServerAddress{peer}, m) {
t.Fatalf("fetchEcIndexFromPeers should fail when no peer has the index")
}
// No stub .ecx must be left behind.
dstBase := erasure_coding.EcShardFileName(collection, dstDir, int(vid))
if _, err := os.Stat(dstBase + ".ecx"); !os.IsNotExist(err) {
t.Errorf("a .ecx stub was left behind; stat err = %v", err)
}
}
// TestVolumeEcShardsMount_RecoverMissingIndex drives the full on-demand path:
// VolumeEcShardsMount with recover_missing_index (volume_id 0 = recover every
// orphan on this server, as ec.rebuild broadcasts it) looks up holders via a
// (fake) master, fetches the missing .ecx/.ecj/.vif from the holding peer over
// gRPC, and mounts the previously-orphaned on-disk shards (issue #10104).
func TestVolumeEcShardsMount_RecoverMissingIndex(t *testing.T) {
const collection = "video-recordings"
vid := needle.VolumeId(6190)
// Holder peer: serves the index files for the volume.
srcDir := filepath.Join(t.TempDir(), "src")
srcStore := newRecoverTestStore(t, srcDir)
srcBase := erasure_coding.EcShardFileName(collection, srcDir, int(vid))
if err := os.WriteFile(srcBase+".ecx", make([]byte, types.NeedleMapEntrySize*4), 0o644); err != nil {
t.Fatalf("write source .ecx: %v", err)
}
if err := os.WriteFile(srcBase+".ecj", nil, 0o644); err != nil {
t.Fatalf("write source .ecj: %v", err)
}
if err := os.WriteFile(srcBase+".vif", []byte("volinfo"), 0o644); err != nil {
t.Fatalf("write source .vif: %v", err)
}
srcGrpcPort := serveGrpc(t, func(s *grpc.Server) {
volume_server_pb.RegisterVolumeServerServer(s, &VolumeServer{store: srcStore})
})
// Fake master points every shard at the holder peer.
masterGrpcPort := serveGrpc(t, func(s *grpc.Server) {
master_pb.RegisterSeaweedServer(s, &fakeMaster{
volumeId: uint32(vid),
locations: []*master_pb.Location{{Url: "127.0.0.1:1", GrpcPort: uint32(srcGrpcPort)}},
})
})
// Receiver: holds orphan shard files on disk, no .ecx anywhere.
dstDir := filepath.Join(t.TempDir(), "dst")
dstStore := newRecoverTestStore(t, dstDir)
const shardSize = 1 << 20
for _, sid := range []erasure_coding.ShardId{0, 5} {
base := erasure_coding.EcShardFileName(collection, dstDir, int(vid))
f, err := os.Create(base + erasure_coding.ToExt(int(sid)))
if err != nil {
t.Fatalf("create shard %d: %v", sid, err)
}
if err := f.Truncate(shardSize); err != nil {
f.Close()
t.Fatalf("truncate shard %d: %v", sid, err)
}
f.Close()
}
receiver := &VolumeServer{
store: dstStore,
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
receiver.setCurrentMaster(pb.NewServerAddress("127.0.0.1", masterGrpcPort-10000, masterGrpcPort))
if _, found := dstStore.FindEcVolume(vid); found {
t.Fatalf("EC volume %d unexpectedly mounted before recovery", vid)
}
// volume_id 0: the receiver discovers the orphan (6190) on disk itself, even
// though the request names no volume and the master never registered it here.
if _, err := receiver.VolumeEcShardsMount(context.Background(), &volume_server_pb.VolumeEcShardsMountRequest{
RecoverMissingIndex: true,
}); err != nil {
t.Fatalf("VolumeEcShardsMount with recover_missing_index: %v", err)
}
ev, found := dstStore.FindEcVolume(vid)
if !found {
t.Fatalf("EC volume %d not mounted after recovery", vid)
}
for _, sid := range []erasure_coding.ShardId{0, 5} {
if _, ok := ev.FindEcVolumeShard(sid); !ok {
t.Errorf("shard %d.%d not registered after recovery", vid, sid)
}
}
}
+2 -1
View File
@@ -124,7 +124,8 @@ func (vs *VolumeServer) ScrubEcVolume(ctx context.Context, req *volume_server_pb
case volume_server_pb.VolumeScrubMode_LOCAL:
files, shardInfos, serrs = v.ScrubLocal()
case volume_server_pb.VolumeScrubMode_FULL:
files, shardInfos, serrs = vs.store.ScrubEcVolume(v.VolumeId)
// TODO: expose force_deleted_needles_check in the RPC and weed shell.
files, shardInfos, serrs = vs.store.ScrubEcVolume(v.VolumeId, false)
case volume_server_pb.VolumeScrubMode_CHECKSUM:
// Verify each local shard's raw bytes against the bitrot sidecar,
// exercising cold parity shards. Read-only. ChecksumScrub's first
+65
View File
@@ -47,6 +47,11 @@ func (c *commandEcRebuild) Help() string {
ec.rebuild [-c EACH_COLLECTION|<collection_name>] [-apply] [-maxParallelization N] [-diskType=<disk_type>]
Before rebuilding, asks volume servers to recover any shards left unmounted by
a missing .ecx index (the index resides only on a peer server). Such shards are
invisible to the master, so recovering them first avoids regenerating data that
is actually present (issue #10104).
Options:
-collection: specify a collection name, or "EACH_COLLECTION" to process all collections
-apply: actually perform the rebuild operations (default is dry-run mode)
@@ -149,6 +154,11 @@ func (c *commandEcRebuild) Do(args []string, commandEnv *CommandEnv, writer io.W
ewg: NewErrorWaitGroup(*maxParallelization),
}
// Recover shards left unmounted by a missing .ecx index before planning: such
// shards never register with the master, so the rebuild below would treat the
// volume as short or unrepairable even though its data is intact (issue #10104).
erb.recoverMissingIndexes()
fmt.Printf("rebuildEcVolumes for %d collection(s)\n", len(collections))
for _, c := range collections {
erb.rebuildEcVolumes(c)
@@ -288,6 +298,61 @@ func (erb *ecRebuilder) rebuildEcVolumes(collection string) {
}
}
// recoverMissingIndexes asks every ec node to fetch a missing .ecx index from a
// peer and mount the on-disk shards it could not load on its own. Shards
// orphaned this way (index only on another server) are absent from the master
// topology, so without this pass ec.rebuild would regenerate or give up on
// shards whose data is actually present — and a volume whose every holder lacks
// the index would not appear in the topology at all. Each node therefore
// recovers all of its on-disk orphans (volume_id 0); an explicit -volumeIds
// list narrows that to the requested volumes. On apply it refreshes the topology
// so the rebuild planning sees the recovered shards (issue #10104).
func (erb *ecRebuilder) recoverMissingIndexes() {
erb.ecNodesMu.Lock()
nodes := append([]*EcNode(nil), erb.ecNodes...)
erb.ecNodesMu.Unlock()
if len(nodes) == 0 {
return
}
// volume_id 0 means "recover every orphan on the node"; a -volumeIds list
// narrows recovery to those ids (each scanned across collections server-side).
vids := erb.volumeIds
if len(vids) == 0 {
vids = []needle.VolumeId{0}
}
if !erb.applyChanges {
erb.write("would ask %d ec node(s) to recover EC shards left unmounted by a missing .ecx index\n", len(nodes))
return
}
for _, node := range nodes {
for _, vid := range vids {
err := operation.WithVolumeServerClient(false, pb.NewServerAddressFromDataNode(node.info), erb.commandEnv.option.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
_, mountErr := client.VolumeEcShardsMount(context.Background(), &volume_server_pb.VolumeEcShardsMountRequest{
VolumeId: uint32(vid),
RecoverMissingIndex: true,
})
return mountErr
})
if err != nil {
erb.write("%s recover missing index (volume %d): %v\n", node.info.Id, vid, err)
}
}
}
// Refresh topology so the rebuild planning sees shards the recovery registered.
refreshed, _, err := collectEcNodes(erb.commandEnv, erb.diskType)
if err != nil {
erb.write("failed to refresh ec nodes after index recovery: %v\n", err)
return
}
erb.ecNodesMu.Lock()
erb.ecNodes = refreshed
erb.ecNodesMu.Unlock()
}
func (erb *ecRebuilder) rebuildOneEcVolume(collection string, volumeId needle.VolumeId, locations EcShardLocations, rebuilder *EcNode) error {
if !erb.isLocked() {
return fmt.Errorf("lock is lost")
+10 -1
View File
@@ -27,6 +27,7 @@ func (c *commandVolumeDeleteEmpty) Help() string {
return `delete empty volumes from all volume servers
volume.deleteEmpty -quietFor=24h -apply
volume.deleteEmpty -collectionPattern=important* -quietFor=24h -apply
This command deletes all empty volumes from one volume server.
@@ -41,6 +42,7 @@ func (c *commandVolumeDeleteEmpty) Do(args []string, commandEnv *CommandEnv, wri
volDeleteCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
quietPeriod := volDeleteCommand.Duration("quietFor", 24*time.Hour, "select empty volumes with no recent writes, avoid newly created ones")
collectionPattern := volDeleteCommand.String("collectionPattern", "", "match with wildcard characters '*' and '?'")
applyBalancing := volDeleteCommand.Bool("apply", false, "apply to delete empty volumes")
// TODO: remove this alias
applyBalancingAlias := volDeleteCommand.Bool("force", false, "apply to delete empty volumes (alias for -apply)")
@@ -67,7 +69,7 @@ func (c *commandVolumeDeleteEmpty) Do(args []string, commandEnv *CommandEnv, wri
eachDataNode(topologyInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
for _, diskInfo := range dn.DiskInfos {
for _, v := range diskInfo.VolumeInfos {
if v.Size <= super_block.SuperBlockSize && v.ModifiedAtSecond > 0 && v.ModifiedAtSecond+quietSeconds < nowUnixSeconds {
if isEmptyVolumeDeleteCandidate(v, quietSeconds, nowUnixSeconds, *collectionPattern) {
if *applyBalancing {
log.Printf("deleting empty volume %d from %s", v.Id, dn.Id)
if deleteErr := deleteVolume(commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id),
@@ -85,3 +87,10 @@ func (c *commandVolumeDeleteEmpty) Do(args []string, commandEnv *CommandEnv, wri
return
}
func isEmptyVolumeDeleteCandidate(v *master_pb.VolumeInformationMessage, quietSeconds, nowUnixSeconds int64, collectionPattern string) bool {
return matchesVolumeCollectionPattern(collectionPattern, v.Collection) &&
v.Size <= super_block.SuperBlockSize &&
v.ModifiedAtSecond > 0 &&
v.ModifiedAtSecond+quietSeconds < nowUnixSeconds
}
@@ -0,0 +1,41 @@
package shell
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
func TestIsEmptyVolumeDeleteCandidateCollectionPattern(t *testing.T) {
now := int64(1000)
quietSeconds := int64(100)
quietEmptyVolume := &master_pb.VolumeInformationMessage{
Size: 0,
ModifiedAtSecond: now - quietSeconds - 1,
Collection: "important-logs",
}
tests := []struct {
name string
pattern string
collection string
want bool
}{
{name: "empty pattern matches named collection", pattern: "", collection: "important-logs", want: true},
{name: "wildcard matches collection", pattern: "important*", collection: "important-logs", want: true},
{name: "wildcard rejects collection", pattern: "important*", collection: "other-logs", want: false},
{name: "default pattern matches empty collection", pattern: CollectionDefault, collection: "", want: true},
{name: "default pattern rejects named collection", pattern: CollectionDefault, collection: "important-logs", want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v := *quietEmptyVolume
v.Collection = tt.collection
if got := isEmptyVolumeDeleteCandidate(&v, quietSeconds, now, tt.pattern); got != tt.want {
t.Fatalf("isEmptyVolumeDeleteCandidate(collection=%q, pattern=%q) = %v, want %v",
tt.collection, tt.pattern, got, tt.want)
}
})
}
}
+20 -38
View File
@@ -4,7 +4,6 @@ import (
"flag"
"fmt"
"io"
"path/filepath"
"strconv"
"strings"
"time"
@@ -15,6 +14,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
@@ -114,6 +114,12 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
var underReplicatedVolumeIds, overReplicatedVolumeIds, misplacedVolumeIds []uint32
for vid, replicas := range volumeReplicas {
replica := replicas[0]
// Filter here so the termination counter matches what gets fixed; else -apply loops forever.
if !c.matchCollectionPattern(replica.info.Collection) {
continue
}
replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
// build locations list for optional verbose output
@@ -255,6 +261,18 @@ func checkOneVolume(a *VolumeReplica, b *VolumeReplica, writer io.Writer, comman
return
}
// matchCollectionPattern reports whether collection matches -collectionPattern:
// empty matches everything, CollectionDefault matches the unnamed collection.
func (c *commandVolumeFixReplication) matchCollectionPattern(collection string) bool {
if *c.collectionPattern == "" {
return true
}
if *c.collectionPattern == CollectionDefault {
return collection == ""
}
return wildcard.MatchesWildcard(*c.collectionPattern, collection)
}
func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, doCheck bool, volumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, selectOneVolumeFn SelectOneVolumeFunc) error {
if len(volumeIds) == 0 {
// nothing to do
@@ -271,23 +289,6 @@ func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, wr
continue
}
// check collection name pattern
if *c.collectionPattern != "" {
var matched bool
if *c.collectionPattern == CollectionDefault {
matched = replica.info.Collection == ""
} else {
var err error
matched, err = filepath.Match(*c.collectionPattern, replica.info.Collection)
if err != nil {
return fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
}
}
if !matched {
continue
}
}
collectionIsMismatch := false
for _, volumeReplica := range replicas {
if volumeReplica.info.Collection != replica.info.Collection {
@@ -365,30 +366,11 @@ func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *Co
replica := pickOneReplicaToCopyFrom(replicas)
replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
foundNewLocation := false
hasSkippedCollection := false
keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
for _, dst := range allLocations {
// check whether data nodes satisfy the constraints
if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
// check collection name pattern
if *c.collectionPattern != "" {
var matched bool
if *c.collectionPattern == CollectionDefault {
matched = replica.info.Collection == ""
} else {
var err error
matched, err = filepath.Match(*c.collectionPattern, replica.info.Collection)
if err != nil {
return false, fmt.Errorf("match pattern %s with collection %s: %v", *c.collectionPattern, replica.info.Collection, err)
}
}
if !matched {
hasSkippedCollection = true
break
}
}
// ask the volume server to replicate the volume
foundNewLocation = true
fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
@@ -414,7 +396,7 @@ func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *Co
}
}
if !foundNewLocation && !hasSkippedCollection {
if !foundNewLocation {
fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
}
return false, nil
@@ -0,0 +1,34 @@
package shell
import "testing"
func TestMatchCollectionPattern(t *testing.T) {
tests := []struct {
name string
pattern string
collection string
expected bool
}{
{name: "empty pattern matches any collection", pattern: "", collection: "jfs-hdfs-test", expected: true},
{name: "empty pattern matches empty collection", pattern: "", collection: "", expected: true},
{name: "default pattern matches empty collection", pattern: CollectionDefault, collection: "", expected: true},
{name: "default pattern rejects named collection", pattern: CollectionDefault, collection: "jfs-hdfs-test", expected: false},
{name: "exact match", pattern: "smart-highlevel-test", collection: "smart-highlevel-test", expected: true},
{name: "exact mismatch", pattern: "smart-highlevel-test", collection: "jfs-hdfs-test", expected: false},
{name: "prefix wildcard match", pattern: "smart*", collection: "smart-highlevel-test", expected: true},
{name: "prefix wildcard mismatch", pattern: "smart*", collection: "jfs-hdfs-test", expected: false},
{name: "single char wildcard match", pattern: "vol?", collection: "vol1", expected: true},
{name: "single char wildcard mismatch", pattern: "vol?", collection: "vol42", expected: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pattern := tt.pattern
c := &commandVolumeFixReplication{collectionPattern: &pattern}
if got := c.matchCollectionPattern(tt.collection); got != tt.expected {
t.Errorf("matchCollectionPattern(pattern=%q, collection=%q) = %v, want %v",
tt.pattern, tt.collection, got, tt.expected)
}
})
}
}
+23 -11
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"flag"
"fmt"
"path/filepath"
"slices"
"sort"
"strings"
@@ -15,6 +14,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
"io"
)
@@ -224,12 +224,17 @@ func (c *commandVolumeList) writeDataCenterInfo(writer io.Writer, t *master_pb.D
return strings.Compare(a.Id, b.Id)
})
dataCenterInfoFound := false
dataCenterHeaderPrinted := false
for _, r := range t.RackInfos {
if *c.rack != "" && *c.rack != r.Id {
continue
}
s.add(c.writeRackInfo(writer, r, verbosityLevel, func() {
if dataCenterHeaderPrinted {
return
}
output(verbosityLevel >= 1, writer, " DataCenter %s%s\n", t.Id, diskInfosToString(t.DiskInfos))
dataCenterHeaderPrinted = true
}))
if !dataCenterInfoFound && !s.isEmpty() {
dataCenterInfoFound = true
@@ -245,13 +250,18 @@ func (c *commandVolumeList) writeRackInfo(writer io.Writer, t *master_pb.RackInf
return strings.Compare(a.Id, b.Id)
})
rackInfoFound := false
rackHeaderPrinted := false
for _, dn := range t.DataNodeInfos {
if *c.dataNode != "" && *c.dataNode != dn.Id {
continue
}
s.add(c.writeDataNodeInfo(writer, dn, verbosityLevel, func() {
outCenterInfo()
if rackHeaderPrinted {
return
}
output(verbosityLevel >= 2, writer, " Rack %s%s\n", t.Id, diskInfosToString(t.DiskInfos))
rackHeaderPrinted = true
}))
if !rackInfoFound && !s.isEmpty() {
rackInfoFound = true
@@ -309,16 +319,8 @@ func (c *commandVolumeList) isNotMatchDiskInfo(readOnly bool, collection string,
if *c.writable && (readOnly || volumeSize == -1 || (c.volumeSizeLimitMb > 0 && uint64(volumeSize) >= c.volumeSizeLimitMb*util.MiByte)) {
return true
}
if *c.collectionPattern != "" {
var matched bool
if *c.collectionPattern == CollectionDefault {
matched = (collection == "")
} else {
matched, _ = filepath.Match(*c.collectionPattern, collection)
}
if !matched {
return true
}
if !matchesVolumeCollectionPattern(*c.collectionPattern, collection) {
return true
}
if *c.volumeId > 0 && *c.volumeId != uint64(volumeId) {
return true
@@ -326,6 +328,16 @@ func (c *commandVolumeList) isNotMatchDiskInfo(readOnly bool, collection string,
return false
}
func matchesVolumeCollectionPattern(pattern, collection string) bool {
if pattern == "" {
return true
}
if pattern == CollectionDefault {
return collection == ""
}
return wildcard.MatchesWildcard(pattern, collection)
}
func (c *commandVolumeList) writeDiskInfo(writer io.Writer, t *master_pb.DiskInfo, verbosityLevel int, outNodeInfo func()) statistics {
var s statistics
diskType := t.Type
+28
View File
@@ -194,6 +194,34 @@ func TestWriteDataNodeInfo_SplitsCollapsedDisksByPhysicalDiskId(t *testing.T) {
}
}
func TestWriteTopologyInfo_PrintsParentHeadersOnce(t *testing.T) {
topo := topoFromNodes(
volNode("node1:8081", &master_pb.VolumeInformationMessage{Id: 1, Collection: "c"}),
volNode("node2:8081", &master_pb.VolumeInformationMessage{Id: 2, Collection: "c"}),
)
topo.DiskInfos = map[string]*master_pb.DiskInfo{"hdd": {Type: "hdd"}}
topo.DataCenterInfos[0].DiskInfos = map[string]*master_pb.DiskInfo{"hdd": {Type: "hdd"}}
topo.DataCenterInfos[0].RackInfos[0].DiskInfos = map[string]*master_pb.DiskInfo{"hdd": {Type: "hdd"}}
c := &commandVolumeList{}
fs := flag.NewFlagSet("volume.list", flag.ContinueOnError)
c.collectionPattern = fs.String("collection", "", "")
c.dataCenter = fs.String("dataCenter", "", "")
c.rack = fs.String("rack", "", "")
c.dataNode = fs.String("dataNode", "", "")
c.readonly = fs.Bool("readonly", false, "")
c.writable = fs.Bool("writable", false, "")
c.volumeId = fs.Uint64("volumeId", 0, "")
var dcBuf bytes.Buffer
c.writeTopologyInfo(&dcBuf, topo, 30000, 1)
assert.Equal(t, 1, strings.Count(dcBuf.String(), " DataCenter dc1 hdd("))
var rackBuf bytes.Buffer
c.writeTopologyInfo(&rackBuf, topo, 30000, 2)
assert.Equal(t, 1, strings.Count(rackBuf.String(), " Rack rack1 hdd("))
}
// volNode builds a single-node topology from (volumeId, collection) pairs so the
// duplicate-detection tests can describe a cluster compactly.
func volNode(nodeId string, volumes ...*master_pb.VolumeInformationMessage) *master_pb.DataNodeInfo {
+21
View File
@@ -512,6 +512,25 @@ var (
Help: "Counter of replication failures by operation and reason (timeout, connection_refused, context_cancelled, server_error).",
}, []string{"operation", "reason"})
// VolumeServerECRebuildHistogram records the duration of EC shard rebuild operations by result (success, failure).
VolumeServerECRebuildHistogram = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: Namespace,
Subsystem: subsystemVolumeServer,
Name: "ec_rebuild_seconds",
Help: "Bucketed histogram of EC shard rebuild/reconstruct duration by result.",
Buckets: prometheus.ExponentialBuckets(0.01, 2, 20),
}, []string{"result"})
// VolumeServerECRebuildCounter counts EC shard rebuild operations by result (success, failure).
VolumeServerECRebuildCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemVolumeServer,
Name: "ec_rebuild_total",
Help: "Counter of EC shard rebuild operations by result.",
}, []string{"result"})
S3RequestCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
@@ -886,6 +905,8 @@ func init() {
Gather.MustRegister(VolumeServerReplicationHistogram)
Gather.MustRegister(VolumeServerReplicationTargets)
Gather.MustRegister(VolumeServerReplicationFailures)
Gather.MustRegister(VolumeServerECRebuildHistogram)
Gather.MustRegister(VolumeServerECRebuildCounter)
Gather.MustRegister(MasterUnderReplicatedVolumes)
Gather.MustRegister(MasterVolumeCreationCounter)
+58
View File
@@ -0,0 +1,58 @@
package stats
import (
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
)
func TestECRebuildMetricsRegistered(t *testing.T) {
t.Cleanup(VolumeServerECRebuildCounter.Reset)
t.Cleanup(VolumeServerECRebuildHistogram.Reset)
// A HistogramVec emits no metric family until it has a child, so observe once.
VolumeServerECRebuildCounter.WithLabelValues("success").Inc()
VolumeServerECRebuildHistogram.WithLabelValues("success").Observe(0.1)
metrics, err := Gather.Gather()
if err != nil {
t.Fatalf("failed to gather metrics: %v", err)
}
counterFound := false
histogramFound := false
for _, mf := range metrics {
if mf.GetName() == "SeaweedFS_volumeServer_ec_rebuild_total" {
counterFound = true
}
if mf.GetName() == "SeaweedFS_volumeServer_ec_rebuild_seconds" {
histogramFound = true
}
}
if !counterFound {
t.Errorf("VolumeServerECRebuildCounter: metric not registered with Gather")
}
if !histogramFound {
t.Errorf("VolumeServerECRebuildHistogram: metric not registered with Gather")
}
}
func TestECRebuildCounterIncrement(t *testing.T) {
VolumeServerECRebuildCounter.Reset()
t.Cleanup(func() {
VolumeServerECRebuildCounter.Reset()
})
VolumeServerECRebuildCounter.WithLabelValues("success").Inc()
VolumeServerECRebuildCounter.WithLabelValues("failure").Inc()
got := testutil.ToFloat64(VolumeServerECRebuildCounter.WithLabelValues("success"))
if got != 1 {
t.Errorf("expected 1.0, got %f", got)
}
got = testutil.ToFloat64(VolumeServerECRebuildCounter.WithLabelValues("failure"))
if got != 1 {
t.Errorf("expected 1.0, got %f", got)
}
}
@@ -0,0 +1,60 @@
package erasure_coding
import (
"encoding/hex"
"os"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
// interopSample is the fully-deterministic sidecar shared with the Rust port's
// ec_bitrot.rs `sample()`. Both binaries must serialize it to identical bytes.
func interopSample() *volume_server_pb.EcBitrotProtection {
return &volume_server_pb.EcBitrotProtection{
Algorithm: volume_server_pb.ChecksumAlgorithm_CHECKSUM_CRC32C,
BlockSize: uint32(DefaultBitrotBlockSize),
EcShardConfig: &volume_server_pb.EcShardConfig{
DataShards: 10,
ParityShards: 4,
},
Shards: []*volume_server_pb.EcShardChecksums{
{ShardId: 0, CoveredSize: 1024 * 1024, BlockCrc32C: packUint32LE([]uint32{0x01020304})},
{ShardId: 1, CoveredSize: 1024 * 1024, BlockCrc32C: packUint32LE([]uint32{0x05060708})},
},
EncodeUuid: []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
}
}
// canonicalInteropHex is the exact on-disk bytes of interopSample(). The Rust
// port's ec_bitrot.rs test_byte_exact_go_interop pins the SAME constant, so a
// format change in EITHER binary (new always-serialized field, renumber,
// EcShardConfig default flip, protobuf canonicalization change) fails that
// binary's test instead of silently desyncing a Go-written sidecar from a
// Rust-written one. If you intentionally change the format, regenerate this
// (run with -v to print the hex) and update the Rust constant in lock-step.
const canonicalInteropHex = "45435355000100000039cc1b826a080110808080082204080a10042a0a108080401a04040302012a0c0801108080401a04080706053210000102030405060708090a0b0c0d0e0f"
// TestBitrotSidecarBytes_RustInterop pins the on-disk bytes so a Go-side format
// drift fails here, and the Rust port asserts the same constant (cross-binary
// sidecar interop).
func TestBitrotSidecarBytes_RustInterop(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "v1.ecsum")
if err := SaveBitrotSidecar(path, interopSample()); err != nil {
t.Fatalf("save: %v", err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read: %v", err)
}
if got := hex.EncodeToString(data); got != canonicalInteropHex {
t.Fatalf("bitrot sidecar bytes drifted from the cross-binary canonical form;\n got=%s\nwant=%s\n(regenerate and update the Rust constant in lock-step)", got, canonicalInteropHex)
}
// Round-trips through the loader.
if _, err := LoadBitrotSidecar(path); err != nil {
t.Fatalf("load: %v", err)
}
}
@@ -0,0 +1,65 @@
package erasure_coding_test
import (
"os"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
// setupScrubLocalVolume seeds one live .ecx entry and a shard 0 whose bytes form
// the needle's on-disk header, then returns a loaded EcVolume with shard 0 added.
func setupScrubLocalVolume(t *testing.T, shard0 []byte) *erasure_coding.EcVolume {
t.Helper()
dir := t.TempDir()
collection := "test"
vid := needle.VolumeId(1)
base := filepath.Join(dir, collection+"_1")
if err := os.WriteFile(base+".ecx", makeNeedleMapEntry(types.NeedleId(1), types.ToOffset(0), types.Size(100)), 0644); err != nil {
t.Fatalf("write ecx: %v", err)
}
if err := os.WriteFile(base+".ecj", []byte{}, 0644); err != nil {
t.Fatalf("write ecj: %v", err)
}
if err := os.WriteFile(base+".vif", []byte{}, 0644); err != nil {
t.Fatalf("write vif: %v", err)
}
if err := os.WriteFile(base+".ec00", shard0, 0644); err != nil {
t.Fatalf("write ec00: %v", err)
}
ecv, err := erasure_coding.NewEcVolume("hdd", dir, dir, collection, vid)
if err != nil {
t.Fatalf("NewEcVolume: %v", err)
}
shard, err := erasure_coding.NewEcVolumeShard("hdd", dir, collection, vid, 0)
if err != nil {
t.Fatalf("NewEcVolumeShard: %v", err)
}
ecv.AddEcVolumeShard(shard)
return ecv
}
// A needle the .ecx still reports as live (size 100) but whose reassembled
// on-disk header carries size 0 is a delete-state disagreement, not corruption.
func TestScrubLocal_SuppressesDeleteStateDisagreement(t *testing.T) {
ecv := setupScrubLocalVolume(t, make([]byte, 256)) // all-zero header => size 0
if _, _, errs := ecv.ScrubLocal(); len(errs) != 0 {
t.Fatalf("delete-state disagreement must be suppressed, got %v", errs)
}
}
// A non-zero on-disk header size that disagrees with the index is genuine
// corruption and must still be reported.
func TestScrubLocal_ReportsGenuineSizeCorruption(t *testing.T) {
shard0 := make([]byte, 256)
shard0[15] = 50 // header size field (big-endian uint32) = 50, != index 100 and != 0
ecv := setupScrubLocalVolume(t, shard0)
if _, _, errs := ecv.ScrubLocal(); len(errs) == 0 {
t.Fatal("a non-zero size mismatch is genuine corruption and must be reported")
}
}
@@ -2,6 +2,7 @@ package erasure_coding
import (
"bytes"
"errors"
"fmt"
"slices"
@@ -280,7 +281,12 @@ func (ecv *EcVolume) ScrubLocal() (int64, []*volume_server_pb.EcShardInfo, []err
// needle was fully recovered from local shards \o/ let's check it
n := needle.Needle{}
if err := n.ReadBytes(data, 0, size, ecv.Version); err != nil {
errs = append(errs, fmt.Errorf("needle %d on volume %d, shards %v: %v", id, ecv.VolumeId, localShardIds, err))
// A delete-state disagreement between the .ecx index and the reassembled
// on-disk header (live index vs zero header size) is not corruption.
deleteStateDisagrees := errors.Is(err, needle.ErrorSizeMismatch) && size.IsDeleted() != (n.Size == 0)
if !deleteStateDisagrees {
errs = append(errs, fmt.Errorf("needle %d on volume %d, shards %v: %v", id, ecv.VolumeId, localShardIds, err))
}
}
}
+13 -2
View File
@@ -56,7 +56,18 @@ func CheckIndexFile(r io.ReaderAt, indexFileSize int64, version needle.Version)
return entries[i].Compare(entries[j]) < 0
})
for i, e := range entries {
// Offset-0 logical tombstones (remote-tier deletes) occupy no physical .dat
// extent, so they cannot overlap anything — exclude them from the overlap
// check. They are still counted below for the index-size check.
physical := make([]*indexEntry, 0, len(entries))
for _, e := range entries {
if e.offset == 0 && e.size.IsDeleted() {
continue
}
physical = append(physical, e)
}
for i, e := range physical {
if i == 0 {
// nothing to check for the first entry
continue
@@ -67,7 +78,7 @@ func CheckIndexFile(r io.ReaderAt, indexFileSize int64, version needle.Version)
end += size - 1
}
last := entries[i-1]
last := physical[i-1]
lastStart, lastEnd := last.offset, last.offset
if lastSize := needle.GetActualSize(last.size, version); lastSize != 0 {
lastEnd += lastSize - 1
+27
View File
@@ -1,14 +1,41 @@
package idx
import (
"bytes"
"fmt"
"os"
"reflect"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
func idxEntryBytes(id types.NeedleId, offset types.Offset, size types.Size) []byte {
b := make([]byte, types.NeedleIdSize+types.OffsetSize+types.SizeSize)
types.NeedleIdToBytes(b[0:types.NeedleIdSize], id)
types.OffsetToBytes(b[types.NeedleIdSize:types.NeedleIdSize+types.OffsetSize], offset)
types.SizeToBytes(b[types.NeedleIdSize+types.OffsetSize:], size)
return b
}
// An offset-0 logical tombstone (remote-tier delete) occupies no physical .dat
// extent, so it must not be flagged as overlapping a real needle. The tombstone
// row is still counted for the index-size check.
func TestCheckIndexFile_IgnoresOffset0Tombstone(t *testing.T) {
var buf []byte
buf = append(buf, idxEntryBytes(types.NeedleId(1), types.ToOffset(8), types.Size(100))...)
buf = append(buf, idxEntryBytes(types.NeedleId(2), types.ToOffset(0), types.TombstoneFileSize)...)
count, errs := CheckIndexFile(bytes.NewReader(buf), int64(len(buf)), needle.Version3)
if count != 2 {
t.Errorf("tombstone row must still count: got %d", count)
}
if len(errs) != 0 {
t.Errorf("offset-0 tombstone must not overlap: %v", errs)
}
}
func TestCheckIndexFile(t *testing.T) {
testCases := []struct {
name string
+83
View File
@@ -0,0 +1,83 @@
package storage
import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
// EcVolumeMissingIndex names an EC volume whose .ec?? shard files are present on
// this store but whose .ecx index is missing on every local disk, so the shards
// cannot be mounted. The per-disk loader and the same-server cross-disk reconcile
// both leave such shards unmounted because the index lives only on a different
// server (issue #10104). The recovery path fetches the index from a peer that
// still holds it and drops it into IdxDir / DataDir, then re-runs the mount.
type EcVolumeMissingIndex struct {
Collection string
VolumeId needle.VolumeId
IdxDir string // destination for the fetched .ecx / .ecj
DataDir string // destination for the fetched .vif
}
// CollectEcVolumesMissingIndex returns every EC volume that has shard files on a
// local disk but no usable .ecx on any local disk — the cross-server orphans a
// peer index fetch must recover. Volumes whose index merely sits on a sibling
// disk are excluded (the same-server reconcile/mirror handles those). The
// destination dirs are taken from the first disk found holding orphan shards;
// MountRecoveredEcShards mirrors the index onto the remaining shard-bearing disks.
//
// It scans on-disk shard files directly, so it surfaces volumes the master never
// learned about — including those whose every holder is missing its index.
func (s *Store) CollectEcVolumesMissingIndex() []EcVolumeMissingIndex {
ecxOwners := s.indexEcxOwners()
seen := make(map[ecKeyForReconcile]bool)
var missing []EcVolumeMissingIndex
for _, loc := range s.Locations {
for key := range loc.collectOrphanEcShards() {
if _, hasLocalIndex := ecxOwners[key]; hasLocalIndex {
continue
}
if seen[key] {
continue
}
seen[key] = true
missing = append(missing, EcVolumeMissingIndex{
Collection: key.collection,
VolumeId: key.vid,
IdxDir: loc.IdxDirectory,
DataDir: loc.Directory,
})
}
}
return missing
}
// MountRecoveredEcShards mounts EC shards that became loadable after a missing
// .ecx was fetched onto a local disk. It mirrors the index onto every
// shard-bearing disk, mounts the disks that now have a local index, and falls
// back to the cross-disk virtual mount for any disk the mirror could not reach.
// Each shard load announces itself through ecShardNotifyHandler so the master
// learns about the now-registered shards.
func (s *Store) MountRecoveredEcShards() {
s.mirrorEcMetadataToShardDisks()
s.loadOrphanEcShardsWithLocalIndex()
s.reconcileEcShardsAcrossDisks()
}
// loadOrphanEcShardsWithLocalIndex mounts on-disk EC shards whose .ecx index is
// now present on the same disk. Unlike reconcileEcShardsAcrossDisks it does not
// require a sibling disk, so a single-disk store recovers too once its index has
// been fetched from a peer.
func (s *Store) loadOrphanEcShardsWithLocalIndex() {
for _, loc := range s.Locations {
orphans := loc.collectOrphanEcShards()
for key, shards := range orphans {
if !loc.HasEcxFileOnDisk(key.collection, key.vid) {
continue
}
if err := loc.loadEcShards(shards, key.collection, key.vid, loc.ecShardNotifyHandler); err != nil {
glog.Errorf("ec volume %d on %s: load after index recovery failed: %v", key.vid, loc.Directory, err)
}
}
}
}
+201
View File
@@ -0,0 +1,201 @@
package storage
import (
"os"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// newDrainingStore builds a Store over dirs and drains its announcement
// channels in the background so loads never block. Files planted before this
// call are picked up by the startup loaders; files planted after are not.
func newDrainingStore(t *testing.T, dirs []string) *Store {
t.Helper()
for _, d := range dirs {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatalf("mkdir %s: %v", d, err)
}
}
maxCounts := make([]int32, len(dirs))
minFree := make([]util.MinFreeSpace, len(dirs))
diskTypes := make([]types.DiskType, len(dirs))
for i := range dirs {
maxCounts[i] = 100
diskTypes[i] = types.HardDriveType
}
store := NewStore(nil, "localhost", 8080, 18080, "http://localhost:8080", "store-id",
dirs, maxCounts, minFree, "",
NeedleMapInMemory, diskTypes, 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)
})
return store
}
func plantEcShard(t *testing.T, dir, collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, size int64) {
t.Helper()
base := erasure_coding.EcShardFileName(collection, dir, int(vid))
f, err := os.Create(base + erasure_coding.ToExt(int(shardId)))
if err != nil {
t.Fatalf("create shard %d.%d: %v", vid, shardId, err)
}
if err := f.Truncate(size); err != nil {
f.Close()
t.Fatalf("truncate shard %d.%d: %v", vid, shardId, err)
}
f.Close()
}
func plantEcIndex(t *testing.T, idxDir, dataDir, collection string, vid needle.VolumeId, datSize int64) {
t.Helper()
idxBase := erasure_coding.EcShardFileName(collection, idxDir, int(vid))
if err := os.WriteFile(idxBase+".ecx", make([]byte, types.NeedleMapEntrySize), 0o644); err != nil {
t.Fatalf("write .ecx: %v", err)
}
if err := os.WriteFile(idxBase+".ecj", nil, 0o644); err != nil {
t.Fatalf("write .ecj: %v", err)
}
dataBase := erasure_coding.EcShardFileName(collection, dataDir, int(vid))
if err := volume_info.SaveVolumeInfo(dataBase+".vif", &volume_server_pb.VolumeInfo{
Version: uint32(needle.Version3),
DatFileSize: datSize,
EcShardConfig: &volume_server_pb.EcShardConfig{
DataShards: 10,
ParityShards: 4,
},
}); err != nil {
t.Fatalf("save .vif: %v", err)
}
}
// TestEcIndexRecovery_CrossServerOrphan reproduces issue #10104: a volume
// server reboots with EC shards on disk but no .ecx index anywhere local (the
// index lives only on a peer server). The startup loaders leave the shards
// unmounted, so the master never learns about them. After the recovery path
// drops the index fetched from a peer onto the local disk, MountRecoveredEcShards
// must mount and announce the shards.
func TestEcIndexRecovery_CrossServerOrphan(t *testing.T) {
tempDir := t.TempDir()
dir0 := filepath.Join(tempDir, "disk0")
dir1 := filepath.Join(tempDir, "disk1")
const collection = "video-recordings"
vid := needle.VolumeId(6190)
const datSize int64 = 10 * 1024 * 1024
shardSize := calculateExpectedShardSize(datSize, 10)
// Pre-seed the on-disk layout the issue describes: shards spread across
// this server's disks, with no .ecx / .ecj / .vif on any of them.
for _, d := range []string{dir0, dir1} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatalf("mkdir %s: %v", d, err)
}
}
plantEcShard(t, dir0, collection, vid, 0, shardSize)
plantEcShard(t, dir0, collection, vid, 5, shardSize)
plantEcShard(t, dir1, collection, vid, 6, shardSize)
store := newDrainingStore(t, []string{dir0, dir1})
// Bug reproduction: the startup loaders left every shard unmounted.
if _, found := store.FindEcVolume(vid); found {
t.Fatalf("EC volume %d unexpectedly mounted without any local .ecx", vid)
}
// The recovery scan must surface this volume as missing its index.
m, ok := findMissingIndex(store.CollectEcVolumesMissingIndex(), collection, vid)
if !ok {
t.Fatalf("CollectEcVolumesMissingIndex did not report volume %d as a cross-server orphan", vid)
}
// Simulate the peer fetch: the server-side path copies .ecx/.ecj/.vif from a
// peer that still has them into m.IdxDir / m.DataDir.
plantEcIndex(t, m.IdxDir, m.DataDir, collection, vid, datSize)
store.MountRecoveredEcShards()
// All shards must now be mounted on the disks that physically hold them.
loc0 := store.Locations[0]
ev, found := loc0.FindEcVolume(vid)
if !found {
t.Fatalf("EC volume %d not mounted on disk0 after index recovery", vid)
}
for _, sid := range []erasure_coding.ShardId{0, 5} {
if _, ok := ev.FindEcVolumeShard(sid); !ok {
t.Errorf("shard %d.%d not registered on disk0 after recovery", vid, sid)
}
}
loc1 := store.Locations[1]
ev1, found := loc1.FindEcVolume(vid)
if !found {
t.Fatalf("EC volume %d not mounted on disk1 after index recovery", vid)
}
if _, ok := ev1.FindEcVolumeShard(6); !ok {
t.Errorf("shard %d.6 not registered on disk1 after recovery", vid)
}
// A second scan must report nothing left to recover.
if _, again := findMissingIndex(store.CollectEcVolumesMissingIndex(), collection, vid); again {
t.Errorf("CollectEcVolumesMissingIndex still reports volume %d after recovery", vid)
}
}
// findMissingIndex returns the entry for (collection, vid) among the reported
// missing-index volumes, if present.
func findMissingIndex(missing []EcVolumeMissingIndex, collection string, vid needle.VolumeId) (EcVolumeMissingIndex, bool) {
for _, m := range missing {
if m.Collection == collection && m.VolumeId == vid {
return m, true
}
}
return EcVolumeMissingIndex{}, false
}
// TestCollectEcVolumesMissingIndex_ExcludesCrossDiskOrphan guards the boundary
// with the existing same-server reconcile: a volume whose .ecx merely sits on a
// sibling disk is NOT a cross-server orphan and must not be reported here —
// mirrorEcMetadataToShardDisks / reconcileEcShardsAcrossDisks already mount it.
func TestCollectEcVolumesMissingIndex_ExcludesCrossDiskOrphan(t *testing.T) {
tempDir := t.TempDir()
dir0 := filepath.Join(tempDir, "disk0")
dir1 := filepath.Join(tempDir, "disk1")
store := newDrainingStore(t, []string{dir0, dir1})
const collection = "mybucket"
vid := needle.VolumeId(42)
const datSize int64 = 10 * 1024 * 1024
shardSize := calculateExpectedShardSize(datSize, 10)
// Plant after NewStore so the startup reconcile does not consume the layout;
// CollectEcVolumesMissingIndex is what's under test. Shard on disk0, index on
// disk1 — the cross-disk layout handled by the same-server reconcile.
plantEcShard(t, dir0, collection, vid, 3, shardSize)
plantEcIndex(t, dir1, dir1, collection, vid, datSize)
if _, missing := findMissingIndex(store.CollectEcVolumesMissingIndex(), collection, vid); missing {
t.Errorf("cross-disk .ecx must not be reported as a cross-server orphan")
}
}
+8 -2
View File
@@ -1,6 +1,7 @@
package storage
import (
"errors"
"fmt"
"slices"
@@ -12,7 +13,7 @@ import (
// ScrubEcVolume checks the full integrity of a EC volume, across both local and remote shards.
// Returns a count of processed file entries, slice of found broken shards, and slice of found errors.
func (s *Store) ScrubEcVolume(vid needle.VolumeId) (int64, []*volume_server_pb.EcShardInfo, []error) {
func (s *Store) ScrubEcVolume(vid needle.VolumeId, forceDeletedNeedlesCheck bool) (int64, []*volume_server_pb.EcShardInfo, []error) {
ecv, found := s.FindEcVolume(vid)
if !found {
return 0, nil, []error{fmt.Errorf("EC volume id %d not found", vid)}
@@ -78,7 +79,12 @@ func (s *Store) ScrubEcVolume(vid needle.VolumeId) (int64, []*volume_server_pb.E
n := needle.Needle{}
if err := n.ReadBytes(data, 0, size, ecv.Version); err != nil {
errs = append(errs, fmt.Errorf("needle %d on EC volume %d: %v", id, ecv.VolumeId, err))
// needles flagged as deleted in the index but not in the volume (or vice-versa) cannot
// be properly hydrated, as the header read by needle.ReadBytes() will mismatch.
deleteSizeMismatch := size.IsDeleted() != (n.Size == 0)
if !errors.Is(err, needle.ErrorSizeMismatch) || !deleteSizeMismatch || forceDeletedNeedlesCheck {
errs = append(errs, fmt.Errorf("needle %d on EC volume %d: %v", id, ecv.VolumeId, err))
}
}
return nil
+5
View File
@@ -79,6 +79,11 @@ func (v *Volume) scrubVolumeData(idxFile *os.File, idxFileSize int64) (int64, []
version := v.Version()
err := idx.WalkIndexFile(idxFile, 0, func(id types.NeedleId, offset types.Offset, size types.Size) error {
count++
// A remote-tier delete records an offset-0 tombstone with no physical .dat
// bytes, so it must not contribute to totalRead.
if offset.IsZero() && size.IsDeleted() {
return nil
}
// compute the actual size of the needle in disk, including needle header, body and alignment padding.
actualSize := int64(needle.GetActualSize(size, version))
+49
View File
@@ -130,6 +130,55 @@ func TestScrubVolumeData(t *testing.T) {
}
}
// TestScrubVolumeData_IgnoresOffset0Tombstone: a remote-tier delete appends an
// offset-0 tombstone to the .idx with no physical .dat bytes; a full scrub must
// not flag the volume — neither via the structural overlap check nor the size
// reconcile.
func TestScrubVolumeData_IgnoresOffset0Tombstone(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
defer v.Close()
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false); err != nil {
t.Fatalf("write needle: %v", err)
}
if err := v.DataBackend.Sync(); err != nil {
t.Fatalf("sync .dat: %v", err)
}
if err := v.nm.Sync(); err != nil {
t.Fatalf("sync .idx: %v", err)
}
// Append an offset-0 logical tombstone, as a remote-tier delete would.
entry := needle_map.NeedleValue{Key: types.NeedleId(99), Offset: types.ToOffset(0), Size: types.TombstoneFileSize}.ToBytes()
f, err := os.OpenFile(v.FileName(".idx"), os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
t.Fatalf("open .idx: %v", err)
}
if _, err := f.Write(entry); err != nil {
f.Close()
t.Fatalf("append tombstone: %v", err)
}
f.Close()
idxFile, err := os.OpenFile(v.FileName(".idx"), os.O_RDONLY, 0644)
if err != nil {
t.Fatalf("reopen .idx: %v", err)
}
defer idxFile.Close()
idxStat, err := idxFile.Stat()
if err != nil {
t.Fatalf("stat .idx: %v", err)
}
if _, errs := v.scrubVolumeData(idxFile, idxStat.Size()); len(errs) != 0 {
t.Fatalf("offset-0 tombstone must not flag the volume, got %v", errs)
}
}
// TestCheckVolumeDataIntegrityWithDeletionTombstone guards the size argument
// passed to ReadData when verifying a trailing deletion tombstone. The .idx
// entry carries TombstoneFileSize (-1) but the appended tombstone needle in
+1 -1
View File
@@ -9,7 +9,7 @@ import (
var (
MAJOR_VERSION = int32(4)
MINOR_VERSION = int32(36)
MINOR_VERSION = int32(37)
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
VERSION = util.SizeLimit + " " + VERSION_NUMBER
COMMIT = ""