mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
Merge remote-tracking branch 'origin/main' into fix/1.0.1-live-holder
This commit is contained in:
commit
6be001de67
40 files changed
+2820
-70
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -342,6 +343,7 @@ func startG15aVolume(t *testing.T, bin, art string, o g15aVolumeOpts) *g15aProc
|
||||
"--replica-id", o.replicaID,
|
||||
"--data-addr", o.dataAddr,
|
||||
"--ctrl-addr", o.ctrlAddr,
|
||||
"--volume-lock-dir-test-only", t.TempDir(),
|
||||
"--durable-root", filepath.Join(art, "store-"+o.logTag),
|
||||
"--durable-impl", "walstore",
|
||||
"--durable-blocks", "256",
|
||||
@@ -349,6 +351,12 @@ func startG15aVolume(t *testing.T, bin, art string, o g15aVolumeOpts) *g15aProc
|
||||
"--heartbeat-interval", "200ms",
|
||||
"--t1-readiness",
|
||||
)
|
||||
// The test override is refused under systemd; do not inherit the test runner's invocation.
|
||||
for _, kv := range os.Environ() {
|
||||
if !strings.HasPrefix(kv, "INVOCATION_ID=") {
|
||||
cmd.Env = append(cmd.Env, kv)
|
||||
}
|
||||
}
|
||||
if o.iscsiAddr != "" {
|
||||
cmd.Args = append(cmd.Args,
|
||||
"--iscsi-listen", o.iscsiAddr,
|
||||
|
||||
@@ -223,21 +223,31 @@ const exitGeometryRefused = 78
|
||||
|
||||
// geometryFlagsRefusal compares the geometry flags with the volume record
|
||||
// before any local store is created, so a wrong flag never leaves a store of
|
||||
// the wrong size behind. It returns the refusal line, or "" when the record
|
||||
// agrees, does not exist yet (the attach check creates it from the flags),
|
||||
// or cannot be read (the attach check still refuses a mismatch later), and
|
||||
// when no store is being created (numBlocks 0: an existing store opens with
|
||||
// its own geometry).
|
||||
func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) string {
|
||||
// the wrong size behind. It returns the refusal line and its exit status:
|
||||
// exitGeometryRefused (78) when the record disagrees or is there but does not
|
||||
// decode; exitWorkspaceRetry (75) when the filer could not be read (an
|
||||
// unknown, never taken as "absent"); ("", 0) when the record agrees, does
|
||||
// not exist yet (the attach
|
||||
// check creates it from the flags), or no store is being created (numBlocks
|
||||
// 0: an existing store opens with its own geometry).
|
||||
func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) (string, int) {
|
||||
if numBlocks == 0 {
|
||||
return "" // an existing store: the flags are not used
|
||||
return "", 0 // an existing store: the flags are not used
|
||||
}
|
||||
v, ok, err := cat.ReadVolume(ctx, volumeID)
|
||||
if err != nil || !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) {
|
||||
return ""
|
||||
if err != nil && chunkstore.CodeOf(err) == chunkstore.CodeRemoteUnavailable {
|
||||
return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", volumeID, err), exitWorkspaceRetry
|
||||
}
|
||||
if err != nil {
|
||||
// A record that is there but does not decode stays that way: a
|
||||
// permanent refusal, not a retry loop.
|
||||
return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", volumeID, err), exitGeometryRefused
|
||||
}
|
||||
if !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) {
|
||||
return "", 0
|
||||
}
|
||||
return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d disagree with the volume record of %s (%d blocks of %d bytes); no local store was created; start it with the record's geometry",
|
||||
numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize)
|
||||
numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize), exitGeometryRefused
|
||||
}
|
||||
|
||||
// chunkHolder is how this host names itself in HEAD: <server-id>/<replica-id>
|
||||
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -117,40 +118,46 @@ func TestChunkVolumeRootStaysInsideBase(t *testing.T) {
|
||||
}
|
||||
|
||||
// Before any local store is created, a geometry flag that disagrees with the
|
||||
// volume record is refused with a line naming both; a matching record, a
|
||||
// missing record (the attach check creates it) and an unreadable one (the
|
||||
// attach check still applies) do not refuse.
|
||||
// volume record is refused with a line naming both (78); a record the filer
|
||||
// could not deliver is refused as retryable (75), never taken as "absent";
|
||||
// a record that is there but does not decode is refused for good (78); a matching
|
||||
// record, a missing record (the attach check creates it) and an existing
|
||||
// store (no create geometry) are not refused.
|
||||
func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" {
|
||||
t.Fatalf("no record yet: %q", got)
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" || code != 0 {
|
||||
t.Fatalf("no record yet: %q, %d", got, code)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" {
|
||||
t.Fatalf("matching flags refused: %q", got)
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" || code != 0 {
|
||||
t.Fatalf("matching flags refused: %q, %d", got, code)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
blocks uint64
|
||||
size uint32
|
||||
}{{32768, 4096}, {65536, 512}} {
|
||||
got := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size)
|
||||
got, code := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size)
|
||||
if code != exitGeometryRefused {
|
||||
t.Fatalf("flags %d x %d: exit %d, want %d", c.blocks, c.size, code, exitGeometryRefused)
|
||||
}
|
||||
for _, want := range []string{"geometry_mismatch", "--durable-blocks", "65536 blocks of 4096 bytes"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("flags %d x %d: refusal %q lacks %q", c.blocks, c.size, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" {
|
||||
t.Fatalf("an existing store (no create geometry) must not be refused: %q", got)
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" || code != 0 {
|
||||
t.Fatalf("an existing store (no create geometry) must not be refused: %q, %d", got, code)
|
||||
}
|
||||
// An unreadable record: the same valid volume over a filer whose
|
||||
// lookups fail. The record is read (and fails), and nothing is refused.
|
||||
// lookups fail. The record is read, fails, and the start is refused as
|
||||
// retryable before anything is created.
|
||||
failing := &lookupFailFiler{MemFiler: chunkstore.NewMemFiler()}
|
||||
failCat, err := chunkstore.NewCatalog(failing, defaultChunkPath)
|
||||
if err != nil {
|
||||
@@ -160,12 +167,40 @@ func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failing.fail, failing.reads = true, 0
|
||||
if got := geometryFlagsRefusal(ctx, failCat, "v1", 32768, 4096); got != "" {
|
||||
t.Fatalf("an unreadable record must not refuse: %q", got)
|
||||
for _, blocks := range []uint64{32768, 65536} { // a wrong and a right flag alike
|
||||
got, code := geometryFlagsRefusal(ctx, failCat, "v1", blocks, 4096)
|
||||
if code != exitWorkspaceRetry || !strings.Contains(got, "the volume record of v1 could not be read") || !strings.Contains(got, "no local store was created; retrying") {
|
||||
t.Fatalf("--durable-blocks %d over an unreadable record: %q, exit %d; want a retryable refusal (%d)", blocks, got, code, exitWorkspaceRetry)
|
||||
}
|
||||
}
|
||||
if failing.reads == 0 {
|
||||
t.Fatal("the unreadable-record case never read the record")
|
||||
}
|
||||
// A record that is there but does not decode: a permanent refusal
|
||||
// (78), not a retry loop, for a wrong and a right flag alike.
|
||||
mem := chunkstore.NewMemFiler()
|
||||
corruptCat, err := chunkstore.NewCatalog(mem, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := corruptCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := path.Join(defaultChunkPath, "v1")
|
||||
e, err := mem.LookupEntry(ctx, dir, "VOLUME")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.Content = []byte("{")
|
||||
if err := mem.UpdateEntry(ctx, dir, e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, blocks := range []uint64{32768, 65536} {
|
||||
got, code := geometryFlagsRefusal(ctx, corruptCat, "v1", blocks, 4096)
|
||||
if code != exitGeometryRefused || !strings.Contains(got, "the volume record of v1 is unreadable (corrupt:") || !strings.Contains(got, "no local store was created") {
|
||||
t.Fatalf("--durable-blocks %d over a corrupt record: %q, exit %d; want a permanent refusal (%d)", blocks, got, code, exitGeometryRefused)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookupFailFiler is a MemFiler whose LookupEntry fails once fail is set; it
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -57,3 +59,79 @@ func TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated(t *testing.T) {
|
||||
t.Fatalf("1.0.1: %s", strings.Join(problems, "; "))
|
||||
}
|
||||
}
|
||||
|
||||
// INV-VOL-GEOMETRY-FLAGS-RECORD-001, the corrupt record: in create mode, a
|
||||
// volume record that is there but does not decode is refused for good (exit
|
||||
// 78) before any local store exists, never taken as "absent" and never
|
||||
// retried. The filer stays up and answers the startup checks; v2's VOLUME
|
||||
// entry is made undecodable. A wrong and a right --durable-blocks alike exit
|
||||
// 78 and leave nothing under --durable-root. With the entry restored the wrong
|
||||
// flag is refused (78, mismatch) and the right flag serves. (A filer that
|
||||
// cannot deliver the record is the retryable case, 75: the unit test.)
|
||||
func TestCorruptRecordIsRefusedBeforeTheStoreIsCreated(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v2")
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
b := env.hosts["n-v2"]
|
||||
right := append([]string{}, env.volArgsFor(b)...)
|
||||
wrong := append([]string{}, right...)
|
||||
for i := range wrong {
|
||||
if wrong[i] == "--durable-blocks" {
|
||||
wrong[i+1] = "32768"
|
||||
}
|
||||
}
|
||||
ctx := context.Background()
|
||||
cl := env.cluster.client(t, "")
|
||||
dir := path.Join(env.chunkPath, "v2")
|
||||
entry, err := cl.LookupEntry(ctx, dir, "VOLUME")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record := append([]byte(nil), entry.Content...)
|
||||
entry.Content = []byte("{")
|
||||
if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{{"wrong", wrong}, {"right", right}} {
|
||||
d := env.h.start(t, "blockvolume-v2-"+c.name+"-corrupt", env.h.volume, c.args...)
|
||||
err := d.wait(60 * time.Second)
|
||||
line := d.line("is unreadable (corrupt:")
|
||||
entries, _ := os.ReadDir(b.root)
|
||||
t.Logf("%s flag over a corrupt record: exit %v; %q; files under --durable-root %d", c.name, err, line, len(entries))
|
||||
if exitCode(err) != 78 || !strings.Contains(line, "no local store was created") || len(entries) != 0 {
|
||||
t.Fatalf("1.0.1: a %s-flag first start over a corrupt record must exit 78 before creating anything; exit %v, line %q, %d files", c.name, err, line, len(entries))
|
||||
}
|
||||
}
|
||||
entry.Content = record
|
||||
if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := env.h.start(t, "blockvolume-v2-wrong-readable", env.h.volume, wrong...)
|
||||
if err := d.wait(60 * time.Second); exitCode(err) != 78 {
|
||||
t.Fatalf("with the record readable again, the wrong flag must be refused (78); exit %v", err)
|
||||
}
|
||||
served := env.startTarget(t, "v2", "blockvolume-v2-right-readable")
|
||||
served.kill(t)
|
||||
}
|
||||
|
||||
// Guard: a first start with the filer stopped ends at the startup filer
|
||||
// check (exit 1) before the record check and before any store exists.
|
||||
func TestFirstStartWithTheFilerDownCreatesNoStore(t *testing.T) {
|
||||
env := startSourceWithSnapshot(t, "v2")
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
b := env.hosts["n-v2"]
|
||||
env.cluster.stopProc(t, "filer")
|
||||
d := env.h.start(t, "blockvolume-v2-filer-down", env.h.volume, env.volArgsFor(b)...)
|
||||
err := d.wait(120 * time.Second)
|
||||
env.cluster.restartProc(t, "filer")
|
||||
w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second)
|
||||
entries, _ := os.ReadDir(b.root)
|
||||
t.Logf("filer down: exit %v; %q; files under --durable-root %d", err, d.line("needs exactly one filer"), len(entries))
|
||||
if exitCode(err) != 1 || d.line("needs exactly one filer") == "" || len(entries) != 0 {
|
||||
t.Fatalf("a first start with the filer down must end at the startup filer check without a store; exit %v, %d files", err, len(entries))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
//go:build subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HEAD size against volume size (V1-SPEC r2.94), informative: it measures,
|
||||
// it does not judge. Runs only with HEADSZ_RUN=1, on a host booked for it.
|
||||
//
|
||||
// For each size in HEADSZ_SIZES (default 10G,100G,1T): one volume of that
|
||||
// size; one 4 KiB block written in every 1 GiB segment; a snapshot (cut 1);
|
||||
// then HEADSZ_CHANGE_CUTS snapshots (default 3), each after changing one
|
||||
// block. Per cut it records the HEAD entry's byte size as the filer returns
|
||||
// it, the number of segments HEAD lists, the cut's total and barrier time,
|
||||
// and the chunks and bytes the cut uploaded. A size the durable root has no
|
||||
// room for is recorded as refused by the blockvolume's headroom check, never
|
||||
// shrunk or bypassed. The JSON report goes to HEADSZ_REPORT.
|
||||
//
|
||||
// HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout (default 60s;
|
||||
// the server caps it at its own operation deadline). HEADSZ_ATTEMPTS (default
|
||||
// 1) retries a failed cut with the same request id; every attempt is
|
||||
// recorded with the volume's chunk-key count in the filer after it, so a
|
||||
// retry shows whether an earlier attempt's uploads were kept. A cut that never
|
||||
// completes is recorded as cut_not_completed, not failed.
|
||||
//
|
||||
// The filer runs on its default store (leveldb2) under the test's directory;
|
||||
// a filer.toml anywhere weed would read one fails the test before any start,
|
||||
// so the store measured is the one named in the report.
|
||||
|
||||
const headSegmentBytes = 1 << 30
|
||||
|
||||
// headSzAttempt is one snapshot command for one cut: a failed attempt is
|
||||
// resent with the same request id, as the command's refusal says.
|
||||
type headSzAttempt struct {
|
||||
Attempt int `json:"attempt"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
WallMs float64 `json:"wall_ms"`
|
||||
KeysAfter int `json:"chunk_keys_after"`
|
||||
LastCutTotalMs float64 `json:"last_cut_total_ms"`
|
||||
LastCutChunks int `json:"last_cut_uploaded_chunks"`
|
||||
// DirtyAfter is the volume's DirtyChunks (capture candidates) after the
|
||||
// attempt: on a failed attempt it shows whether the work done was kept.
|
||||
DirtyAfter int `json:"dirty_chunks_after"`
|
||||
// ChunkStatusAfter is the volume's whole chunk section of its durable
|
||||
// status after the attempt, as served (every counter and the full
|
||||
// LastCut), so a term no named field covers can still be read.
|
||||
ChunkStatusAfter json.RawMessage `json:"chunk_status_after,omitempty"`
|
||||
// the volume's last SUCCESSFUL cut's candidates, unchanged chunks and
|
||||
// payload (streaming, copy, upload) wall time, as its durable status
|
||||
// reports them (a failed attempt does not change them)
|
||||
LastCutCandidates int `json:"last_cut_candidate_chunks"`
|
||||
LastCutUnchanged int `json:"last_cut_unchanged_chunks"`
|
||||
LastCutPayloadMs float64 `json:"last_cut_payload_ms"`
|
||||
}
|
||||
|
||||
type headSzCut struct {
|
||||
Cut int `json:"cut"`
|
||||
Completed bool `json:"completed"`
|
||||
Attempts []headSzAttempt `json:"attempts"`
|
||||
ChangedBlocks int `json:"changed_blocks"`
|
||||
HeadBytes int `json:"head_bytes"`
|
||||
HeadSegments int `json:"head_segments"`
|
||||
CutTotalMs float64 `json:"cut_total_ms"`
|
||||
BarrierPauseMs float64 `json:"cut_barrier_pause_ms"`
|
||||
UploadedChunks int `json:"uploaded_chunks"`
|
||||
UploadedBytes int64 `json:"uploaded_bytes"`
|
||||
SnapshotMs float64 `json:"snapshot_command_ms"`
|
||||
}
|
||||
|
||||
type headSzSize struct {
|
||||
Size string `json:"size"`
|
||||
Bytes uint64 `json:"bytes"`
|
||||
Segments int `json:"segments"`
|
||||
Result string `json:"result"` // measured | refused_headroom | cut_not_completed
|
||||
Refusal string `json:"refusal,omitempty"`
|
||||
WriteMs float64 `json:"write_ms,omitempty"`
|
||||
// DirtyBeforeCut1 is the volume's DirtyChunks (its capture candidates)
|
||||
// from the durable status right before the first cut.
|
||||
DirtyBeforeCut1 int `json:"dirty_chunks_before_cut1"`
|
||||
Cuts []headSzCut `json:"cuts,omitempty"`
|
||||
HeadPerGiB float64 `json:"head_bytes_per_gib,omitempty"`
|
||||
}
|
||||
|
||||
type headSzReport struct {
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FilerStore string `json:"filer_store"`
|
||||
ChunkPath string `json:"chunk_path"`
|
||||
Sizes []headSzSize `json:"sizes"`
|
||||
}
|
||||
|
||||
func headSzParse(t *testing.T, s string) uint64 {
|
||||
t.Helper()
|
||||
s = strings.ToUpper(strings.TrimSpace(s))
|
||||
mul := map[byte]uint64{'G': 1 << 30, 'T': 1 << 40}[s[len(s)-1]]
|
||||
n, err := strconv.ParseUint(s[:len(s)-1], 10, 64)
|
||||
if mul == 0 || err != nil || n == 0 {
|
||||
t.Fatalf("HEADSZ_SIZES: %q is not <n>G or <n>T", s)
|
||||
}
|
||||
return n * mul
|
||||
}
|
||||
|
||||
// headSzAmbientFilerToml fails the test when weed could read a filer.toml
|
||||
// other than none: its working directory (the cluster dir) and the standard
|
||||
// configuration directories.
|
||||
func headSzAmbientFilerToml(t *testing.T, clusterDir string) {
|
||||
t.Helper()
|
||||
home, _ := os.UserHomeDir()
|
||||
for _, d := range []string{clusterDir, filepath.Join(home, ".seaweedfs"), "/usr/local/etc/seaweedfs", "/etc/seaweedfs"} {
|
||||
if _, err := os.Stat(filepath.Join(d, "filer.toml")); err == nil {
|
||||
t.Fatalf("a filer.toml in %s would replace the default filer store: remove it or run elsewhere", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeadSizeAgainstVolumeSize(t *testing.T) {
|
||||
if os.Getenv("HEADSZ_RUN") != "1" {
|
||||
t.Skip("HEADSZ_RUN=1 not set")
|
||||
}
|
||||
sizes := strings.Split(os.Getenv("HEADSZ_SIZES"), ",")
|
||||
if os.Getenv("HEADSZ_SIZES") == "" {
|
||||
sizes = []string{"10G", "100G", "1T"}
|
||||
}
|
||||
changeCuts := 3
|
||||
if v := os.Getenv("HEADSZ_CHANGE_CUTS"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 0 {
|
||||
t.Fatalf("HEADSZ_CHANGE_CUTS=%q", v)
|
||||
}
|
||||
changeCuts = n
|
||||
}
|
||||
cfg := headSzConfig{snapshotTimeout: "60s", attempts: 1}
|
||||
if v := os.Getenv("HEADSZ_SNAPSHOT_TIMEOUT"); v != "" {
|
||||
if _, err := time.ParseDuration(v); err != nil {
|
||||
t.Fatalf("HEADSZ_SNAPSHOT_TIMEOUT=%q: %v", v, err)
|
||||
}
|
||||
cfg.snapshotTimeout = v
|
||||
}
|
||||
if v := os.Getenv("HEADSZ_ATTEMPTS"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 {
|
||||
t.Fatalf("HEADSZ_ATTEMPTS=%q", v)
|
||||
}
|
||||
cfg.attempts = n
|
||||
}
|
||||
h := newPlannedHandoffHarness(t)
|
||||
clusterDir := filepath.Join(h.dir, "weed")
|
||||
if err := os.MkdirAll(clusterDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
headSzAmbientFilerToml(t, clusterDir)
|
||||
env := &handoffEnv{h: h, cluster: startWorkspaceWeedWith(t, clusterDir, w4WeedOpts{VolumeSizeLimitMB: 1024, VolumeMax: 64}),
|
||||
chunkPath: fmt.Sprintf("/headsz-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
|
||||
rep := &headSzReport{StartedAt: time.Now().UTC(), ChunkPath: env.chunkPath,
|
||||
FilerStore: "leveldb2 (weed filer default store), -defaultStoreDir=" + filepath.Join(clusterDir, "f") + ", no filer.toml"}
|
||||
defer func() {
|
||||
if p := os.Getenv("HEADSZ_REPORT"); p != "" {
|
||||
b, _ := json.MarshalIndent(rep, "", " ")
|
||||
if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil {
|
||||
t.Errorf("HEADSZ_REPORT: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// one cluster spec with every size's volume; one replica each on s1
|
||||
var vols strings.Builder
|
||||
for i, s := range sizes {
|
||||
b := headSzParse(t, s)
|
||||
id := "h" + strings.ToLower(strings.TrimSpace(s))
|
||||
env.hosts[id] = bvHost{id: id, server: "s1", replica: fmt.Sprintf("r%d", i+1), volume: id, root: filepath.Join(h.dir, "vol-"+id),
|
||||
data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)}
|
||||
fmt.Fprintf(&vols, " - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r%d\n", id, b, i+1)
|
||||
}
|
||||
spec := filepath.Join(h.dir, "cluster-spec.yaml")
|
||||
if err := os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mstate := filepath.Join(h.dir, "master")
|
||||
master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
|
||||
"--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath)
|
||||
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
|
||||
|
||||
for _, s := range sizes {
|
||||
rep.Sizes = append(rep.Sizes, headSzOne(t, env, cfg, s, changeCuts))
|
||||
}
|
||||
}
|
||||
|
||||
// headSzConfig: HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout
|
||||
// (the server caps it at its own operation deadline); HEADSZ_ATTEMPTS is how
|
||||
// many times one cut is tried before it is recorded as not completed.
|
||||
type headSzConfig struct {
|
||||
snapshotTimeout string
|
||||
attempts int
|
||||
}
|
||||
|
||||
// headSzOne measures one size; its blockvolume is stopped at the end.
|
||||
func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, changeCuts int) headSzSize {
|
||||
t.Helper()
|
||||
bytes := headSzParse(t, size)
|
||||
id := "h" + strings.ToLower(strings.TrimSpace(size))
|
||||
b := env.hosts[id]
|
||||
row := headSzSize{Size: strings.TrimSpace(size), Bytes: bytes, Segments: int((bytes + headSegmentBytes - 1) / headSegmentBytes)}
|
||||
env.volExtra = []string{"--durable-blocks", strconv.FormatUint(bytes/4096, 10), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
d := env.h.start(t, "blockvolume-"+id, env.h.volume, env.volArgsFor(b)...)
|
||||
primary := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica)
|
||||
end := time.Now().Add(120 * time.Second)
|
||||
for !d.has(primary) {
|
||||
select {
|
||||
case <-d.done:
|
||||
if l := d.line("bytes free"); l != "" {
|
||||
row.Result, row.Refusal = "refused_headroom", strings.TrimSpace(l)
|
||||
return row
|
||||
}
|
||||
t.Fatalf("blockvolume %s exited before it adopted its volume: %v", id, d.err)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
if time.Now().After(end) {
|
||||
t.Fatalf("blockvolume %s did not adopt its volume in 120 s", id)
|
||||
}
|
||||
}
|
||||
defer d.term(t, 60*time.Second)
|
||||
poll(t, 60*time.Second, id+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) })
|
||||
|
||||
c := dialNVMe(t, b.nvme, plannedHandoffNQN)
|
||||
write := func(lba uint64, tag string) {
|
||||
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
|
||||
c.write(t, lba, f1Block(id, 0, tag, lba))
|
||||
}
|
||||
start := time.Now()
|
||||
for seg := 0; seg < row.Segments; seg++ {
|
||||
write(uint64(seg)*headSegmentBytes/4096, "seg")
|
||||
}
|
||||
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
|
||||
c.flush(t)
|
||||
row.WriteMs = ms(time.Since(start))
|
||||
row.DirtyBeforeCut1 = headSzDirty(t, b)
|
||||
for cut := 1; cut <= 1+changeCuts; cut++ {
|
||||
changed := 0
|
||||
if cut > 1 {
|
||||
write(uint64(cut), fmt.Sprintf("change%d", cut))
|
||||
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
|
||||
c.flush(t)
|
||||
changed = 1
|
||||
}
|
||||
r := headSzCutOnce(t, env, cfg, b, cut, changed)
|
||||
row.Cuts = append(row.Cuts, r)
|
||||
if !r.Completed {
|
||||
row.Result = "cut_not_completed"
|
||||
return row
|
||||
}
|
||||
}
|
||||
row.Result = "measured"
|
||||
if row.Segments > 0 && len(row.Cuts) > 0 {
|
||||
row.HeadPerGiB = float64(row.Cuts[0].HeadBytes) / float64(row.Segments)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
// headSzCutOnce takes one snapshot, retried with the same request id up to
|
||||
// cfg.attempts times, and reads what it wrote: HEAD from the filer, the cut
|
||||
// from the volume's durable status. After every attempt it counts the
|
||||
// volume's chunk keys in the filer, so a retry shows whether the chunks an
|
||||
// earlier attempt uploaded are still there.
|
||||
func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cut, changed int) headSzCut {
|
||||
t.Helper()
|
||||
r := headSzCut{Cut: cut, ChangedBlocks: changed}
|
||||
start := time.Now()
|
||||
for a := 1; a <= cfg.attempts; a++ {
|
||||
as := time.Now()
|
||||
out, code := headSzRun(t, env, cfg.snapshotTimeout, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout,
|
||||
"--name", fmt.Sprintf("headsz-%d", cut), "--request-id", fmt.Sprintf("headsz-%s-%d", b.volume, cut))
|
||||
at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: headSzCountDir(t, env, env.chunkPath+"/"+b.volume+"/keys")}
|
||||
if code != 0 {
|
||||
var e struct{ Code, Message string }
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(out)), &e) == nil {
|
||||
at.Code, at.Message = e.Code, e.Message
|
||||
} else {
|
||||
at.Message = strings.TrimSpace(out)
|
||||
}
|
||||
}
|
||||
at.DirtyAfter = headSzDirty(t, b)
|
||||
at.ChunkStatusAfter = headSzChunkStatus(t, b)
|
||||
lc := headSzLastCut(t, b)
|
||||
at.LastCutTotalMs, at.LastCutChunks = float64(lc.TotalNs)/1e6, lc.UploadedChunks
|
||||
at.LastCutCandidates, at.LastCutUnchanged, at.LastCutPayloadMs = lc.CandidateChunks, lc.UnchangedChunks, float64(lc.PayloadNs)/1e6
|
||||
r.Attempts = append(r.Attempts, at)
|
||||
if code == 0 {
|
||||
r.Completed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
r.SnapshotMs = ms(time.Since(start))
|
||||
if !r.Completed {
|
||||
return r
|
||||
}
|
||||
var st struct {
|
||||
Volumes []struct {
|
||||
VolumeID string
|
||||
Chunk *struct {
|
||||
Stats struct {
|
||||
LastCut *struct {
|
||||
TotalNs, BarrierPauseNs int64
|
||||
UploadedChunks int
|
||||
UploadedBytes int64
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil {
|
||||
t.Fatalf("durable status of %s: %v", b.volume, err)
|
||||
}
|
||||
for _, s := range st.Volumes {
|
||||
if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil {
|
||||
l := s.Chunk.Stats.LastCut
|
||||
r.CutTotalMs, r.BarrierPauseMs = float64(l.TotalNs)/1e6, float64(l.BarrierPauseNs)/1e6
|
||||
r.UploadedChunks, r.UploadedBytes = l.UploadedChunks, l.UploadedBytes
|
||||
}
|
||||
}
|
||||
head := headSzGet(t, "http://"+env.cluster.filerHTTP+env.chunkPath+"/"+b.volume+"/HEAD", 256<<20)
|
||||
r.HeadBytes = len(head)
|
||||
var doc struct {
|
||||
Segments map[string]json.RawMessage `json:"segments"`
|
||||
}
|
||||
if err := json.Unmarshal(head, &doc); err != nil {
|
||||
t.Fatalf("HEAD of %s is not JSON (%d bytes): %v", b.volume, len(head), err)
|
||||
}
|
||||
r.HeadSegments = len(doc.Segments)
|
||||
return r
|
||||
}
|
||||
|
||||
// headSzLastCutStats is the part of the volume's last cut an attempt records.
|
||||
type headSzLastCutStats struct {
|
||||
TotalNs, PayloadNs int64
|
||||
UploadedChunks, CandidateChunks, UnchangedChunks int
|
||||
}
|
||||
|
||||
// headSzLastCut reads the volume's last cut from its durable status; zeros
|
||||
// when there is no last cut yet.
|
||||
func headSzLastCut(t *testing.T, b bvHost) headSzLastCutStats {
|
||||
t.Helper()
|
||||
var st struct {
|
||||
Volumes []struct {
|
||||
VolumeID string
|
||||
Chunk *struct {
|
||||
Stats struct {
|
||||
LastCut *headSzLastCutStats
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil {
|
||||
t.Fatalf("durable status of %s: %v", b.volume, err)
|
||||
}
|
||||
for _, s := range st.Volumes {
|
||||
if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil {
|
||||
return *s.Chunk.Stats.LastCut
|
||||
}
|
||||
}
|
||||
return headSzLastCutStats{}
|
||||
}
|
||||
|
||||
// headSzCountDir counts the entries of one filer directory by its JSON
|
||||
// listing; a directory that does not exist yet counts 0.
|
||||
func headSzCountDir(t *testing.T, env *handoffEnv, dir string) int {
|
||||
t.Helper()
|
||||
c := &http.Client{Timeout: 30 * time.Second}
|
||||
n, last := 0, ""
|
||||
for {
|
||||
req, _ := http.NewRequest(http.MethodGet, "http://"+env.cluster.filerHTTP+dir+"/?limit=1000&lastFileName="+url.QueryEscape(last), nil)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("filer list %s: %v", dir, err)
|
||||
}
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
resp.Body.Close()
|
||||
return n
|
||||
}
|
||||
var page struct {
|
||||
Entries []struct{ FullPath string }
|
||||
ShouldDisplayLoadMore bool
|
||||
LastFileName string
|
||||
}
|
||||
err = json.NewDecoder(resp.Body).Decode(&page)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("filer list %s: %v", dir, err)
|
||||
}
|
||||
n += len(page.Entries)
|
||||
if !page.ShouldDisplayLoadMore || page.LastFileName == "" {
|
||||
return n
|
||||
}
|
||||
last = page.LastFileName
|
||||
}
|
||||
}
|
||||
|
||||
// headSzRun runs sw-block with its own bound, the snapshot command's
|
||||
// --timeout plus a minute, so the server's operation deadline answers first
|
||||
// (the shared runner's fixed 150 s would kill a longer cut). A command that
|
||||
// still has to be killed returns exit code -1 and its output, a recorded
|
||||
// attempt, never a test failure.
|
||||
func headSzRun(t *testing.T, env *handoffEnv, timeout string, args ...string) (string, int) {
|
||||
t.Helper()
|
||||
d, err := time.ParseDuration(timeout)
|
||||
if err != nil {
|
||||
t.Fatalf("timeout %q: %v", timeout, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), d+time.Minute)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, env.h.cli, args...)
|
||||
cmd.Dir = env.h.dir
|
||||
cmd.WaitDelay = 5 * time.Second
|
||||
var stdout, stderr strings.Builder
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err = cmd.Run()
|
||||
env.h.logCommand(args, stdout.String(), stderr.String(), err)
|
||||
var exit *exec.ExitError
|
||||
switch {
|
||||
case err == nil:
|
||||
return stdout.String(), 0
|
||||
case errors.As(err, &exit) && ctx.Err() == nil:
|
||||
return stdout.String(), exit.ExitCode()
|
||||
case ctx.Err() != nil:
|
||||
return "killed after " + (d + time.Minute).String() + ": " + strings.TrimSpace(stdout.String()+" "+stderr.String()), -1
|
||||
}
|
||||
t.Fatalf("sw-block %q: %v\nstdout: %s\nstderr: %s", args, err, stdout.String(), stderr.String())
|
||||
return "", -1
|
||||
}
|
||||
|
||||
// headSzChunkStatus returns the volume's chunk section of its durable status
|
||||
// as served, unparsed; nil when there is none.
|
||||
func headSzChunkStatus(t *testing.T, b bvHost) json.RawMessage {
|
||||
t.Helper()
|
||||
var st struct {
|
||||
Volumes []struct {
|
||||
VolumeID string
|
||||
Chunk json.RawMessage
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil {
|
||||
t.Fatalf("durable status of %s: %v", b.volume, err)
|
||||
}
|
||||
for _, s := range st.Volumes {
|
||||
if s.VolumeID == b.volume && len(s.Chunk) > 0 && string(s.Chunk) != "null" {
|
||||
return s.Chunk
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// headSzDirty reads the volume's DirtyChunks (its capture candidates) from
|
||||
// its durable status; -1 when the status has no chunk section.
|
||||
func headSzDirty(t *testing.T, b bvHost) int {
|
||||
t.Helper()
|
||||
var st struct {
|
||||
Volumes []struct {
|
||||
VolumeID string
|
||||
Chunk *struct {
|
||||
Stats struct{ DirtyChunks int }
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil {
|
||||
t.Fatalf("durable status of %s: %v", b.volume, err)
|
||||
}
|
||||
for _, s := range st.Volumes {
|
||||
if s.VolumeID == b.volume && s.Chunk != nil {
|
||||
return s.Chunk.Stats.DirtyChunks
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func headSzGet(t *testing.T, u string, limit int64) []byte {
|
||||
t.Helper()
|
||||
c := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := c.Get(u)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", u, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, limit))
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GET %s: status %d err %v", u, resp.StatusCode, err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
@@ -737,7 +737,7 @@ func runVolume(f flags, exits *processExit) int {
|
||||
// between it and the record is the attach check's.
|
||||
if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.catalog != nil {
|
||||
readCtx, readCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
refusal := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize))
|
||||
refusal, code := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize))
|
||||
readCancel()
|
||||
if refusal != "" {
|
||||
fmt.Fprintln(os.Stderr, refusal)
|
||||
@@ -747,7 +747,7 @@ func runVolume(f flags, exits *processExit) int {
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return exitGeometryRefused
|
||||
return code
|
||||
}
|
||||
}
|
||||
var dp *durable.DurableProvider
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Phase 0 baseline: what blockmaster's loss costs the guests today, measured
|
||||
// with real binaries and an in-test NVMe/TCP initiator, so that phase 0
|
||||
// (mTLS on the master/holder link) can be gated against it. One write of 4
|
||||
// KiB every 10 ms per volume, each with a 30 s command deadline.
|
||||
//
|
||||
// (a) blockmaster SIGKILLed and restarted 5 s later under guest writes:
|
||||
// guest write errors (expected 0) and the write latency;
|
||||
// (b) blockmaster down 60 s: the time until each volume fences, then,
|
||||
// with the master back, until it serves again. The harness restarts
|
||||
// an exited blockvolume after the shipped RestartSec (5 s), as the unit
|
||||
// does, and counts the starts against the shipped start limit (10 in
|
||||
// 600 s);
|
||||
// (c) as (b) with 3 volumes.
|
||||
//
|
||||
// The numbers are logged as PHASE0 lines; only (a)'s zero write errors and
|
||||
// (b)/(c)'s serving again are asserted.
|
||||
|
||||
const (
|
||||
baselineEvery = 10 * time.Millisecond
|
||||
baselineDeadline = 30 * time.Second
|
||||
unitRestartSec = 5 * time.Second
|
||||
unitStartLimit = 10
|
||||
unitStartLimitSpan = 600 * time.Second
|
||||
)
|
||||
|
||||
type baselineWriter struct {
|
||||
mu sync.Mutex
|
||||
samples []f1Sample
|
||||
errAt time.Time
|
||||
err error
|
||||
stopped chan struct{}
|
||||
stopOnce sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// startBaselineWriter writes to vol's frontend until stopped or until the
|
||||
// first failed write (the fence, when the master is gone).
|
||||
func startBaselineWriter(t *testing.T, env *handoffEnv, key string) *baselineWriter {
|
||||
t.Helper()
|
||||
b := env.hosts[key]
|
||||
c := dialNVMe(t, b.nvme, plannedHandoffNQN)
|
||||
w := &baselineWriter{stopped: make(chan struct{}), done: make(chan struct{})}
|
||||
go func() {
|
||||
defer close(w.done)
|
||||
defer c.close()
|
||||
for n := uint64(0); ; n++ {
|
||||
select {
|
||||
case <-w.stopped:
|
||||
return
|
||||
case <-time.After(baselineEvery):
|
||||
}
|
||||
lba := n % 1024
|
||||
s := time.Now()
|
||||
_ = c.io.SetDeadline(s.Add(baselineDeadline))
|
||||
err := c.tryWrite(lba, f1Block(b.volume, 0, "phase0", lba))
|
||||
w.mu.Lock()
|
||||
w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)})
|
||||
if err != nil {
|
||||
w.err, w.errAt = err, time.Now()
|
||||
}
|
||||
w.mu.Unlock()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *baselineWriter) stop() {
|
||||
w.stopOnce.Do(func() { close(w.stopped) })
|
||||
<-w.done
|
||||
}
|
||||
|
||||
// maxLatency is the longest write that started in [from, to].
|
||||
func (w *baselineWriter) maxLatency(from, to time.Time) (time.Duration, int) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
var max time.Duration
|
||||
n := 0
|
||||
for _, s := range w.samples {
|
||||
if !s.start.Before(from) && !s.start.After(to) {
|
||||
n++
|
||||
if s.d > max {
|
||||
max = s.d
|
||||
}
|
||||
}
|
||||
}
|
||||
return max, n
|
||||
}
|
||||
|
||||
func TestPhase0BaselineMasterKilledAndRestartedUnderWrites(t *testing.T) {
|
||||
env, _ := f1StartEnv(t, f1Config{Volumes: 1})
|
||||
vols := f1StartSources(t, env, 1)
|
||||
w := startBaselineWriter(t, env, vols[0].id)
|
||||
time.Sleep(10 * time.Second)
|
||||
killAt := time.Now()
|
||||
env.masterProcess.kill(t)
|
||||
time.Sleep(5 * time.Second)
|
||||
env.masterProcess = env.h.start(t, "blockmaster-restarted", env.h.master, env.masterArgs...)
|
||||
env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
|
||||
backAt := time.Now()
|
||||
time.Sleep(30 * time.Second)
|
||||
w.stop()
|
||||
all, n := w.maxLatency(time.Time{}, time.Now())
|
||||
around, m := w.maxLatency(killAt, backAt.Add(5*time.Second))
|
||||
t.Logf("PHASE0 (a) master SIGKILL + restart after 5 s: writes %d, write errors %d (%v), max write latency %v, max in the kill window (%d writes) %v, master back after %v",
|
||||
n, map[bool]int{true: 1, false: 0}[w.err != nil], w.err, all.Round(time.Microsecond), m, around.Round(time.Microsecond), backAt.Sub(killAt).Round(time.Millisecond))
|
||||
if w.err != nil {
|
||||
t.Fatalf("phase 0 baseline (a): a guest write failed while the master was down 5 s: %v", w.err)
|
||||
}
|
||||
}
|
||||
|
||||
// unitEmulator restarts an exited blockvolume after unitRestartSec, as the
|
||||
// shipped unit does, and records every exit.
|
||||
type unitEmulator struct {
|
||||
mu sync.Mutex
|
||||
d *daemon
|
||||
starts []time.Time
|
||||
exits []string
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func emulateUnit(t *testing.T, env *handoffEnv, key string, d *daemon) *unitEmulator {
|
||||
u := &unitEmulator{d: d, starts: []time.Time{time.Now()}, stop: make(chan struct{}), done: make(chan struct{})}
|
||||
go func() {
|
||||
defer close(u.done)
|
||||
for {
|
||||
u.mu.Lock()
|
||||
cur := u.d
|
||||
u.mu.Unlock()
|
||||
select {
|
||||
case <-u.stop:
|
||||
return
|
||||
case <-cur.done:
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.exits = append(u.exits, fmt.Sprintf("%s exit %d", time.Now().Format("15:04:05.000"), exitCode(cur.err)))
|
||||
u.mu.Unlock()
|
||||
select {
|
||||
case <-u.stop:
|
||||
return
|
||||
case <-time.After(unitRestartSec):
|
||||
}
|
||||
next := env.h.start(t, fmt.Sprintf("blockvolume-%s-unit-%d", key, len(u.starts)), env.h.volume, env.volArgsFor(env.hosts[key])...)
|
||||
u.mu.Lock()
|
||||
u.d, u.starts = next, append(u.starts, time.Now())
|
||||
u.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
return u
|
||||
}
|
||||
|
||||
// startLimitHit reports whether the unit's starts would have exceeded the
|
||||
// shipped limit (more than unitStartLimit starts within unitStartLimitSpan).
|
||||
func (u *unitEmulator) startLimitHit() bool {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
for i := range u.starts {
|
||||
n := 0
|
||||
for _, s := range u.starts[i:] {
|
||||
if s.Sub(u.starts[i]) <= unitStartLimitSpan {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n > unitStartLimit {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func phase0MasterDown60s(t *testing.T, n int) {
|
||||
env, _ := f1StartEnv(t, f1Config{Volumes: n})
|
||||
vols := f1StartSources(t, env, n)
|
||||
writers := make([]*baselineWriter, n)
|
||||
units := make([]*unitEmulator, n)
|
||||
for i, v := range vols {
|
||||
writers[i] = startBaselineWriter(t, env, v.id)
|
||||
units[i] = emulateUnit(t, env, v.id, v.d)
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
killAt := time.Now()
|
||||
env.masterProcess.kill(t)
|
||||
time.Sleep(60 * time.Second)
|
||||
env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...)
|
||||
env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
|
||||
backAt := time.Now()
|
||||
for i, v := range vols {
|
||||
b := env.hosts[v.id]
|
||||
poll(t, 5*time.Minute, v.id+" never served again after the master came back", func() bool { return volumeFrontendReady(b.status, b.volume) })
|
||||
servedAt := time.Now()
|
||||
probe := startBaselineWriter(t, env, v.id)
|
||||
time.Sleep(time.Second)
|
||||
probe.stop()
|
||||
if probe.err != nil {
|
||||
t.Fatalf("%s serves again but a write failed: %v", v.id, probe.err)
|
||||
}
|
||||
writers[i].stop()
|
||||
close(units[i].stop)
|
||||
<-units[i].done
|
||||
w, u := writers[i], units[i]
|
||||
u.mu.Lock()
|
||||
starts, exits := len(u.starts), append([]string(nil), u.exits...)
|
||||
u.mu.Unlock()
|
||||
fence := "none"
|
||||
if w.err != nil {
|
||||
fence = w.errAt.Sub(killAt).Round(time.Millisecond).String()
|
||||
}
|
||||
firstExit := "none"
|
||||
if len(exits) > 0 {
|
||||
firstExit = exits[0]
|
||||
}
|
||||
t.Logf("PHASE0 (%s) master down 60 s, volume %s: first failed write after %s (%v); exits %v (first %s); starts %d, start limit (%d in %v) hit %v; serving again %v after the master came back",
|
||||
map[int]string{1: "b", 3: "c"}[n], v.id, fence, w.err, exits, firstExit, starts, unitStartLimit, unitStartLimitSpan, u.startLimitHit(), servedAt.Sub(backAt).Round(time.Millisecond))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhase0BaselineMasterDown60sOneVolume(t *testing.T) { phase0MasterDown60s(t, 1) }
|
||||
func TestPhase0BaselineMasterDown60sThreeVolumes(t *testing.T) { phase0MasterDown60s(t, 3) }
|
||||
@@ -235,10 +235,12 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) {
|
||||
spec := filepath.Join(h.dir, "cluster-spec.yaml")
|
||||
must(os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644))
|
||||
mstate := filepath.Join(h.dir, "master")
|
||||
master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
|
||||
env.masterArgs = []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
|
||||
"--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath)
|
||||
"--workspace-rpc", "--workspace-head-base-url", "http://" + env.cluster.filerHTTP + env.chunkPath}
|
||||
master := h.start(t, "blockmaster", h.master, env.masterArgs...)
|
||||
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
|
||||
env.masterProcess = master
|
||||
return env, master
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//go:build linux && subprocess && chunkstore_integration && systemd_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The operator guide's procedure for a first start during a long filer
|
||||
// outage, run as written under real systemd (root): the blockvolume unit,
|
||||
// with the shipped restart policy and a short start limit, starts while the
|
||||
// filer is down; each start fails at the startup filer check (exit 1, no
|
||||
// store) until systemd stops retrying (its start limit). The filer comes
|
||||
// back; `systemctl
|
||||
// reset-failed <unit>` and `systemctl start <unit>` then serve the volume.
|
||||
//
|
||||
// A runtime unit file (/run/systemd/system) stands for the installed unit:
|
||||
// a transient systemd-run unit would be removed by reset-failed.
|
||||
func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) {
|
||||
if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" {
|
||||
t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof")
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
t.Fatal("systemd qualification needs root")
|
||||
}
|
||||
env := startSourceWithSnapshot(t, "v2")
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
b := env.hosts["n-v2"]
|
||||
|
||||
shipped := gap1ShippedPolicy(t)
|
||||
unit := fmt.Sprintf("swb-c04-filer-outage-%d.service", os.Getpid())
|
||||
unitPath := filepath.Join("/run/systemd/system", unit)
|
||||
// Under systemd blockvolume refuses the test-only lock directory: the
|
||||
// unit uses the real one, as an installed unit does.
|
||||
quoted := []string{fmt.Sprintf("%q", env.h.volume)}
|
||||
args := env.volArgsFor(b)
|
||||
for i := 0; i < len(args); i++ {
|
||||
if args[i] == "--volume-lock-dir-test-only" {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
quoted = append(quoted, fmt.Sprintf("%q", args[i]))
|
||||
}
|
||||
// Create the lock directory and its parent only if missing, and remove
|
||||
// only what this test created (child first); nothing pre-existing is
|
||||
// touched.
|
||||
const lockDir = "/run/sw-block/locks"
|
||||
var created []string
|
||||
for _, dir := range []string{filepath.Dir(lockDir), lockDir} {
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
if err := os.Mkdir(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created = append(created, dir)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for i := len(created) - 1; i >= 0; i-- {
|
||||
_ = os.Remove(created[i])
|
||||
}
|
||||
})
|
||||
spec := strings.Join([]string{
|
||||
"[Unit]",
|
||||
"Description=sw-block test unit: first start during a filer outage",
|
||||
"StartLimitIntervalSec=600",
|
||||
"StartLimitBurst=2",
|
||||
"[Service]",
|
||||
"Type=exec",
|
||||
"ExecStart=" + strings.Join(quoted, " "),
|
||||
"Restart=on-failure",
|
||||
"RestartSec=" + shipped["RestartSec"],
|
||||
"RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"],
|
||||
"TimeoutStopSec=" + shipped["TimeoutStopSec"],
|
||||
"",
|
||||
}, "\n")
|
||||
systemctl := func(args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
|
||||
return string(out), err
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
gap1CleanupUnit(t, unit)
|
||||
_ = os.Remove(unitPath)
|
||||
_, _ = systemctl("daemon-reload")
|
||||
})
|
||||
if err := os.WriteFile(unitPath, []byte(spec), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := systemctl("daemon-reload"); err != nil {
|
||||
t.Fatalf("daemon-reload: %v %s", err, out)
|
||||
}
|
||||
|
||||
env.cluster.stopProc(t, "filer")
|
||||
if out, err := systemctl("start", "--no-block", unit); err != nil {
|
||||
t.Fatalf("start %s: %v %s", unit, err, out)
|
||||
}
|
||||
// systemd gives up when the start limit is hit: the unit stays failed
|
||||
// after StartLimitBurst restarts, and the journal says "Start request
|
||||
// repeated too quickly" (systemd 249 keeps Result=exit-code).
|
||||
var state map[string]string
|
||||
poll(t, 8*time.Minute, unit+" never stopped retrying with the filer down", func() bool {
|
||||
s, err := gap1ReadUnit(unit)
|
||||
state = s
|
||||
return err == nil && s["ActiveState"] == "failed" && s["NRestarts"] == "2"
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput()
|
||||
cancel()
|
||||
entries, _ := os.ReadDir(b.root)
|
||||
t.Logf("filer down: %s gave up: Result %s, NRestarts %s, ExecMainStatus %s, ActiveState %s; files under --durable-root %d",
|
||||
unit, state["Result"], state["NRestarts"], state["ExecMainStatus"], state["ActiveState"], len(entries))
|
||||
if !strings.Contains(string(journal), "Start request repeated too quickly") || state["ExecMainStatus"] != "1" {
|
||||
t.Fatalf("the unit did not stop on its start limit after failing at the startup filer check (status %s):\n%s", state["ExecMainStatus"], journal)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("the failed starts created %d files under --durable-root", len(entries))
|
||||
}
|
||||
|
||||
env.cluster.restartProc(t, "filer")
|
||||
w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second)
|
||||
// The guide, as written: reset-failed, then start.
|
||||
if out, err := systemctl("reset-failed", unit); err != nil {
|
||||
t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out)
|
||||
}
|
||||
if out, err := systemctl("start", unit); err != nil {
|
||||
t.Fatalf("systemctl start %s: %v %s", unit, err, out)
|
||||
}
|
||||
poll(t, 2*time.Minute, "v2 never served after reset-failed and start", func() bool {
|
||||
return volumeFrontendReady(b.status, "v2")
|
||||
})
|
||||
head := env.headOf(t, "v2")
|
||||
if strings.Contains(head, `"holder":""`) {
|
||||
t.Fatalf("v2 serves but its HEAD is not claimed: %s", head)
|
||||
}
|
||||
t.Logf("after reset-failed + start: v2 serves; HEAD %s", head)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//go:build linux && subprocess && chunkstore_integration && systemd_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A long blockmaster outage under real systemd (root), with the shipped
|
||||
// unit's restart policy AND its shipped start limit: a serving volume's
|
||||
// blockvolume fences, exits 75 and is restarted by the unit; each start
|
||||
// waits for a grant and exits 75 again. The test keeps the master down until
|
||||
// systemd stops retrying (the start limit) or 12 minutes pass, records when
|
||||
// and after how many restarts, then brings the master back and records
|
||||
// whether the volume serves by itself, and, if the unit failed, how long
|
||||
// `systemctl reset-failed` + `systemctl start` take to serve it.
|
||||
//
|
||||
// A runtime unit file (/run/systemd/system) stands for the installed unit.
|
||||
func TestSystemdMasterOutagePastTheStartLimit(t *testing.T) {
|
||||
if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" {
|
||||
t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof")
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
t.Fatal("systemd qualification needs root")
|
||||
}
|
||||
shipped := gap1ShippedPolicy(t)
|
||||
interval, burst := shippedStartLimit(t)
|
||||
|
||||
env := startHandoffEnv(t, 1)
|
||||
b := env.hosts["s1"]
|
||||
unit := fmt.Sprintf("swb-c04-master-outage-%d.service", os.Getpid())
|
||||
writeRuntimeUnit(t, unit, env.h.volume, env.volArgsFor(b), []string{
|
||||
"StartLimitIntervalSec=" + interval,
|
||||
"StartLimitBurst=" + burst,
|
||||
}, []string{
|
||||
"Restart=on-failure",
|
||||
"RestartSec=" + shipped["RestartSec"],
|
||||
"RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"],
|
||||
"TimeoutStopSec=" + shipped["TimeoutStopSec"],
|
||||
})
|
||||
if out, err := runSystemctl("start", unit); err != nil {
|
||||
t.Fatalf("start %s: %v %s", unit, err, out)
|
||||
}
|
||||
poll(t, 2*time.Minute, "v1 never served under the unit", func() bool { return volumeFrontendReady(b.status, "v1") })
|
||||
|
||||
killAt := time.Now()
|
||||
env.masterProcess.kill(t)
|
||||
var state map[string]string
|
||||
gaveUp := false
|
||||
for deadline := killAt.Add(12 * time.Minute); time.Now().Before(deadline); time.Sleep(2 * time.Second) {
|
||||
s, err := gap1ReadUnit(unit)
|
||||
if err == nil {
|
||||
state = s
|
||||
if s["ActiveState"] == "failed" {
|
||||
gaveUp = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
downFor := time.Since(killAt)
|
||||
journal := unitJournal(unit)
|
||||
t.Logf("PHASE0-SYSTEMD master down %v: unit gave up (start limit %s in %s) %v; NRestarts %s; ActiveState %s; Result %s; 'Start request repeated too quickly' %v",
|
||||
downFor.Round(time.Second), burst, interval, gaveUp, state["NRestarts"], state["ActiveState"], state["Result"], strings.Contains(journal, "Start request repeated too quickly"))
|
||||
|
||||
env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...)
|
||||
env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
|
||||
backAt := time.Now()
|
||||
served := false
|
||||
for deadline := backAt.Add(90 * time.Second); time.Now().Before(deadline) && !served; time.Sleep(time.Second) {
|
||||
served = volumeFrontendReady(b.status, "v1")
|
||||
}
|
||||
if served {
|
||||
t.Logf("PHASE0-SYSTEMD with the master back, v1 served by itself after %v", time.Since(backAt).Round(time.Millisecond))
|
||||
return
|
||||
}
|
||||
t.Logf("PHASE0-SYSTEMD with the master back, v1 did not serve by itself within 90 s (unit %s)", state["ActiveState"])
|
||||
if out, err := runSystemctl("reset-failed", unit); err != nil {
|
||||
t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out)
|
||||
}
|
||||
resetAt := time.Now()
|
||||
if out, err := runSystemctl("start", unit); err != nil {
|
||||
t.Fatalf("systemctl start %s: %v %s", unit, err, out)
|
||||
}
|
||||
poll(t, 3*time.Minute, "v1 never served after reset-failed and start", func() bool { return volumeFrontendReady(b.status, "v1") })
|
||||
t.Logf("PHASE0-SYSTEMD after reset-failed + start, v1 served after %v", time.Since(resetAt).Round(time.Millisecond))
|
||||
}
|
||||
|
||||
// shippedStartLimit reads StartLimitIntervalSec and StartLimitBurst from the
|
||||
// shipped sw-blockvolume.service.
|
||||
func shippedStartLimit(t *testing.T) (interval, burst string) {
|
||||
t.Helper()
|
||||
f, err := os.Open(filepath.Join("..", "..", "deploy", "systemd", "sw-blockvolume.service"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if v, ok := strings.CutPrefix(line, "StartLimitIntervalSec="); ok {
|
||||
interval = v
|
||||
}
|
||||
if v, ok := strings.CutPrefix(line, "StartLimitBurst="); ok {
|
||||
burst = v
|
||||
}
|
||||
}
|
||||
if _, err := strconv.Atoi(burst); err != nil || interval == "" {
|
||||
t.Fatalf("shipped unit start limit unreadable: interval %q burst %q", interval, burst)
|
||||
}
|
||||
return interval, burst
|
||||
}
|
||||
|
||||
// writeRuntimeUnit installs a runtime unit (removed, with daemon-reload,
|
||||
// when the test ends) that runs exe with args, minus the test-only lock
|
||||
// directory: under systemd blockvolume uses the real one, which is created
|
||||
// for the test when missing and removed only if this test created it.
|
||||
func writeRuntimeUnit(t *testing.T, unit, exe string, args, unitSection, serviceSection []string) {
|
||||
t.Helper()
|
||||
quoted := []string{fmt.Sprintf("%q", exe)}
|
||||
for i := 0; i < len(args); i++ {
|
||||
if args[i] == "--volume-lock-dir-test-only" {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
quoted = append(quoted, fmt.Sprintf("%q", args[i]))
|
||||
}
|
||||
const lockDir = "/run/sw-block/locks"
|
||||
var created []string
|
||||
for _, dir := range []string{filepath.Dir(lockDir), lockDir} {
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
if err := os.Mkdir(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created = append(created, dir)
|
||||
}
|
||||
}
|
||||
path := filepath.Join("/run/systemd/system", unit)
|
||||
t.Cleanup(func() {
|
||||
gap1CleanupUnit(t, unit)
|
||||
_ = os.Remove(path)
|
||||
_, _ = runSystemctl("daemon-reload")
|
||||
for i := len(created) - 1; i >= 0; i-- {
|
||||
_ = os.Remove(created[i])
|
||||
}
|
||||
})
|
||||
lines := append([]string{"[Unit]", "Description=sw-block test unit"}, unitSection...)
|
||||
lines = append(lines, "[Service]", "Type=exec", "ExecStart="+strings.Join(quoted, " "))
|
||||
lines = append(lines, serviceSection...)
|
||||
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := runSystemctl("daemon-reload"); err != nil {
|
||||
t.Fatalf("daemon-reload: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func runSystemctl(args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
|
||||
return string(out), err
|
||||
}
|
||||
|
||||
func unitJournal(unit string) string {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
out, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput()
|
||||
return string(out)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//go:build subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestProcedureRetireTemplateSource runs the template-holder procedure:
|
||||
// fork the seed, publish the template on the holder, fork a consumer, then
|
||||
// seal/revoke/ACK and delete the original source. No GC grace is advanced;
|
||||
// the final ordinary pass proves its command and reads, not reclamation.
|
||||
func TestProcedureRetireTemplateSource(t *testing.T) {
|
||||
env := startHandoffEnvWith(t, 1, []string{"template-holder", "consumer"})
|
||||
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
source := env.start(t, "blockvolume-source", "s1")
|
||||
e := env.adopt(t, source, "s1")
|
||||
const template = "template-holder"
|
||||
want := map[uint64][]byte{5: pattern("template-seed!!!")}
|
||||
env.writeBlock(t, "s1", 5, want[5])
|
||||
env.snapshot(t, "s1", "v1", "seed")
|
||||
for _, step := range []struct{ source, snapshot, target string }{
|
||||
{"v1", "seed", template}, {template, "template-v1", "consumer"},
|
||||
} {
|
||||
env.h.command(t, "ops", "chunk", "fork", "--source", step.source, "--snapshot", step.snapshot,
|
||||
"--target", step.target, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
|
||||
"--request-id", "fork-"+step.target)
|
||||
env.startTarget(t, step.target, "blockvolume-"+step.target)
|
||||
env.requireBlocks(t, "n-"+step.target, 0, 16, want)
|
||||
env.requireEdges(t, "n-"+step.target)
|
||||
if step.target == template {
|
||||
env.snapshot(t, "n-"+template, template, "template-v1")
|
||||
}
|
||||
}
|
||||
g := env.seal(t, "s1", e)
|
||||
env.revoke(t, e, g)
|
||||
// The process must ACK and exit naturally; a signal would skip the ACK.
|
||||
if err := source.wait(30 * time.Second); err != nil {
|
||||
t.Fatalf("source did not exit naturally after revocation: %v", err)
|
||||
}
|
||||
env.waitAck(t, e, g)
|
||||
env.deleteSnapshot(t, "v1", "seed")
|
||||
out, stderr, code := env.volumeDelete(t, "delete-template-source")
|
||||
requireDeleteCompleted(t, out, stderr, code, false)
|
||||
env.requireDeletedForGood(t, "delete-template-source")
|
||||
check := func() {
|
||||
for _, vol := range []string{template, "consumer"} {
|
||||
env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", "--timeout", "2m",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
|
||||
env.requireBlocks(t, "n-"+vol, 0, 16, want)
|
||||
env.requireEdges(t, "n-"+vol)
|
||||
}
|
||||
env.requireSnapshotNames(t, template, "template-v1")
|
||||
}
|
||||
check()
|
||||
env.h.command(t, "ops", "chunk", "gc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
|
||||
"--master", env.h.masterAddr, "--apply")
|
||||
check()
|
||||
t.Logf("template source retired; %s/template-v1 and consumer read unchanged after a default-grace GC pass", template)
|
||||
}
|
||||
@@ -70,6 +70,17 @@ func startWorkspaceWeed(t *testing.T) *w4WeedCluster {
|
||||
// A caller-owned root lets process qualification retain its filer evidence
|
||||
// when external-service cleanup is uncertain. Existing tests keep TempDir.
|
||||
func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster {
|
||||
t.Helper()
|
||||
return startWorkspaceWeedWith(t, dir, w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32})
|
||||
}
|
||||
|
||||
// w4WeedOpts sizes the weed volume server: VolumeMax volumes of
|
||||
// VolumeSizeLimitMB each (the default holds about 8 GiB of chunks).
|
||||
type w4WeedOpts struct {
|
||||
VolumeSizeLimitMB, VolumeMax int
|
||||
}
|
||||
|
||||
func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedCluster {
|
||||
t.Helper()
|
||||
weed := os.Getenv("CHUNKSTORE_WEED")
|
||||
if weed == "" {
|
||||
@@ -110,9 +121,9 @@ func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000")
|
||||
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.VolumeSizeLimitMB), "-defaultReplication=000")
|
||||
w4WaitTCP(t, c.master, 20*time.Second)
|
||||
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32")
|
||||
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax))
|
||||
run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f"))
|
||||
w4WaitTCP(t, c.filerGRPC, 30*time.Second)
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"path"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestForkGrandchildReadsEveryBlockWithoutAncestorImages(t *testing.T) {
|
||||
f, b, c, source := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "seed", RequestID: "seed"}, source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "seed", Target: "v2", RequestID: "parent"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parent, err := NewChunkRemote(f, b, catBase+"/v2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ph, err := parent.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "template", RequestID: "template"}, ph); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v2", Snapshot: "template", Target: "v3", RequestID: "grandchild"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Remove only ancestor image metadata, preserving immutable object bindings.
|
||||
for vol, name := range map[string]string{"v1": "seed", "v2": "template"} {
|
||||
attempt := snapPath(t, f, vol, name)
|
||||
for _, entry := range []string{attempt, path.Join(catBase, vol, snapNamesDir, name), path.Join(catBase, vol, headName)} {
|
||||
if err := f.DeleteEntry(ctx, path.Dir(entry), path.Base(entry), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, path.Dir(entry), path.Base(entry)); err == nil {
|
||||
t.Fatalf("ancestor image metadata remains: %s", entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Open a fresh reader: no cached parent HEAD or snapshot can supply data.
|
||||
grandchild, err := NewChunkRemote(f, b, catBase+"/v3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := grandchild.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(h.Chunks) != 2 {
|
||||
t.Fatalf("grandchild lost its complete image: %d chunks", len(h.Chunks))
|
||||
}
|
||||
for block := uint64(0); block < uint64(catGeo.NumBlocks); block++ {
|
||||
got := make([]byte, catGeo.BlockSize)
|
||||
if ref, ok := h.Chunks[block/uint64(catGeo.ChunkBlocks)]; ok {
|
||||
data, err := grandchild.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
t.Fatalf("block %d: %v", block, err)
|
||||
}
|
||||
off := (block % uint64(catGeo.ChunkBlocks)) * uint64(catGeo.BlockSize)
|
||||
copy(got, data[off:off+uint64(catGeo.BlockSize)])
|
||||
}
|
||||
var fill byte
|
||||
switch block / uint64(catGeo.ChunkBlocks) {
|
||||
case 0:
|
||||
fill = 0x10
|
||||
case 3:
|
||||
fill = 0x13
|
||||
}
|
||||
if !bytes.Equal(got, bytes.Repeat([]byte{fill}, int(catGeo.BlockSize))) {
|
||||
t.Fatalf("block %d differs after ancestor images were removed", block)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package durable_test
|
||||
|
||||
// The first cut of a volume. A fresh local store (its first attach not yet
|
||||
// committed) knows every chunk its claimed HEAD does not name is zero on both
|
||||
// sides, so its first cut scans only the chunks written since; a
|
||||
// store that is not fresh (one an earlier release created, or any store
|
||||
// after its first attach commit) keeps its chunks' state as persisted. Chunks
|
||||
// HEAD names stay absent and are hydrated from HEAD.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// fcutChunks is chunkProvider's chunk count: pcBlocks blocks of pcChunkBlocks.
|
||||
const fcutChunks = pcBlocks / pcChunkBlocks
|
||||
|
||||
func fcutProvider(t *testing.T, root string, remote storage.ChunkRemote) *durable.DurableProvider {
|
||||
return chunkProvider(t, root, remote, v1View(), 0)
|
||||
}
|
||||
|
||||
// fcutCheckpointedPast waits until the store's checkpoint has moved past
|
||||
// from, so a write made after from has left the WAL's dirty map.
|
||||
func fcutCheckpointedPast(t *testing.T, st storage.LogicalStorage, from uint64) {
|
||||
t.Helper()
|
||||
ws := st.(*storage.WALStore)
|
||||
waitFor(t, 10*time.Second, "the WAL checkpoint past the write", func() bool { return ws.CheckpointLSN() > from })
|
||||
}
|
||||
|
||||
// fcutStats returns v1's chunk-layer counters.
|
||||
func fcutStats(t *testing.T, p *durable.DurableProvider) storage.ChunkLayerStats {
|
||||
t.Helper()
|
||||
for _, st := range p.DurableStatuses() {
|
||||
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached {
|
||||
return st.Chunk.Stats
|
||||
}
|
||||
}
|
||||
t.Fatal("v1 has no attached chunk layer")
|
||||
return storage.ChunkLayerStats{}
|
||||
}
|
||||
|
||||
func fcutOpen(t *testing.T, ctx context.Context, p *durable.DurableProvider) storage.LogicalStorage {
|
||||
t.Helper()
|
||||
st, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func fcutWrite(t *testing.T, ctx context.Context, p *durable.DurableProvider, lba int, fill byte) []byte {
|
||||
t.Helper()
|
||||
data := bytes.Repeat([]byte{fill}, 4096)
|
||||
b := p.Backend("v1")
|
||||
if n, err := b.Write(ctx, int64(lba)*4096, data); err != nil || n != len(data) {
|
||||
t.Fatalf("write lba %d: %d %v", lba, n, err)
|
||||
}
|
||||
if err := b.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// fcutHeadBlock reads block lba from the published HEAD (zero if its chunk
|
||||
// is not named).
|
||||
func fcutHeadBlock(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, lba int) []byte {
|
||||
t.Helper()
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, ok := head.Chunks[uint64(lba/pcChunkBlocks)]
|
||||
if !ok {
|
||||
return make([]byte, 4096)
|
||||
}
|
||||
c, err := remote.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
off := (lba % pcChunkBlocks) * 4096
|
||||
return c[off : off+4096]
|
||||
}
|
||||
|
||||
// TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks: a store created
|
||||
// empty against a HEAD never claimed, with two chunks written (one of them
|
||||
// already checkpointed out of the WAL), has two first-cut candidates, and
|
||||
// its first cut publishes both. Today every chunk of the volume is a
|
||||
// candidate (all 16 start Unknown).
|
||||
func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := fcutProvider(t, t.TempDir(), remote)
|
||||
st := fcutOpen(t, ctx, p)
|
||||
cp0 := st.(*storage.WALStore).CheckpointLSN()
|
||||
a := fcutWrite(t, ctx, p, pcChunkBlocks*1+1, 0x31) // chunk 1, checkpointed below
|
||||
fcutCheckpointedPast(t, st, cp0)
|
||||
b := fcutWrite(t, ctx, p, pcChunkBlocks*9+3, 0x39) // chunk 9, still in the WAL
|
||||
if got := fcutStats(t, p).DirtyChunks; got != 2 {
|
||||
t.Errorf("before the first cut: %d candidate chunks; want 2 (the written ones), not all %d", got, fcutChunks)
|
||||
}
|
||||
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := fcutStats(t, p).LastCut.CandidateChunks; got != 2 {
|
||||
t.Errorf("first cut: %d candidate chunks; want 2", got)
|
||||
}
|
||||
if !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*1+1), a) || !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*9+3), b) {
|
||||
t.Fatal("the first cut did not publish both written blocks")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks: a store created
|
||||
// empty against a HEAD another store already claimed (no data published) is
|
||||
// fresh too: every chunk that HEAD does not name starts equal to it (both
|
||||
// zero), so the first cut has no candidates. General form of the rule: the
|
||||
// premise is the store's fresh marker, not the HEAD's history.
|
||||
func TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
first := fcutProvider(t, t.TempDir(), remote)
|
||||
fcutOpen(t, ctx, first)
|
||||
if err := first.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if head, err := remote.GetHead(ctx); err != nil || head.Gen == 0 || len(head.Chunks) != 0 {
|
||||
t.Fatalf("setup: HEAD %+v %v; want a claimed HEAD naming no chunk", head, err)
|
||||
}
|
||||
p := fcutProvider(t, t.TempDir(), remote)
|
||||
fcutOpen(t, ctx, p)
|
||||
if got := fcutStats(t, p).DirtyChunks; got != 0 {
|
||||
t.Fatalf("fresh store against a claimed HEAD naming nothing: %d candidate chunks; want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstCutOfARestoreTargetKeepsItsHydrationPath: a fresh store against a
|
||||
// HEAD that names chunks keeps those chunks absent (hydrated from HEAD; a
|
||||
// read returns HEAD's data, never zeros) and starts every other chunk equal
|
||||
// to HEAD (zero), so its first cut has no candidates.
|
||||
func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
first := fcutProvider(t, t.TempDir(), remote)
|
||||
fcutOpen(t, ctx, first)
|
||||
a := fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33)
|
||||
b := fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37)
|
||||
if _, err := first.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := first.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := fcutProvider(t, t.TempDir(), remote)
|
||||
fcutOpen(t, ctx, p)
|
||||
if s := fcutStats(t, p); s.AbsentChunks != 2 || s.DirtyChunks != 0 {
|
||||
t.Fatalf("restore target: %d absent, %d candidate chunks; want 2 absent and 0 candidates", s.AbsentChunks, s.DirtyChunks)
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
for lba, want := range map[int][]byte{pcChunkBlocks * 3: a, pcChunkBlocks * 7: b} {
|
||||
if n, err := p.Backend("v1").Read(ctx, int64(lba)*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) {
|
||||
t.Fatalf("restore target read of HEAD-named block %d: %d %v, data equal %v; want HEAD's data, not zeros", lba, n, err, bytes.Equal(got, want))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestExplicitWALStoreRefusesAFreshChunkRoot: a root carrying chunk metadata
|
||||
// (here the fresh marker of a store that never attached) is refused by an
|
||||
// explicitly configured plain walstore as by auto, so no write can reach a
|
||||
// store whose marker says none ever did.
|
||||
func TestExplicitWALStoreRefusesAFreshChunkRoot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
p := fcutProvider(t, root, storage.NewMemChunkRemote())
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = plain.Close() })
|
||||
if _, err := plain.EnsureStorage("v1"); !errors.Is(err, durable.ErrImplKindMismatch) {
|
||||
t.Fatalf("explicit walstore on a fresh chunk root: %v; want ErrImplKindMismatch", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func hydrationProgress(t *testing.T, p *DurableProvider) (absent int, hydrated uint64) {
|
||||
t.Helper()
|
||||
for _, st := range p.DurableStatuses() {
|
||||
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached {
|
||||
return st.Chunk.Stats.AbsentChunks, st.Chunk.Stats.Hydration.Completed
|
||||
}
|
||||
}
|
||||
t.Fatal("v1 has no attached chunk layer")
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
// INV-CUT-HYDRATION-PROGRESS-001: the status reports, per volume, the
|
||||
// chunks still to hydrate (AbsentChunks: HEAD-named, not yet local) and the
|
||||
// chunks hydrated so far (Hydration.Completed, cumulative). A read of an
|
||||
// un-hydrated chunk moves both by one; a second read of it moves neither. A
|
||||
// caller can therefore prove that a read happened before its chunk was
|
||||
// hydrated by reading the two before and after it.
|
||||
func TestHydrationProgressCountersFollowFirstReads(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
mem := storage.NewMemChunkRemote()
|
||||
src := kzProvider(t, t.TempDir(), mem)
|
||||
if _, err := src.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := src.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := map[int64][]byte{3: bytes.Repeat([]byte{0x33}, 4096), 7: bytes.Repeat([]byte{0x77}, 4096)}
|
||||
for chunk, b := range data {
|
||||
if _, err := src.Backend("v1").Write(ctx, chunk*16*4096, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := src.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := src.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := src.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := kzProvider(t, t.TempDir(), mem)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []struct {
|
||||
read int64 // chunk read before the check (-1: none)
|
||||
absent int
|
||||
hydrated uint64
|
||||
}{{-1, 2, 0}, {3, 1, 1}, {3, 1, 1}, {7, 0, 2}}
|
||||
got := make([]byte, 4096)
|
||||
for _, w := range want {
|
||||
if w.read >= 0 {
|
||||
if n, err := p.Backend("v1").Read(ctx, w.read*16*4096, got); err != nil || n != len(got) || !bytes.Equal(got, data[w.read]) {
|
||||
t.Fatalf("read of chunk %d: %d %v, data equal %v", w.read, n, err, bytes.Equal(got, data[w.read]))
|
||||
}
|
||||
}
|
||||
if absent, hydrated := hydrationProgress(t, p); absent != w.absent || hydrated != w.hydrated {
|
||||
t.Fatalf("after reading chunk %d: %d still to hydrate, %d hydrated; want %d, %d", w.read, absent, hydrated, w.absent, w.hydrated)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// kzProvider is a walstore-chunk provider for v1 (256 blocks, 16 per
|
||||
// chunk: 16 chunks) over root and remote.
|
||||
func kzProvider(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider {
|
||||
t.Helper()
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
|
||||
p, err := NewDurableProvider(ProviderConfig{
|
||||
Impl: ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, precopyQueueView{id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p
|
||||
}
|
||||
|
||||
func kzCandidates(t *testing.T, p *DurableProvider) int {
|
||||
t.Helper()
|
||||
for _, st := range p.DurableStatuses() {
|
||||
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached {
|
||||
return st.Chunk.Stats.DirtyChunks
|
||||
}
|
||||
}
|
||||
t.Fatal("v1 has no attached chunk layer")
|
||||
return -1
|
||||
}
|
||||
|
||||
// The premise of RULE-FRESH-KNOWN-ZERO: until the attach commit retires the
|
||||
// fresh marker, no write reaches the store. Held at that boundary (after the
|
||||
// claim and the certification, before the commit), a frontend write is not
|
||||
// admitted (it may wait; here it is bounded) and appends no WAL record. After
|
||||
// the commit the store has no candidates: nothing was written.
|
||||
func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
p := kzProvider(t, t.TempDir(), storage.NewMemChunkRemote())
|
||||
st, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws := st.(*storage.WALStore)
|
||||
var writeErr error
|
||||
var nextAtBoundary uint64
|
||||
held := false
|
||||
p.testBeforeChunkFreshRetire = func() error {
|
||||
held = true
|
||||
wctx, wcancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer wcancel()
|
||||
_, writeErr = p.Backend("v1").Write(wctx, 0, bytes.Repeat([]byte{0x5a}, 4096))
|
||||
nextAtBoundary = ws.NextLSN()
|
||||
return nil
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.testBeforeChunkFreshRetire = nil
|
||||
if !held {
|
||||
t.Fatal("the attach did not reach its commit boundary")
|
||||
}
|
||||
if writeErr == nil || nextAtBoundary != 1 {
|
||||
t.Fatalf("at the commit boundary a frontend write returned %v and the WAL's next LSN was %d; want refused, 1", writeErr, nextAtBoundary)
|
||||
}
|
||||
if got := kzCandidates(t, p); got != 0 {
|
||||
t.Fatalf("after the commit: %d candidate chunks; want 0 (nothing was written)", got)
|
||||
}
|
||||
for _, st := range p.DurableStatuses() {
|
||||
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Stats.KnownZeroChunks != 16 {
|
||||
t.Fatalf("status KnownZeroChunks %d; want 16", st.Chunk.Stats.KnownZeroChunks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RULE-FRESH-KNOWN-ZERO needs THIS start's create: a first start that
|
||||
// crashes before its attach commit leaves the fresh marker, but the next
|
||||
// start did not create the store, so it certifies nothing (one scan: every
|
||||
// chunk a candidate), and its next cut still publishes a write.
|
||||
func TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
root, remote := t.TempDir(), storage.NewMemChunkRemote()
|
||||
p := kzProvider(t, root, remote)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crash := errors.New("crash before the attach commit")
|
||||
p.testBeforeChunkFreshRetire = func() error { return crash }
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, crash) {
|
||||
t.Fatalf("first start: %v; want the injected crash", err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil {
|
||||
t.Fatalf("fresh marker after the crash: %v; want it kept", err)
|
||||
}
|
||||
p2 := kzProvider(t, root, remote)
|
||||
if _, err := p2.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := kzCandidates(t, p2); got != 16 {
|
||||
t.Fatalf("second start: %d candidate chunks; want all 16 (it did not create the store)", got)
|
||||
}
|
||||
kzWriteAndPublish(t, ctx, p2, remote)
|
||||
}
|
||||
|
||||
// The same after a restart between the create and any attach (test #13).
|
||||
func TestFreshKnownZeroNotAfterARestartBeforeAnyAttach(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
root, remote := t.TempDir(), storage.NewMemChunkRemote()
|
||||
p := kzProvider(t, root, remote)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p2 := kzProvider(t, root, remote)
|
||||
if _, err := p2.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := kzCandidates(t, p2); got != 16 {
|
||||
t.Fatalf("restart before any attach: %d candidate chunks; want all 16", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The order: the attach commit retires the marker, THEN the marking is made
|
||||
// durable, THEN the volume serves. A crash between the first two leaves no
|
||||
// marker and every chunk UNKNOWN: the next start scans every chunk once, and
|
||||
// is correct. (Marking before the retirement would leave certified chunks
|
||||
// behind a marker a later start could trust.)
|
||||
func TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
root, remote := t.TempDir(), storage.NewMemChunkRemote()
|
||||
p := kzProvider(t, root, remote)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crash := errors.New("crash after the marker retirement, before the marking")
|
||||
p.testAfterChunkFreshRetire = func() error { return crash }
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, crash) {
|
||||
t.Fatalf("first start: %v; want the injected crash", err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) {
|
||||
t.Fatalf("fresh marker after the crash: %v; want it retired", err)
|
||||
}
|
||||
p2 := kzProvider(t, root, remote)
|
||||
if _, err := p2.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := kzCandidates(t, p2); got != 16 {
|
||||
t.Fatalf("restart after a crash between marker retirement and marking: %d candidate chunks; want all 16 (one scan)", got)
|
||||
}
|
||||
kzWriteAndPublish(t, ctx, p2, remote)
|
||||
}
|
||||
|
||||
// kzWriteAndPublish writes chunk 5, cuts, and checks HEAD publishes it.
|
||||
func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, remote *storage.MemChunkRemote) {
|
||||
t.Helper()
|
||||
want := bytes.Repeat([]byte{0x6b}, 4096)
|
||||
if _, err := p.Backend("v1").Write(ctx, 5*16*4096, want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, ok := head.Chunks[5]
|
||||
if !ok {
|
||||
t.Fatal("the cut did not publish chunk 5")
|
||||
}
|
||||
chunk, err := remote.Get(ctx, ref.Key)
|
||||
if err != nil || !bytes.Equal(chunk[:4096], want) {
|
||||
t.Fatalf("published chunk 5: %v", err)
|
||||
}
|
||||
if got := kzCandidates(t, p); got != 0 {
|
||||
t.Fatalf("after the cut: %d candidate chunks; want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// kzCountingRemote counts chunk reads (Get) of the remote it wraps.
|
||||
type kzCountingRemote struct {
|
||||
storage.ChunkRemote
|
||||
gets atomic.Int64
|
||||
}
|
||||
|
||||
func (r *kzCountingRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
r.gets.Add(1)
|
||||
return r.ChunkRemote.Get(ctx, key)
|
||||
}
|
||||
|
||||
// The premise again, for fills (test #12): until the attach commit retires
|
||||
// the fresh marker, no fetch and no extent write reaches the store. A restore
|
||||
// target whose HEAD names two chunks is held at the commit boundary; a
|
||||
// frontend read of a HEAD-named block there is not served (it may wait;
|
||||
// here it is bounded), the remote serves no chunk read, and after the
|
||||
// commit both named chunks are still absent with no fetch started: no fill
|
||||
// wrote the extent. After that the read returns HEAD's data.
|
||||
func TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
mem := storage.NewMemChunkRemote()
|
||||
src := kzProvider(t, t.TempDir(), mem)
|
||||
if _, err := src.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := src.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := bytes.Repeat([]byte{0x3c}, 4096)
|
||||
for _, chunk := range []int64{3, 7} {
|
||||
if _, err := src.Backend("v1").Write(ctx, chunk*16*4096, want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := src.Backend("v1").Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := src.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := src.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
remote := &kzCountingRemote{ChunkRemote: mem}
|
||||
p := kzProvider(t, t.TempDir(), remote)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var readErr error
|
||||
var getsAtBoundary int64 = -1
|
||||
p.testBeforeChunkFreshRetire = func() error {
|
||||
before := remote.gets.Load()
|
||||
rctx, rcancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer rcancel()
|
||||
_, readErr = p.Backend("v1").Read(rctx, 3*16*4096, make([]byte, 4096))
|
||||
getsAtBoundary = remote.gets.Load() - before
|
||||
return nil
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.testBeforeChunkFreshRetire = nil
|
||||
if readErr == nil || getsAtBoundary != 0 {
|
||||
t.Fatalf("at the commit boundary a frontend read of a HEAD-named block returned %v and the remote served %d chunk reads; want refused, 0", readErr, getsAtBoundary)
|
||||
}
|
||||
for _, st := range p.DurableStatuses() {
|
||||
if st.VolumeID == "v1" && st.Chunk != nil {
|
||||
if h := st.Chunk.Stats.Hydration; st.Chunk.Stats.AbsentChunks != 2 || h.Fetches != 0 || h.Completed != 0 {
|
||||
t.Fatalf("after the commit: %d absent chunks, %d fetches, %d completed; want 2 absent and no fetch (no fill before the commit)", st.Chunk.Stats.AbsentChunks, h.Fetches, h.Completed)
|
||||
}
|
||||
}
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
if n, err := p.Backend("v1").Read(ctx, 3*16*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) {
|
||||
t.Fatalf("read after the commit: %d %v, data equal %v; want HEAD's data", n, err, bytes.Equal(got, want))
|
||||
}
|
||||
}
|
||||
@@ -267,6 +267,9 @@ type DurableProvider struct {
|
||||
|
||||
// testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary.
|
||||
testBeforeChunkFreshRetire func() error
|
||||
// testAfterChunkFreshRetire runs after the attach commit retired the
|
||||
// fresh marker, before the known-zero marking is made durable.
|
||||
testAfterChunkFreshRetire func() error
|
||||
|
||||
// testWALStoreFactory selects a dark store only in provider caller controls.
|
||||
// No production option, flag or environment variable installs it.
|
||||
@@ -297,8 +300,11 @@ type volHandle struct {
|
||||
// volume file, written before the file is created and removed only
|
||||
// after the first attach succeeded, so an interrupted initialization
|
||||
// is still fresh after a restart.
|
||||
fresh bool
|
||||
attachMu sync.Mutex // serializes recovery and attach of this volume
|
||||
fresh bool
|
||||
// createdThisStart: this process start created the store (in memory,
|
||||
// never persisted); RULE-FRESH-KNOWN-ZERO needs it with fresh.
|
||||
createdThisStart bool
|
||||
attachMu sync.Mutex // serializes recovery and attach of this volume
|
||||
// recoverGen numbers this volume's RecoverVolume calls (written under
|
||||
// attachMu and p.mu). waitGen is the generation of the live authority
|
||||
// wait, 0 if none: a recovered volume whose layer waits for master
|
||||
@@ -809,17 +815,19 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: stat %s: %w", path, err)
|
||||
}
|
||||
if p.cfg.Impl == ImplAuto {
|
||||
if p.cfg.Impl != ImplWALStoreChunk {
|
||||
// A walstore-chunk volume shares walstore's on-disk format, and its
|
||||
// authoritative bytes may live only in the remote HEAD. Opened as
|
||||
// plain walstore it would serve local (possibly absent) extents, so
|
||||
// auto refuses any root carrying chunk metadata; it never deletes
|
||||
// or converts it.
|
||||
// plain walstore it would serve local (possibly absent) extents, and
|
||||
// a write through it would reach a store whose fresh marker still
|
||||
// says no write ever did (RULE-FRESH-KNOWN-ZERO). So every other
|
||||
// implementation, auto or explicit, refuses a root carrying chunk
|
||||
// metadata; it never deletes or converts it.
|
||||
if side, err := chunkSidecars(path); err != nil {
|
||||
return nil, err
|
||||
} else if len(side) > 0 {
|
||||
return nil, fmt.Errorf("%w: %s is a chunk-managed volume (%s present); auto cannot open it: set --durable-impl=walstore-chunk with its remote configuration",
|
||||
ErrImplKindMismatch, path, strings.Join(side, ", "))
|
||||
return nil, fmt.Errorf("%w: %s is a chunk-managed volume (%s present); %s cannot open it: set --durable-impl=walstore-chunk with its remote configuration",
|
||||
ErrImplKindMismatch, path, strings.Join(side, ", "), p.cfg.Impl)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -862,7 +870,7 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
|
||||
}
|
||||
h, err := p.createFresh(volumeID, path, impl)
|
||||
if err == nil && p.cfg.Impl == ImplWALStoreChunk {
|
||||
h.fresh = true
|
||||
h.fresh, h.createdThisStart = true, true
|
||||
}
|
||||
return h, err
|
||||
}
|
||||
|
||||
@@ -321,6 +321,18 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
|
||||
} else if err := commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
// RULE-FRESH-KNOWN-ZERO order: the marker is retired (above), THEN the
|
||||
// marking is made durable, THEN the volume serves (after this attach).
|
||||
if h.fresh {
|
||||
if hook := p.testAfterChunkFreshRetire; hook != nil {
|
||||
if err := hook(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if kz, ok := layer.(interface{ ApplyFreshKnownZero() }); ok {
|
||||
kz.ApplyFreshKnownZero()
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.closed {
|
||||
@@ -418,6 +430,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
Epoch: lin.epoch,
|
||||
Holder: holder,
|
||||
FreshFromHead: h.fresh,
|
||||
CreatedThisStart: h.fresh && h.createdThisStart,
|
||||
ReadMissTimeout: p.cfg.ChunkReadMissTimeout,
|
||||
HydrationWorkers: p.cfg.ChunkHydrationWorkers,
|
||||
HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth,
|
||||
|
||||
@@ -113,7 +113,7 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPlainDetachSkipsPrecopyCostAdmission(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := precopyProvider(t, remote, &parkView{stubView: v1View()})
|
||||
|
||||
@@ -126,10 +126,10 @@ func TestCheckpointDiagnostics_LogRateLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A starved checkpoint: flush cycles keep succeeding (clamped to the
|
||||
// acknowledged frontier, nothing persisted moves) while the persisted
|
||||
// CheckpointLSN and the last advance stay frozen. Only a real move of the
|
||||
// persisted checkpoint counts as an advance.
|
||||
// A starved checkpoint: writes that are never synced are never flushed
|
||||
// (INV-WAL-V3-WRITE-AHEAD-001), so flush cycles move nothing: the persisted
|
||||
// CheckpointLSN, the success count and the last advance stay frozen. Only a
|
||||
// real move of the persisted checkpoint counts as an advance.
|
||||
func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
@@ -150,8 +150,8 @@ func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) {
|
||||
}
|
||||
}
|
||||
starved := s.CheckpointPersistence()
|
||||
if starved.Successes <= first.Successes {
|
||||
t.Fatalf("flush cycles did not keep succeeding: %+v", starved)
|
||||
if starved.Successes != first.Successes {
|
||||
t.Fatalf("flush cycles over unsynced writes made a checkpoint call: first %+v starved %+v", first, starved)
|
||||
}
|
||||
if starved.CheckpointLSN != 1 || starved.Advances != 1 || !starved.LastAdvance.Equal(first.LastAdvance) {
|
||||
t.Fatalf("a clamped success counted as an advance: first %+v starved %+v", first, starved)
|
||||
|
||||
@@ -621,7 +621,7 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec
|
||||
}
|
||||
}
|
||||
order := hotChunkKeys(indices, recent)
|
||||
out, intents, err := l.streamCutPayloads(ctx, order, head, func(ctx context.Context, idx uint64) (capturedChunk, error) {
|
||||
out, intents, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) {
|
||||
c, ok, err := l.copyCOWEntry(w, idx)
|
||||
if err != nil {
|
||||
return capturedChunk{}, err
|
||||
|
||||
@@ -41,7 +41,10 @@ func hotChunkKeys(indices map[uint64]bool, recent map[uint64]uint64) []uint64 {
|
||||
// image through PUT/retry, then reads its next candidate independently of slow
|
||||
// workers. One durable intent covers all candidate keys before the first PUT;
|
||||
// unused keys are harmless and retain no payload memory.
|
||||
func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) {
|
||||
//
|
||||
// staging says the batch is a staging round (before the barrier): each chunk
|
||||
// it finishes is counted in Stats.StagedChunks as it finishes.
|
||||
func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, staging bool, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) {
|
||||
out := make([]capturedChunk, len(batch))
|
||||
keys := make([]string, len(batch))
|
||||
for i, idx := range batch {
|
||||
@@ -74,7 +77,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
|
||||
return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
|
||||
}
|
||||
}
|
||||
l.rememberPayload(c, head.Gen)
|
||||
l.rememberPayload(c, head.Gen, staging)
|
||||
c.data = nil
|
||||
out[i] = c
|
||||
return nil
|
||||
@@ -86,7 +89,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) {
|
||||
out, intents, err := l.streamCutPayloads(ctx, batch, head, func(ctx context.Context, idx uint64) (capturedChunk, error) {
|
||||
out, intents, err := l.streamCutPayloads(ctx, batch, head, true, func(ctx context.Context, idx uint64) (capturedChunk, error) {
|
||||
data, err := l.readChunk(idx)
|
||||
if err != nil {
|
||||
return capturedChunk{}, err
|
||||
@@ -114,11 +117,16 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64,
|
||||
// until this version is superseded or a confirmed HEAD makes it reachable.
|
||||
// This cache belongs to one layer/owner lifetime. Generation equality is not
|
||||
// a reuse proof across reopen or takeover; those require content-hash matching.
|
||||
func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64) {
|
||||
// A staged chunk is counted in Stats.StagedChunks here, when it is
|
||||
// remembered, so an interrupted round counts what it finished.
|
||||
func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64, staged bool) {
|
||||
|
||||
c.data = nil
|
||||
l.stMu.Lock()
|
||||
defer l.stMu.Unlock()
|
||||
if staged {
|
||||
l.stats.StagedChunks++
|
||||
}
|
||||
if l.reusable == nil {
|
||||
l.reusable = make(map[uint64]stagedChunk)
|
||||
}
|
||||
|
||||
@@ -727,6 +727,7 @@ func crashableStore(t *testing.T) (*WALStore, string, func()) {
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashOwnedMap(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,6 +754,7 @@ func reopen(t *testing.T, path string) (*WALStore, func()) {
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashOwnedMap(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1133,3 +1135,13 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// crashOwnedMap closes the owned-map file of a crashed store without
|
||||
// persisting anything, as the process's exit would; otherwise its handle
|
||||
// stays open and a platform that refuses to delete an open file fails the
|
||||
// test's directory cleanup.
|
||||
func crashOwnedMap(s *WALStore) {
|
||||
if s.v3 != nil && s.v3.ownedMap != nil && s.v3.ownedMap.fd != nil {
|
||||
_ = s.v3.ownedMap.fd.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package storage
|
||||
|
||||
import "log"
|
||||
|
||||
// RULE-FRESH-KNOWN-ZERO (INV-CUT-FRESH-KNOWN-ZERO-001). A store this process
|
||||
// start created (CreatedThisStart, in memory) that is still fresh at its
|
||||
// attach (FreshFromHead: the .chunkfresh marker is present and no BASE is
|
||||
// installed) has never had a write or a fill reach it: frontend I/O is
|
||||
// admitted only after the attach commit retires the marker, a chunk volume
|
||||
// takes no replication apply, no cut or hydration can resolve the layer
|
||||
// before that commit, and no other implementation opens a root that carries
|
||||
// chunk metadata. Its extent therefore holds the creation bytes (zeros) in
|
||||
// every chunk, and a chunk the claimed HEAD does not name is zero there too:
|
||||
// the two are equal, so the chunk need not be a cut candidate.
|
||||
//
|
||||
// freshKnownZeroCandidates samples, under the attach's capture barrier, the
|
||||
// mutation token of every chunk the claimed HEAD does not name whose owned
|
||||
// map entry is still its creation value {LSN 0, Unknown}; the entry test is
|
||||
// an extra exclusion, not the premise. ApplyFreshKnownZero then clears only
|
||||
// the UNKNOWN bit of those whose token is unchanged, through the cut's own
|
||||
// persistCapturedMapV3. The order is: the attach commit retires the marker,
|
||||
// THEN the marking is made durable, THEN the volume serves. A crash between
|
||||
// the first two leaves no marker and every chunk UNKNOWN (one scan); a
|
||||
// failed map publication leaves them UNKNOWN on disk (conservative).
|
||||
func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 {
|
||||
s := l.s
|
||||
if s.v3 == nil || s.v3.ownedMap == nil {
|
||||
return nil
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := map[uint64]uint64{}
|
||||
for idx := uint64(0); idx < l.numChunks && idx < uint64(len(s.v3.mapEntries)); idx++ {
|
||||
if _, named := head.Chunks[idx]; named {
|
||||
continue
|
||||
}
|
||||
if e := s.v3.mapEntries[idx]; e.LSN != 0 || !e.Unknown {
|
||||
continue
|
||||
}
|
||||
out[idx] = l.chunkVersion(idx)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ApplyFreshKnownZero makes the fresh attach's certification durable: called
|
||||
// once, by the provider, after the attach commit retired the fresh marker and
|
||||
// before the volume serves, outside the capture barrier (as for a cut).
|
||||
// It counts the chunks it certified in Stats.KnownZeroChunks and logs the
|
||||
// outcome: a failed map publication or a raced write leaves chunks UNKNOWN,
|
||||
// and the first cut then scans them (the log says why).
|
||||
func (l *chunkLayerImpl) ApplyFreshKnownZero() {
|
||||
tokens := l.freshKnownZero
|
||||
if tokens == nil {
|
||||
return
|
||||
}
|
||||
l.freshKnownZero = nil
|
||||
l.persistCapturedMapV3(tokens)
|
||||
s := l.s
|
||||
s.mu.RLock()
|
||||
certified := 0
|
||||
for idx := range tokens {
|
||||
if idx < uint64(len(s.v3.mapEntries)) && !s.v3.mapEntries[idx].Unknown {
|
||||
certified++
|
||||
}
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
l.stMu.Lock()
|
||||
l.stats.KnownZeroChunks = uint64(certified)
|
||||
l.stMu.Unlock()
|
||||
if certified == len(tokens) {
|
||||
log.Printf("storage: fresh attach: %d chunks HEAD does not name start known-zero", certified)
|
||||
} else {
|
||||
log.Printf("storage: WARNING: fresh attach: %d of %d chunks HEAD does not name start known-zero; the rest stay unknown (map publication failed or a write raced) and the first cut scans them", certified, len(tokens))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fkzConfig is a fresh attach's config (FreshFromHead) or an existing
|
||||
// store's.
|
||||
func fkzConfig(fresh bool) chunkLayerConfig {
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead, cfg.CreatedThisStart = fresh, fresh
|
||||
return cfg
|
||||
}
|
||||
|
||||
// fkzAttach attaches and applies the certification, as the provider does
|
||||
// after its attach commit.
|
||||
func fkzAttach(t *testing.T, s *WALStore, r chunkRemote, cfg chunkLayerConfig) chunkLayer {
|
||||
t.Helper()
|
||||
l := mustAttach(t, s, r, cfg)
|
||||
l.(*chunkLayerImpl).ApplyFreshKnownZero()
|
||||
return l
|
||||
}
|
||||
|
||||
func fkzCandidates(l chunkLayer) int { return l.Stats().DirtyChunks }
|
||||
|
||||
// A fresh attach certifies every chunk the claimed HEAD does not name whose
|
||||
// owned-map entry is still the creation value; a chunk whose entry recorded
|
||||
// a write (LSN >= 1) is never certified and stays a candidate, even where
|
||||
// that LSN is not above HEAD's RemoteLSN (so "LSN above HEAD" alone would
|
||||
// not make it one): here HEAD is at 100 and the write at 1.
|
||||
func TestFreshKnownZeroNeverCertifiesARecordedWrite(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
if _, err := s.Write(uint32(2*ctChunkBlocks+1), bytes.Repeat([]byte{0x22}, ctBlockSize)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := newFakeChunkRemote()
|
||||
remote.head = chunkHead{Gen: 1, Epoch: 1, RemoteLSN: 100, State: ChunkHeadActive}
|
||||
l := fkzAttach(t, s, remote, fkzConfig(true))
|
||||
if got := fkzCandidates(l); got != 1 {
|
||||
t.Fatalf("fresh attach after a recorded write to chunk 2: %d candidates; want 1 (that chunk only)", got)
|
||||
}
|
||||
if got, want := l.Stats().KnownZeroChunks, uint64(l.(*chunkLayerImpl).numChunks-1); got != want {
|
||||
t.Fatalf("KnownZeroChunks %d; want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Without the fresh premise (an existing store) nothing is certified: every
|
||||
// chunk keeps its persisted UNKNOWN.
|
||||
func TestFreshKnownZeroNotWithoutTheFreshPremise(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
l := fkzAttach(t, s, newFakeChunkRemote(), fkzConfig(false))
|
||||
if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want {
|
||||
t.Fatalf("existing-store attach: %d candidates; want all %d", got, want)
|
||||
}
|
||||
if got := l.Stats().KnownZeroChunks; got != 0 {
|
||||
t.Fatalf("KnownZeroChunks %d without the fresh premise; want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The certification clears only chunks whose mutation token is unchanged
|
||||
// since it was sampled under the attach barrier: a write landing between the
|
||||
// sample and the clear keeps its chunk a candidate.
|
||||
func TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
raw, err := attachChunkLayerImpl(s, newFakeChunkRemote(), fkzConfig(true))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := raw.(*chunkLayerImpl)
|
||||
t.Cleanup(func() { _ = l.Close() })
|
||||
sampled := len(l.freshKnownZero)
|
||||
if sampled == 0 {
|
||||
t.Fatal("no chunk sampled for certification")
|
||||
}
|
||||
if _, err := s.Write(uint32(3*ctChunkBlocks), bytes.Repeat([]byte{0x33}, ctBlockSize)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.ApplyFreshKnownZero()
|
||||
if got := fkzCandidates(l); got != 1 {
|
||||
t.Fatalf("a write between the sample and the clear: %d candidates; want 1 (the written chunk)", got)
|
||||
}
|
||||
if got := l.Stats().KnownZeroChunks; got != uint64(sampled-1) {
|
||||
t.Fatalf("KnownZeroChunks %d; want %d (every sampled chunk but the written one)", got, sampled-1)
|
||||
}
|
||||
}
|
||||
|
||||
// A fresh marker alone is not trusted: an attach whose store this start did
|
||||
// not create (CreatedThisStart false) certifies nothing.
|
||||
func TestFreshKnownZeroNeedsThisStartsCreate(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
cfg := fkzConfig(true)
|
||||
cfg.CreatedThisStart = false
|
||||
l := fkzAttach(t, s, newFakeChunkRemote(), cfg)
|
||||
if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want {
|
||||
t.Fatalf("fresh attach of a store this start did not create: %d candidates; want all %d", got, want)
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,10 @@ type chunkLayerImpl struct {
|
||||
remote chunkRemote
|
||||
cfg chunkLayerConfig
|
||||
|
||||
// freshKnownZero: the mutation tokens RULE-FRESH-KNOWN-ZERO sampled at a
|
||||
// fresh attach; applied once by ApplyFreshKnownZero.
|
||||
freshKnownZero map[uint64]uint64
|
||||
|
||||
blockSize int
|
||||
chunkBlocks uint64
|
||||
numChunks uint64
|
||||
@@ -287,6 +291,9 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
l.absentGen[idx]++
|
||||
}
|
||||
l.presenceVer++
|
||||
if cfg.CreatedThisStart {
|
||||
l.freshKnownZero = l.freshKnownZeroCandidates(head)
|
||||
}
|
||||
} else if err := l.loadPresence(); err != nil {
|
||||
l.cancel()
|
||||
return nil, err
|
||||
@@ -778,9 +785,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
if !guestFrozen {
|
||||
staged, intents, err = l.stage(ctx, &st, spill.bytes)
|
||||
}
|
||||
if st.UploadedBytes > 0 {
|
||||
st.PayloadNs += time.Since(stageStart).Nanoseconds()
|
||||
}
|
||||
st.PayloadNs += time.Since(stageStart).Nanoseconds()
|
||||
if err != nil {
|
||||
dropCapturedIntents(ctx, intents)
|
||||
return chunkCutResult{}, err
|
||||
|
||||
@@ -202,7 +202,7 @@ func TestCutPayloadReadsOverlapEarlierUploadsWithinBudget(t *testing.T) {
|
||||
t.Cleanup(func() { cancel(); free(); cowWaitSignal(t, done, "overlap cleanup") })
|
||||
go func() {
|
||||
defer close(done)
|
||||
_, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, func(_ context.Context, idx uint64) (capturedChunk, error) {
|
||||
_, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) {
|
||||
if idx == 2 {
|
||||
close(readThird)
|
||||
}
|
||||
@@ -233,7 +233,7 @@ func TestCutPayloadIntentCountLargeCandidateSets(t *testing.T) {
|
||||
for i := range batch {
|
||||
batch[i] = uint64(i)
|
||||
}
|
||||
_, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, func(_ context.Context, idx uint64) (capturedChunk, error) {
|
||||
_, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) {
|
||||
data := makeBlock(ctBlockSize, byte(idx%255+1))
|
||||
return capturedChunk{idx: idx, data: data, sum: sha256.Sum256(data)}, nil
|
||||
})
|
||||
|
||||
@@ -343,6 +343,11 @@ type chunkLayerConfig struct {
|
||||
// HEAD (every block absent, read lazily). False means an existing local
|
||||
// volume. Never inferred from the local contents.
|
||||
FreshFromHead bool
|
||||
// CreatedThisStart says this process start created the local store (an
|
||||
// in-memory fact, never persisted). RULE-FRESH-KNOWN-ZERO samples only
|
||||
// with it and FreshFromHead: a fresh marker left by an earlier start, an
|
||||
// older binary or another opener is never trusted.
|
||||
CreatedThisStart bool
|
||||
// RestoreGuard binds fresh attachment to the HEAD the provider claimed
|
||||
// and durably seeded. A changed read refuses before hooks/readiness; the
|
||||
// next recovery must repeat claim and seed. Nil is for direct layer users.
|
||||
@@ -489,8 +494,17 @@ type chunkCutStats struct {
|
||||
// results whose outcome stayed unresolved after the HEAD re-read.
|
||||
// - PendingUnresolved: an unresolved proposal is held now.
|
||||
// - DirtyChunks is the number of chunks dirty since the last HEAD now
|
||||
// (the C11 bitmap popcount); the cut scheduler's threshold reads it.
|
||||
// Chunks still awaiting reconciliation are not counted.
|
||||
// (the C11 bitmap popcount): the next cut's candidates, not its
|
||||
// progress (it does not fall while a cut runs or across failed
|
||||
// attempts); the cut scheduler's threshold reads it. Chunks still
|
||||
// awaiting reconciliation are not counted.
|
||||
// - StagedChunks counts the chunks staging finished (read, hashed,
|
||||
// uploaded when not zero, and remembered for reuse) in every cut
|
||||
// attempt of this layer: a failed attempt and an interrupted round
|
||||
// count what they finished. It only grows: a chunk staged again (after
|
||||
// a guest write re-dirtied it, or in a later cut) counts again; it is
|
||||
// in-process (a restart starts at 0). The progress a cut retried after
|
||||
// its deadline has made.
|
||||
// - Reconciling: the dirty set is being reconciled against HEAD; no cut
|
||||
// publishes until it is done. ReconcileDone of ReconcileTotal chunks
|
||||
// are compared.
|
||||
@@ -508,7 +522,9 @@ type chunkLayerStats struct {
|
||||
CASConflicts uint64 // HEAD CAS precondition failures
|
||||
CASUnknown uint64 // HEAD CAS results still unresolved after the re-read
|
||||
PendingUnresolved bool // an unresolved HEAD proposal is held now
|
||||
DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation)
|
||||
DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress
|
||||
StagedChunks uint64 // chunks staged by every cut attempt, failed ones included (in-process)
|
||||
KnownZeroChunks uint64 // chunks this layer's fresh attach certified known-zero (RULE-FRESH-KNOWN-ZERO); 0 otherwise
|
||||
Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile
|
||||
ReconcileDone int // chunks compared so far
|
||||
ReconcileTotal int // chunks to compare
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// zeroStagedLayer is a layer past its zero baseline cut with n chunks
|
||||
// rewritten with zeros: candidates that staging reads and hashes but never
|
||||
// uploads. The spill cap of two chunks makes the cut stage them.
|
||||
func zeroStagedLayer(t *testing.T, n int) (*fakeChunkRemote, *chunkLayerImpl) {
|
||||
t.Helper()
|
||||
s, f, l, w := precopyLayer(t, 1, 0)
|
||||
l.cfg.COWSpillLimit = 2 * ctChunkBytes
|
||||
for c := 0; c < n; c++ {
|
||||
w.write(t, s, uint32(c*ctChunkBlocks+2), 0)
|
||||
}
|
||||
return f, l
|
||||
}
|
||||
|
||||
// The payload time of a cut counts its staging rounds even when they
|
||||
// upload nothing (every staged chunk was zero), so a first cut that spent
|
||||
// its time reading and hashing shows it.
|
||||
func TestChunkStage_PayloadTimeCountsStagingWithoutUploads(t *testing.T) {
|
||||
_, l := zeroStagedLayer(t, 6)
|
||||
// Staging takes measurable time on any clock resolution.
|
||||
l.testAfterStageHook = func(int) { time.Sleep(20 * time.Millisecond) }
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := r.Stats
|
||||
if st.StageRounds == 0 || st.StagedChunks == 0 {
|
||||
t.Fatalf("cut stats %+v; want staging rounds", st)
|
||||
}
|
||||
if st.UploadedBytes != 0 {
|
||||
t.Fatalf("uploaded %d bytes; want none (every staged chunk is zero)", st.UploadedBytes)
|
||||
}
|
||||
if st.PayloadNs < int64(20*time.Millisecond) {
|
||||
t.Fatalf("payload time %d ns with %d chunks staged; want the staging time", st.PayloadNs, st.StagedChunks)
|
||||
}
|
||||
}
|
||||
|
||||
// The layer counts every chunk staged by any cut attempt, a failed one
|
||||
// included, so a first cut retried after its deadline shows the progress
|
||||
// its earlier attempts made; the last successful cut's stats do not move.
|
||||
// An attempt that staged all 6 candidates counts exactly 6.
|
||||
func TestChunkStage_StagedChunksCountsFailedAttempts(t *testing.T) {
|
||||
_, l := zeroStagedLayer(t, 6)
|
||||
before := l.Stats()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
l.testBeforeBarrierLockHook = cancel
|
||||
if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cut: %v; want it cancelled before the barrier", err)
|
||||
}
|
||||
l.testBeforeBarrierLockHook = nil
|
||||
after := l.Stats()
|
||||
if got := after.StagedChunks - before.StagedChunks; got != 6 {
|
||||
t.Fatalf("a failed attempt that staged all 6 candidates counted %d", got)
|
||||
}
|
||||
if after.CutSeq != before.CutSeq || after.LastCut.StagedChunks != before.LastCut.StagedChunks {
|
||||
t.Fatal("a failed attempt changed the last successful cut")
|
||||
}
|
||||
// A retry stages nothing again (the chunks are reused) and counts nothing.
|
||||
if _, err := l.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := l.Stats().StagedChunks - after.StagedChunks; got != 0 {
|
||||
t.Fatalf("the retry counted %d staged chunks; want 0 (every chunk reused)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A round that fails partway counts the chunks it finished, each remembered
|
||||
// for reuse, and not the ones it did not: one upload worker stages the five
|
||||
// zero chunks (the most recent writes go first), then the non-zero chunk's
|
||||
// upload fails at its intent.
|
||||
func TestChunkStage_StagedChunksCountsAnInterruptedRound(t *testing.T) {
|
||||
s, f, l, w := precopyLayer(t, 1, 0)
|
||||
l.cfg.COWSpillLimit = 2 * ctChunkBytes
|
||||
l.cfg.UploadConcurrency = 1
|
||||
w.write(t, s, uint32(0*ctChunkBlocks+2), 0x5a) // oldest write: staged last
|
||||
for c := 1; c <= 5; c++ {
|
||||
w.write(t, s, uint32(c*ctChunkBlocks+2), 0)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.failPutIntent = errors.New("intent refused")
|
||||
f.mu.Unlock()
|
||||
before := l.Stats().StagedChunks
|
||||
l.stMu.Lock()
|
||||
reusedBefore := len(l.reusable)
|
||||
l.stMu.Unlock()
|
||||
if _, err := l.Cut(ctTimeout(t)); err == nil {
|
||||
t.Fatal("cut succeeded; want the staging round to fail at the intent")
|
||||
}
|
||||
l.stMu.Lock()
|
||||
remembered := len(l.reusable) - reusedBefore
|
||||
l.stMu.Unlock()
|
||||
got := l.Stats().StagedChunks - before
|
||||
if got != 5 || uint64(remembered) != got {
|
||||
t.Fatalf("interrupted round counted %d staged chunks, remembered %d; want 5 and 5", got, remembered)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Page writeback has no order across offsets of one file, so an extent
|
||||
// written from a WAL record that is not yet durable could survive a power
|
||||
// loss that loses the record (an unacked write). After recovery the chunk's
|
||||
// map entry would not have moved, the chunk would not be a cut candidate,
|
||||
// and local reads would return the lost write's bytes while the published
|
||||
// HEAD holds the chunk without them. The flusher therefore writes extents
|
||||
// only from synced records (INV-WAL-V3-WRITE-AHEAD-001). Local and published
|
||||
// must agree for every block of a chunk that is not a candidate.
|
||||
//
|
||||
// The crash is injected, not raced: the real flusher runs and is stopped at
|
||||
// its fsync; the store file after the crash is the file as it was before the
|
||||
// unacked write, plus that block's extent page as the flusher left it, as if
|
||||
// only that page had reached the disk. A flusher that writes extents only
|
||||
// from synced records leaves the page unchanged and passes.
|
||||
func TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart(t *testing.T) {
|
||||
// The name keeps its red-first form so the history and the row match.
|
||||
ctx := context.Background()
|
||||
s, path, crash := crashableStore(t)
|
||||
remote := NewMemChunkRemote()
|
||||
cfg := chunkLayerConfig{ChunkBlocks: ctChunkBlocks, Epoch: 1, Holder: "h"}
|
||||
layer := mustAttach(t, s, remote, cfg)
|
||||
|
||||
acked := bytes.Repeat([]byte{0xA1}, ctBlockSize)
|
||||
if _, err := s.Write(1, acked); err != nil { // chunk 0
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Capture(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Time passes: the flusher checkpoints, so the cut's clear of chunk 0
|
||||
// is in the persisted map (chunk 0 is not a candidate any more).
|
||||
mustSyncFlush(t, s)
|
||||
if n := layer.Stats().DirtyChunks; n != 0 {
|
||||
t.Fatalf("after the cut and a checkpoint: %d candidate chunks; want 0", n)
|
||||
}
|
||||
// Read through the store's own handle (another open of the file is
|
||||
// refused on some platforms while the store holds its lock).
|
||||
fi, err := s.fd.Stat()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := make([]byte, fi.Size())
|
||||
if _, err := s.fd.ReadAt(before, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// An unacked write to another block of chunk 0. The flusher runs (below
|
||||
// the WAL pressure threshold, as in normal use); the power is cut at its
|
||||
// fsync: the extent pages it wrote may be on the disk, the WAL record
|
||||
// (never synced) is not, and no checkpoint follows.
|
||||
lost := bytes.Repeat([]byte{0xB2}, ctBlockSize)
|
||||
const lostLBA = 2
|
||||
if _, err := s.Write(lostLBA, lost); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
off := int64(s.extentBase) + int64(lostLBA)*int64(ctBlockSize)
|
||||
page := make([]byte, ctBlockSize)
|
||||
s.testBeforeFileSync = func() {
|
||||
if _, err := s.fd.ReadAt(page, off); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
s.noteFsyncFailure(errors.New("power cut"))
|
||||
}
|
||||
_ = s.flusher.flushOnce() // fails at its fsync: no checkpoint
|
||||
s.testBeforeFileSync = nil
|
||||
crash()
|
||||
|
||||
// The disk after the crash: the earlier file, plus only that extent page
|
||||
// as the flusher left it.
|
||||
img := append([]byte(nil), before...)
|
||||
copy(img[off:off+int64(ctBlockSize)], page)
|
||||
if err := os.WriteFile(path, img, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2, _ := reopen(t, path)
|
||||
layer2 := mustAttach(t, s2, remote, cfg)
|
||||
|
||||
local, err := s2.Read(lostLBA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
published := make([]byte, ctBlockSize)
|
||||
if ref, ok := head.Chunks[0]; ok {
|
||||
chunk, err := remote.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inChunk := (lostLBA % ctChunkBlocks) * ctBlockSize
|
||||
copy(published, chunk[inChunk:inChunk+ctBlockSize])
|
||||
}
|
||||
candidate := layer2.Stats().DirtyChunks > 0
|
||||
t.Logf("after the crash: local block %d = %#x..., published = %#x..., chunk 0 a cut candidate: %v", lostLBA, local[0], published[0], candidate)
|
||||
if !bytes.Equal(local, published) && !candidate {
|
||||
t.Fatalf("block %d reads the lost write's bytes locally (%#x) while HEAD holds %#x, and chunk 0 is not a cut candidate: local and published disagree with nothing to reconcile them", lostLBA, local[0], published[0])
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,7 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) {
|
||||
select {
|
||||
case <-r.failed:
|
||||
cancel() // retries are now allowed; terminate this cut explicitly
|
||||
case <-time.After(time.Second):
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("uploads did not overlap")
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -183,7 +183,21 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
recoveryGen = store.v3.recoverGen.Load()
|
||||
|
||||
entries := store.dm.snapshot()
|
||||
// Write-ahead (INV-WAL-V3-WRITE-AHEAD-001): only entries whose WAL
|
||||
// record is durable reach the extent. An entry above the synced WAL
|
||||
// frontier stays dirty for a later cycle: written now, a power loss
|
||||
// could keep its extent page and lose its record, leaving extent bytes
|
||||
// that no recovered record or map entry accounts for. A cycle with no
|
||||
// synced entry is idle: no extent write and no fsync.
|
||||
synced := store.v3.wack.Load()
|
||||
store.mu.RUnlock()
|
||||
kept := entries[:0]
|
||||
for _, e := range entries {
|
||||
if e.LSN <= synced {
|
||||
kept = append(kept, e)
|
||||
}
|
||||
}
|
||||
entries = kept
|
||||
if len(entries) == 0 {
|
||||
|
||||
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The flusher skips an LBA whose newest entry is not yet synced, so a
|
||||
// cycle's checkpoint can pass an OLDER synced record of that LBA that never
|
||||
// reached the extent (it was superseded in the dirty map by the unsynced
|
||||
// one). That is safe only because the cycle's sync is the whole-file fsync
|
||||
// of the one descriptor holding WAL and extent: it makes the newer record
|
||||
// durable before the checkpoint is published, so recovery replays it
|
||||
// (INV-WAL-FLUSH-SYNC-COVERS-WAL-001). b=X, c=Y, Sync, b=Z unsynced, one
|
||||
// flusher cycle, crash after its checkpoint: b must read X or Z, never the
|
||||
// bytes from before X.
|
||||
//
|
||||
// The crash image keeps the WAL region as of the last sync that covered it
|
||||
// and everything else as of the crash. The product's syncs (the WAL sync and
|
||||
// the flusher's) both cover the WAL. The control models a flusher sync that
|
||||
// covers only the extent (a range sync, or WAL and extent in separate files)
|
||||
// and shows the checkpoint bound would then lose X: the premise is
|
||||
// load-bearing.
|
||||
func TestFlusherCheckpointOverASupersededSyncedRecord(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
flushCoversWAL bool
|
||||
wantBeforeXRead bool
|
||||
}{
|
||||
{"whole-file flusher sync (product)", true, false},
|
||||
{"control: extent-only flusher sync", false, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s, path, crash := crashableStore(t)
|
||||
d := s.v3.pub.current()
|
||||
walOff, walLen := int64(d.WALOffset), int64(d.WALSize)
|
||||
readWAL := func() []byte {
|
||||
b := make([]byte, walLen)
|
||||
if _, err := s.fd.ReadAt(b, walOff); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
durableWAL := readWAL()
|
||||
realWALSync, realFlushSync := s.syncWALFile, s.syncExtentFile
|
||||
s.syncWALFile = func() error {
|
||||
err := realWALSync()
|
||||
if err == nil {
|
||||
durableWAL = readWAL()
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.syncExtentFile = func() error {
|
||||
err := realFlushSync()
|
||||
if err == nil && c.flushCoversWAL {
|
||||
durableWAL = readWAL()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
const b, cLBA = 3, 9
|
||||
X, Y, Z := bytes.Repeat([]byte{0x58}, ctBlockSize), bytes.Repeat([]byte{0x59}, ctBlockSize), bytes.Repeat([]byte{0x5a}, ctBlockSize)
|
||||
before, err := s.Read(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(b, X); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(cLBA, Y); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(b, Z); err != nil { // unsynced: supersedes X in the dirty map
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cp := s.CheckpointLSN(); cp < 2 {
|
||||
t.Fatalf("checkpoint %d after the cycle; want it past X's record (it covers Y)", cp)
|
||||
}
|
||||
crash()
|
||||
|
||||
img, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copy(img[walOff:walOff+walLen], durableWAL)
|
||||
if err := os.WriteFile(path, img, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2, _ := reopen(t, path)
|
||||
got, err := s2.Read(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
isBefore := bytes.Equal(got, before) && !bytes.Equal(got, X)
|
||||
switch {
|
||||
case c.wantBeforeXRead && !isBefore:
|
||||
t.Fatalf("control: block %d reads %#x after the crash; the model should lose X here (premise not shown load-bearing)", b, got[0])
|
||||
case !c.wantBeforeXRead && !bytes.Equal(got, X) && !bytes.Equal(got, Z):
|
||||
t.Fatalf("block %d reads %#x after the crash; want X (%#x) or Z (%#x), never the bytes from before X", b, got[0], X[0], Z[0])
|
||||
}
|
||||
t.Logf("block %d after the crash: %#x", b, got[0])
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A guest that never flushes: below the WAL pressure threshold its writes
|
||||
// are not synced, so the flusher writes none of their extents
|
||||
// (INV-WAL-V3-WRITE-AHEAD-001) and the checkpoint stays; once the WAL is
|
||||
// past the threshold, the flusher's pressure sync makes them durable and the
|
||||
// same cycle writes every block's newest bytes to the extent and advances
|
||||
// the checkpoint. The data never waits for a guest flush that does not come.
|
||||
func TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure(t *testing.T) {
|
||||
for _, mode := range []WMode{WModeStrict, WModeLagged} {
|
||||
t.Run(map[WMode]string{WModeStrict: "A", WModeLagged: "C"}[mode], func(t *testing.T) {
|
||||
s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "pressure"), 64, 4096, 64*1024, mode, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
expected := map[uint32][]byte{}
|
||||
write := func(lba uint32) {
|
||||
t.Helper()
|
||||
data := bytes.Repeat([]byte{byte(s.NextLSN())}, 4096)
|
||||
if _, err := s.Write(lba, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected[lba] = data
|
||||
}
|
||||
extent := func(lba uint32) []byte {
|
||||
t.Helper()
|
||||
b, err := s.readFromExtent(lba)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
write(0)
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Equal(extent(0), expected[0]) || s.CheckpointLSN() != 0 {
|
||||
t.Fatalf("below pressure: an unsynced write reached the extent (checkpoint %d)", s.CheckpointLSN())
|
||||
}
|
||||
|
||||
for lba := uint32(1); s.walUsedFraction() < 0.72; lba = (lba + 1) % 64 {
|
||||
write(lba)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba, want := range expected {
|
||||
if !bytes.Equal(extent(lba), want) {
|
||||
t.Fatalf("after the pressure sync: block %d's extent does not hold its newest write", lba)
|
||||
}
|
||||
}
|
||||
if s.CheckpointLSN() == 0 {
|
||||
t.Fatal("after the pressure sync: the checkpoint did not advance")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// INV-WAL-FLUSH-SYNC-COVERS-WAL-001, checked in the source: the flusher's
|
||||
// extent sync and the WAL sync are the same whole-file sync of the store's
|
||||
// one descriptor. The checkpoint bound rests on it (a checkpoint may pass a
|
||||
// synced record superseded by an unsynced newer one only because the
|
||||
// flusher's sync makes the newer record durable too). In the package's
|
||||
// non-test Go files:
|
||||
// - the function that sets syncExtentFile binds exactly one data sync
|
||||
// (bindDataFileSync of the store file) and no other function sets it;
|
||||
// - every assignment to syncExtentFile assigns exactly that result;
|
||||
// - every assignment to syncWALFile is a function that calls that result.
|
||||
//
|
||||
// A range sync, a second descriptor for the WAL or the extent, or a WAL sync
|
||||
// that no longer calls the shared sync fails here first.
|
||||
func TestSyncCoversWALGuard(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
binds, extentOK, extentBad, walOK, walBad := 0, 0, []string{}, 0, []string{}
|
||||
shared := "" // the variable bindDataFileSync's sync result is bound to
|
||||
type asg struct {
|
||||
field string
|
||||
rhs ast.Expr
|
||||
pos token.Position
|
||||
}
|
||||
var asgs []asg
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
continue
|
||||
}
|
||||
src, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file, err := parser.ParseFile(fset, f, src, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, decl := range file.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
continue
|
||||
}
|
||||
var fnBinds []string
|
||||
setsExtent := false
|
||||
ast.Inspect(fn.Body, func(n ast.Node) bool {
|
||||
a, ok := n.(*ast.AssignStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
for i, rhs := range a.Rhs {
|
||||
if call, ok := rhs.(*ast.CallExpr); ok {
|
||||
if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "bindDataFileSync" && len(a.Lhs) > 0 {
|
||||
if lhs, ok := a.Lhs[0].(*ast.Ident); ok {
|
||||
fnBinds = append(fnBinds, lhs.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if i < len(a.Lhs) {
|
||||
if sel, ok := a.Lhs[i].(*ast.SelectorExpr); ok && (sel.Sel.Name == "syncExtentFile" || sel.Sel.Name == "syncWALFile") {
|
||||
asgs = append(asgs, asg{sel.Sel.Name, rhs, fset.Position(a.Pos())})
|
||||
if sel.Sel.Name == "syncExtentFile" {
|
||||
setsExtent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if setsExtent {
|
||||
binds += len(fnBinds)
|
||||
if len(fnBinds) > 0 {
|
||||
shared = fnBinds[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if binds != 1 || shared == "" {
|
||||
t.Fatalf("the function setting syncExtentFile binds %d data syncs (first bound to %q); want exactly one: one descriptor, one sync", binds, shared)
|
||||
}
|
||||
callsShared := func(e ast.Expr) bool {
|
||||
found := false
|
||||
ast.Inspect(e, func(n ast.Node) bool {
|
||||
if c, ok := n.(*ast.CallExpr); ok {
|
||||
if id, ok := c.Fun.(*ast.Ident); ok && id.Name == shared {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return !found
|
||||
})
|
||||
return found
|
||||
}
|
||||
for _, a := range asgs {
|
||||
switch a.field {
|
||||
case "syncExtentFile":
|
||||
if id, ok := a.rhs.(*ast.Ident); ok && id.Name == shared {
|
||||
extentOK++
|
||||
} else {
|
||||
extentBad = append(extentBad, a.pos.String())
|
||||
}
|
||||
case "syncWALFile":
|
||||
if fl, ok := a.rhs.(*ast.FuncLit); ok && callsShared(fl) {
|
||||
walOK++
|
||||
} else {
|
||||
walBad = append(walBad, a.pos.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
if extentOK == 0 || len(extentBad) > 0 {
|
||||
t.Fatalf("syncExtentFile assigned the shared sync %q %d times; other assignments at %v: the flusher's sync must be the WAL's whole-file sync", shared, extentOK, extentBad)
|
||||
}
|
||||
if walOK == 0 || len(walBad) > 0 {
|
||||
t.Fatalf("syncWALFile assigned a function calling %q %d times; other assignments at %v", shared, walOK, walBad)
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto
|
||||
- Each HEAD is logically full: restore never chains deltas.
|
||||
- A flat (format 1) HEAD is upgraded at its next cut ([chunk manifests](../chunk-manifests.md)). In a host-side proxy, the root of a 10 GiB volume shrank from 261,531 bytes (flat) to 2,172 bytes (two-level) (§13).
|
||||
|
||||
**How versions share data.** A HEAD, a snapshot and a fork root are each a complete map from chunk index to chunk key. There is no backing chain and no per-layer bitmap that falls through to a parent, as qcow2 backing files or overlay layers have.
|
||||
**How versions share data.** A HEAD, a snapshot and a fork root are each a complete map from chunk index to chunk key. There is no backing chain and no per-layer bitmap that falls through to a parent, as qcow2 backing files or overlay layers have. This is `INV-HEAD-FLAT-001`: immutable segment indirection is part of one image map, not a parent-image chain.
|
||||
- A cut uploads a new key only for a chunk whose content changed (§5, step 6) and rewrites only the segments that list such chunks. Every other index keeps its key, and every other segment its object, from the previous HEAD. A snapshot copies the root; a fork writes a new root with the same references (§6). Neither copies a chunk or a segment.
|
||||
- So a chunk that was not rewritten after a snapshot is the same object in that snapshot, in every later snapshot and in HEAD. A chunk rewritten after the snapshot has an old key that only the snapshot (and any earlier version that shares it) still references.
|
||||
- A read looks up one map: the root, one segment, one chunk. It never walks a chain, and deleting a version never requires merging another one.
|
||||
|
||||
@@ -46,6 +46,7 @@ The local storage engine and the durable backend in front of it. Diagrams in the
|
||||
stateDiagram-v2
|
||||
[*] --> Opened: OpenWALStore / CreateWALStore
|
||||
[*] --> CreateRefused: CreateWALStore without local headroom (free < size + WAL)
|
||||
[*] --> CreateRefused: chunk volume, create mode: geometry flags disagree with the volume record, or the record is not read
|
||||
Opened --> Recovering: RecoverVolume
|
||||
Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready
|
||||
Serving --> Closed: runtime HEAD fence, exit 78 head_fenced
|
||||
@@ -62,6 +63,7 @@ stateDiagram-v2
|
||||
|---|---|---|---|---|
|
||||
| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` |
|
||||
| — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL, checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` |
|
||||
| — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` |
|
||||
| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` |
|
||||
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001` |
|
||||
| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` |
|
||||
@@ -495,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
|
||||
|
||||
## Part B. Invariant ledger
|
||||
|
||||
319 rows: 248 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 new.
|
||||
324 rows: 254 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 309 new.
|
||||
|
||||
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
|
||||
|
||||
@@ -527,6 +529,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-WAL-V3-ACTIVATION-PROVIDER-001` | The durable provider's capture, HEAD restore and status paths probe, open and create volumes through the public v3 selectors (`ProbeWALStoreV3`, `OpenWALStore`, `CreateWALStoreWithOptions`). | M1 open/create/readonly | `core/frontend/durable/provider.go` `openOrCreate` | `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`) | — | ACTIVE |
|
||||
| `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE |
|
||||
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
|
||||
| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE |
|
||||
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
|
||||
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB |
|
||||
| `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
|
||||
@@ -744,7 +747,7 @@ Notes:
|
||||
| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`; `cmd/blockvolume/workspace_lease.go` `workspaceDetachedGeneration` | `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`); `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE |
|
||||
| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE |
|
||||
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; a missing record keeps the create path; an unreadable record falls to the attach check, never a refusal. | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE |
|
||||
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE |
|
||||
| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn` (a rolled-back copy), is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`); `TestRolledBackCopyBelowHeadLSNIsRefused` (`core/frontend/durable/rolled_back_copy_test.go`); `TestCutPublishesOnlyLocallyDurableLSN` (`core/frontend/durable/cut_durable_before_cas_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
|
||||
@@ -818,7 +821,9 @@ Notes:
|
||||
| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |
|
||||
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
|
||||
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE |
|
||||
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE |
|
||||
| `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE |
|
||||
@@ -853,6 +858,7 @@ Notes:
|
||||
| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |
|
||||
| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE |
|
||||
| `INV-CUT-HYDRATION-PROGRESS-001` | The status reports per volume the HEAD-named chunks still to hydrate (`AbsentChunks`) and the chunks hydrated so far (`Hydration.Completed`, cumulative); a read of an un-hydrated chunk moves both by one, a repeat read neither. Observation only. | M5 hydration (reader; no transition) | `core/storage/chunk_layer.go` `Stats` (`absentHydratable`); `core/storage/chunk_hydration.go` `hydrationWorker` | `TestHydrationProgressCountersFollowFirstReads` (`core/frontend/durable/hydration_progress_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch) | — | ACTIVE |
|
||||
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
|
||||
@@ -884,6 +890,7 @@ Notes:
|
||||
|
||||
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `INV-HEAD-FLAT-001` | Every HEAD and snapshot root is a complete image map, directly or through immutable segments. Forks preserve original object owners; reads never fall through to a parent HEAD or snapshot, so successive forks add no backing-chain depth. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`; `core/frontend/chunkstore/manifest.go` `qualifyManifestKey`, `resolveManifest` | `TestForkGrandchildReadsEveryBlockWithoutAncestorImages` (`core/frontend/chunkstore/flat_head_test.go`); `TestFork_ForkOfForkKeepsOriginalOwner` (`core/frontend/chunkstore/catalog_test.go`); `TestManifest_ForkAfterParentSnapshotDelete` (`core/frontend/chunkstore/manifest_test.go`) | —; existing representation, no new transition | ACTIVE |
|
||||
| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE |
|
||||
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
|
||||
| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE |
|
||||
@@ -1013,12 +1020,12 @@ Notes:
|
||||
| `INV-WAL-DATA-SYNC-STATUS-001` | The data sync mode chosen at open and its reason are logged and exposed in durable status. | M1 Create / Sync / Checkpoint | `data_sync.go` `bindDataFileSync`, `DataSyncPolicy`; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`) | — | ACTIVE |
|
||||
| `INV-WAL-ALLOCATION-001` | `SWBLOCK_ALLOCATION` selects allocation at create: sparse, the default, or prezero; fallocate is refused. `SWBLOCK_PREZERO=1` is an alias of prezero. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestDefaultCreatedVolumeStaysSparse`, `TestFallocateAllocationIsRefused` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE |
|
||||
| `INV-WAL-PREZERO-001` | Prezero writes every byte at create and fsyncs; a file opened as initialized is refused when it has holes or unwritten extent mappings. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE |
|
||||
| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | — | — | STUB |
|
||||
| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherCheckpointOverASupersededSyncedRecord` (`core/storage/flusher_superseded_record_test.go`; its control models an extent-only flusher sync and loses X); `TestSyncCoversWALGuard` (`core/storage/sync_covers_wal_guard_test.go`: the store opener binds one data sync, and the flusher sync and the WAL sync both use it) | — | ACTIVE |
|
||||
|
||||
- `INV-WAL-DATA-SYNC-001` and the rows split from it: enforced by reading, with no test of their own: the mode is not reselected during the life of an open volume; descriptor, map, create and directory durability always use fsync, whatever the data sync mode; an existing file is never prezeroed.
|
||||
Notes:
|
||||
|
||||
- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; no test asserts it yet. Fault-injection tests replace the WAL sync and the extent sync separately and do not check that they are the same call.
|
||||
- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; `TestFlusherCheckpointOverASupersededSyncedRecord` shows why it is load-bearing (a checkpoint over a superseded synced record is safe only if the flusher's sync made the newer record durable; its control, an extent-only sync, loses the older record). `TestSyncCoversWALGuard` checks in the source that the WAL sync and the flusher's extent sync are the one data sync the store opener binds for its file.
|
||||
|
||||
## Part C. Change rules
|
||||
|
||||
|
||||
@@ -55,6 +55,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p
|
||||
A first start whose `--durable-blocks` or `--durable-blocksize` disagrees with the volume record is refused before
|
||||
any local store is created: it exits 78 (the unit does not restart it) with a line `geometry_mismatch: --durable-blocks
|
||||
... disagree with the volume record`; correct the flag and start it again.
|
||||
If that first start cannot read the volume record because the filer failed the read, it exits 75 with `the volume
|
||||
record of <vol> could not be read ... no local store was created; retrying` and the unit starts it again. During a long
|
||||
outage the unit can reach its start limit; once the filer answers, run `systemctl reset-failed <unit>` and start it.
|
||||
If the record is there but corrupt, it exits 78 with `the volume record of <vol> is unreadable (corrupt: ...)`: restore
|
||||
or recreate the record, then start it.
|
||||
A wrong-size local store left by an earlier release's first start is different: its log repeats `chunk attach check:
|
||||
chunkstore: geometry_mismatch` and it exits; waiting or restarting with the right flags does not help. In one sitting: stop the unit first; then check that the volume never served:
|
||||
`sw-block ops chunk show --volume <vol> --chunk-filer <filer> --chunk-path <path>` prints `"epoch":0` and
|
||||
@@ -130,10 +135,10 @@ default) can expire the host's slots; keep host clocks synchronized.
|
||||
- scheduled and manual snapshots;
|
||||
- deleting snapshots, and getting space back:
|
||||
- GC deletes the chunks after the grace (`--grace`, 1 hour by default), so a deleted snapshot's space is
|
||||
reclaimed about 2 hours after the delete;
|
||||
reclaimed about 2 hours after the delete unless still referenced by a snapshot, fork or restore;
|
||||
- then the asynchronous SeaweedFS vacuum compacts the volume files;
|
||||
- `ops chunk verify`;
|
||||
- restoring a snapshot into a new, independent volume.
|
||||
- forking a snapshot into a new volume that shares immutable objects, or restoring it into a new, independent volume.
|
||||
|
||||
A snapshot can be refused with `host_slot_busy` / `no background slot` (retryable) while every host slot is held by
|
||||
other volumes' cuts; retry with the same request id. With many volumes on a host, a snapshot may wait for a slot:
|
||||
@@ -205,6 +210,7 @@ Every command on the pages above, and the test that runs it.
|
||||
| A snapshot refused with `host_slot_busy` / `no background slot` while every host slot is held, retried with the same request id | `TestSnapshotLadderF1VolumesOneHost` (`cmd/blockvolume`, `F1_RUN=1`, `F1_HOST_LIMIT_DIR` set, 3 slots; `F1_SLOT_RETRY_SECONDS=0` is its negative control) | binary |
|
||||
| Full local disk; full `--host-limit-dir` | `TestProcedureLocalDiskFull` (`cmd/blockvolume`, root, `testdata/diskfull.sh`); what a Linux guest sees: `TestProcedureLocalDiskFullKernelInitiator` (kernel NVMe/TCP host) | binary |
|
||||
| A first start with the wrong `--durable-blocks`: refused before any local store is created (exit 78) | `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary |
|
||||
| A first start over a corrupt volume record: exit 78 before any local store is created; a start once the record is restored | `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary |
|
||||
| A wrong-size local store left by an earlier release (`geometry_mismatch` at attach): the guard (`sw-block ops chunk show`), removing the local files, a start with the right flags | `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`; the store is planted from a capture of such a run) | binary |
|
||||
| SeaweedFS (filer or volume server) down during a cut | `TestProcedureStoreDownDuringACut` (`cmd/blockvolume`) | binary |
|
||||
| `blockmaster` refuses a `--workspace-max-clock-skew` whose half does not exceed its fence-exit budget (at or below 10.1 s) | `TestBlockmasterRefusesASkewBoundAtOrBelowTheFenceExit` (`cmd/blockvolume`, tag `subprocess`) | binary |
|
||||
|
||||
@@ -202,7 +202,7 @@ with `move target node "s2" is not registered`.
|
||||
| `SWB_HEARTBEAT_INTERVAL` | `--heartbeat-interval` | `2s` | Heartbeat interval |
|
||||
| `SWB_RECOVER_TIMEOUT` | `--recover-timeout` | `30s` | Time to become promotion-ready before reporting `recovery_timeout` |
|
||||
| `SWB_DURABLE_ROOT` | `--durable-root` | empty (in memory, not durable) | Storage directory; writable by the service user |
|
||||
| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root. Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. |
|
||||
| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root; so does every explicit value other than `walstore-chunk` (a chunk root holds data that may live only in the remote HEAD: open it with `--durable-impl=walstore-chunk` and its remote configuration). Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. |
|
||||
| `SWB_DURABLE_BLOCKS` | `--durable-blocks` | `2048` | Blocks on first create |
|
||||
| `SWB_DURABLE_BLOCKSIZE` | `--durable-blocksize` | `4096` | Block size on first create |
|
||||
| `SWB_NVME_LISTEN` | `--nvme-listen` | empty (off) | NVMe/TCP target; loopback only, no authentication |
|
||||
@@ -506,7 +506,7 @@ Space comes back in two steps. Neither is immediate.
|
||||
1. **GC deletes the chunks**, after the grace. The grace is `sw-block ops chunk gc --grace`, **1 hour by default**.
|
||||
- A deleted snapshot keeps its chunks rooted for the grace after the delete.
|
||||
- A chunk is then reclaimed only once two complete GC marks, at least the grace apart, have both seen it unreferenced.
|
||||
- With the default grace, a deleted snapshot's chunks are reclaimed about **2 hours** after the delete. That needs a GC pass at least 1 hour after the delete and another at least 1 hour after that.
|
||||
- With the default grace, a deleted snapshot's unreferenced chunks are reclaimed about **2 hours** after the delete. Chunks still referenced by another snapshot, fork or restore remain live. That needs a GC pass at least 1 hour after the delete and another at least 1 hour after that.
|
||||
- Automatic GC is off by default (`--chunk-maintenance-gc`), so run the passes yourself:
|
||||
|
||||
```bash
|
||||
@@ -564,6 +564,54 @@ therefore see every chunk of every volume and snapshot as unreferenced.
|
||||
- Space is returned only by the two steps above (`sw-block ops chunk gc`, then a SeaweedFS vacuum). `volume.vacuum`
|
||||
is safe: it compacts needles that were already deleted.
|
||||
|
||||
### Forking a snapshot into a new volume
|
||||
|
||||
A fork creates a new volume sharing the snapshot's immutable chunks and segments:
|
||||
|
||||
```bash
|
||||
sw-block ops chunk fork --source v1 --snapshot before-upgrade --target v2 --chunk-filer FILER --request-id fork-v2
|
||||
```
|
||||
|
||||
Keep the request id to retry an uncertain result. The new HEAD contains a complete image map; reads do not walk back through parent volumes or snapshots. A fork of a fork preserves the original object owners without adding a backing chain. Deleting the source snapshot does not delete objects still referenced by the fork. Use restore when the target must eventually own its data independently.
|
||||
|
||||
### Retiring the source of a template
|
||||
|
||||
A template is an ordinary immutable snapshot, not a separate volume kind. Keep the volume holding an offered template snapshot: volume deletion refuses while any snapshot name exists. To retire the original source instead, first move the template image into a dedicated holder using existing fork and snapshot operations.
|
||||
|
||||
Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone cluster spec has new volume placements for `template-holder` and `consumer`. Neither target blockvolume has started yet. Use the same filer and chunk namespace throughout.
|
||||
|
||||
1. Create the holder:
|
||||
|
||||
```bash
|
||||
sw-block ops chunk fork --source v1 --snapshot seed --target template-holder --chunk-filer FILER --request-id fork-template-holder
|
||||
```
|
||||
|
||||
2. Start `template-holder` with the normal standalone blockvolume command and its own volume id, endpoints and local root. Wait for its frontend readiness; read back the seed's known data before proceeding. Take the template snapshot:
|
||||
|
||||
```bash
|
||||
sw-block ops chunk snapshot --volume template-holder --status-addr HOLDER_STATUS --name template-v1
|
||||
```
|
||||
|
||||
3. Create a consumer, start its blockvolume on its own placement and root, and verify its known data:
|
||||
|
||||
```bash
|
||||
sw-block ops chunk fork --source template-holder --snapshot template-v1 --target consumer --chunk-filer FILER --request-id fork-consumer
|
||||
```
|
||||
|
||||
4. Stop the source writer. Follow [Delete a volume](volume-lifecycle.md#delete-a-volume) for `v1`: plain detach, revoke its exact replica/epoch/sealed generation, wait for its recorded ACK and natural exit, delete `seed`, then delete `v1`. Do not signal the process in place of waiting for its ACK. Require the completed delete answer and `show` state `deleted` before continuing.
|
||||
|
||||
5. Verify both surviving images, including the holder's template snapshot:
|
||||
|
||||
```bash
|
||||
sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --timeout 2m --chunk-filer FILER
|
||||
sw-block ops chunk verify --volume consumer --all-snapshots --depth data --timeout 2m --chunk-filer FILER
|
||||
sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply
|
||||
```
|
||||
|
||||
Read back the known data again and repeat both verify commands after the pass. This immediate pass is not a reclamation measurement: its default grace has not elapsed. Continue namespace-wide GC as described above for unused objects; attached-volume maintenance alone does not collect a deleted source's namespace.
|
||||
|
||||
Keep `template-holder/template-v1` while it is offered for new consumers. Retiring that snapshot later does not delete objects still referenced by existing consumers. Deleting the holder volume itself still requires the ordinary seal/revoke/ACK and snapshot-deletion procedure; do not remove its backing filer directory or object bindings by hand.
|
||||
|
||||
### Restoring a snapshot into a new volume
|
||||
|
||||
A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards.
|
||||
|
||||
@@ -227,7 +227,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
|
||||
| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures |
|
||||
| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read |
|
||||
| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now |
|
||||
| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation) |
|
||||
| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress |
|
||||
| `Volumes[].Chunk.Stats.StagedChunks` | uint64 | chunks staged by every cut attempt, failed ones included (in-process) |
|
||||
| `Volumes[].Chunk.Stats.KnownZeroChunks` | uint64 | chunks this layer's fresh attach certified known-zero (RULE-FRESH-KNOWN-ZERO); 0 otherwise |
|
||||
| `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile |
|
||||
| `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far |
|
||||
| `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare |
|
||||
|
||||
Reference in new issue
Block a user