mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-08-30 20:57:07 +00:00
* ec: uniform shard block layout An EC volume is striped as 1GiB blocks until less than one row remains, then 1MiB blocks, and consecutive blocks land on different shards. With ec.encode's -fullPercent 95 against the 30GiB default limit, ~30% of every volume sits in that 1MiB tail, so a 4MB filer chunk there is five stripes on five servers. New encodes now use one block per shard, sized ceil(datSize/dataShards) rounded up to 1MiB and recorded in the .vif (EcShardConfig.block_size, also carried by the .ecsum manifest). A needle now maps to one shard unless it is larger than the block or straddles a boundary. The chosen size equals the legacy layout's padded shard length for every input, so shard sizes, capacity math, and the shard-size credibility checks are unchanged; only the byte placement moved. Reads, decode, and scrub resolve the block sizes from the volume's .vif; absence keeps the legacy interpretation, so existing EC volumes read exactly as before. Rebuild is layout-agnostic. weed fix -ecx recovers the layout from the .vif, else the .ecsum sidecar, and with neither de-stripes under both candidate layouts and keeps the one that indexes more valid needles. Same change in the Rust volume server, which now also streams the encode in 256KB sub-batches like Go instead of allocating whole blocks, and computes the large-row count as shardSize/largeBlock to match Go on exact multiples. On a 26MB fixture both encoders produce byte-identical shards, and a Go-written .vif parses in Rust with the block size intact. * ec: resolve the rust ecx rebuild through the recorded layout The Rust rebuild path regenerated a lost .ecx by scanning the logical .dat through a hand-rolled pure-1MiB striping, which was already wrong for legacy volumes with large-block rows and is wrong for any uniform volume with a block past 1MiB. Route the scan through locate_data with the .vif-recorded block size, the same mapping the read path uses. Also seed the new tests' random data instead of the deprecated global math/rand.Read. * ec: fail the Rust ecx rebuild on any shard read error A read error mid-scan published the entries collected so far as a successful .ecx, and read_at's byte count was ignored so a legal short read passed as complete — a truncated or failing shard could produce a silently incomplete recovery index. Exact-read semantics in read_from_data_shards, error propagation in the needle walk, and a truncated-shard regression test. * ec: fail the mount on an unreadable or malformed vif Both servers silently fell back to the legacy layout when an existing .vif could not be read or parsed. Every new encode records a positive uniform block size there, so the fallback mounted the same shards with legacy offset math and could return wrong data. Absent stays legal (legacy volumes predate the sidecar), and a zero-byte stub still reads as absent (Go's MaybeLoadVolumeInfo convention, now mirrored in Rust); a present-but-unreadable or malformed .vif fails the mount instead. * ec: bound the reconstruct fan-out of one needle's intervals A degraded interval fans out a read to every reachable shard location, each with a buffer the size of the interval. Reading a needle's intervals in parallel multiplied that by the interval concurrency: a needle spanning 8 blocks could hold 8 x MaxShardCount remote reads and buffers at once, where the sequential version peaked at MaxShardCount. Give each needle a single reconstruct budget its intervals share, held for the buffer's lifetime, so separate reads stay independent but one read cannot multiply its own fan-out. * ec: drop the duplicated shard-size formula calculateExpectedShardSize reimplemented the padding rule that UniformBlockSize already owns — TestUniformBlockSizeMatchesLegacyShardSize asserts the two agree for every input — so a change to the rule would have had to be made in both. Defer to the helper, keeping the historic answer for an empty .dat. * ec: resolve the shard block layout from whatever records it Four places still answered the layout question by inference when a record of it was available, or accepted an answer that was not one: - A mount with no .vif defaulted to the legacy layout; the bitrot sidecar records the same config at encode time, so take it when present, as weed fix -ecx already does. The vif itself is now parsed once per mount rather than twice. - The Rust ecx rebuild derived its row count from the padded shard extent, which under the legacy layout reads a shard that is an exact large-block multiple as one row too many. Pass the encode-time .dat size from the .vif and keep the extent as the fallback. - weed fix -ecx read the block size outside the EC-config guard (collapsing the unknown sentinel into a definitive legacy), only wrote the recovered layout back when the .vif was absent rather than unusable, and broke a scan tie by candidate order instead of the documented reach. - The uniform layout tripped writeDatFile's large-block ambiguity guard, which cannot apply when the large and small blocks are the same size. * ec: give the index-recovery tests a parseable vif The fixtures wrote the literal bytes "volinfo" as the source .vif and the recovery copies it verbatim, so the receiving server then mounted the volume from a .vif it could not parse. That used to pass by silently defaulting to the legacy layout; a mount now refuses a vif it cannot read, which is what the tests were exercising all along without meaning to. * ec: validate the layout a vif records, not just its syntax Review follow-ups on the mount-strictness change: - A .vif can parse and still record a block size no encoder could have produced (negative, or not a whole number of small blocks). Both servers took it and mapped every read through it. ValidateBlockSize / the Rust mirror now refuse the mount, the same way an unparseable vif does; 0 stays valid as the legacy two-tier layout. - The bitrot-sidecar fallback accepted parity_shards == 0 and summed the counts in their own width, so values near the ceiling wrapped past the MaxShardCount bound. Require both counts and sum in a wider type. - weed fix -ecx treated a config with only DataShards > 0 as usable, so a half-written .vif suppressed the recovery paths AND survived the rewrite. Require a complete, in-range config before trusting it. - Returning the vif-load error left the .ecx and .ecj descriptors open; repeated mount attempts on malformed metadata could exhaust them. * ec: refuse to act on a layout the metadata does not establish - The worker encode only logged a failed .vif write and skipped it in the distribution set, and treated the .ecsum write as best-effort. A worker whose disk filled after the much larger shards landed could still distribute, mount, verify shard inventory, and delete the source replicas — leaving holders with shards whose geometry nothing records. Both writes and both inclusions are encode success conditions now. - A generation-matching .ecsum that disagreed with the .vif geometry only disabled checksums in Go, and in Rust was not compared at all, so protection stayed On while reads used the other layout. Both files record the layout their generation was encoded with, so a disagreement now fails the mount. * ec: reject an invalid recorded block size in weed fix -ecx A .vif with valid shard counts but a negative or unaligned block size was marked usable: a positive invalid value pinned the scan to a geometry that de-stripes to garbage, and a negative one ran the dual scan but left the invalid .vif in place afterwards. Validate it with the same rule the mount applies, and when it fails leave the layout unknown so the scan recovers it and the file is rewritten. * ec: validate the sidecar layout weed fix -ecx recovers from The .ecsum fallback was taken on DataShards > 0 alone, so a CRC-valid sidecar carrying the wrong generation, an incomplete ratio, or an unaligned block size would pin the reconstruction to one incorrect uniform-layout candidate instead of letting the dual scan decide. Require generation 0, a complete in-range ratio, and a valid block size; anything less leaves the layout unknown, which is the answer that still recovers by scanning. * ec: let only a genuinely absent sidecar choose the legacy layout With no .vif the bitrot sidecar is the only record of a volume's layout, and the mount fallback read a failed load, an unusable config, or a sidecar stamped for another generation as "assume legacy". A uniform generation-0 volume could therefore mount with legacy or another generation's geometry and answer reads with the wrong bytes. Present-but-unusable now fails the mount; only actual absence keeps the legacy defaults. Shared as EcShardConfigFromSidecar so every caller reads the sidecar the same way. * ec: treat a recorded-but-impossible layout as corruption, not as legacy - A .vif whose ecShardConfig is PRESENT but records an impossible ratio was answered with the default 10+4 and the legacy block layout, in both languages. That reads a uniform volume's shards at the wrong offsets and returns the wrong bytes. Only an entirely absent config still means "this predates the record"; a present one that cannot be true fails the mount. - The shard-count bound summed two uint32 counts as int, which wraps on a 32-bit build: 0x7fffffff + 0x7fffffff lands at -2 and slips under MaxShardCount. ValidEcShardCounts sums in uint64, and every EC call site that checked a recorded ratio now goes through it. * ec: rebuild on the geometry the sidecar records, and flag it when it disagrees The rebuild RPC passes BackgroundECContext, so RebuildEcFiles resolves the layout itself — and it resolved a missing or invalid .vif to the default 10+4 with the legacy block size. Two consequences: a 12+4 volume was reconstructed through a 10+4 matrix, which produces wrong bytes and never regenerates shards 14-15; and the chosen geometry then contradicted a valid uniform sidecar, which loadRebuildSidecar reported as BitrotOff — silently skipping the input and regenerated-shard checksum checks precisely when the volume had already lost its metadata. The layout now resolves from the bitrot sidecar (found across the server's disks, not just beside the base name) before falling back to the defaults, and a present-but-impossible ratio fails instead of being replaced. A sidecar that contradicts the chosen geometry is BitrotInvalid, which the existing unsafeIgnoreSidecar override still lets an operator push past. * ec: let the Rust rebuild read metadata off a sibling disk read_ec_shard_config searches only the location the rebuild writes into, so a volume whose .vif or generation-0 .ecsum sits on another of the server's disks resolved to the default 10+4 with the legacy block layout — the Rust half of the geometry-guessing the Go rebuild just stopped doing. It then reconstructs a custom-ratio or uniform volume through the wrong Reed-Solomon matrix and de-striping geometry. The rebuild now looks for the .vif in its own location and then each sibling, falls back to the generation-0 sidecar wherever that lives, and only defaults when neither exists anywhere. The encode-time .dat size the ecx rebuild needs is resolved the same way. * ec: resolve a rebuild's vif from every directory that may hold it RebuildEcFiles probed only <data-base>.vif. The caller knows the selected location's index directory and the sibling locations, but passed neither for metadata: additionalDirs carried shard directories only, and were searched for shards and the checksum sidecar. A split -dir/-dir.idx layout, or a disk holding only shards, therefore resolved a pre-sidecar custom-ratio volume to 10+4 and reconstructed through the wrong matrix — never regenerating shards 14-15. The caller now hands over the index and sibling directories, and the resolver probes the vif across all of them, matching what the Rust resolver already does for both the vif and the sidecar. * ec: make every rebuild consumer agree on the layout it resolved - The post-rebuild bitrot backfill re-derived the geometry from this directory's .vif alone and dropped the block size entirely, so a rebuild that resolved its layout from a sibling, the sidecar, or a uniform vif wrote a manifest describing a DIFFERENT layout — one later mounts reject, or that covers only the default shard count. The layout is resolved once now, through an exported ResolveRebuildECContext, and the rebuild and the backfill share that answer. - The Rust rebuild collected only each location's data directory, so a sibling's INDEX directory — where a split -dir/-dir.idx layout keeps .ecx/.ecj/.vif — was never probed, and a custom-ratio volume still resolved to 10+4 with the legacy layout. Both directories of every location are carried now, deduped against the rebuild's own. - A shard delivery can bring the checksum manifest with it, but the receive path only writes the file: a server that already had the volume mounted kept its resolved protection state (off) until a remount. The mount RPC re-resolves it once the shards it describes have been added. * ec: cover the rebuild's directory search with tests Reviewers flagged the sibling index directory twice, and the fix that closed it had no test of its own: the assembly sat inline in the rebuild handler, reachable only through a gRPC call against a populated store. Lifting it into rebuildSearchDirs / select_rebuild_location makes the rule assertable — a sibling contributes BOTH its data and its index directory, a shared index directory is listed once, and the rebuild's own data directory never repeats. Writing the Rust cases surfaced that the two implementations do not agree on where the rebuild's own index directory belongs, and both are right: Go's resolver takes a single directory list, so that directory has to be inside it, while Rust's takes the rebuild's data and index directories as their own arguments and would search them twice. The tests now state which contract each side is holding to, so neither drifts into the other's shape. Pure refactor otherwise; no behaviour change. * ec: search the index directory for the layout sidecar The Rust resolver looked for the generation-0 .ecsum in the rebuild's data directory and the sibling list, but not in the rebuild's own index directory — while the .vif lookup directly above it did, and Go's findBitrotSidecar has always checked both bases. On a split -dir/-dir.idx location that directory is where the metadata lives, and callers leave it out of the sibling list precisely because it is passed here separately, so nothing searched it. With no .vif anywhere the sidecar is the only surviving record of the layout. Missing it resolved a 12+4 uniform volume to 10+4 with the legacy striping — the test added here fails with (10, 4, 0) against the old code — and the rebuild then reconstructs through the wrong matrix and writes .ecx offsets that no reader can follow. * ec: let the rebuild see its own index directory The Rust rebuild takes a single flat directory list — the shape Go's RebuildEcFiles uses — so it cannot be handed the rebuild location's index directory separately the way the layout resolvers are, and the handler was passing the sibling list, which deliberately omits exactly that directory. On a split -dir/-dir.idx location that is where .ecx and .vif live, so the shard and index lookups could not see them. Go has always carried that directory in additionalDirs; this lines the two call sites up. * ec: let a config-free vif fall through to the layout sidecar A .vif that carries no ecShardConfig answers nothing about the layout, so it is no more informative than an absent one — but both trees treated its mere existence as the end of the search. Go went straight to the 10+4 legacy defaults without consulting the sidecar at all; Rust returned whatever ec_shard_config_from could make of a single directory. A 12+4 uniform volume with a legacy config-free vif therefore resolved as 10+4 legacy, and every read landed at the wrong shard offset. The sidecar lookup was also single-directory on both sides, while a split -dir/-dir.idx layout keeps .vif and .ecsum with the INDEX. Go's findBitrotSidecar has always taken both bases; the callers here passed only the data base, and the Rust bitrot resolver derived its path from the data base alone. Rust's layout resolver now takes a candidate directory list — data, index, then any siblings — and searches all of it, which also removes the early return that made the vif's presence decisive. load_vif_info_across_dirs reported `dir` even when load_vif_info had found the vif in `dir_idx`. Nothing reads that field today, so this changes no behaviour; it stops the next caller that resolves the rest of the volume's metadata against the answer from being sent to a disk holding none of it. Absence stays legal throughout: a volume with neither record is genuinely legacy. Present-but-unusable still fails the mount, now in the config-free-vif branch too. * ec: activate a delivered sidecar on every per-disk runtime A vid mounts as one EcVolume per disk, each with its own resolved protection state, but the post-delivery reload used the first-match lookup and so touched exactly one of them. The siblings kept reporting no protection until a remount — and since shard distribution deduplicates the metadata files onto the first target disk for a node, the runtime that got the .ecsum is not necessarily the one the lookup returns. Iterate every runtime instead, via a new FindAllEcVolumes and its Rust mut equivalent. Combined with each runtime now resolving its sidecar against its index directory as well as its data directory, a server sharing one -dir.idx across its disks activates all of them from the single delivered copy. The Rust volume server had no post-mount reload at all; it gets one here, matching Go. * ec: resolve the delivered sidecar across every EC metadata directory Reloading every per-disk runtime, added last round, did not by itself make the delivered manifest reachable. Startup mirroring copies .ecx/.ecj/.vif to every shard-bearing disk so each mounts self-contained, but deliberately not .ecsum, and a repair delivers exactly one copy. Each runtime was resolving against its own two directories, so every sibling of the disk that received the file kept reporting no protection however often it reloaded. Resolve one authoritative copy across every EC metadata directory instead of duplicating the file. Mirroring .ecsum would have to keep pace with a file that is rewritten as shards are repaired, and would not help the reported case at all: the delivery happens at runtime, and mirroring only runs at startup. The regression test pins both halves — a reload restricted to the volume's own directories still finds nothing, and the same reload given the server's metadata directories turns protection on. * ec: ask every directory before writing a TOFU baseline After a rebuild the opportunistic backfill asks whether this volume already has a checksum manifest, and answered from the data base alone. A split -dir/-dir.idx layout keeps the sidecar with the index, and a multi-disk server may keep it on a sibling, so an existing manifest read as absent. The consequence is worse than a missed read. On a false "no" the backfill writes a fresh sidecar at the data base from whatever the shards say right now — and the data base is the first candidate every resolver checks, so that TOFU baseline shadows the real manifest rather than sitting beside it. A shard that was silently corrupt gets blessed, and the record that would have caught it stops being consulted. FindBitrotSidecar exports the search the package already used internally, so the question is asked of the data base, the index base and the sibling disks — the same candidates the rebuild resolves its layout from. * ec: refuse a shard block size no encoder could have produced weed fix -ecx derived one from the raw shard extent, so a truncated or partially copied shard wrote a .vif that NewEcVolume then permanently refuses — the volume the tool was run to rescue could never mount again. An extent that is not a whole number of small blocks cannot have come from a uniform encode, so it is no longer offered as a candidate, and nothing unvalidated reaches the .vif. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * ec: derive the .vif's dat size and block size from one measurement VolumeEcShardsGenerate stat'ed the .dat before the encode while WriteEcFiles stat'ed it again to size the blocks. A write landing between the two produced a .vif whose own two fields describe different files. WriteEcFiles now leaves both on the context, and fills a placeholder context in place so the caller can read them back. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * ec: keep the source volume until every holder serves its shard layout The uniform layout rides in a .vif field older volume servers never knew: they discard it, mount the shards as legacy and return wrong bytes with nothing erroring, and the shard files are the same length either way so no other check notices. The upgrade order lived only in the release note. VolumeEcShardsInfo now reports the block size the holder actually serves, in both the Go and Rust servers, and the pre-delete verification refuses to drop the source unless every reachable holder echoes the one the shards were encoded with — while a rollback still exists. A server that predates the field answers 0, which is the negative answer. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * ec: drop the rebuild's dead block-size parameters generateMissingEcFiles never reads largeBlockSize/smallBlockSize — Reed-Solomon reconstruction is layout-agnostic — so passing the legacy constants only advertised a layout the rebuild does not use. Also move UniformBlockSize's doc off ValidateBlockSize. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * ec: warn about EC defaults only when the mount used them The "vif file not found, using defaults" warning fired even after the bitrot sidecar supplied a non-default layout, sending anyone triaging wrong bytes after the legacy layout the volume never mounted on. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * ec: stat the distributed bitrot sidecar once The strict check re-stat'ed the file immediately before the stat that already gates inclusion, and a failed sidecar write now fails the encode outright, so the first could only fire on a deletion between the two lines. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * ec: say what the reconstruct budget actually bounds A shard's buffer stays in bufs until its interval reconstructs, which is after the read that filled it released its permit, so the semaphore bounds round trips in flight and not retained bytes. Peak memory is the intervals reconstructing at once times the shards each reaches times the interval size. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7 * test: let the fake volume server report its delivered EC layout The pre-delete verification now asks each holder which shard block layout it serves, and a fake that always answered "unset" looked exactly like a volume server too old to know the field. Distribution ships the .vif to every holder alongside its shards, so read the layout back out of it as a real holder does. Claude-Session: https://claude.ai/code/session_011FRRoNKBiGbH58rs2AQyA7
1267 lines
51 KiB
Go
1267 lines
51 KiB
Go
package weed_server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"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/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/storage/volume_info"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
/*
|
|
|
|
Steps to apply erasure coding to .dat .idx files
|
|
0. ensure the volume is readonly
|
|
1. client call VolumeEcShardsGenerate to generate the .ecx and .ec00 ~ .ec13 files
|
|
2. client ask master for possible servers to hold the ec files
|
|
3. client call VolumeEcShardsCopy on above target servers to copy ec files from the source server
|
|
4. target servers report the new ec files to the master
|
|
5. master stores vid -> [14]*DataNode
|
|
6. client checks master. If all 14 slices are ready, delete the original .idx, .idx files
|
|
|
|
*/
|
|
|
|
// VolumeEcShardsGenerate generates the .ecx and .ec00 ~ .ec13 files
|
|
func (vs *VolumeServer) VolumeEcShardsGenerate(ctx context.Context, req *volume_server_pb.VolumeEcShardsGenerateRequest) (*volume_server_pb.VolumeEcShardsGenerateResponse, error) {
|
|
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := vs.CheckMaintenanceMode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
glog.V(0).Infof("VolumeEcShardsGenerate: %v", req)
|
|
|
|
v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
|
|
if v == nil {
|
|
return nil, fmt.Errorf("volume %d not found", req.VolumeId)
|
|
}
|
|
baseFileName := v.DataFileName()
|
|
|
|
if v.Collection != req.Collection {
|
|
return nil, fmt.Errorf("existing collection:%v unexpected input: %v", v.Collection, req.Collection)
|
|
}
|
|
|
|
// Create EC context - prefer existing .vif config if present (for regeneration scenarios)
|
|
ecCtx := erasure_coding.NewDefaultECContext(req.Collection, needle.VolumeId(req.VolumeId))
|
|
if volumeInfo, _, found, _ := volume_info.MaybeLoadVolumeInfo(baseFileName + ".vif"); found && volumeInfo.EcShardConfig != nil {
|
|
ds := int(volumeInfo.EcShardConfig.DataShards)
|
|
ps := int(volumeInfo.EcShardConfig.ParityShards)
|
|
|
|
// Validate and use existing EC config
|
|
if ds > 0 && ps > 0 && ds+ps <= erasure_coding.MaxShardCount {
|
|
ecCtx.DataShards = ds
|
|
ecCtx.ParityShards = ps
|
|
glog.V(0).Infof("Using existing EC config for volume %d: %s", req.VolumeId, ecCtx.String())
|
|
} else {
|
|
glog.Warningf("Invalid EC config in .vif for volume %d (data=%d, parity=%d), using defaults", req.VolumeId, ds, ps)
|
|
}
|
|
} else {
|
|
glog.V(0).Infof("Using default EC config for volume %d: %s", req.VolumeId, ecCtx.String())
|
|
}
|
|
|
|
shouldCleanup := true
|
|
defer func() {
|
|
if !shouldCleanup {
|
|
return
|
|
}
|
|
for i := 0; i < ecCtx.Total(); i++ {
|
|
os.Remove(baseFileName + ecCtx.ToExt(i))
|
|
}
|
|
os.Remove(v.IndexFileName() + ".ecx")
|
|
os.Remove(erasure_coding.BitrotSidecarPath(baseFileName, 0))
|
|
}()
|
|
|
|
// Wipe any EC artifacts from a prior encode so a retry never mixes two runs.
|
|
// Evict the in-memory EcVolume first so the unlink frees the inodes instead
|
|
// of leaving open fds serving the old bytes. Sweep every disk: stale shards
|
|
// can sit on a sibling disk and would otherwise survive and be mounted
|
|
// against the new index at reconcile. Scans the cap for custom ratios.
|
|
vs.store.UnloadEcVolume(needle.VolumeId(req.VolumeId))
|
|
for _, loc := range vs.store.Locations {
|
|
dataBase := storage.VolumeFileName(loc.Directory, req.Collection, int(req.VolumeId))
|
|
idxBase := storage.VolumeFileName(loc.IdxDirectory, req.Collection, int(req.VolumeId))
|
|
if err := removeStaleEcArtifacts(dataBase, idxBase, erasure_coding.MaxShardCount); err != nil {
|
|
return nil, fmt.Errorf("wipe stale EC artifacts for volume %d on %s: %w", req.VolumeId, loc.Directory, err)
|
|
}
|
|
}
|
|
|
|
// IMPORTANT: Generate .ecx BEFORE EC shards to prevent a race condition.
|
|
// If .ecx were generated after EC shards, any write (e.g. from WriteNeedleBlob
|
|
// during replica sync) between the two steps would add entries to .idx that
|
|
// end up in .ecx but whose data is NOT in the EC shards — causing "shard too
|
|
// short" and "size mismatch" errors on reads.
|
|
//
|
|
// By generating .ecx first, it reflects the .idx state at or before the .dat
|
|
// is read for EC encoding. If a write sneaks in after .ecx but before/during
|
|
// EC encoding, the shards contain MORE data than .ecx references, which is
|
|
// harmless (the extra data is simply not indexed).
|
|
|
|
// write .ecx file from the current .idx
|
|
if err := erasure_coding.WriteSortedFileFromIdx(v.IndexFileName(), ".ecx"); err != nil {
|
|
return nil, fmt.Errorf("WriteSortedFileFromIdx %s: %v", v.IndexFileName(), err)
|
|
}
|
|
|
|
// write .ec00 ~ .ec[TotalShards-1] files using context
|
|
ecBitrot, err := erasure_coding.WriteEcFiles(baseFileName, ecCtx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("WriteEcFiles %s: %v", baseFileName, err)
|
|
}
|
|
// Persist the generation-0 bitrot checksum sidecar (<base>.ecsum) alongside
|
|
// the shards so it travels with them during distribution (copy_ecsum_file).
|
|
// The source loading its own canonical sidecar is correct — it holds all
|
|
// shards and a complete manifest. Best-effort: a failed sidecar write leaves
|
|
// the generation unprotected rather than failing the encode.
|
|
if erasure_coding.BitrotProtectionEnabled && ecBitrot != nil {
|
|
if serr := erasure_coding.SaveBitrotSidecar(erasure_coding.BitrotSidecarPath(baseFileName, 0), ecBitrot); serr != nil {
|
|
glog.Warningf("failed to write EC bitrot sidecar for volume %d: %v", req.VolumeId, serr)
|
|
}
|
|
}
|
|
|
|
// write .vif files
|
|
var expireAtSec uint64
|
|
if v.Ttl != nil {
|
|
ttlSecond := v.Ttl.ToSeconds()
|
|
if ttlSecond > 0 {
|
|
expireAtSec = uint64(time.Now().Unix()) + ttlSecond //calculated expiration time
|
|
}
|
|
}
|
|
volumeInfo := &volume_server_pb.VolumeInfo{Version: uint32(v.Version())}
|
|
volumeInfo.ExpireAtSec = expireAtSec
|
|
// The size the encode actually read, not a separate stat: a replica-sync
|
|
// write can land between two stats of a live .dat, and the .vif would then
|
|
// record a DatFileSize and a BlockSize describing different files.
|
|
volumeInfo.DatFileSize = ecCtx.DatFileSize
|
|
|
|
// Validate EC configuration before saving to .vif
|
|
if ecCtx.DataShards <= 0 || ecCtx.ParityShards <= 0 || ecCtx.Total() > erasure_coding.MaxShardCount {
|
|
return nil, fmt.Errorf("invalid EC config before saving: data=%d, parity=%d, total=%d (max=%d)",
|
|
ecCtx.DataShards, ecCtx.ParityShards, ecCtx.Total(), erasure_coding.MaxShardCount)
|
|
}
|
|
|
|
// EncodeTsNs stamps this run's identity into the .vif (copied with the
|
|
// shards), so a read served from a different run's shard is rejected.
|
|
volumeInfo.EcShardConfig = &volume_server_pb.EcShardConfig{
|
|
DataShards: uint32(ecCtx.DataShards),
|
|
ParityShards: uint32(ecCtx.ParityShards),
|
|
EncodeTsNs: time.Now().UnixNano(),
|
|
BlockSize: ecCtx.BlockSize,
|
|
}
|
|
glog.V(1).Infof("Saving EC config to .vif for volume %d: %d+%d (total: %d)",
|
|
req.VolumeId, ecCtx.DataShards, ecCtx.ParityShards, ecCtx.Total())
|
|
|
|
if err := volume_info.SaveVolumeInfo(baseFileName+".vif", volumeInfo); err != nil {
|
|
return nil, fmt.Errorf("SaveVolumeInfo %s: %v", baseFileName, err)
|
|
}
|
|
|
|
shouldCleanup = false
|
|
|
|
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.checkGrpcAdminAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := vs.CheckMaintenanceMode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
glog.V(0).Infof("VolumeEcShardsRebuild: %v", req)
|
|
baseFileName := erasure_coding.EcShardBaseFileName(req.Collection, int(req.VolumeId))
|
|
|
|
var rebuiltShardIds []uint32
|
|
|
|
// Find the rebuild location: the location with the most shards and an .ecx file.
|
|
// With multi-disk servers, shards may be spread across different locations.
|
|
var rebuildLocation *storage.DiskLocation
|
|
var rebuildShardCount int
|
|
var otherLocationsWithShards []*storage.DiskLocation
|
|
|
|
for _, location := range vs.store.Locations {
|
|
_, _, existingShardCount, err := checkEcVolumeStatus(baseFileName, location)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
indexBaseFileName := path.Join(location.IdxDirectory, baseFileName)
|
|
if !util.FileExists(indexBaseFileName+".ecx") && location.IdxDirectory != location.Directory {
|
|
indexBaseFileName = path.Join(location.Directory, baseFileName)
|
|
}
|
|
hasEcx := util.FileExists(indexBaseFileName + ".ecx")
|
|
|
|
// Skip locations that have neither shard files nor an .ecx file.
|
|
if existingShardCount == 0 && !hasEcx {
|
|
continue
|
|
}
|
|
|
|
if hasEcx && (rebuildLocation == nil || existingShardCount > rebuildShardCount) {
|
|
if rebuildLocation != nil {
|
|
otherLocationsWithShards = append(otherLocationsWithShards, rebuildLocation)
|
|
}
|
|
rebuildLocation = location
|
|
rebuildShardCount = existingShardCount
|
|
} else {
|
|
otherLocationsWithShards = append(otherLocationsWithShards, location)
|
|
}
|
|
}
|
|
|
|
if rebuildLocation == nil {
|
|
return &volume_server_pb.VolumeEcShardsRebuildResponse{}, nil
|
|
}
|
|
|
|
// Collect additional directories where shard files may exist.
|
|
// On multi-disk servers, existing local shards may be on a different disk
|
|
// than where copied shards were placed during ec.rebuild.
|
|
rebuildDataDir := rebuildLocation.Directory
|
|
additionalDirs := rebuildSearchDirs(rebuildLocation, otherLocationsWithShards)
|
|
|
|
// 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)
|
|
// Resolve the layout ONCE and use that same answer for the rebuild and for
|
|
// the backfill below: a manifest describing these shards has to record the
|
|
// geometry they were actually reconstructed with.
|
|
rebuildCtx, resolveErr := erasure_coding.ResolveRebuildECContext(dataBaseFileName, erasure_coding.BackgroundECContext(), additionalDirs)
|
|
if resolveErr != nil {
|
|
recordEcRebuild("failure", time.Since(start))
|
|
return nil, fmt.Errorf("resolve rebuild layout for %s: %v", dataBaseFileName, resolveErr)
|
|
}
|
|
generatedShardIds, err := erasure_coding.RebuildEcFiles(dataBaseFileName, rebuildCtx, req.UnsafeIgnoreSidecar, additionalDirs...)
|
|
if err != nil {
|
|
recordEcRebuild("failure", time.Since(start))
|
|
return nil, fmt.Errorf("RebuildEcFiles %s: %v", dataBaseFileName, err)
|
|
}
|
|
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
|
|
// blesses current bytes; ComputeProtectionFromShards refuses a partial
|
|
// manifest, so a multi-server rebuild that cannot reach all shards just skips.
|
|
if erasure_coding.BitrotProtectionEnabled {
|
|
// "No sidecar yet" has to be asked of every place one could be, not
|
|
// just this directory. A split -dir/-dir.idx layout keeps it with the
|
|
// index and a sibling disk may hold it, and answering from the data
|
|
// base alone would write a fresh TOFU baseline over a volume that
|
|
// already has a manifest — blessing whatever the shards currently say
|
|
// and shadowing the real record, since the data base is searched first.
|
|
if erasure_coding.FindBitrotSidecar(0, dataBaseFileName, indexBaseFileName, additionalDirs...) == "" {
|
|
sidecarPath := erasure_coding.BitrotSidecarPath(dataBaseFileName, 0)
|
|
// The manifest must describe the shards as rebuilt, so it takes the
|
|
// context the rebuild resolved — not a narrower re-derivation that
|
|
// reads only this directory's .vif and drops the block size, which
|
|
// records the legacy layout for shards written with a uniform one.
|
|
ctx := rebuildCtx
|
|
if prot, berr := erasure_coding.ComputeProtectionFromShards(dataBaseFileName, ctx, 0, additionalDirs); berr != nil {
|
|
glog.V(2).Infof("bitrot backfill skipped for %s: %v", dataBaseFileName, berr)
|
|
} else if werr := erasure_coding.SaveBitrotSidecar(sidecarPath, prot); werr != nil {
|
|
glog.Warningf("bitrot backfill: write sidecar for %s: %v", dataBaseFileName, werr)
|
|
} else {
|
|
glog.V(0).Infof("bitrot backfill: wrote sidecar for %s after rebuild", dataBaseFileName)
|
|
}
|
|
}
|
|
}
|
|
|
|
return &volume_server_pb.VolumeEcShardsRebuildResponse{
|
|
RebuiltShardIds: rebuiltShardIds,
|
|
}, nil
|
|
}
|
|
|
|
// VolumeEcShardsCopy copy the .ecx and some ec data slices
|
|
func (vs *VolumeServer) VolumeEcShardsCopy(ctx context.Context, req *volume_server_pb.VolumeEcShardsCopyRequest) (*volume_server_pb.VolumeEcShardsCopyResponse, error) {
|
|
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := vs.CheckMaintenanceMode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
glog.V(0).Infof("VolumeEcShardsCopy: %v", req)
|
|
|
|
var location *storage.DiskLocation
|
|
|
|
// Select the target location for storing EC shard files.
|
|
//
|
|
// When req.DiskId > 0 the caller is explicitly choosing a disk:
|
|
// location = vs.store.Locations[req.DiskId]
|
|
// (DiskId=1 → Locations[1], DiskId=2 → Locations[2], etc.)
|
|
//
|
|
// When req.DiskId == 0 (the protobuf default, meaning "not specified")
|
|
// we auto-select location by preferring the disk that already holds EC
|
|
// shards for this volume, then falling back to any HDD, then any disk.
|
|
//
|
|
// Note: Locations[0] cannot be targeted explicitly via DiskId because 0
|
|
// is indistinguishable from "unset". It can still be chosen by the
|
|
// auto-select logic.
|
|
if req.DiskId > 0 {
|
|
// Validate disk ID is within bounds
|
|
if int(req.DiskId) >= len(vs.store.Locations) {
|
|
return nil, fmt.Errorf("invalid disk_id %d: only have %d disks", req.DiskId, len(vs.store.Locations))
|
|
}
|
|
|
|
// Use the specific disk location
|
|
location = vs.store.Locations[req.DiskId]
|
|
glog.V(1).Infof("Using disk %d for EC shard copy: %s", req.DiskId, location.Directory)
|
|
} else {
|
|
// Auto-select the target disk: prefer a disk that already has the
|
|
// EC volume mounted, then a disk that owns the .ecx on disk (the
|
|
// volume hasn't been mounted yet — relevant for ec.rebuild, where
|
|
// only the first shard carries .ecx and subsequent shards must
|
|
// land on the same disk; see #9212), then any HDD, then any disk.
|
|
// Pass the build's default data-shard count for free-slot maths;
|
|
// the helper takes it as a parameter so custom-ratio builds (e.g.
|
|
// enterprise) can swap it without touching this file.
|
|
location = vs.store.FindEcShardTargetLocation(req.Collection, needle.VolumeId(req.VolumeId), erasure_coding.DataShardsCount)
|
|
if location == nil {
|
|
return nil, fmt.Errorf("no space left")
|
|
}
|
|
}
|
|
|
|
dataBaseFileName := storage.VolumeFileName(location.Directory, req.Collection, int(req.VolumeId))
|
|
indexBaseFileName := storage.VolumeFileName(location.IdxDirectory, req.Collection, int(req.VolumeId))
|
|
|
|
// One throttler for the whole request, so the limit caps the transfer as a
|
|
// whole rather than each file separately — same shape as VolumeCopy.
|
|
ioBytePerSecond := vs.maintenanceBytePerSecond
|
|
if req.IoBytePerSecond > 0 {
|
|
ioBytePerSecond = req.IoBytePerSecond
|
|
}
|
|
throttler := util.NewWriteThrottler(ioBytePerSecond)
|
|
|
|
err := operation.WithVolumeServerClient(true, pb.ServerAddress(req.SourceDataNode), vs.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
|
|
|
// copy ec data slices
|
|
for _, shardId := range req.ShardIds {
|
|
if _, err := vs.doCopyFileWithThrottler(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, dataBaseFileName, erasure_coding.ToExt(int(shardId)), false, false, nil, throttler); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if req.CopyEcxFile {
|
|
|
|
// copy ecx file
|
|
if _, err := vs.doCopyFileWithThrottler(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, indexBaseFileName, ".ecx", false, false, nil, throttler); err != nil {
|
|
return err
|
|
}
|
|
// Defense in depth: writeToFile now removes partial files on
|
|
// stream error, but a source that genuinely held a 0-byte
|
|
// .ecx (e.g. a corrupted upstream replica) would otherwise
|
|
// leave a 0-byte file here and the mount path would reject
|
|
// it later. Catch that at distribute time so the orchestrator
|
|
// can pick a different source rather than learning about it
|
|
// at mount.
|
|
// Stat failure must not silently pass. doCopyFile reported
|
|
// success, but if the file is gone, unreadable, or a directory
|
|
// somehow, the orchestrator should learn now — at mount time
|
|
// the operator only sees "no .ecx found" with no useful context
|
|
// about which step actually failed.
|
|
ecxPath := indexBaseFileName + ".ecx"
|
|
info, statErr := os.Stat(ecxPath)
|
|
if statErr != nil {
|
|
return fmt.Errorf("VolumeEcShardsCopy volume %d: stat copied .ecx %s: %w", req.VolumeId, ecxPath, statErr)
|
|
}
|
|
if info.IsDir() {
|
|
return fmt.Errorf("VolumeEcShardsCopy volume %d: copied .ecx path %s is a directory", req.VolumeId, ecxPath)
|
|
}
|
|
if info.Size() == 0 {
|
|
if removeErr := os.Remove(ecxPath); removeErr != nil && !os.IsNotExist(removeErr) {
|
|
glog.Warningf("VolumeEcShardsCopy volume %d: remove 0-byte .ecx %s: %v", req.VolumeId, ecxPath, removeErr)
|
|
}
|
|
return fmt.Errorf("VolumeEcShardsCopy volume %d: source .ecx is 0 bytes", req.VolumeId)
|
|
}
|
|
}
|
|
|
|
if req.CopyEcjFile {
|
|
// copy ecj file
|
|
if _, err := vs.doCopyFileWithThrottler(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, indexBaseFileName, ".ecj", true, true, nil, throttler); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if req.CopyVifFile {
|
|
// copy vif file
|
|
if _, err := vs.doCopyFileWithThrottler(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, dataBaseFileName, ".vif", false, true, nil, throttler); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if req.CopyEcsumFile {
|
|
// Propagate the generation-0 bitrot checksum sidecar when the source
|
|
// has one. This non-2PC copy path (balance / fresh-encode / rebuild
|
|
// distribution) has no Prepare backstop, and fresh-encode sidecar
|
|
// writes are best-effort, so a missing source sidecar is a no-op
|
|
// (ignore-not-found): the holder is simply unprotected.
|
|
if _, err := vs.doCopyFileWithThrottler(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, dataBaseFileName, erasure_coding.BitrotSidecarExt, false, true, nil, throttler); err != nil {
|
|
return fmt.Errorf("VolumeEcShardsCopy volume %d: copy %s sidecar: %w", req.VolumeId, erasure_coding.BitrotSidecarExt, err)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("VolumeEcShardsCopy volume %d: %v", req.VolumeId, err)
|
|
}
|
|
|
|
return &volume_server_pb.VolumeEcShardsCopyResponse{}, nil
|
|
}
|
|
|
|
// VolumeEcShardsDelete local delete the .ecx and some ec data slices if not needed
|
|
// the shard should not be mounted before calling this.
|
|
func (vs *VolumeServer) VolumeEcShardsDelete(ctx context.Context, req *volume_server_pb.VolumeEcShardsDeleteRequest) (*volume_server_pb.VolumeEcShardsDeleteResponse, error) {
|
|
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := vs.CheckMaintenanceMode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
bName := erasure_coding.EcShardBaseFileName(req.Collection, int(req.VolumeId))
|
|
|
|
if req.FullTeardown {
|
|
if req.EncodeTsNs == 0 {
|
|
// Blanket teardown (shell pre-encode cleanup / pre-upgrade caller): evict the
|
|
// volume and wipe every EC artifact for it on every disk, not just the listed
|
|
// shards, so a remote node retains no stale generation a fresh copy collides with.
|
|
glog.V(0).Infof("ec volume %s full teardown", bName)
|
|
vs.store.UnloadEcVolume(needle.VolumeId(req.VolumeId))
|
|
for _, location := range vs.store.Locations {
|
|
dataBase := storage.VolumeFileName(location.Directory, req.Collection, int(req.VolumeId))
|
|
idxBase := storage.VolumeFileName(location.IdxDirectory, req.Collection, int(req.VolumeId))
|
|
if err := removeStaleEcArtifacts(dataBase, idxBase, erasure_coding.MaxShardCount); err != nil {
|
|
return nil, fmt.Errorf("full teardown of ec volume %d on %s: %w", req.VolumeId, location.Directory, err)
|
|
}
|
|
}
|
|
return &volume_server_pb.VolumeEcShardsDeleteResponse{FullTeardownDone: true}, nil
|
|
}
|
|
// Generation-fenced teardown (stale-worker pre-distribute cleanup): wipe only a
|
|
// disk whose .vif generation is strictly OLDER than the request; preserve
|
|
// same-or-newer, generation 0 (recovered/pre-upgrade live volume), and an
|
|
// unreadable .vif, so a stale run can never wipe a newer run's live shards.
|
|
// Unload and remove only the strictly-older disks, never node-wide.
|
|
glog.V(0).Infof("ec volume %s full teardown fenced at generation %d", bName, req.EncodeTsNs)
|
|
for _, location := range vs.store.Locations {
|
|
dataBase := storage.VolumeFileName(location.Directory, req.Collection, int(req.VolumeId))
|
|
idxBase := storage.VolumeFileName(location.IdxDirectory, req.Collection, int(req.VolumeId))
|
|
diskGen, readable := readEcGenerationTsNs(dataBase, idxBase)
|
|
if !readable || diskGen == 0 || diskGen >= req.EncodeTsNs {
|
|
glog.V(1).Infof("ec volume %d on %s preserved: disk generation %d (readable=%v) not older than request %d", req.VolumeId, location.Directory, diskGen, readable, req.EncodeTsNs)
|
|
continue
|
|
}
|
|
location.UnloadEcVolume(needle.VolumeId(req.VolumeId))
|
|
if err := removeStaleEcArtifacts(dataBase, idxBase, erasure_coding.MaxShardCount); err != nil {
|
|
return nil, fmt.Errorf("fenced teardown of ec volume %d on %s: %w", req.VolumeId, location.Directory, err)
|
|
}
|
|
}
|
|
return &volume_server_pb.VolumeEcShardsDeleteResponse{FullTeardownDone: true}, nil
|
|
}
|
|
|
|
glog.V(0).Infof("ec volume %s shard delete %v", bName, req.ShardIds)
|
|
|
|
// Pass 1: delete the requested shard files (and any now-orphaned per-disk bitrot
|
|
// sidecars) on every disk.
|
|
for diskId, location := range vs.store.Locations {
|
|
if err := deleteEcShardIdsForEachLocation(bName, location, vs.store.Locations, req.ShardIds); err != nil {
|
|
glog.Errorf("deleteEcShards from disk_id:%d %s %s.%v: %v", diskId, location.Directory, bName, req.ShardIds, err)
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
// Pass 2: the shared .ecx/.ecj index (and the .vif) is removed only when NO shard
|
|
// of this volume remains on ANY disk of this node. A per-disk check would orphan a
|
|
// sibling disk's shards (split-disk reconciled volumes) by deleting their index.
|
|
nodeWideShards := 0
|
|
type ecLocationStatus struct {
|
|
location *storage.DiskLocation
|
|
hasEcxFile bool
|
|
hasIdxFile bool
|
|
}
|
|
statuses := make([]ecLocationStatus, 0, len(vs.store.Locations))
|
|
for _, location := range vs.store.Locations {
|
|
hasEcxFile, hasIdxFile, existingShardCount, err := checkEcVolumeStatus(bName, location)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nodeWideShards += existingShardCount
|
|
statuses = append(statuses, ecLocationStatus{location, hasEcxFile, hasIdxFile})
|
|
}
|
|
if nodeWideShards == 0 {
|
|
// Reuse the status from the count pass above so the directory listing is not
|
|
// repeated per location.
|
|
for _, st := range statuses {
|
|
if err := removeEcSharedIndexFiles(bName, st.location, st.hasEcxFile, st.hasIdxFile); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
}
|
|
|
|
return &volume_server_pb.VolumeEcShardsDeleteResponse{}, nil
|
|
}
|
|
|
|
func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocation, locations []*storage.DiskLocation, shardIds []uint32) error {
|
|
|
|
found := false
|
|
|
|
indexBaseFilename := path.Join(location.IdxDirectory, bName)
|
|
dataBaseFilename := path.Join(location.Directory, bName)
|
|
|
|
// Delete the requested shard files unconditionally. Gating on a local .ecx
|
|
// (still used for index-file routing below) would leak an orphan shard left
|
|
// by a failed copy that reconciliation later mounts under a foreign index.
|
|
for _, shardId := range shardIds {
|
|
shardFileName := dataBaseFilename + erasure_coding.ToExt(int(shardId))
|
|
if util.FileExists(shardFileName) {
|
|
found = true
|
|
if err := removeFileIfExists(shardFileName); err != nil {
|
|
return fmt.Errorf("remove ec shard %s: %w", shardFileName, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
return nil
|
|
}
|
|
|
|
_, _, existingShardCount, err := checkEcVolumeStatus(bName, location)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if existingShardCount == 0 {
|
|
// This disk's shards for the volume are gone. Remove the bitrot checksum
|
|
// sidecar(s) (.ecsum and any .ecsum.v<N>) here, since they protect this
|
|
// disk's shards and are now orphaned. The shared .ecx/.ecj/.vif index is
|
|
// NOT removed here: a sibling disk may still hold shards that need it; the
|
|
// caller removes the shared index only once no shard remains node-wide.
|
|
if err := removeBitrotSidecars(dataBaseFilename); err != nil {
|
|
return err
|
|
}
|
|
if location.IdxDirectory != location.Directory && !idxSidecarInUse(bName, location.IdxDirectory, locations) {
|
|
if err := removeBitrotSidecars(indexBaseFilename); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// One -dir.idx serves every disk, so the idx-base sidecar is shared: it stays
|
|
// while any disk using that idx directory still holds shards of this volume.
|
|
// A status error counts as in-use so a transient failure never strips it early.
|
|
func idxSidecarInUse(bName string, idxDirectory string, locations []*storage.DiskLocation) bool {
|
|
for _, other := range locations {
|
|
if other.IdxDirectory != idxDirectory {
|
|
continue
|
|
}
|
|
if _, _, count, err := checkEcVolumeStatus(bName, other); err != nil || count > 0 {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// removeEcSharedIndexFiles removes the shared .ecx/.ecj index (and the .vif when no
|
|
// .idx is present) for an EC volume on one disk. The caller invokes it only after
|
|
// the whole node's shards for the volume are gone, so a sibling disk's shards are
|
|
// never orphaned by deleting their index. A surviving stale .ecx is the orphan-index
|
|
// condition this prevents, so a real removal failure is surfaced. hasEcxFile and
|
|
// hasIdxFile come from the caller's checkEcVolumeStatus so the directory is not
|
|
// re-listed here.
|
|
func removeEcSharedIndexFiles(bName string, location *storage.DiskLocation, hasEcxFile, hasIdxFile bool) error {
|
|
indexBaseFilename := path.Join(location.IdxDirectory, bName)
|
|
dataBaseFilename := path.Join(location.Directory, bName)
|
|
if hasEcxFile {
|
|
// .ecx/.ecj may be in either dir depending on when -dir.idx was configured.
|
|
for _, p := range []string{indexBaseFilename + ".ecx", indexBaseFilename + ".ecj"} {
|
|
if err := removeFileIfExists(p); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if location.IdxDirectory != location.Directory {
|
|
for _, p := range []string{dataBaseFilename + ".ecx", dataBaseFilename + ".ecj"} {
|
|
if err := removeFileIfExists(p); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Remove the .vif when no .idx is present (so this is not a live normal/tiered
|
|
// volume), independent of .ecx presence: the caller only reaches here once no
|
|
// shard remains node-wide, so an EC .vif left without its .ecx is stale
|
|
// generation metadata that would otherwise leak.
|
|
if !hasIdxFile {
|
|
if err := removeFileIfExists(dataBaseFilename + ".vif"); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// removeFileIfExists removes path, treating "already gone" as success and
|
|
// returning only a real failure (so a stale shard left behind is not silently
|
|
// reported as cleaned).
|
|
func removeFileIfExists(path string) error {
|
|
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// readEcGenerationTsNs returns the EC encode generation recorded in a disk's .vif
|
|
// (data dir first, then idx dir for the split-disk layout) and whether a .vif file
|
|
// was present. A present .vif with no EcShardConfig — or one that failed to parse —
|
|
// yields (0, true): generation 0, which the fenced teardown preserves anyway (a
|
|
// recovered or pre-upgrade live volume). (0, false) means no .vif file was found.
|
|
// Both 0 and a missing .vif are preserved, so the read is fail-safe in every case.
|
|
func readEcGenerationTsNs(dataBaseFileName, indexBaseFileName string) (int64, bool) {
|
|
for _, base := range []string{dataBaseFileName, indexBaseFileName} {
|
|
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(base + ".vif"); found {
|
|
return vi.GetEcShardConfig().GetEncodeTsNs(), true
|
|
}
|
|
if dataBaseFileName == indexBaseFileName {
|
|
break
|
|
}
|
|
}
|
|
return 0, false
|
|
}
|
|
|
|
// removeStaleEcArtifacts deletes the shard, index, journal, and bitrot sidecar
|
|
// files of a prior encode so a fresh encode never mixes runs. total is the
|
|
// shard-id range to scan (pass the cap for custom ratios). Returns the first
|
|
// real removal failure; does not touch the source .dat/.idx/.vif.
|
|
func removeStaleEcArtifacts(dataBaseFileName, indexBaseFileName string, total int) error {
|
|
var firstErr error
|
|
record := func(err error) {
|
|
if err != nil && firstErr == nil {
|
|
firstErr = err
|
|
}
|
|
}
|
|
for i := 0; i < total; i++ {
|
|
record(removeFileIfExists(dataBaseFileName + erasure_coding.ToExt(i)))
|
|
}
|
|
// .ecx/.ecj/.ecsum may sit in either dir depending on -dir.idx; clear both.
|
|
record(removeFileIfExists(indexBaseFileName + ".ecx"))
|
|
record(removeFileIfExists(indexBaseFileName + ".ecj"))
|
|
record(removeBitrotSidecars(indexBaseFileName))
|
|
if dataBaseFileName != indexBaseFileName {
|
|
record(removeFileIfExists(dataBaseFileName + ".ecx"))
|
|
record(removeFileIfExists(dataBaseFileName + ".ecj"))
|
|
record(removeBitrotSidecars(dataBaseFileName))
|
|
}
|
|
|
|
// Canonical <base>.vif. A shard copy installs shards + .ecx before .vif, so an
|
|
// interrupted copy can leave a stale .vif whose run identity / shard ratio /
|
|
// dat_file_size a fresh generation would inherit. Remove it only on a shard-only
|
|
// EC node: where a normal <base>.idx exists this is the source volume holder and
|
|
// the .vif belongs to that live volume — keep it. This mirrors the !hasIdxFile
|
|
// gate in the per-shard delete path.
|
|
if _, statErr := os.Stat(indexBaseFileName + ".idx"); os.IsNotExist(statErr) {
|
|
record(removeFileIfExists(indexBaseFileName + ".vif"))
|
|
if dataBaseFileName != indexBaseFileName {
|
|
if _, dStatErr := os.Stat(dataBaseFileName + ".idx"); os.IsNotExist(dStatErr) {
|
|
record(removeFileIfExists(dataBaseFileName + ".vif"))
|
|
}
|
|
}
|
|
}
|
|
return firstErr
|
|
}
|
|
|
|
// removeBitrotSidecars removes the legacy <base>.ecsum and any versioned
|
|
// <base>.ecsum.v<N> sidecars, returning the first real removal failure.
|
|
func removeBitrotSidecars(baseFilename string) error {
|
|
var firstErr error
|
|
if err := removeFileIfExists(baseFilename + erasure_coding.BitrotSidecarExt); err != nil {
|
|
firstErr = err
|
|
}
|
|
matches, _ := filepath.Glob(baseFilename + erasure_coding.BitrotSidecarExt + ".v*")
|
|
for _, m := range matches {
|
|
if err := removeFileIfExists(m); err != nil && firstErr == nil {
|
|
firstErr = err
|
|
}
|
|
}
|
|
return firstErr
|
|
}
|
|
|
|
// rebuildSearchDirs lists every directory besides the rebuild's own data
|
|
// directory that a rebuild may have to read from. Shards are only half of it:
|
|
// a split -dir/-dir.idx layout keeps .ecx/.ecj/.vif with the index, and on a
|
|
// multi-disk server the chosen disk may hold nothing but shards while the
|
|
// volume's .vif or generation-0 .ecsum sits on a sibling. Miss those and the
|
|
// layout resolution falls back to the default ratio and the legacy block
|
|
// size, reconstructing through the wrong matrix. The rebuild's own INDEX
|
|
// directory belongs here too — callers pass the data-directory base name, so
|
|
// it is not otherwise searched. Empty and duplicate entries are dropped.
|
|
func rebuildSearchDirs(rebuildLocation *storage.DiskLocation, otherLocations []*storage.DiskLocation) []string {
|
|
var dirs []string
|
|
appendDir := func(dir string) {
|
|
if dir == "" || dir == rebuildLocation.Directory {
|
|
return
|
|
}
|
|
for _, existing := range dirs {
|
|
if existing == dir {
|
|
return
|
|
}
|
|
}
|
|
dirs = append(dirs, dir)
|
|
}
|
|
appendDir(rebuildLocation.IdxDirectory)
|
|
for _, otherLocation := range otherLocations {
|
|
appendDir(otherLocation.Directory)
|
|
appendDir(otherLocation.IdxDirectory)
|
|
}
|
|
return dirs
|
|
}
|
|
|
|
func checkEcVolumeStatus(bName string, location *storage.DiskLocation) (hasEcxFile bool, hasIdxFile bool, existingShardCount int, err error) {
|
|
// check whether to delete the .ecx and .ecj file also
|
|
fileInfos, err := os.ReadDir(location.Directory)
|
|
if err != nil {
|
|
return false, false, 0, err
|
|
}
|
|
if location.IdxDirectory != location.Directory {
|
|
idxFileInfos, err := os.ReadDir(location.IdxDirectory)
|
|
if err != nil {
|
|
return false, false, 0, err
|
|
}
|
|
fileInfos = append(fileInfos, idxFileInfos...)
|
|
}
|
|
for _, fileInfo := range fileInfos {
|
|
if fileInfo.Name() == bName+".ecx" || fileInfo.Name() == bName+".ecj" {
|
|
hasEcxFile = true
|
|
continue
|
|
}
|
|
if fileInfo.Name() == bName+".idx" {
|
|
hasIdxFile = true
|
|
continue
|
|
}
|
|
if isEcDataShardFile(fileInfo.Name(), bName) {
|
|
existingShardCount++
|
|
}
|
|
}
|
|
return hasEcxFile, hasIdxFile, existingShardCount, nil
|
|
}
|
|
|
|
func isEcDataShardFile(fileName, baseName string) bool {
|
|
const ecDataShardSuffixLen = 2 // ".ecNN"
|
|
prefix := baseName + ".ec"
|
|
if !strings.HasPrefix(fileName, prefix) {
|
|
return false
|
|
}
|
|
suffix := strings.TrimPrefix(fileName, prefix)
|
|
if len(suffix) != ecDataShardSuffixLen {
|
|
return false
|
|
}
|
|
shardId, err := strconv.Atoi(suffix)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return shardId >= 0 && shardId < erasure_coding.MaxShardCount
|
|
}
|
|
|
|
func (vs *VolumeServer) VolumeEcShardsMount(ctx context.Context, req *volume_server_pb.VolumeEcShardsMountRequest) (*volume_server_pb.VolumeEcShardsMountResponse, error) {
|
|
|
|
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)
|
|
|
|
if err != nil {
|
|
glog.Errorf("ec shard mount %v: %v", req, err)
|
|
} else {
|
|
glog.V(2).Infof("ec shard mount %v", req)
|
|
}
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("mount %d.%d: %v", req.VolumeId, shardId, err)
|
|
}
|
|
}
|
|
|
|
// A shard delivery can bring the checksum manifest with it, but the receive
|
|
// path only writes the file. When this server already had the volume
|
|
// mounted, the EcVolume in memory keeps whatever protection state it
|
|
// resolved at mount — off, for a volume whose sidecar arrives now — until a
|
|
// remount. Re-resolve it here, where the shards it describes were added.
|
|
// Every per-disk runtime, not just the first: a vid mounts as one EcVolume
|
|
// per disk, the delivery lands the .ecsum on one of them, and the
|
|
// first-match FindEcVolume would leave the siblings reporting no protection
|
|
// until a remount. Each re-resolves against its own data and index base, so
|
|
// a shared -dir.idx reaches all of them.
|
|
//
|
|
// Resolving across every EC metadata directory is what makes that reload
|
|
// mean something. Startup mirroring gives each shard-bearing disk its own
|
|
// .ecx/.ecj/.vif but deliberately not the sidecar, so a runtime restricted
|
|
// to its own two directories would find nothing however often it reloaded.
|
|
// One delivered copy, reachable from all of them.
|
|
ecMetadataDirs := vs.store.EcMetadataDirs()
|
|
for _, v := range vs.store.FindAllEcVolumes(needle.VolumeId(req.VolumeId)) {
|
|
v.ReloadBitrotSidecar(ecMetadataDirs...)
|
|
}
|
|
|
|
return &volume_server_pb.VolumeEcShardsMountResponse{}, nil
|
|
}
|
|
|
|
func (vs *VolumeServer) VolumeEcShardsUnmount(ctx context.Context, req *volume_server_pb.VolumeEcShardsUnmountRequest) (*volume_server_pb.VolumeEcShardsUnmountResponse, error) {
|
|
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
glog.V(0).Infof("VolumeEcShardsUnmount: %v", req)
|
|
|
|
for _, shardId := range req.ShardIds {
|
|
err := vs.store.UnmountEcShards(needle.VolumeId(req.VolumeId), erasure_coding.ShardId(shardId), req.EncodeTsNs)
|
|
|
|
if err != nil {
|
|
glog.Errorf("ec shard unmount %v: %v", req, err)
|
|
} else {
|
|
glog.V(2).Infof("ec shard unmount %v", req)
|
|
}
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unmount %d.%d: %v", req.VolumeId, shardId, err)
|
|
}
|
|
}
|
|
|
|
return &volume_server_pb.VolumeEcShardsUnmountResponse{}, nil
|
|
}
|
|
|
|
func (vs *VolumeServer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error {
|
|
|
|
// Resolve the shard together with the EcVolume on the disk that owns it,
|
|
// rather than a first-match volume on a sibling disk: on a multi-disk server
|
|
// those can belong to different encode generations, and the guard must
|
|
// validate the identity of the volume whose bytes we serve.
|
|
ecVolume, ecShard, found := vs.store.FindEcVolumeWithShard(needle.VolumeId(req.VolumeId), erasure_coding.ShardId(req.ShardId))
|
|
if !found {
|
|
return fmt.Errorf("not found ec shard %d.%d", req.VolumeId, req.ShardId)
|
|
}
|
|
// Reject a shard whose identity doesn't match the caller's index; the caller
|
|
// then recovers from parity. Lenient only when the caller has no identity
|
|
// (pre-upgrade reader): a known caller must not accept an unstamped holder,
|
|
// which would serve a stale pre-upgrade shard.
|
|
if req.EncodeTsNs != 0 && req.EncodeTsNs != ecVolume.EncodeTsNs {
|
|
return fmt.Errorf("ec shard %d.%d belongs to a different encode run", req.VolumeId, req.ShardId)
|
|
}
|
|
|
|
if req.FileKey != 0 {
|
|
_, size, _ := ecVolume.FindNeedleFromEcx(types.Uint64ToNeedleId(req.FileKey))
|
|
if size.IsDeleted() {
|
|
return stream.Send(&volume_server_pb.VolumeEcShardReadResponse{
|
|
IsDeleted: true,
|
|
EncodeTsNs: ecVolume.EncodeTsNs,
|
|
})
|
|
}
|
|
}
|
|
|
|
bufSize := req.Size
|
|
if bufSize > BufferSizeLimit {
|
|
bufSize = BufferSizeLimit
|
|
}
|
|
buffer := make([]byte, bufSize)
|
|
|
|
startOffset, bytesToRead := req.Offset, req.Size
|
|
|
|
for bytesToRead > 0 {
|
|
// min of bytesToRead and bufSize
|
|
bufferSize := bufSize
|
|
if bufferSize > bytesToRead {
|
|
bufferSize = bytesToRead
|
|
}
|
|
bytesread, err := ecShard.ReadAt(buffer[0:bufferSize], startOffset)
|
|
|
|
// println("read", ecShard.FileName(), "startOffset", startOffset, bytesread, "bytes, with target", bufferSize)
|
|
if bytesread > 0 {
|
|
|
|
if int64(bytesread) > bytesToRead {
|
|
bytesread = int(bytesToRead)
|
|
}
|
|
err = stream.Send(&volume_server_pb.VolumeEcShardReadResponse{
|
|
Data: buffer[:bytesread],
|
|
EncodeTsNs: ecVolume.EncodeTsNs,
|
|
})
|
|
if err != nil {
|
|
// println("sending", bytesread, "bytes err", err.Error())
|
|
return err
|
|
}
|
|
|
|
startOffset += int64(bytesread)
|
|
bytesToRead -= int64(bytesread)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
if err != io.EOF {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
func (vs *VolumeServer) VolumeEcBlobDelete(ctx context.Context, req *volume_server_pb.VolumeEcBlobDeleteRequest) (*volume_server_pb.VolumeEcBlobDeleteResponse, error) {
|
|
if err := vs.CheckMaintenanceMode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
glog.V(0).Infof("VolumeEcBlobDelete: %v", req)
|
|
|
|
resp := &volume_server_pb.VolumeEcBlobDeleteResponse{}
|
|
|
|
for _, location := range vs.store.Locations {
|
|
if localEcVolume, found := location.FindEcVolume(needle.VolumeId(req.VolumeId)); found {
|
|
|
|
_, size, _, err := localEcVolume.LocateEcShardNeedle(types.NeedleId(req.FileKey), needle.Version(req.Version))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("locate in local ec volume: %w", err)
|
|
}
|
|
if size.IsDeleted() {
|
|
return resp, nil
|
|
}
|
|
|
|
err = localEcVolume.DeleteNeedleFromEcx(types.NeedleId(req.FileKey))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
break
|
|
}
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
// VolumeEcShardsToVolume generates the .idx, .dat files from .ecx, .ecj and .ec01 ~ .ec14 files
|
|
func (vs *VolumeServer) VolumeEcShardsToVolume(ctx context.Context, req *volume_server_pb.VolumeEcShardsToVolumeRequest) (*volume_server_pb.VolumeEcShardsToVolumeResponse, error) {
|
|
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := vs.CheckMaintenanceMode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
glog.V(0).Infof("VolumeEcShardsToVolume: %v", req)
|
|
|
|
// Staged mode: the caller decoded the shards off-box and streamed the normal
|
|
// volume here as <base><ext>.copying (ReceiveFile staged-new-volume). Adopt
|
|
// those files as a normal volume; this server holds no EC shards for the vid,
|
|
// so there is no local EC decode to run.
|
|
if req.FromStaged {
|
|
return vs.adoptStagedVolume(req)
|
|
}
|
|
|
|
// Collect all EC shards (NewEcVolume will load EC config from .vif into v.ECContext)
|
|
// Use MaxShardCount (32) to support custom EC ratios up to 32 total shards
|
|
tempShards := make([]string, erasure_coding.MaxShardCount)
|
|
v, found := vs.store.CollectEcShards(needle.VolumeId(req.VolumeId), tempShards)
|
|
if !found {
|
|
return nil, fmt.Errorf("ec volume %d not found", req.VolumeId)
|
|
}
|
|
|
|
if v.Collection != req.Collection {
|
|
return nil, fmt.Errorf("existing collection:%v unexpected input: %v", v.Collection, req.Collection)
|
|
}
|
|
|
|
// Use EC context (already loaded from .vif) to determine data shard count
|
|
dataShards := v.ECContext.DataShards
|
|
|
|
// Defensive validation to prevent panics from corrupted ECContext
|
|
if dataShards <= 0 || dataShards > erasure_coding.MaxShardCount {
|
|
return nil, fmt.Errorf("invalid data shard count %d for volume %d (must be 1..%d)", dataShards, req.VolumeId, erasure_coding.MaxShardCount)
|
|
}
|
|
|
|
shardFileNames := tempShards[:dataShards]
|
|
glog.V(1).Infof("Using EC config from volume %d: %d data shards", req.VolumeId, dataShards)
|
|
|
|
// Verify all data shards are present
|
|
for shardId := 0; shardId < dataShards; shardId++ {
|
|
if shardFileNames[shardId] == "" {
|
|
return nil, fmt.Errorf("ec volume %d missing shard %d", req.VolumeId, shardId)
|
|
}
|
|
}
|
|
|
|
dataBaseFileName, indexBaseFileName := v.DataBaseFileName(), v.IndexBaseFileName()
|
|
if !util.FileExists(indexBaseFileName + ".ecx") {
|
|
indexBaseFileName = dataBaseFileName
|
|
}
|
|
|
|
// Merge .ecj deletions into .ecx so that HasLiveNeedles and FindDatFileSize
|
|
// see the full set of deleted needles. Without this, needles deleted after the
|
|
// last ecx rebuild would still appear live, causing the decoded .dat to include
|
|
// data that should be skipped and HasLiveNeedles to return a false positive.
|
|
if err := erasure_coding.RebuildEcxFile(indexBaseFileName); err != nil {
|
|
return nil, fmt.Errorf("RebuildEcxFile %s: %v", indexBaseFileName, err)
|
|
}
|
|
|
|
// If the EC index contains no live entries, decoding should be a no-op:
|
|
// just allow the caller to purge EC shards and do not generate an empty normal volume.
|
|
hasLive, err := erasure_coding.HasLiveNeedles(indexBaseFileName)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("HasLiveNeedles %s: %w", indexBaseFileName, err)
|
|
}
|
|
if !hasLive {
|
|
return nil, status.Errorf(codes.FailedPrecondition, "ec volume %d %s", req.VolumeId, erasure_coding.EcNoLiveEntriesSubstring)
|
|
}
|
|
|
|
// calculate .dat file size. Pass shard 0's resolved path: on a multi-disk
|
|
// server the volume's shards can sit on several disks, so the .ec00 is not
|
|
// necessarily beside the EcVolume's own base path.
|
|
datFileSize, err := erasure_coding.FindDatFileSize(shardFileNames[0], indexBaseFileName)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("FindDatFileSize %s: %v", shardFileNames[0], err)
|
|
}
|
|
|
|
// The shard block layout was fixed by the .dat size at encode time (recorded
|
|
// in .vif); deletions can shrink the live extent below a large-block row
|
|
// boundary, so the layout must not be derived from datFileSize. WriteDatFile
|
|
// infers the layout from the shard size when .vif does not record it.
|
|
// write .dat file from .ec00 ~ .ec09 files
|
|
if err := erasure_coding.WriteDatFile(dataBaseFileName, datFileSize, v.DatFileSize(), shardFileNames, v.ECContext.LargeBlockSize(), v.ECContext.SmallBlockSize()); err != nil {
|
|
return nil, fmt.Errorf("WriteDatFile %s: %v", dataBaseFileName, err)
|
|
}
|
|
|
|
// Fail the decode rather than report a short volume: the caller deletes the
|
|
// shards once this call returns, and today its only check is that the files
|
|
// are non-empty.
|
|
if err := erasure_coding.VerifyDecodedDatFile(dataBaseFileName, datFileSize); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// write .idx file from .ecx and .ecj files
|
|
if err := erasure_coding.WriteIdxFileFromEcIndex(indexBaseFileName); err != nil {
|
|
return nil, fmt.Errorf("WriteIdxFileFromEcIndex %s: %v", v.IndexBaseFileName(), err)
|
|
}
|
|
|
|
// The EC generation is gone; drop its bitrot sidecar(s) so a later EC
|
|
// re-encode cannot mistake a stale .ecsum for protection.
|
|
removeBitrotSidecars(dataBaseFileName)
|
|
if indexBaseFileName != dataBaseFileName {
|
|
removeBitrotSidecars(indexBaseFileName)
|
|
}
|
|
|
|
var volumeLocation *storage.DiskLocation
|
|
for _, location := range vs.store.Locations {
|
|
if candidate, found := location.FindEcVolume(needle.VolumeId(req.VolumeId)); found && candidate == v {
|
|
volumeLocation = location
|
|
break
|
|
}
|
|
}
|
|
if volumeLocation == nil {
|
|
return nil, fmt.Errorf("ec volume %d location not found for offline compaction", req.VolumeId)
|
|
}
|
|
|
|
if err := vs.store.CompactVolumeFiles(
|
|
needle.VolumeId(req.VolumeId),
|
|
v.Collection,
|
|
volumeLocation,
|
|
vs.needleMapKind,
|
|
vs.ldbTimout,
|
|
0,
|
|
vs.compactionBytePerSecond,
|
|
); err != nil {
|
|
glog.Errorf("CompactVolumeFiles %s: %v", dataBaseFileName, err)
|
|
}
|
|
|
|
// Co-locate the rebuilt index with the data. The rebuild wrote the .idx to
|
|
// the shared -dir.idx directory, but the on-demand VolumeMount scans only
|
|
// the data directory and matches on .idx/.vif: with the index off in the
|
|
// index directory it would find the volume's leftover EC .vif instead and
|
|
// skip it as EC metadata. Moving the .idx next to the .dat lets the mount
|
|
// find the volume; VolumeConsolidateIndex returns it to the index directory
|
|
// once the EC shards are deleted.
|
|
if volumeLocation.IdxDirectory != volumeLocation.Directory {
|
|
idxSrc := storage.VolumeFileName(volumeLocation.IdxDirectory, v.Collection, int(req.VolumeId)) + ".idx"
|
|
idxDst := storage.VolumeFileName(volumeLocation.Directory, v.Collection, int(req.VolumeId)) + ".idx"
|
|
if util.FileExists(idxSrc) {
|
|
if moveErr := storage.RenameOrCopyFile(idxSrc, idxDst); moveErr != nil {
|
|
glog.Warningf("co-locate rebuilt index %s -> %s: %v", idxSrc, idxDst, moveErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
return &volume_server_pb.VolumeEcShardsToVolumeResponse{}, nil
|
|
}
|
|
|
|
// adoptStagedVolume finalizes a normal volume the caller decoded off-box and
|
|
// streamed here as <base><ext>.copying (ReceiveFile staged-new-volume mode). It
|
|
// renames the staged files into place under a .note in-progress marker and
|
|
// mounts the volume, so <vid> is registered here only as a normal volume — never
|
|
// as an EC/normal twin in one directory.
|
|
func (vs *VolumeServer) adoptStagedVolume(req *volume_server_pb.VolumeEcShardsToVolumeRequest) (*volume_server_pb.VolumeEcShardsToVolumeResponse, error) {
|
|
vid := needle.VolumeId(req.VolumeId)
|
|
if vs.store.GetVolume(vid) != nil {
|
|
return nil, fmt.Errorf("staged volume %d already exists on this server", req.VolumeId)
|
|
}
|
|
want := types.ToDiskType(req.DiskType)
|
|
|
|
// Locate the disk the ReceiveFile push staged onto: the disk_type location
|
|
// whose <base>.dat.copying exists.
|
|
var base string
|
|
for _, l := range vs.store.Locations {
|
|
if l.DiskType != want {
|
|
continue
|
|
}
|
|
candidate := storage.VolumeFileName(l.Directory, req.Collection, int(req.VolumeId))
|
|
if util.FileExists(candidate + ".dat.copying") {
|
|
base = candidate
|
|
break
|
|
}
|
|
}
|
|
if base == "" {
|
|
return nil, fmt.Errorf("staged volume %d: no .dat.copying found on a %s disk", req.VolumeId, req.DiskType)
|
|
}
|
|
for _, ext := range []string{".dat", ".idx", ".vif"} {
|
|
if !util.FileExists(base + ext + ".copying") {
|
|
return nil, fmt.Errorf("staged volume %d missing %s.copying", req.VolumeId, ext)
|
|
}
|
|
}
|
|
|
|
// .note in-progress marker (VolumeCopy discipline): a crash mid-rename leaves a
|
|
// .note that fails the load and sweeps the partial volume on restart.
|
|
noteFile := base + ".note"
|
|
if err := util.WriteFile(noteFile, []byte(fmt.Sprintf("adopting decoded volume %d", req.VolumeId)), 0644); err != nil {
|
|
return nil, fmt.Errorf("write .note for volume %d: %w", req.VolumeId, err)
|
|
}
|
|
|
|
// Rename staged files into place, then drop the .note before mounting — a
|
|
// volume that still carries a .note is swept by loadExistingVolume.
|
|
for _, ext := range []string{".vif", ".dat", ".idx"} {
|
|
if err := os.Rename(base+ext+".copying", base+ext); err != nil {
|
|
os.Remove(noteFile)
|
|
return nil, fmt.Errorf("rename staged %s for volume %d: %w", ext, req.VolumeId, err)
|
|
}
|
|
}
|
|
os.Remove(noteFile)
|
|
|
|
if err := vs.store.MountVolume(vid); err != nil {
|
|
return nil, fmt.Errorf("mount staged volume %d: %w", req.VolumeId, err)
|
|
}
|
|
glog.V(0).Infof("VolumeEcShardsToVolume: adopted decoded volume %d from staging (%s)", req.VolumeId, base)
|
|
return &volume_server_pb.VolumeEcShardsToVolumeResponse{}, nil
|
|
}
|
|
|
|
func (vs *VolumeServer) VolumeEcShardsInfo(ctx context.Context, req *volume_server_pb.VolumeEcShardsInfoRequest) (*volume_server_pb.VolumeEcShardsInfoResponse, error) {
|
|
glog.V(0).Infof("VolumeEcShardsInfo: volume %d", req.VolumeId)
|
|
|
|
vid := needle.VolumeId(req.GetVolumeId())
|
|
|
|
// Multi-disk volume servers register one EcVolume per DiskLocation
|
|
// that holds shards for the same vid: shards may be spread across
|
|
// disks while the .ecx lives on whichever disk owned the original
|
|
// .dat. Walk every DiskLocation here so the response reflects the
|
|
// full local shard set; the per-disk ecVolumesLock is taken inside
|
|
// DiskLocation.FindEcVolume.
|
|
var primary *erasure_coding.EcVolume
|
|
var seenShards erasure_coding.ShardBits
|
|
shardInfos := make([]*volume_server_pb.EcShardInfo, 0, erasure_coding.MaxShardCount)
|
|
for _, location := range vs.store.Locations {
|
|
ecv, ok := location.FindEcVolume(vid)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if primary == nil {
|
|
primary = ecv
|
|
}
|
|
for _, s := range ecv.Shards {
|
|
if seenShards.Has(s.ShardId) {
|
|
continue
|
|
}
|
|
seenShards = seenShards.Set(s.ShardId)
|
|
shardInfos = append(shardInfos, s.ToEcShardInfo())
|
|
}
|
|
}
|
|
if primary == nil {
|
|
return nil, fmt.Errorf("VolumeEcShardsInfo: EC volume %d not found", vid)
|
|
}
|
|
|
|
var files, filesDeleted, totalSize uint64
|
|
err := primary.WalkIndex(func(_ types.NeedleId, _ types.Offset, size types.Size) error {
|
|
// deleted files are counted when computing EC volume sizes. this aligns with VolumeStatus(),
|
|
// which reports the raw data backend file size, regardless of deleted files.
|
|
totalSize += uint64(size.Raw())
|
|
|
|
if size.IsDeleted() {
|
|
filesDeleted++
|
|
} else {
|
|
files++
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Report the layout this holder will actually serve reads through. It is
|
|
// the only way a coordinator can tell a holder that understands the
|
|
// uniform block layout from one that dropped the unknown .vif field on the
|
|
// floor and mounted the volume as legacy.
|
|
var ecShardConfig *volume_server_pb.EcShardConfig
|
|
if primary.ECContext != nil {
|
|
ecShardConfig = &volume_server_pb.EcShardConfig{
|
|
DataShards: uint32(primary.ECContext.DataShards),
|
|
ParityShards: uint32(primary.ECContext.ParityShards),
|
|
BlockSize: primary.ECContext.BlockSize,
|
|
}
|
|
}
|
|
|
|
res := &volume_server_pb.VolumeEcShardsInfoResponse{
|
|
EcShardInfos: shardInfos,
|
|
FileCount: files,
|
|
FileDeletedCount: filesDeleted,
|
|
VolumeSize: totalSize,
|
|
EcShardConfig: ecShardConfig,
|
|
}
|
|
|
|
return res, nil
|
|
}
|