diff --git a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go index 27a76a4c3f..5dfb390539 100644 --- a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go +++ b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go @@ -821,3 +821,25 @@ func g15dReadFile(t *testing.T, parts ...string) string { } return string(raw) } + +// The node-loss gate checks what this release claims: no automatic promotion +// while the primary's node is lost, then the same primary serves again. +func TestNodeLossGateExpectsNoAutomaticPromotion(t *testing.T) { + gate := g15dReadFile(t, "testops", "scenarios", "node-loss-survival-rf3-reattach-chain.yaml") + demo := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh") + for _, want := range []string{"SW_BLOCK_DEMO_EXPECT_NO_AUTO_PROMOTION=1", "failover_status: recovered_same_primary", "auto_promotion_while_node_lost=none"} { + if !strings.Contains(gate, want) { + t.Fatalf("node-loss gate missing %q", want) + } + } + for _, gone := range []string{"failover_status: promoted\"", "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS", "result=promoted"} { + if strings.Contains(gate, gone) { + t.Fatalf("node-loss gate still expects %q", gone) + } + } + for _, want := range []string{"SW_BLOCK_DEMO_EXPECT_NO_AUTO_PROMOTION", "failover_status: unexpected_auto_promotion", "failover_status: no_auto_promotion_unproven", "failover_status: recovered_same_primary", "primary frontend_primary_ready=false", "kubectl uncordon"} { + if !strings.Contains(demo, want) { + t.Fatalf("run-alpha-app-demo.sh missing %q", want) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index fec741db8e..64c56a107b 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -8,6 +8,8 @@ import ( "errors" "fmt" "io" + "math/rand" + "net" "net/http" "net/url" "os" @@ -159,14 +161,11 @@ func TestHeadSizeAgainstVolumeSize(t *testing.T) { } cfg.attempts = n } - h := newPlannedHandoffHarness(t) - clusterDir := filepath.Join(h.dir, "weed") - if err := os.MkdirAll(clusterDir, 0o700); err != nil { - t.Fatal(err) + var vols []headSzVol + for _, s := range sizes { + vols = append(vols, headSzVol{id: "h" + strings.ToLower(strings.TrimSpace(s)), bytes: headSzParse(t, s)}) } - 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{}} + env, clusterDir := headSzStartCluster(t, "headsz", vols) 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() { @@ -178,36 +177,159 @@ func TestHeadSizeAgainstVolumeSize(t *testing.T) { } }() - // 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)) } } +// headSzVol is one volume of the test cluster spec. server "" places it on +// s1 (replica rN); any other server gets its own node in the spec and the +// volume's one replica r1 on it (a restore or fork target, as +// startHandoffEnvWith places its targets). +type headSzVol struct { + id string + bytes uint64 + server string + // host, when set, is another machine that runs this volume's blockvolume: + // its spec data and ctrl addresses are host: (ports picked here, not + // probed there), and the test running on that host uses the same ones. + host string +} + +// headSzStartCluster starts one weed cluster (the filer's default store, no +// filer.toml) and a blockmaster whose spec holds vols. It returns the env, +// with one bvHost per volume, and the cluster dir. The chunk path is +// /-. +func headSzStartCluster(t *testing.T, prefix string, vols []headSzVol) (*handoffEnv, string) { + t.Helper() + 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("/%s-%d", prefix, time.Now().UnixNano()), hosts: map[string]bvHost{}} + var spec strings.Builder + nodes := fmt.Sprintf(" - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n", h.dataAddr, h.ctrlAddr) + for i, v := range vols { + server, replica := "s1", fmt.Sprintf("r%d", i+1) + if v.server != "" { + server, replica = v.server, "r1" + } + b := bvHost{id: v.id, server: server, replica: replica, volume: v.id, root: filepath.Join(h.dir, "vol-"+v.id), + data: handoffAddress(t), ctrl: handoffAddress(t), status: headSzLoopbackAddr(t), nvme: headSzLoopbackAddr(t)} + if v.host != "" { + b.data, b.ctrl = headSzRemoteAddr(t, v.host), headSzRemoteAddr(t, v.host) + } + env.hosts[v.id] = b + if v.server != "" { + nodes += fmt.Sprintf(" - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", server, b.data, b.ctrl) + } + fmt.Fprintf(&spec, " - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", v.id, v.bytes, server, replica) + } + specPath := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(specPath, []byte("nodes:\n"+nodes+"volumes:\n"+spec.String()), 0o644); err != nil { + t.Fatal(err) + } + mstate := filepath.Join(h.dir, "master") + margs := []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + "--cluster-spec", specPath, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, + "--workspace-rpc", "--workspace-head-base-url", "http://" + env.cluster.filerHTTP + env.chunkPath} + if testListenHost() != "127.0.0.1" { + // a lab run spanning two hosts: blockmaster refuses a non-loopback listen without this + margs = append(margs, "--insecure-external-bind") + } + master := h.start(t, "blockmaster", h.master, margs...) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + return env, clusterDir +} + +// headSzLoopbackAddr picks a free 127.0.0.1 port from the harness's range: +// blockvolume's NVMe/TCP target and status endpoint refuse any non-loopback +// bind, and the test (user-space client, kernel nvme connect, sw-block ops +// --status-addr) always reaches them from the same host as that blockvolume, +// also when SWBLOCK_TEST_LISTEN_HOST names a host address. +func headSzLoopbackAddr(t *testing.T) string { + t.Helper() + handoffPorts.Lock() + defer handoffPorts.Unlock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for i := 0; i < 500; i++ { + p := 10000 + rand.Intn(10000) + if handoffPorts.used[p] { + continue + } + addr := fmt.Sprintf("127.0.0.1:%d", p) + if ln, err := net.Listen("tcp", addr); err == nil { + ln.Close() + handoffPorts.used[p] = true + return addr + } + } + t.Fatal("no free loopback port") + return "" +} + +// headSzRemoteAddr picks host: for a process on another machine from +// the same port range handoffAddress uses, never handing out a port twice. +func headSzRemoteAddr(t *testing.T, host string) string { + t.Helper() + handoffPorts.Lock() + defer handoffPorts.Unlock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for i := 0; i < 500; i++ { + p := 10000 + rand.Intn(10000) + if !handoffPorts.used[p] { + handoffPorts.used[p] = true + return fmt.Sprintf("%s:%d", host, p) + } + } + t.Fatal("no port left for " + host) + return "" +} + // 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. +// many times one cut is tried before it is recorded as not completed. name +// is the snapshot name prefix ("headsz" when empty): cut N is "-N". type headSzConfig struct { snapshotTimeout string attempts int + name string +} + +// headSzStartVolume starts b's blockvolume for a volume of bytes (no capture +// interval, no snapshot schedule: cuts happen only when the test asks), waits +// until it adopted the volume as PRIMARY and its frontend is ready, and +// returns it. When the volume refuses for headroom it returns nil and the +// refusal line; any other early exit or timeout fails the test. The caller +// stops the daemon. +func headSzStartVolume(t *testing.T, env *handoffEnv, b bvHost, bytes uint64, extra ...string) (*daemon, string) { + t.Helper() + env.volExtra = append([]string{"--durable-blocks", strconv.FormatUint(bytes/4096, 10), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}, extra...) + d := env.h.start(t, "blockvolume-"+b.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 != "" { + return nil, strings.TrimSpace(l) + } + t.Fatalf("blockvolume %s exited before it adopted its volume: %v", b.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", b.id) + } + } + poll(t, 60*time.Second, b.id+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) }) + return d, "" } // headSzOne measures one size; its blockvolume is stopped at the end. @@ -217,26 +339,12 @@ func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, cha 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) - } + d, refusal := headSzStartVolume(t, env, b, bytes) + if d == nil { + row.Result, row.Refusal = "refused_headroom", refusal + return row } 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) { @@ -281,11 +389,15 @@ func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, cha func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cut, changed int) headSzCut { t.Helper() r := headSzCut{Cut: cut, ChangedBlocks: changed} + name := cfg.name + if name == "" { + name = "headsz" + } 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)) + "--name", fmt.Sprintf("%s-%d", name, cut), "--request-id", fmt.Sprintf("%s-%s-%d", name, 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 } diff --git a/seaweed-block/cmd/blockvolume/hold_kzhold.go b/seaweed-block/cmd/blockvolume/hold_kzhold.go new file mode 100644 index 0000000000..3fc55846cc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hold_kzhold.go @@ -0,0 +1,24 @@ +//go:build kzhold + +package main + +import ( + "log" + "os" + "path/filepath" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// applyBuildTagHold: in a kzhold build (test-only, never released) with +// SWBLOCK_KZHOLD_DIR set, the provider holds before the fresh marker is +// retired: it writes /reached and waits for /release. +func applyBuildTagHold(dp *durable.DurableProvider) { + dir := os.Getenv("SWBLOCK_KZHOLD_DIR") + if dir == "" { + return + } + log.Printf("blockvolume: TEST-ONLY build (kzhold): holding before the fresh-marker retire; reached=%s release=%s", + filepath.Join(dir, "reached"), filepath.Join(dir, "release")) + dp.HoldBeforeChunkFreshRetireForTest(filepath.Join(dir, "reached"), filepath.Join(dir, "release")) +} diff --git a/seaweed-block/cmd/blockvolume/hold_release.go b/seaweed-block/cmd/blockvolume/hold_release.go new file mode 100644 index 0000000000..7900f7e4d2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hold_release.go @@ -0,0 +1,8 @@ +//go:build !kzhold + +package main + +import "github.com/seaweedfs/seaweed-block/core/frontend/durable" + +// applyBuildTagHold does nothing in a normal build. +func applyBuildTagHold(*durable.DurableProvider) {} diff --git a/seaweed-block/cmd/blockvolume/known_zero_acceptance_integration_test.go b/seaweed-block/cmd/blockvolume/known_zero_acceptance_integration_test.go new file mode 100644 index 0000000000..0bc8dcef1f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_acceptance_integration_test.go @@ -0,0 +1,812 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" +) + +// TestKnownZeroAcceptance is the KNOWN-ZERO acceptance test of a fresh volume, +// gated by KZ_RUN=1. Source role (this file, steps 1-2): +// +// (1) a fresh volume of KZ_SIZE (default 1T) and an empty first snapshot S0: +// it finishes in seconds, stages and uploads nothing, and HEAD names no +// segment; the fresh attach certified chunks known-zero. +// (2) mkfs (KZ_FS: ext4 and xfs, one volume each) on the kernel NVMe/TCP +// device, small files with known sha256, sync, snapshot S1: the chunks +// mkfs dirtied, staged chunks, uploaded bytes and HEAD size, bounded by +// the touched chunks. +// +// Device steps run only with KZ_DEVICE=1 (root through sudo -n, nvme-cli, +// mkfs). Every device path comes from kzResolve on this run's own NQN; a path +// given by name is never formatted. Without KZ_DEVICE the test writes known +// blocks through the user-space NVMe client instead (a smoke of the counters, +// not the acceptance run). Each step prints one "KZ STEP n PASS|FAIL " +// line and its counters into KZ_REPORT. +func TestKnownZeroAcceptance(t *testing.T) { + if os.Getenv("KZ_RUN") != "1" { + t.Skip("KZ_RUN=1 not set") + } + size := os.Getenv("KZ_SIZE") + if size == "" { + size = "1T" + } + bytes := headSzParse(t, size) + fss := strings.Split(os.Getenv("KZ_FS"), ",") + if os.Getenv("KZ_FS") == "" { + fss = []string{"ext4", "xfs"} + } + device := os.Getenv("KZ_DEVICE") == "1" + run := os.Getenv("KZ_RUN_ID") + if run == "" { + run = fmt.Sprintf("local-%d", time.Now().Unix()) + } + // KZ_ROLE: "" = every step in this process (the smoke); "source" = steps + // 1, 2 and 5 here, the restore and fork targets on KZ_TARGET_HOST (the + // second host), handed over through KZ_HANDOFF; "target" = steps + // 3 and 4 on this host against the source's cluster named in KZ_HANDOFF. + role := os.Getenv("KZ_ROLE") + rep := &kzReport{Run: run, Size: size, Bytes: bytes, Device: device, Role: role, StartedAt: time.Now().UTC()} + defer rep.write(t) + if role == "target" { + kzTargetRole(t, rep, bytes, device, run) + return + } + targetHost := "" + if role == "source" { + if targetHost = os.Getenv("KZ_TARGET_HOST"); targetHost == "" || os.Getenv("KZ_HANDOFF") == "" { + t.Fatal("KZ_ROLE=source needs KZ_TARGET_HOST and KZ_HANDOFF") + } + } else if role != "" { + t.Fatalf("KZ_ROLE %q: want source, target or unset", role) + } + // per file system: the source and two targets of its S1, each target on + // its own server node (on KZ_TARGET_HOST in the source role) + var vols []headSzVol + for _, fs := range fss { + vols = append(vols, headSzVol{id: "kz" + fs, bytes: bytes}, + headSzVol{id: "kz" + fs + "r", bytes: bytes, server: "t-" + fs + "r", host: targetHost}, + headSzVol{id: "kz" + fs + "f", bytes: bytes, server: "t-" + fs + "f", host: targetHost}) + } + // step 5: up to kzCrashTries fresh volumes (a try whose stop lands after the + // attach commit has committed that store, so a retry needs a new one) + for i := 1; i <= kzCrashTries; i++ { + vols = append(vols, headSzVol{id: fmt.Sprintf("kzc%d", i), bytes: bytes}) + } + env, _ := headSzStartCluster(t, "kz", vols) + rep.ChunkPath = env.chunkPath + ho := kzHandoff{Run: run, Bytes: bytes, FilerGRPC: env.cluster.filerGRPC, FilerHTTP: env.cluster.filerHTTP, + Master: env.h.masterAddr, ChunkPath: env.chunkPath} + for _, fs := range fss { + v := kzSource(t, env, rep, env.hosts["kz"+fs], fs, bytes, device, run) + rep.Volumes = append(rep.Volumes, v) + if !v.S1.Completed { + continue + } + for _, kind := range []string{"restore", "fork"} { + tb := env.hosts["kz"+fs+kind[:1]] + if role == "source" { + ho.Targets = append(ho.Targets, kzHandoffTarget{Kind: kind, Volume: tb.volume, Server: tb.server, Data: tb.data, Ctrl: tb.ctrl, + Source: v.Volume, S1: v.S1Name, Dirty1: v.Dirty1, Files: v.Files, Blocks: kzHexBlocks(v.Blocks)}) + continue + } + rep.Targets = append(rep.Targets, kzTarget(t, env, rep, v, kind, tb, bytes, device, run)) + } + } + if role == "source" { + kzWriteHandoff(t, ho) + kzWaitTargetDone(t) + } + rep.Crash = kzCrashFirstStart(t, env, rep, bytes, run) +} + +// kzHandoff is what the source role hands to the target role (KZ_HANDOFF): +// the cluster to use and, per target, the S1 to restore or fork and what the +// source wrote into it. +type kzHandoff struct { + Run string `json:"run"` + Bytes uint64 `json:"bytes"` + FilerGRPC string `json:"filer_grpc"` + FilerHTTP string `json:"filer_http"` + Master string `json:"master"` + ChunkPath string `json:"chunk_path"` + Targets []kzHandoffTarget `json:"targets"` +} + +type kzHandoffTarget struct { + Kind string `json:"kind"` + Volume string `json:"volume"` + Server string `json:"server"` + Data string `json:"data_addr"` + Ctrl string `json:"ctrl_addr"` + Source string `json:"source"` + S1 string `json:"s1"` + Dirty1 int `json:"dirty1"` + Files map[string]string `json:"files_sha256"` + Blocks map[string]string `json:"blocks_hex"` +} + +func kzHexBlocks(b map[uint64][]byte) map[string]string { + out := map[string]string{} + for lba, d := range b { + out[fmt.Sprint(lba)] = hex.EncodeToString(d) + } + return out +} + +func kzWriteHandoff(t *testing.T, ho kzHandoff) { + t.Helper() + b, _ := json.MarshalIndent(ho, "", " ") + p := os.Getenv("KZ_HANDOFF") + if err := os.WriteFile(p+".tmp", append(b, '\n'), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Rename(p+".tmp", p); err != nil { + t.Fatal(err) + } + t.Logf("KZ HANDOFF written: %s (%d targets)", p, len(ho.Targets)) +} + +// kzWaitTargetDone waits for KZ_TARGET_DONE (the window script creates it +// after the target role ended), at most KZ_TARGET_WAIT (default 90m). The +// source's cluster must stay up while the targets run. +func kzWaitTargetDone(t *testing.T) { + t.Helper() + done := os.Getenv("KZ_TARGET_DONE") + if done == "" { + t.Fatal("KZ_ROLE=source needs KZ_TARGET_DONE") + } + wait := 90 * time.Minute + if v := os.Getenv("KZ_TARGET_WAIT"); v != "" { + d, err := time.ParseDuration(v) + if err != nil { + t.Fatalf("KZ_TARGET_WAIT=%q: %v", v, err) + } + wait = d + } + poll(t, wait, "the target role never finished ("+done+" absent)", func() bool { + _, err := os.Stat(done) + return err == nil + }) +} + +// kzTargetEnv reserves the data and ctrl ports the source's cluster spec names +// for the targets BEFORE the harness picks any port of its own (its +// constructor allocates five), then builds the env on the source's filer and +// blockmaster. +func kzTargetEnv(t *testing.T, ho kzHandoff, newHarness func(*testing.T) *plannedHandoffHarness) *handoffEnv { + t.Helper() + handoffPorts.Lock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for _, ht := range ho.Targets { + if err := kzReserve(handoffPorts.used, ht.Data, ht.Ctrl); err != nil { + handoffPorts.Unlock() + t.Fatalf("KZ_HANDOFF target %s: %v", ht.Volume, err) + } + } + handoffPorts.Unlock() + h := newHarness(t) + h.masterAddr = ho.Master + return &handoffEnv{h: h, cluster: &w4WeedCluster{filerGRPC: ho.FilerGRPC, filerHTTP: ho.FilerHTTP}, chunkPath: ho.ChunkPath, hosts: map[string]bvHost{}} +} + +// TestKnownZeroTargetReservesBeforeHarness: when the harness constructor runs, +// every handed-off port is already reserved, so none of its own five ports can +// be one of them (and then be refused as a collision). +func TestKnownZeroTargetReservesBeforeHarness(t *testing.T) { + ho := kzHandoff{Master: "10.9.9.1:1", Targets: []kzHandoffTarget{{Volume: "v", Data: "10.9.9.2:19991", Ctrl: "10.9.9.2:19992"}}} + called := false + kzTargetEnv(t, ho, func(t *testing.T) *plannedHandoffHarness { + called = true + handoffPorts.Lock() + defer handoffPorts.Unlock() + if !handoffPorts.used[19991] || !handoffPorts.used[19992] { + t.Fatal("the harness was built before the handed-off ports were reserved") + } + return &plannedHandoffHarness{dir: t.TempDir()} + }) + if !called { + t.Fatal("the harness constructor was never called") + } +} + +// kzTargetRole runs steps 3 and 4 on this host: no weed cluster or +// blockmaster of its own; every blockvolume uses the source's filer and +// blockmaster from KZ_HANDOFF, with the data and ctrl addresses the source's +// cluster spec names for it. +func kzTargetRole(t *testing.T, rep *kzReport, bytes uint64, device bool, run string) { + t.Helper() + b, err := os.ReadFile(os.Getenv("KZ_HANDOFF")) + if err != nil { + t.Fatalf("KZ_HANDOFF: %v", err) + } + var ho kzHandoff + if err := json.Unmarshal(b, &ho); err != nil { + t.Fatalf("KZ_HANDOFF: %v", err) + } + if ho.Run != run || ho.Bytes != bytes || len(ho.Targets) == 0 { + t.Fatalf("KZ_HANDOFF run %q bytes %d targets %d; this run %q bytes %d", ho.Run, ho.Bytes, len(ho.Targets), run, bytes) + } + env := kzTargetEnv(t, ho, newPlannedHandoffHarness) + h := env.h + rep.ChunkPath = ho.ChunkPath + for _, ht := range ho.Targets { + tb := bvHost{id: ht.Volume, server: ht.Server, replica: "r1", volume: ht.Volume, root: filepath.Join(h.dir, "vol-"+ht.Volume), + data: ht.Data, ctrl: ht.Ctrl, status: headSzLoopbackAddr(t), nvme: headSzLoopbackAddr(t)} + env.hosts[ht.Volume] = tb + src := kzVolume{Volume: ht.Source, S1Name: ht.S1, Dirty1: ht.Dirty1, Files: ht.Files, Blocks: map[uint64][]byte{}} + for k, v := range ht.Blocks { + var lba uint64 + if _, err := fmt.Sscan(k, &lba); err != nil { + t.Fatalf("KZ_HANDOFF block %q: %v", k, err) + } + d, err := hex.DecodeString(v) + if err != nil { + t.Fatalf("KZ_HANDOFF block %q: %v", k, err) + } + src.Blocks[lba] = d + } + rep.Targets = append(rep.Targets, kzTarget(t, env, rep, src, ht.Kind, tb, bytes, device, run)) + } +} + +type kzTargetRecord struct { + Volume string `json:"volume"` + Kind string `json:"kind"` + Source string `json:"source"` + Snapshot string `json:"snapshot"` + NQN string `json:"nqn"` + Identity string `json:"device_identity,omitempty"` + Before kzStats `json:"stats_before_reads"` + After kzStats `json:"stats_after_reads"` + ReadsEqual int `json:"reads_equal"` + ReadsZero int `json:"reads_zero"` + Reads int `json:"reads"` + FilesEqual int `json:"files_equal"` + FirstCut kzCutRecord `json:"first_snapshot"` +} + +// kzTarget restores or forks the source's S1 into tb, then runs step 4 (read +// the S1-named blocks BEFORE hydration: data, never zeros; the read itself +// waits for its chunk) and step 3 (all contents equal the source; the target's +// first snapshot completes without a full scan). +func kzTarget(t *testing.T, env *handoffEnv, rep *kzReport, src kzVolume, kind string, tb bvHost, bytes uint64, device bool, run string) kzTargetRecord { + t.Helper() + r := kzTargetRecord{Volume: tb.volume, Kind: kind, Source: src.Volume, Snapshot: src.S1Name, + NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, tb.volume)} + env.h.command(t, "ops", "chunk", kind, "--source", src.Volume, "--snapshot", src.S1Name, "--target", tb.volume, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--request-id", "kz-"+kind+"-"+tb.volume) + d, refusal := headSzStartVolume(t, env, tb, bytes, "--nvme-subsysnqn", r.NQN) + if d == nil { + rep.step(t, 3, tb.volume, false, kind+" target refused: "+refusal) + return r + } + defer d.term(t, 60*time.Second) + + // (4) wrong-zero guard, before any hydration (a restore is driven only after) + r.Before = kzReadStats(t, tb) + c := dialNVMe(t, tb.nvme, r.NQN) + zero := make([]byte, 4096) + for lba, want := range src.Blocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + got := c.read(t, lba, 4096) + r.Reads++ + switch { + case string(got) == string(want): + r.ReadsEqual++ + case string(got) == string(zero): + r.ReadsZero++ + } + } + c.close() + r.After = kzReadStats(t, tb) + waited := r.After.Hydration.WaitCalls - r.Before.Hydration.WaitCalls + ok4 := r.Reads > 0 && r.ReadsEqual == r.Reads && r.ReadsZero == 0 && r.Before.AbsentChunks > 0 && waited > 0 + rep.step(t, 4, tb.volume, ok4, fmt.Sprintf("%s reads=%d equal=%d zero=%d absent_before=%d absent_after=%d read_waits=%d fetches=%d", + kind, r.Reads, r.ReadsEqual, r.ReadsZero, r.Before.AbsentChunks, r.After.AbsentChunks, waited, + r.After.Hydration.Fetches-r.Before.Hydration.Fetches)) + + // (3) contents equal + first snapshot without a full scan + if kind == "restore" { + env.h.command(t, "ops", "chunk", "restore", "--volume", tb.volume, "--status-addr", tb.status) + } + if device { + r.Identity, r.FilesEqual = kzDeviceVerify(t, tb, r.NQN, src, run) + } else { + c := dialNVMe(t, tb.nvme, r.NQN) + for lba, want := range src.Blocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + if string(c.read(t, lba, 4096)) == string(want) { + r.FilesEqual++ + } + } + c.close() + } + total := int((bytes + kzChunkBytes - 1) / kzChunkBytes) + r.FirstCut = kzCut(t, env, headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + tb.volume + "-s"}, tb, 0, total) + want := len(src.Files) + cand := kzLC(r.FirstCut.Stats).CandidateChunks + ok3 := r.FilesEqual == want && want > 0 && r.FirstCut.Completed && cand <= src.Dirty1 + rep.step(t, 3, tb.volume, ok3, fmt.Sprintf("%s files_equal=%d/%d first_snapshot completed=%v candidates=%d (source dirtied %d) of %d chunks wall_ms=%.0f", + kind, r.FilesEqual, want, r.FirstCut.Completed, cand, src.Dirty1, total, r.FirstCut.WallMs)) + return r +} + +// kzWaitDevice resolves this run's NQN from sysfs for up to 30 s; on timeout +// the last refusal is in the failure, so a lab log names the check that held. +func kzWaitDevice(t *testing.T, nqn string) kzDevice { + t.Helper() + sys := os.DirFS("/sys/class") + var last error + deadline := time.Now().Add(30 * time.Second) + for time.Now().Before(deadline) { + d, err := kzResolve(sys, nqn, "") + if err == nil { + return d + } + last = err + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("kernel device for %s never appeared: %v", nqn, last) + return kzDevice{} +} + +// kzDeviceVerify connects the target through the kernel, resolves it by +// NQN, mounts it read-only under the run's scratch, compares every source +// file's sha256, unmounts and disconnects. +func kzDeviceVerify(t *testing.T, tb bvHost, nqn string, src kzVolume, run string) (string, int) { + t.Helper() + host, port := kzSplit(t, tb.nvme) + kzSudo(t, "nvme", "connect", "-t", "tcp", "-n", nqn, "-a", host, "-s", port) + defer kzSudo(t, "nvme", "disconnect", "-n", nqn) + var dev kzDevice + dev = kzWaitDevice(t, nqn) + t.Log(dev.Identity()) + mnt := filepath.Join(os.TempDir(), "kz-"+run, tb.volume) + if err := os.MkdirAll(mnt, 0o755); err != nil { + t.Fatal(err) + } + kzSudo(t, "mount", "-o", "ro", dev.Path, mnt) + defer kzSudo(t, "umount", mnt) + equal := 0 + for name, want := range src.Files { + out := kzSudo(t, "sha256sum", filepath.Join(mnt, name)) + if f := strings.Fields(out); len(f) > 0 && f[0] == want { + equal++ + } + } + return dev.Identity(), equal +} + +// kzReport is the JSON evidence (KZ_REPORT); Lines are the step verdicts. +type kzReport struct { + Run string `json:"run"` + Size string `json:"size"` + Bytes uint64 `json:"bytes"` + Device bool `json:"device"` + Role string `json:"role,omitempty"` + ChunkPath string `json:"chunk_path"` + StartedAt time.Time `json:"started_at"` + Volumes []kzVolume `json:"volumes"` + Targets []kzTargetRecord `json:"targets"` + Crash kzCrashRecord `json:"crash"` + HoldBin string `json:"hold_bin,omitempty"` + Lines []string `json:"lines"` +} + +const kzCrashTries = 3 + +type kzCrashTry struct { + Volume string `json:"volume"` + Markers []string `json:"markers_at_stop"` + Before bool `json:"stopped_before_commit"` +} + +type kzCrashRecord struct { + Tries []kzCrashTry `json:"tries"` + Volume string `json:"volume,omitempty"` + FreshLine string `json:"fresh_line_after_restart,omitempty"` + S0 kzCutRecord `json:"s0_after_restart"` + Dirty1 int `json:"dirty_chunks_before_s1"` + S1 kzCutRecord `json:"s1_after_restart"` + Equal int `json:"blocks_equal"` + Blocks int `json:"blocks"` +} + +// kzHoldBin is KZ_HOLD_BIN: the kzhold-tagged blockvolume (go build -tags kzhold +// ./cmd/blockvolume), test-only and never released; its sha256 goes into the +// report so the evidence names exactly which binary held. +func kzHoldBin(t *testing.T, rep *kzReport) string { + t.Helper() + p := os.Getenv("KZ_HOLD_BIN") + if p == "" { + t.Fatal("step 5 needs KZ_HOLD_BIN (a blockvolume built with -tags kzhold)") + } + b, err := os.ReadFile(p) + if err != nil { + t.Fatalf("KZ_HOLD_BIN: %v", err) + } + sum := sha256.Sum256(b) + rep.HoldBin = p + " sha256:" + hex.EncodeToString(sum[:]) + return p +} + +// kzCrashFirstStart is step 5: +// the first start of a fresh volume runs the kzhold test binary, which holds +// at the boundary before the fresh marker is retired; the test requires the +// .chunkfresh marker present there, then SIGKILLs it. More than one try fails +// the step. Then restart that volume and +// repeat steps 1-2: nothing certified known-zero (KnownZeroChunks 0, no +// fresh-attach line), the first cut scans every chunk once, the next cut only +// the touched ones, and the written blocks read back exactly. +func kzCrashFirstStart(t *testing.T, env *handoffEnv, rep *kzReport, bytes uint64, run string) kzCrashRecord { + t.Helper() + var r kzCrashRecord + total := int((bytes + kzChunkBytes - 1) / kzChunkBytes) + var b bvHost + for i := 1; i <= kzCrashTries; i++ { + b = env.hosts[fmt.Sprintf("kzc%d", i)] + nqn := fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume) + env.volExtra = []string{"--durable-blocks", fmt.Sprint(bytes / 4096), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off", "--nvme-subsysnqn", nqn} + // Deterministic, with no hook in a release binary: the + // first start runs KZ_HOLD_BIN, a blockvolume built with the kzhold tag + // (test-only, never released), which holds at the provider's existing + // boundary after presence and before the fresh marker is retired (the + // attach commit) and writes /reached there. The release stays + // absent: the process is killed while held. + holdDir := filepath.Join(env.h.dir, "kzhold-"+b.id) + if err := os.MkdirAll(holdDir, 0o755); err != nil { + t.Fatal(err) + } + reached := filepath.Join(holdDir, "reached") + os.Setenv("SWBLOCK_KZHOLD_DIR", holdDir) + d := env.h.start(t, "blockvolume-"+b.id+"-first", kzHoldBin(t, rep), env.volArgsFor(b)...) + os.Unsetenv("SWBLOCK_KZHOLD_DIR") + end := time.Now().Add(120 * time.Second) + for { + if _, err := os.Stat(reached); err == nil { + break + } + select { + case <-d.done: + t.Fatalf("%s exited before the hold was reached: %v", b.id, d.err) + case <-time.After(20 * time.Millisecond): + } + if time.Now().After(end) { + t.Fatalf("%s never reached the hold (%s)", b.id, reached) + } + } + if !d.has("TEST-ONLY build (kzhold)") { + t.Fatalf("%s: the first start is not the kzhold build", b.id) + } + if err := d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("SIGSTOP %s: %v", b.id, err) + } + markers, _ := filepath.Glob(filepath.Join(b.root, "*.chunkfresh")) + more, _ := filepath.Glob(b.root + "*.chunkfresh") + markers = append(markers, more...) + d.kill(t) + try := kzCrashTry{Volume: b.volume, Markers: markers, Before: len(markers) > 0} + r.Tries = append(r.Tries, try) + if try.Before { + break + } + } + last := r.Tries[len(r.Tries)-1] + if !last.Before { + rep.step(t, 5, "kzc", false, fmt.Sprintf("no try stopped before the attach commit in %d tries (marker always gone)", len(r.Tries))) + return r + } + r.Volume = b.volume + nqn := fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume) + d, refusal := headSzStartVolume(t, env, b, bytes, "--nvme-subsysnqn", nqn) + if d == nil { + rep.step(t, 5, b.volume, false, "restart refused: "+refusal) + return r + } + defer d.term(t, 60*time.Second) + r.FreshLine = strings.TrimSpace(d.line("known-zero")) + cfg := headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + b.volume + "-s"} + r.S0 = kzCut(t, env, cfg, b, 0, total) + _, blocks := kzUserSpaceFiles(t, b, nqn, bytes) + r.Dirty1 = kzReadStats(t, b).DirtyChunks + r.S1 = kzCut(t, env, cfg, b, 1, total) + c := dialNVMe(t, b.nvme, nqn) + for lba, want := range blocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + r.Blocks++ + if string(c.read(t, lba, 4096)) == string(want) { + r.Equal++ + } + } + c.close() + s0, s1 := kzLC(r.S0.Stats), kzLC(r.S1.Stats) + // the stop is deterministic (the kzhold hold), so an acceptance run must catch the marker on the FIRST try + ok := len(r.Tries) == 1 && r.S0.Completed && r.S1.Completed && r.S0.Stats.KnownZeroChunks == 0 && r.FreshLine == "" && + s0.CandidateChunks == total && s1.CandidateChunks <= r.Dirty1 && r.Equal == r.Blocks && r.Blocks > 0 + rep.step(t, 5, b.volume, ok, fmt.Sprintf("tries=%d marker_at_stop=%v known_zero=%d fresh_line=%t s0_candidates=%d/%d s0_uploaded=%d s1_candidates=%d (dirtied %d) blocks_equal=%d/%d", + len(r.Tries), last.Markers, r.S0.Stats.KnownZeroChunks, r.FreshLine != "", s0.CandidateChunks, total, s0.UploadedChunks, s1.CandidateChunks, r.Dirty1, r.Equal, r.Blocks)) + return r +} + +func (r *kzReport) step(t *testing.T, n int, vol string, pass bool, why string) { + t.Helper() + v := "FAIL" + if pass { + v = "PASS" + } + l := fmt.Sprintf("KZ STEP %d %s %s %s", n, v, vol, why) + r.Lines = append(r.Lines, l) + t.Log(l) + if !pass { + t.Error(l) + } +} + +func (r *kzReport) write(t *testing.T) { + if p := os.Getenv("KZ_REPORT"); p != "" { + b, _ := json.MarshalIndent(r, "", " ") + if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil { + t.Errorf("KZ_REPORT: %v", err) + } + } +} + +type kzVolume struct { + Volume string `json:"volume"` + FS string `json:"fs"` + NQN string `json:"nqn"` + Identity string `json:"device_identity,omitempty"` + Fresh string `json:"fresh_attach_line"` + S0 kzCutRecord `json:"s0"` + Dirty1 int `json:"dirty_chunks_before_s1"` + Discard string `json:"discard,omitempty"` + S1 kzCutRecord `json:"s1"` + Files map[string]string `json:"files_sha256,omitempty"` + S1Name string `json:"s1_name"` + Blocks map[uint64][]byte `json:"-"` +} + +type kzCutRecord struct { + Cut headSzCut `json:"cut"` + Stats kzStats `json:"stats_after"` + Total int `json:"total_chunks"` + WallMs float64 `json:"wall_ms"` + Completed bool `json:"completed"` +} + +func kzReadStats(t *testing.T, b bvHost) kzStats { + t.Helper() + var c struct{ Stats kzStats } + raw := headSzChunkStatus(t, b) + if raw == nil { + t.Fatalf("%s: durable status has no chunk section", b.volume) + } + if err := json.Unmarshal(raw, &c); err != nil { + t.Fatalf("%s: chunk status: %v", b.volume, err) + } + return c.Stats +} + +const kzChunkBytes = 4 << 20 + +func kzSource(t *testing.T, env *handoffEnv, rep *kzReport, b bvHost, fs string, bytes uint64, device bool, run string) kzVolume { + t.Helper() + total := int((bytes + kzChunkBytes - 1) / kzChunkBytes) + v := kzVolume{Volume: b.volume, FS: fs, NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume)} + d, refusal := headSzStartVolume(t, env, b, bytes, "--nvme-subsysnqn", v.NQN) + if d == nil { + rep.step(t, 1, b.volume, false, "volume refused: "+refusal) + return v + } + defer d.term(t, 60*time.Second) + v.Fresh = strings.TrimSpace(d.line("known-zero")) + + // (1) empty S0 + cfg := headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + b.volume + "-s"} + v.S0 = kzCut(t, env, cfg, b, 0, total) + st := v.S0.Stats + ok1, why1 := kzStep1Pass(st, v.S0.Completed, v.S0.Cut.HeadSegments, total, v.Fresh != "") + rep.step(t, 1, b.volume, ok1, fmt.Sprintf("%s s0 completed=%v wall_ms=%.0f candidates=%d staged=%d uploaded_chunks=%d head_segments=%d head_bytes=%d known_zero=%d/%d fresh_line=%t", + why1, v.S0.Completed, v.S0.WallMs, kzLC(st).CandidateChunks, kzLC(st).StagedChunks, kzLC(st).UploadedChunks, v.S0.Cut.HeadSegments, v.S0.Cut.HeadBytes, st.KnownZeroChunks, total, v.Fresh != "")) + + // (2) mkfs + files + S1 + if device { + var first map[string]uint64 + v.Identity, v.Discard, v.Files, first = kzDeviceFiles(t, b, v.NQN, fs, run) + v.Blocks = kzDeviceWitnesses(t, b, v.NQN, first) + } else { + v.Files, v.Blocks = kzUserSpaceFiles(t, b, v.NQN, bytes) + } + v.Dirty1 = kzReadStats(t, b).DirtyChunks + v.S1 = kzCut(t, env, cfg, b, 1, total) + v.S1Name = cfg.name + "-1" + st = v.S1.Stats + touched := v.Dirty1 + ok2 := v.S1.Completed && st.LastCut != nil && touched > 0 && st.LastCut.CandidateChunks <= touched && + st.LastCut.StagedChunks <= touched && st.LastCut.UploadedBytes <= int64(touched)*kzChunkBytes && len(v.Files) > 0 && + len(v.Blocks) == len(v.Files) // one block witness per written file or block, for step 4 + rep.step(t, 2, b.volume, ok2, fmt.Sprintf("s1 completed=%v wall_ms=%.0f dirtied=%d candidates=%d staged=%d uploaded_bytes=%d head_bytes=%d files=%d discard=%q", + v.S1.Completed, v.S1.WallMs, touched, kzLC(st).CandidateChunks, kzLC(st).StagedChunks, kzLC(st).UploadedBytes, v.S1.Cut.HeadBytes, len(v.Files), v.Discard)) + return v +} + +// kzLC returns the last cut or a zero value, for printing only. +func kzLC(s kzStats) struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 +} { + if s.LastCut == nil { + return struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + }{} + } + return *s.LastCut +} + +func kzCut(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, n, total int) kzCutRecord { + t.Helper() + start := time.Now() + c := headSzCutOnce(t, env, cfg, b, n, 0) + return kzCutRecord{Cut: c, Stats: kzReadStats(t, b), Total: total, WallMs: ms(time.Since(start)), Completed: c.Completed} +} + +// kzUserSpaceFiles writes three known 4 KiB blocks (the first, middle and last +// block of the volume, so three different chunks) through the user-space +// client and flushes (smoke only: no file system). +func kzUserSpaceFiles(t *testing.T, b bvHost, nqn string, bytes uint64) (map[string]string, map[uint64][]byte) { + t.Helper() + c := dialNVMe(t, b.nvme, nqn) + out, blocks := map[string]string{}, map[uint64][]byte{} + last := bytes/4096 - 1 + for i, lba := range []uint64{0, last / 2, last} { + blk := f1Block(b.id, 0, "kz", lba) + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.write(t, lba, blk) + blocks[lba] = blk + sum := sha256.Sum256(blk) + out[fmt.Sprintf("block-%d", i)] = hex.EncodeToString(sum[:]) + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.flush(t) + return out, blocks +} + +// kzDeviceFiles connects this run's NQN through the kernel, resolves the +// device by NQN, formats it, writes files with known sha256, syncs, unmounts +// and disconnects. It returns the identity line, whether mkfs sent a discard, +// the files' sha256 and each file's first device block (FIEMAP, 4 KiB blocks). +func kzDeviceFiles(t *testing.T, b bvHost, nqn, fs, run string) (string, string, map[string]string, map[string]uint64) { + t.Helper() + host, port := kzSplit(t, b.nvme) + kzSudo(t, "nvme", "connect", "-t", "tcp", "-n", nqn, "-a", host, "-s", port) + defer kzSudo(t, "nvme", "disconnect", "-n", nqn) + var dev kzDevice + dev = kzWaitDevice(t, nqn) + t.Log(dev.Identity()) + mkfs := map[string][]string{"ext4": {"mkfs.ext4", "-F", "-v"}, "xfs": {"mkfs.xfs", "-f"}}[fs] + if mkfs == nil { + t.Fatalf("KZ_FS %q: want ext4 or xfs", fs) + } + out := kzSudo(t, append(mkfs, dev.Path)...) + discard := "no" + if strings.Contains(strings.ToLower(out), "discard") { + discard = "yes: " + kzFirstLine(out, "iscard") + } + mnt := filepath.Join(os.TempDir(), "kz-"+run, b.volume) + if err := os.MkdirAll(mnt, 0o755); err != nil { + t.Fatal(err) + } + kzSudo(t, "mount", dev.Path, mnt) + files, first := map[string]string{}, map[string]uint64{} + func() { + defer kzSudo(t, "umount", mnt) + if bs := strings.TrimSpace(kzSudo(t, "stat", "-f", "-c", "%S", mnt)); bs != "4096" { + t.Fatalf("%s: file-system block size %s, the witness mapping needs 4096", mnt, bs) + } + for i := 0; i < 4; i++ { + name := fmt.Sprintf("kz-%d.bin", i) + data := make([]byte, (i+1)*64*1024) + for j := range data { + data[j] = byte(i*31 + j%251) + } + kzSudoWrite(t, filepath.Join(mnt, name), data) + sum := sha256.Sum256(data) + files[name] = hex.EncodeToString(sum[:]) + } + kzSudo(t, "sync") + for name := range files { + pb, err := kzFirstPhysical(kzSudo(t, "filefrag", "-e", filepath.Join(mnt, name))) + if err != nil { + t.Fatalf("filefrag %s: %v", name, err) + } + first[name] = pb + } + }() + return dev.Identity(), discard, files, first +} + +// kzDeviceWitnesses reads, through the user-space client after the kernel +// disconnected, the first block of every file and requires it to be that +// file's first 4 KiB as written: the block witnesses step 4 reads on the +// targets before hydration. +func kzDeviceWitnesses(t *testing.T, b bvHost, nqn string, first map[string]uint64) map[uint64][]byte { + t.Helper() + c := dialNVMe(t, b.nvme, nqn) + defer c.close() + out := map[uint64][]byte{} + for name, lba := range first { + var i int + if _, err := fmt.Sscanf(name, "kz-%d.bin", &i); err != nil { + t.Fatalf("file %q: %v", name, err) + } + want := make([]byte, 4096) + for j := range want { + want[j] = byte(i*31 + j%251) + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + got := c.read(t, lba, 4096) + if string(got) != string(want) { + t.Fatalf("%s: device block %d is not the file's first 4 KiB (the witness mapping is wrong)", name, lba) + } + out[lba] = got + } + return out +} + +func kzSudo(t *testing.T, args ...string) string { + t.Helper() + out, err := exec.Command("sudo", append([]string{"-n"}, args...)...).CombinedOutput() + if err != nil { + t.Fatalf("sudo %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) + } + return string(out) +} + +func kzSudoWrite(t *testing.T, path string, data []byte) { + t.Helper() + c := exec.Command("sudo", "-n", "tee", path) + c.Stdin = strings.NewReader(string(data)) + out, err := c.CombinedOutput() + sum := sha256.Sum256(data) + back := "" + if err == nil { + if f := strings.Fields(kzSudo(t, "sha256sum", path)); len(f) > 0 { + back = f[0] + } + } + if err := kzCheckWrite(out, err, hex.EncodeToString(sum[:]), back); err != nil { + t.Fatalf("%s: %v", path, err) + } +} + +func kzSplit(t *testing.T, addr string) (string, string) { + t.Helper() + i := strings.LastIndex(addr, ":") + if i < 0 { + t.Fatalf("address %q has no port", addr) + } + return addr[:i], addr[i+1:] +} + +func kzFirstLine(s, sub string) string { + for _, l := range strings.Split(s, "\n") { + if strings.Contains(l, sub) { + return strings.TrimSpace(l) + } + } + return "" +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_checks_test.go b/seaweed-block/cmd/blockvolume/known_zero_checks_test.go new file mode 100644 index 0000000000..2541ec9972 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_checks_test.go @@ -0,0 +1,176 @@ +package main_test + +import ( + "errors" + "fmt" + "net" + "regexp" + "strconv" + "strings" + "testing" +) + +// kzStats is the part of the chunk layer's durable status the KNOWN-ZERO +// acceptance test reads. +type kzStats struct { + DirtyChunks int + StagedChunks uint64 + KnownZeroChunks uint64 + AbsentChunks int + Hydration struct{ WaitCalls, Fetches, Completed, FetchErrors uint64 } + LastCut *struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + } +} + +// kzStep1Pass is step 1's verdict: the empty first snapshot completed, +// considered no chunk, staged and uploaded nothing, HEAD names no segment, and +// the fresh attach certified EVERY chunk known-zero (a partial certification +// means the first cut scanned the rest). +func kzStep1Pass(s kzStats, completed bool, headSegments, total int, freshLine bool) (bool, string) { + switch { + case !completed: + return false, "s0 did not complete" + case s.LastCut == nil: + return false, "no last cut" + case s.LastCut.CandidateChunks != 0: + return false, fmt.Sprintf("s0 considered %d chunks (want 0: no scan)", s.LastCut.CandidateChunks) + case s.LastCut.StagedChunks != 0 || s.LastCut.UploadedChunks != 0: + return false, "s0 staged or uploaded chunks" + case headSegments != 0: + return false, fmt.Sprintf("HEAD names %d segments", headSegments) + case s.KnownZeroChunks != uint64(total): + return false, fmt.Sprintf("known-zero %d of %d chunks (want all)", s.KnownZeroChunks, total) + case !freshLine: + return false, "no fresh-attach line" + } + return true, "" +} + +// kzCheckWrite: a file write is good only when the writer exited 0 (any +// error fails, also one that came with output, as tee prints the data it was +// given) and the file read back has the sha256 of what was written. +func kzCheckWrite(out []byte, err error, want, readBack string) error { + if err != nil { + return fmt.Errorf("write failed: %v (%d bytes of output)", err, len(out)) + } + if readBack != want { + return fmt.Errorf("read back sha256 %s, wrote %s", readBack, want) + } + return nil +} + +var kzExtentRE = regexp.MustCompile(`^\s*\d+:\s+\d+\.\.\s*\d+:\s+(\d+)\.\.\s*\d+:\s+\d+:`) + +// kzFirstPhysical parses `filefrag -e FILE` and returns the physical start +// (in file-system blocks) of the file's first extent: where its first block +// lives on the device. ext4 and XFS print the same table. +func kzFirstPhysical(out string) (uint64, error) { + for _, l := range strings.Split(out, "\n") { + if m := kzExtentRE.FindStringSubmatch(l); m != nil { + return strconv.ParseUint(m[1], 10, 64) + } + } + return 0, errors.New("no extent in filefrag output") +} + +// kzReserve marks the ports of addrs used, refusing one already taken: the +// target role reserves the data and ctrl ports the source's cluster spec +// names for it before it picks its own local ports. +func kzReserve(used map[int]bool, addrs ...string) error { + for _, a := range addrs { + _, p, err := net.SplitHostPort(a) + if err != nil { + return fmt.Errorf("address %q: %v", a, err) + } + n, err := strconv.Atoi(p) + if err != nil { + return fmt.Errorf("address %q: %v", a, err) + } + if used[n] { + return fmt.Errorf("port %d of %q is already taken", n, a) + } + used[n] = true + } + return nil +} + +func TestKnownZeroStep1Verdict(t *testing.T) { + lc := func(cand, staged, up int) *struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + } { + return &struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + }{CandidateChunks: cand, StagedChunks: staged, UploadedChunks: up} + } + cases := []struct { + name string + s kzStats + segs int + fresh bool + want bool + }{ + {"all-certified", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, 0, true, true}, + {"partial-certification", kzStats{KnownZeroChunks: 1, LastCut: lc(255, 0, 0)}, 0, true, false}, + {"partial-certification-no-candidates-shown", kzStats{KnownZeroChunks: 255, LastCut: lc(0, 0, 0)}, 0, true, false}, + {"full-zero-scan", kzStats{KnownZeroChunks: 0, LastCut: lc(256, 0, 0)}, 0, true, false}, + {"all-certified-but-scanned", kzStats{KnownZeroChunks: 256, LastCut: lc(3, 0, 0)}, 0, true, false}, + {"uploaded", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 1)}, 0, true, false}, + {"head-names-a-segment", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, 1, true, false}, + {"no-fresh-line", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, 0, false, false}, + {"no-last-cut", kzStats{KnownZeroChunks: 256}, 0, true, false}, + } + for _, c := range cases { + if got, why := kzStep1Pass(c.s, true, c.segs, 256, c.fresh); got != c.want { + t.Errorf("%s: got %v (%s), want %v", c.name, got, why, c.want) + } + } + if ok, _ := kzStep1Pass(kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, false, 0, 256, true); ok { + t.Error("an incomplete s0 passed") + } +} + +func TestKnownZeroWriteCheck(t *testing.T) { + if err := kzCheckWrite([]byte("data"), nil, "aa", "aa"); err != nil { + t.Errorf("good write refused: %v", err) + } + if err := kzCheckWrite([]byte("data echoed by tee"), errors.New("exit status 1"), "aa", "aa"); err == nil { + t.Error("a failed write that produced output passed") + } + if err := kzCheckWrite(nil, nil, "aa", "bb"); err == nil { + t.Error("a short or wrong file (read-back sha256 differs) passed") + } +} + +func TestKnownZeroFirstPhysical(t *testing.T) { + ext4 := "Filesystem type is: ef53\nFile size of /m/kz-0.bin is 65536 (16 blocks of 4096 bytes)\n ext: logical_offset: physical_offset: length: expected: flags:\n 0: 0.. 15: 34816.. 34831: 16: last,eof\n/m/kz-0.bin: 1 extent found\n" + xfs := "Filesystem type is: 58465342\nFile size of /m/kz-1.bin is 131072 (32 blocks of 4096 bytes)\n ext: logical_offset: physical_offset: length: expected: flags:\n 0: 0.. 31: 24.. 55: 32: last,eof\n/m/kz-1.bin: 1 extent found\n" + for name, c := range map[string]struct { + out string + want uint64 + }{"ext4": {ext4, 34816}, "xfs": {xfs, 24}} { + got, err := kzFirstPhysical(c.out) + if err != nil || got != c.want { + t.Errorf("%s: got %d %v, want %d", name, got, err, c.want) + } + } + if _, err := kzFirstPhysical("Filesystem type is: ef53\n/m/x: 0 extents found\n"); err == nil { + t.Error("an empty file (no extent) gave a block") + } +} + +func TestKnownZeroImportedPortReservation(t *testing.T) { + used := map[int]bool{} + if err := kzReserve(used, "10.0.0.2:12001", "10.0.0.2:12002"); err != nil { + t.Fatalf("fresh ports refused: %v", err) + } + if err := kzReserve(used, "10.0.0.2:12002"); err == nil { + t.Error("a port collision with an imported address passed") + } + if err := kzReserve(used, "no-port"); err == nil { + t.Error("an address without a port passed") + } +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_device_test.go b/seaweed-block/cmd/blockvolume/known_zero_device_test.go new file mode 100644 index 0000000000..4502a30ce0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_device_test.go @@ -0,0 +1,224 @@ +package main_test + +import ( + "fmt" + "io/fs" + "path" + "regexp" + "sort" + "strings" + "testing" + "testing/fstest" +) + +// kzDevice is the only way the KNOWN-ZERO acceptance test gets a block +// device path. It reads sysfs (the same source the CSI node uses) and returns +// /dev/ only when exactly one subsystem has subsysnqn == nqn (string +// equality, never a prefix), it has exactly one controller with transport tcp +// (and serial == serial when serial is not empty), and exactly one namespace. +// mkfs and mount take its result; a path given by name alone is never +// formatted. +type kzDevice struct { + Path, Ctrl, NQN, Serial string +} + +// Identity is the evidence line recorded before any mkfs. +func (d kzDevice) Identity() string { + s := d.Serial + if s == "" { + s = "-" + } + return fmt.Sprintf("DEVICE-IDENTITY nqn=%s serial=%s ctrl=%s transport=tcp namespace=%s match=exact", d.NQN, s, d.Ctrl, d.Path) +} + +var ( + kzCtrlName = regexp.MustCompile(`^nvme[0-9]+$`) + kzNSName = regexp.MustCompile(`^nvme[0-9]+n[0-9]+$`) +) + +// kzRead and kzNames return every read error: an unreadable entry is not +// an empty one, so a partial inventory can never look like exactly one device. +func kzRead(sys fs.FS, p string) (string, error) { + b, err := fs.ReadFile(sys, p) + if err != nil { + return "", fmt.Errorf("refused: incomplete sysfs inventory: %v", err) + } + return strings.TrimSpace(string(b)), nil +} + +func kzNames(sys fs.FS, dir string, re *regexp.Regexp) ([]string, error) { + ents, err := fs.ReadDir(sys, dir) + if err != nil { + return nil, fmt.Errorf("refused: incomplete sysfs inventory: %v", err) + } + var out []string + for _, e := range ents { + if re.MatchString(e.Name()) { + out = append(out, e.Name()) + } + } + return out, nil +} + +// kzResolve reads a sysfs class tree (/sys/class): nvme-subsystem/*/subsysnqn +// names the subsystem, its nvmeN entries are its controllers, and namespaces +// are nvmeXnY entries under the subsystem (native multipath) or under the +// controller (nvme//), whichever the kernel uses. +func kzResolve(sys fs.FS, nqn, serial string) (kzDevice, error) { + if !strings.HasPrefix(nqn, "nqn.") { + return kzDevice{}, fmt.Errorf("refused: %q is not an NQN (a device path is never accepted)", nqn) + } + // discovery lists the class directory itself (fs.Glob drops directory + // errors) and reads every subsystem's NQN; any failure refuses + ents, err := fs.ReadDir(sys, "nvme-subsystem") + if err != nil { + return kzDevice{}, fmt.Errorf("refused: incomplete sysfs inventory: %v", err) + } + var subs, hits []string + for _, e := range ents { + d := path.Join("nvme-subsystem", e.Name()) + subs = append(subs, d) + got, err := kzRead(sys, d+"/subsysnqn") + if err != nil { + return kzDevice{}, err + } + if got == nqn { + hits = append(hits, d) + } + } + if len(hits) != 1 { + return kzDevice{}, fmt.Errorf("refused: %d subsystems with NQN == %s (want exactly 1; %d subsystems seen)", len(hits), nqn, len(subs)) + } + dir := hits[0] + ctrls, err := kzNames(sys, dir, kzCtrlName) + if err != nil { + return kzDevice{}, err + } + if len(ctrls) != 1 { + return kzDevice{}, fmt.Errorf("refused: subsystem %s has %d controllers %v (want exactly 1)", nqn, len(ctrls), ctrls) + } + c := ctrls[0] + tr, err := kzRead(sys, "nvme/"+c+"/transport") + if err != nil { + return kzDevice{}, err + } + if tr != "tcp" { + return kzDevice{}, fmt.Errorf("refused: controller %s transport %q (want tcp)", c, tr) + } + got, err := kzRead(sys, "nvme/"+c+"/serial") + if err != nil { + return kzDevice{}, err + } + if serial != "" && got != serial { + return kzDevice{}, fmt.Errorf("refused: controller %s serial %q != %q", c, got, serial) + } + set := map[string]bool{} + for _, d := range []string{dir, "nvme/" + c} { + names, err := kzNames(sys, d, kzNSName) + if err != nil { + return kzDevice{}, err + } + for _, n := range names { + set[n] = true + } + } + if len(set) != 1 { + ns := make([]string, 0, len(set)) + for n := range set { + ns = append(ns, n) + } + sort.Strings(ns) + return kzDevice{}, fmt.Errorf("refused: subsystem %s has %d namespaces %v (want exactly 1)", nqn, len(set), ns) + } + var dev string + for n := range set { + dev = "/dev/" + n + } + return kzDevice{Path: dev, Ctrl: c, NQN: nqn, Serial: serial}, nil +} + +// kzSub adds one subsystem to a fake /sys/class tree. nsUnderSub puts the +// namespaces under the subsystem (native multipath), otherwise under the +// controller. +func kzSub(m fstest.MapFS, idx int, nqn, ctrl, transport, serial string, nsUnderSub bool, ns ...string) { + d := fmt.Sprintf("nvme-subsystem/nvme-subsys%d", idx) + m[d+"/subsysnqn"] = &fstest.MapFile{Data: []byte(nqn + "\n")} + m[d+"/"+ctrl] = &fstest.MapFile{Mode: fs.ModeDir} + m["nvme/"+ctrl+"/transport"] = &fstest.MapFile{Data: []byte(transport + "\n")} + m["nvme/"+ctrl+"/serial"] = &fstest.MapFile{Data: []byte(serial + " \n")} + for _, n := range ns { + if nsUnderSub { + m[d+"/"+n] = &fstest.MapFile{Mode: fs.ModeDir} + } else { + m["nvme/"+ctrl+"/"+n] = &fstest.MapFile{Mode: fs.ModeDir} + } + } +} + +func kzTree(f ...func(fstest.MapFS)) fstest.MapFS { + m := fstest.MapFS{} + for _, x := range f { + x(m) + } + return m +} + +// TestKnownZeroDeviceResolver: each refusal is the only check that can refuse +// its case (a real local disk, a longer or shorter NQN, duplicates, two +// controllers, two namespaces, a wrong serial, a path instead of an NQN). +func TestKnownZeroDeviceResolver(t *testing.T) { + const ours = "nqn.2026-11.io.seaweedfs:kz-r1-v1" + real := func(m fstest.MapFS) { + kzSub(m, 0, "nqn.2014.08.org.nvmexpress:uuid:real-disk", "nvme0", "pcie", "S1", false, "nvme0n1") + } + one := func(ns bool) func(fstest.MapFS) { + return func(m fstest.MapFS) { kzSub(m, 1, ours, "nvme1", "tcp", "SWB1", ns, "nvme1n1") } + } + cases := []struct { + name, nqn, serial string + sys fstest.MapFS + want, refusal string + }{ + {"exact-single-match-ns-under-subsystem", ours, "", kzTree(real, one(true)), "/dev/nvme1n1", ""}, + {"exact-single-match-ns-under-controller", ours, "", kzTree(real, one(false)), "/dev/nvme1n1", ""}, + {"serial-match", ours, "SWB1", kzTree(real, one(true)), "/dev/nvme1n1", ""}, + {"absent", ours, "", kzTree(real), "", "0 subsystems"}, + {"duplicate", ours, "", kzTree(func(m fstest.MapFS) { + kzSub(m, 1, ours, "nvme1", "tcp", "A", true, "nvme1n1") + kzSub(m, 2, ours, "nvme2", "tcp", "B", true, "nvme2n1") + }), "", "2 subsystems"}, + {"longer-nqn-not-ours", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, ours+"-other", "nvme1", "tcp", "A", true, "nvme1n1") }), "", "0 subsystems"}, + {"shorter-nqn-not-ours", ours, "", kzTree(func(m fstest.MapFS) { + kzSub(m, 1, "nqn.2026-11.io.seaweedfs:kz-r1", "nvme1", "tcp", "A", true, "nvme1n1") + }), "", "0 subsystems"}, + {"pcie-real-disk", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 0, ours, "nvme0", "pcie", "A", true, "nvme0n1") }), "", `transport "pcie"`}, + {"two-controllers", ours, "", kzTree(one(true), func(m fstest.MapFS) { + m["nvme-subsystem/nvme-subsys1/nvme3"] = &fstest.MapFile{Mode: fs.ModeDir} + }), "", "2 controllers"}, + {"two-namespaces", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, ours, "nvme1", "tcp", "A", true, "nvme1n1", "nvme1n2") }), "", "2 namespaces"}, + {"no-namespace", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, ours, "nvme1", "tcp", "A", true) }), "", "0 namespaces"}, + {"wrong-serial", ours, "SWB9", kzTree(one(true)), "", `serial "SWB1" != "SWB9"`}, + {"literal-path", "/dev/nvme1n1", "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, "/dev/nvme1n1", "nvme1", "tcp", "A", true, "nvme1n1") }), "", "is not an NQN"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + d, err := kzResolve(c.sys, c.nqn, c.serial) + if c.refusal != "" { + if err == nil || !strings.Contains(err.Error(), c.refusal) { + t.Fatalf("want refusal containing %q, got path %q err %v", c.refusal, d.Path, err) + } + return + } + if err != nil || d.Path != c.want { + t.Fatalf("want %s, got %q err %v", c.want, d.Path, err) + } + }) + } + d, err := kzResolve(kzTree(one(true)), ours, "SWB1") + if err != nil { + t.Fatal(err) + } + if got, want := d.Identity(), "DEVICE-IDENTITY nqn="+ours+" serial=SWB1 ctrl=nvme1 transport=tcp namespace=/dev/nvme1n1 match=exact"; got != want { + t.Fatalf("identity line\n got %s\nwant %s", got, want) + } +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_partial_inventory_test.go b/seaweed-block/cmd/blockvolume/known_zero_partial_inventory_test.go new file mode 100644 index 0000000000..f73c01a6bf --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_partial_inventory_test.go @@ -0,0 +1,74 @@ +package main_test + +import ( + "io/fs" + "strings" + "testing" + "testing/fstest" +) + +type kzFaultFS struct { + tree fstest.MapFS + denyDir, denyFile string +} + +func (s kzFaultFS) Open(name string) (fs.File, error) { return s.tree.Open(name) } + +func (s kzFaultFS) ReadDir(name string) ([]fs.DirEntry, error) { + if name == s.denyDir { + return nil, fs.ErrPermission + } + return s.tree.ReadDir(name) +} + +func (s kzFaultFS) ReadFile(name string) ([]byte, error) { + if name == s.denyFile { + return nil, fs.ErrPermission + } + return s.tree.ReadFile(name) +} + +func TestKnownZeroPartialNamespaceInventoryMustRefuse(t *testing.T) { + const nqn = "nqn.2026-11.io.seaweedfs:kz-review" + m := kzTree(func(m fstest.MapFS) { + kzSub(m, 1, nqn, "nvme1", "tcp", "S1", true, "nvme1n1") + m["nvme/nvme1/nvme1n2"] = &fstest.MapFile{Mode: fs.ModeDir} + }) + if _, err := kzResolve(m, nqn, ""); err == nil || !strings.Contains(err.Error(), "2 namespaces") { + t.Fatalf("complete inventory control must refuse two namespaces: %v", err) + } + d, err := kzResolve(kzFaultFS{tree: m, denyDir: "nvme/nvme1"}, nqn, "") + if err == nil { + t.Fatalf("partial inventory accepted %s; unreadable controller namespace listing is not an empty listing", d.Path) + } +} + +func TestKnownZeroUnreadableMatchingSubsystemMustRefuse(t *testing.T) { + const nqn = "nqn.2026-11.io.seaweedfs:kz-review" + m := kzTree(func(m fstest.MapFS) { + kzSub(m, 1, nqn, "nvme1", "tcp", "S1", true, "nvme1n1") + kzSub(m, 2, nqn, "nvme2", "tcp", "S2", true, "nvme2n1") + }) + if _, err := kzResolve(m, nqn, ""); err == nil || !strings.Contains(err.Error(), "2 subsystems") { + t.Fatalf("complete inventory control must refuse two subsystems: %v", err) + } + d, err := kzResolve(kzFaultFS{tree: m, denyFile: "nvme-subsystem/nvme-subsys2/subsysnqn"}, nqn, "") + if err == nil { + t.Fatalf("partial inventory accepted %s; unreadable subsystem identity is not proof of no match", d.Path) + } +} + +func TestKnownZeroGlobSuppressedInventoryErrorMustRefuse(t *testing.T) { + const nqn = "nqn.2026-11.io.seaweedfs:kz-review" + m := kzTree(func(m fstest.MapFS) { + kzSub(m, 1, nqn, "nvme1", "tcp", "S1", true, "nvme1n1") + kzSub(m, 2, nqn, "nvme2", "tcp", "S2", true, "nvme2n1") + }) + if _, err := kzResolve(m, nqn, ""); err == nil || !strings.Contains(err.Error(), "2 subsystems") { + t.Fatalf("complete inventory control must refuse two subsystems: %v", err) + } + d, err := kzResolve(kzFaultFS{tree: m, denyDir: "nvme-subsystem/nvme-subsys2"}, nqn, "") + if err == nil { + t.Fatalf("partial discovery accepted %s; fs.Glob hid a directory error", d.Path) + } +} diff --git a/seaweed-block/cmd/blockvolume/kzhold_release_symbols_test.go b/seaweed-block/cmd/blockvolume/kzhold_release_symbols_test.go new file mode 100644 index 0000000000..a33e8d4fba --- /dev/null +++ b/seaweed-block/cmd/blockvolume/kzhold_release_symbols_test.go @@ -0,0 +1,38 @@ +package main_test + +import ( + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// TestKZHoldNeverInReleaseBuild: the kzhold hold (a test-only stop before the +// fresh marker is retired) exists only in a binary built with -tags kzhold. +// A normal build of blockvolume must contain no symbol of it; the kzhold build +// must (the positive control: a check that finds nothing in either build would +// prove nothing). +func TestKZHoldNeverInReleaseBuild(t *testing.T) { + dir := t.TempDir() + syms := func(name string, tags ...string) string { + t.Helper() + out := filepath.Join(dir, name) + args := append([]string{"build"}, tags...) + args = append(args, "-o", out, "github.com/seaweedfs/seaweed-block/cmd/blockvolume") + if b, err := exec.Command("go", args...).CombinedOutput(); err != nil { + t.Fatalf("go %s: %v\n%s", strings.Join(args, " "), err, b) + } + b, err := exec.Command("go", "tool", "nm", out).CombinedOutput() + if err != nil { + t.Fatalf("go tool nm %s: %v\n%s", out, err, b) + } + return string(b) + } + const hold = "HoldBeforeChunkFreshRetireForTest" + if s := syms("release"); strings.Contains(s, hold) || strings.Contains(strings.ToLower(s), "kzhold") { + t.Fatalf("a normal build of blockvolume contains the test-only kzhold hold") + } + if s := syms("kzhold", "-tags", "kzhold"); !strings.Contains(s, hold) { + t.Fatalf("the kzhold build lacks %s: this check would pass blindly", hold) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 3d549be97e..ec467d4a86 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -780,6 +780,9 @@ func runVolume(f flags, exits *processExit) int { err := geometryErr if err == nil { dp, err = durable.NewDurableProvider(cfg, h.ProjectionView()) + if err == nil { + applyBuildTagHold(dp) // a no-op except in a kzhold (test-only) build + } } if chunkErr != nil { err = chunkErr diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index dd4e1bed7d..f59ac9ef37 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -436,14 +436,14 @@ func handoffAddress(t *testing.T) string { if handoffPorts.used[p] { continue } - addr := fmt.Sprintf("127.0.0.1:%d", p) + addr := fmt.Sprintf("%s:%d", testListenHost(), p) if ln, err := net.Listen("tcp", addr); err == nil { ln.Close() handoffPorts.used[p] = true return addr } } - t.Fatal("no free loopback port below the ephemeral range") + t.Fatal("no free port below the ephemeral range on " + testListenHost()) return "" } diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go index 26e85326df..525a919f10 100644 --- a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go @@ -24,6 +24,17 @@ type w4WeedCluster struct { procs map[string]*w4WeedProc } +// testListenHost is the address the test harness binds and advertises for +// its weed cluster, blockmaster and blockvolume ports: 127.0.0.1 unless +// SWBLOCK_TEST_LISTEN_HOST names another (a lab run whose processes span two +// hosts). Unset, every test behaves exactly as before. +func testListenHost() string { + if h := os.Getenv("SWBLOCK_TEST_LISTEN_HOST"); h != "" { + return h + } + return "127.0.0.1" +} + func w4FreePortPair(t *testing.T, used map[int]bool) int { t.Helper() for i := 0; i < 200; i++ { @@ -33,7 +44,7 @@ func w4FreePortPair(t *testing.T, used map[int]bool) int { } ok := true for _, q := range []int{p, p + 10000} { - l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", q)) + l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), q)) if err != nil { ok = false break @@ -92,9 +103,9 @@ func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedClust used := map[int]bool{} mp, vp, fp := w4FreePortPair(t, used), w4FreePortPair(t, used), w4FreePortPair(t, used) c := &w4WeedCluster{ - master: fmt.Sprintf("127.0.0.1:%d", mp), - filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp), - filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000), + master: fmt.Sprintf("%s:%d", testListenHost(), mp), + filerHTTP: fmt.Sprintf("%s:%d", testListenHost(), fp), + filerGRPC: fmt.Sprintf("%s:%d", testListenHost(), fp+10000), dir: dir, weed: weed, } @@ -121,10 +132,10 @@ func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedClust t.Fatal(err) } } - 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") + run("master", "master", "-ip="+testListenHost(), 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, 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")) + run("volume", "volume", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax)) + run("filer", "filer", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f")) w4WaitTCP(t, c.filerGRPC, 30*time.Second) // Wait until an assign succeeds (volume registered, volumes growable). diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 3af952a2e1..6ebce13b42 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -2,6 +2,7 @@ package chunkstore import ( "context" + "errors" "go/ast" "go/parser" "go/token" @@ -12,6 +13,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -38,6 +40,7 @@ var headReaders = map[string]string{ "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", + "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", "core/frontend/chunkstore/volume_delete.go markHeadDeleting -> ReadHead": "zero HEAD: creates the deleting HEAD (probe DeleteVolume)", @@ -252,6 +255,15 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("AbortFork over an absent HEAD: %t %v; today it creates an aborted HEAD", claimed, err) } }) + t.Run("LayoutTransition", func(t *testing.T) { + st := &absentLayoutHead{} + if _, err := layout.RunBegin(ctx, st, layout.HolderID{Epoch: 1, Holder: "h"}, "s"); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("layout transition over an absent HEAD: %v; want ErrHeadAbsent", err) + } + if st.updates != 0 { + t.Fatalf("layout transition over an absent HEAD wrote %d times", st.updates) + } + }) t.Run("ForkReplay", func(t *testing.T) { f, b := headReaderForkFixture(t) c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) @@ -273,3 +285,15 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { } }) } + +// absentLayoutHead is a layout HEAD store whose HEAD is absent. +type absentLayoutHead struct{ updates int } + +func (a *absentLayoutHead) ReadHead(context.Context) (layout.Head, bool, error) { + return layout.Head{}, false, nil +} + +func (a *absentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) error { + a.updates++ + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/claim.go b/seaweed-block/core/frontend/chunkstore/layout/claim.go new file mode 100644 index 0000000000..2275e6e6a9 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/claim.go @@ -0,0 +1,60 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// ErrStaleEpoch: the caller's epoch is below HEAD's; a newer holder has +// claimed the volume. +var ErrStaleEpoch = errors.New("layout: epoch below HEAD's") + +// LeaseWait is the time premise of a claim: it returns nil only once the +// lease of every holder below epoch has ended, and an error otherwise. A +// claim calls it immediately before its HEAD update, every time. +type LeaseWait interface { + OldLeaseEnded(ctx context.Context, epoch uint64) error +} + +// Claim is transition 1 as a pure step on HEAD: a holder granted epoch e > +// HEAD's epoch takes HEAD (epoch = e, holder = me) and voids any open +// session or cleaning (activity idle); the image and the snapshots are +// unchanged. A HEAD already claimed by me at e is a replay. A HEAD at e +// held by another server is ErrNotHolder; one above e is ErrStaleEpoch. +func (h Head) Claim(me HolderID) (next Head, changed bool, err error) { + if me.Epoch == 0 || me.Holder == "" { + return Head{}, false, errors.New("layout: Claim needs an epoch and a holder") + } + switch { + case me.Epoch < h.Epoch: + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d, caller %d", ErrStaleEpoch, h.Epoch, me.Epoch) + case me.Epoch == h.Epoch && h.Holder == me.Holder: + return h, false, nil + case me.Epoch == h.Epoch: + return Head{}, false, fmt.Errorf("%w: epoch %d is held by %q", ErrNotHolder, h.Epoch, h.Holder) + } + next = h.clone() + next.Epoch, next.Holder = me.Epoch, me.Holder + next.Activity = Activity{Kind: ActIdle} + return next, true, nil +} + +// RunClaim reads HEAD, applies Claim, waits for the old lease's end (the +// check runs after the read and before the update), and commits by one +// conditional update. An absent HEAD refuses. +func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { + if lease == nil { + return Head{}, errors.New("layout: Claim needs a lease wait") + } + return runTransition(ctx, st, func(h Head) (Head, bool, error) { + next, changed, err := h.Claim(me) + if err != nil || !changed { + return next, changed, err + } + if err := lease.OldLeaseEnded(ctx, me.Epoch); err != nil { + return Head{}, false, fmt.Errorf("layout: claim at epoch %d: %w", me.Epoch, err) + } + return next, true, nil + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/claim_test.go b/seaweed-block/core/frontend/chunkstore/layout/claim_test.go new file mode 100644 index 0000000000..d3a6852710 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/claim_test.go @@ -0,0 +1,130 @@ +package layout + +import ( + "context" + "errors" + "testing" +) + +var newer = HolderID{Epoch: 4, Holder: "srv-b"} + +// fakeLease records its calls; ended says whether old leases are over. +type fakeLease struct { + ended bool + calls []uint64 + check func() // runs inside the call +} + +func (l *fakeLease) OldLeaseEnded(_ context.Context, epoch uint64) error { + l.calls = append(l.calls, epoch) + if l.check != nil { + l.check() + } + if !l.ended { + return errors.New("the previous holder's lease has not ended") + } + return nil +} + +func TestClaim_Closure(t *testing.T) { + for name, h := range map[string]Head{ + "idle": idleHead(), + "snap(s)": snapHead("s1"), + "clean(c)": {Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}}, + } { + next, changed, err := h.Claim(newer) + if err != nil || !changed || next.Epoch != 4 || next.Holder != "srv-b" || next.Activity != (Activity{Kind: ActIdle}) { + t.Fatalf("Claim over %s: %+v %t %v; want epoch 4, srv-b, idle", name, next, changed, err) + } + if (next.Current == nil) != (h.Current == nil) || next.Position != h.Position || len(next.Snapshots) != len(h.Snapshots) { + t.Fatalf("Claim over %s changed the image or snapshots: %+v", name, next) + } + if h.Epoch != 3 { + t.Fatal("Claim changed its receiver") + } + if again, changed, err := next.Claim(newer); err != nil || changed || again.Epoch != 4 { + t.Fatalf("Claim of a HEAD I hold at that epoch: %+v %t %v; want a replay", again, changed, err) + } + } + h := idleHead() + for name, tc := range map[string]struct { + me HolderID + want error + }{ + "older epoch": {HolderID{Epoch: 2, Holder: "srv-b"}, ErrStaleEpoch}, + "same epoch, another server": {HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + } { + if _, _, err := h.Claim(tc.me); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } + if _, _, err := h.Claim(HolderID{Epoch: 5}); err == nil { + t.Error("Claim without a holder accepted") + } +} + +// The lease wait runs after HEAD is read and before it is updated, on +// every claim that changes HEAD; a wait not yet over refuses and writes +// nothing. +func TestRunClaim_WaitsForTheOldLease(t *testing.T) { + ctx := context.Background() + h := snapHead("s1") + st := &memHead{h: &h} + lease := &fakeLease{} + if _, err := RunClaim(ctx, st, lease, newer); err == nil { + t.Fatal("claim before the old lease ended succeeded") + } + if st.updates != 0 || st.h.Epoch != 3 || len(lease.calls) != 1 || lease.calls[0] != 4 { + t.Fatalf("refused claim: updates %d, HEAD epoch %d, lease calls %v", st.updates, st.h.Epoch, lease.calls) + } + lease.ended = true + lease.check = func() { + if st.updates != 0 { + t.Error("the lease wait ran after the HEAD update") + } + } + got, err := RunClaim(ctx, st, lease, newer) + if err != nil || got.Epoch != 4 || st.h.Holder != "srv-b" || st.h.Activity.Kind != ActIdle { + t.Fatalf("claim: %+v %v", got, err) + } + if _, err := RunClaim(ctx, st, nil, newer); err == nil { + t.Fatal("claim without a lease wait accepted") + } + if _, err := RunClaim(ctx, &memHead{}, lease, newer); !errors.Is(err, ErrHeadAbsent) { + t.Fatalf("claim of an absent HEAD: %v; want ErrHeadAbsent, nothing created", err) + } +} + +// After a claim the old holder's open session is void: its commit and its +// abort are refused, and a new Begin needs the new epoch. +func TestRunClaim_VoidsTheOldSession(t *testing.T) { + ctx := context.Background() + f, h, req := commitFixture(t) + st := &memHead{h: &h} + if _, err := RunClaim(ctx, st, &fakeLease{ended: true}, newer); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotHolder) { + t.Fatalf("the old holder's commit after a claim: %v; want ErrNotHolder", err) + } + if _, err := RunAbort(ctx, st, me, "s1"); !errors.Is(err, ErrNotHolder) { + t.Fatalf("the old holder's abort after a claim: %v; want ErrNotHolder", err) + } + if _, err := RunBegin(ctx, st, me, "s9"); !errors.Is(err, ErrNotHolder) { + t.Fatalf("the old holder's begin after a claim: %v; want ErrNotHolder", err) + } + if got, err := RunBegin(ctx, st, newer, "t1"); err != nil || got.Activity.Session != "t1" { + t.Fatalf("the new holder's begin: %+v %v", got, err) + } +} + +func TestRunClaim_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, snapHead("s1"), func(st HeadStore) error { + _, err := RunClaim(context.Background(), st, &fakeLease{ended: true}, newer) + return err + }, func(t *testing.T, h Head) { + if h.Epoch != 4 || h.Holder != "srv-b" || h.Activity != (Activity{Kind: ActIdle}) || h.Position != 40 { + t.Fatalf("HEAD after Claim: %+v", h) + } + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/clean.go b/seaweed-block/core/frontend/chunkstore/layout/clean.go new file mode 100644 index 0000000000..ba292a9869 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/clean.go @@ -0,0 +1,61 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// BeginClean is transition 6: activity idle -> clean(session), by the +// holder at HEAD's epoch. While it is open no snapshot session can begin, +// so no name is removed while a snapshot is open. BeginClean of the +// cleaning already open is a replay; any other open activity is ErrBusy. +func (h Head) BeginClean(me HolderID, session string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: BeginClean needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + switch { + case h.Activity == Activity{Kind: ActClean, Session: session}: + return h, false, nil + case h.Activity.Kind != ActIdle: + return Head{}, false, fmt.Errorf("%w: %s(%s)", ErrBusy, h.Activity.Kind, h.Activity.Session) + } + next = h.clone() + next.Activity = Activity{Kind: ActClean, Session: session} + return next, true, nil +} + +// EndClean is transition 8: activity clean(session) -> idle, by the holder +// at HEAD's epoch. EndClean over idle succeeds and writes nothing: it means +// only that no activity remains (the cleaning ended, or never began). +// Another open session or cleaning is ErrNoSession. +func (h Head) EndClean(me HolderID, session string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: EndClean needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + switch { + case h.Activity.Kind == ActIdle: + return h, false, nil + case h.Activity != Activity{Kind: ActClean, Session: session}: + return Head{}, false, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) + } + next = h.clone() + next.Activity = Activity{Kind: ActIdle} + return next, true, nil +} + +// RunBeginClean applies BeginClean by one conditional update. +func RunBeginClean(ctx context.Context, st HeadStore, me HolderID, session string) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.BeginClean(me, session) }) +} + +// RunEndClean applies EndClean by one conditional update. +func RunEndClean(ctx context.Context, st HeadStore, me HolderID, session string) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.EndClean(me, session) }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/clean_test.go b/seaweed-block/core/frontend/chunkstore/layout/clean_test.go new file mode 100644 index 0000000000..598e04d7fc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/clean_test.go @@ -0,0 +1,134 @@ +package layout + +import ( + "context" + "errors" + "testing" +) + +func cleanHead(session string) Head { + h := snapHead("x") + h.Activity = Activity{Kind: ActClean, Session: session} + return h +} + +func TestBeginClean_Closure(t *testing.T) { + h := idleHead() + next, changed, err := h.BeginClean(me, "c1") + if err != nil || !changed || next.Activity != (Activity{Kind: ActClean, Session: "c1"}) { + t.Fatalf("BeginClean from idle: %+v %t %v", next, changed, err) + } + if again, changed, err := next.BeginClean(me, "c1"); err != nil || changed || again.Activity != next.Activity { + t.Fatalf("BeginClean of the open cleaning: %+v %t %v; want a replay", again, changed, err) + } + for name, tc := range map[string]struct { + h Head + me HolderID + want error + }{ + "snapshot open": {snapHead("s1"), me, ErrBusy}, + "other cleaning": {cleanHead("c2"), me, ErrBusy}, + "other epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, + "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + } { + if _, _, err := tc.h.BeginClean(tc.me, "c1"); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } + if _, _, err := h.BeginClean(me, ""); err == nil { + t.Error("BeginClean without a session id accepted") + } +} + +func TestEndClean_Closure(t *testing.T) { + h := cleanHead("c1") + next, changed, err := h.EndClean(me, "c1") + if err != nil || !changed || next.Activity != (Activity{Kind: ActIdle}) || next.Position != h.Position || len(next.Snapshots) != len(h.Snapshots) { + t.Fatalf("EndClean: %+v %t %v", next, changed, err) + } + if again, changed, err := next.EndClean(me, "c1"); err != nil || changed { + t.Fatalf("EndClean over idle: %+v %t %v; want a replay", again, changed, err) + } + for name, tc := range map[string]struct { + h Head + me HolderID + want error + }{ + "snapshot open": {snapHead("c1"), me, ErrNoSession}, + "other cleaning": {cleanHead("c2"), me, ErrNoSession}, + "other epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, + "same epoch, other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + } { + if _, _, err := tc.h.EndClean(tc.me, "c1"); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } +} + +// EndClean over idle succeeds and writes nothing whatever came before (a +// cleaning ended, or never begun): it means only that no activity remains. +func TestEndClean_IdleMeansNoActivityRemains(t *testing.T) { + for name, h := range map[string]Head{ + "never begun": idleHead(), + "already ended": func() Head { n, _, _ := cleanHead("c1").EndClean(me, "c1"); return n }(), + } { + next, changed, err := h.EndClean(me, "c1") + if err != nil || changed || next.Activity.Kind != ActIdle { + t.Errorf("EndClean over idle (%s): %+v %t %v; want unchanged, no error", name, next, changed, err) + } + } +} + +// A cleaning and a snapshot exclude each other: no snapshot begins while a +// cleaning is open, no cleaning begins while a snapshot is open; a claim +// voids an open cleaning. +func TestClean_ExcludesSnapshot(t *testing.T) { + ctx := context.Background() + h := idleHead() + st := &memHead{h: &h} + if _, err := RunBeginClean(ctx, st, me, "c1"); err != nil { + t.Fatal(err) + } + if _, err := RunBegin(ctx, st, me, "s1"); !errors.Is(err, ErrBusy) { + t.Fatalf("Begin during a cleaning: %v; want ErrBusy", err) + } + if _, err := RunEndClean(ctx, st, me, "c1"); err != nil { + t.Fatal(err) + } + if _, err := RunBegin(ctx, st, me, "s1"); err != nil { + t.Fatal(err) + } + if _, err := RunBeginClean(ctx, st, me, "c2"); !errors.Is(err, ErrBusy) { + t.Fatalf("BeginClean during a snapshot: %v; want ErrBusy", err) + } + c := cleanHead("c1") + st2 := &memHead{h: &c} + if _, err := RunClaim(ctx, st2, &fakeLease{ended: true}, newer); err != nil { + t.Fatal(err) + } + if _, err := RunEndClean(ctx, st2, me, "c1"); !errors.Is(err, ErrNotHolder) { + t.Fatalf("the old holder's EndClean after a claim: %v; want ErrNotHolder", err) + } +} + +func TestRunBeginClean_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, idleHead(), func(st HeadStore) error { + _, err := RunBeginClean(context.Background(), st, me, "c1") + return err + }, func(t *testing.T, h Head) { + if h.Activity != (Activity{Kind: ActClean, Session: "c1"}) { + t.Fatalf("HEAD after BeginClean: %+v", h.Activity) + } + }) +} + +func TestRunEndClean_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, cleanHead("c1"), func(st HeadStore) error { + _, err := RunEndClean(context.Background(), st, me, "c1") + return err + }, func(t *testing.T, h Head) { + if h.Activity != (Activity{Kind: ActIdle}) { + t.Fatalf("HEAD after EndClean: %+v", h.Activity) + } + }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go new file mode 100644 index 0000000000..3afbc378a1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -0,0 +1,167 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "sort" +) + +// Commit refusals. +var ( + // ErrNotPrepared: an object the new root reaches is not in the store + // yet (a chunk of this volume, a segment or the root itself). + ErrNotPrepared = errors.New("layout: commit names an object not written yet") + // ErrStaleBase: the previous manifest given is not HEAD's current + // root, so what is new cannot be told. + ErrStaleBase = errors.New("layout: previous manifest is not HEAD's current root") + // ErrSnapshotExists: the snapshot name is taken by another root. + ErrSnapshotExists = errors.New("layout: snapshot name taken") + // ErrTooManySnapshots: HEAD already holds MaxSnapshots. + ErrTooManySnapshots = errors.New("layout: snapshot limit reached") +) + +// CommitRequest is what a snapshot session commits: the image at +// Position, as a manifest, and optionally a snapshot name for it. Prev is +// the manifest of HEAD's current root that the session computed what is +// new against: empty when HEAD has no current root, and empty also when +// the current root is that of an empty image. +type CommitRequest struct { + Session string + Prev map[uint64]Ref + Next map[uint64]Ref + Position uint64 + Snapshot string // "" = no named snapshot +} + +// rootOf names the root of a manifest. +func rootOf(m map[uint64]Ref) (RootName, map[SegName][]byte, error) { + root, segs, err := Build(m) + if err != nil { + return RootName{}, nil, err + } + rn, _, err := NameRoot(root) + return rn, segs, err +} + +// newOwn returns the entries of next held in vol's pool whose name is not +// at the same index of prev: the only chunks a commit must look up (every +// name prev's root names is already in its owner's pool). +func newOwn(vol string, prev, next map[uint64]Ref) map[uint64]Ref { + out := map[uint64]Ref{} + for i, r := range next { + if r.Owner == vol && prev[i] != r { + out[i] = r + } + } + return out +} + +// Commit is transition 4 as a pure step on HEAD: for the holder at HEAD's +// epoch with snap(session) open, current = root, position, the optional +// snapshot added, activity idle. A HEAD that already shows this commit +// applied (idle, current = root, position, the snapshot) is a replay: +// unchanged, changed=false. +func (h Head) Commit(me HolderID, session string, root RootName, position uint64, snapshot string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: Commit needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + if h.Activity.Kind == ActIdle && h.Current != nil && *h.Current == root && h.Position == position { + if s, ok := h.Snapshots[snapshot]; snapshot == "" || ok && s.Root == root { + return h, false, nil + } + } + if h.Activity != (Activity{Kind: ActSnap, Session: session}) { + return Head{}, false, fmt.Errorf("%w: HEAD has %s(%s), not snap(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) + } + next = h.clone() + if snapshot != "" { + if s, ok := next.Snapshots[snapshot]; ok { + if s.Root != root { + return Head{}, false, fmt.Errorf("%w: %q", ErrSnapshotExists, snapshot) + } + } else { + if len(next.Snapshots) >= MaxSnapshots { + return Head{}, false, fmt.Errorf("%w: %d", ErrTooManySnapshots, MaxSnapshots) + } + if next.Snapshots == nil { + next.Snapshots = map[string]Snapshot{} + } + next.Snapshots[snapshot] = Snapshot{Root: root} + } + } + rn := root + next.Current = &rn + next.Position = position + next.Activity = Activity{Kind: ActIdle} + return next, true, nil +} + +// RunCommit checks that every object the new root reaches is written (the +// new chunks of this volume against HEAD's current root, every segment, +// the root), then commits by one conditional update. Prev must build to +// HEAD's current root; a re-run after a lost reply finds the commit +// applied and writes nothing. +func RunCommit(ctx context.Context, st HeadStore, look Lookup, volRoot, vol string, me HolderID, req CommitRequest) (Head, error) { + root, segs, err := rootOf(req.Next) + if err != nil { + return Head{}, err + } + return runTransition(ctx, st, func(h Head) (Head, bool, error) { + if next, changed, err := h.Commit(me, req.Session, root, req.Position, req.Snapshot); err != nil || !changed { + return next, changed, err // refused, or already applied: no lookups + } + // The base is HEAD's current root. Before any commit there is none + // and the previous manifest must be empty; after one (even of an + // empty image, which is a real root) the previous manifest must + // build to it. + if h.Current == nil { + if len(req.Prev) > 0 { + return Head{}, false, ErrStaleBase + } + } else { + base, _, err := rootOf(req.Prev) + if err != nil { + return Head{}, false, err + } + if base != *h.Current { + return Head{}, false, ErrStaleBase + } + } + missing, err := MissingOwn(ctx, look, volRoot, vol, newOwn(vol, req.Prev, req.Next)) + if err != nil { + return Head{}, false, err + } + if len(missing) > 0 { + return Head{}, false, fmt.Errorf("%w: %d chunks, first %s", ErrNotPrepared, len(missing), missing[0]) + } + names := make([]SegName, 0, len(segs)) + for n := range segs { + names = append(names, n) + } + sort.Slice(names, func(a, b int) bool { return names[a].Shard < names[b].Shard }) + for _, n := range names { + if err := present(ctx, look, volRoot, n.Path()); err != nil { + return Head{}, false, err + } + } + if err := present(ctx, look, volRoot, root.Path()); err != nil { + return Head{}, false, err + } + return h.Commit(me, req.Session, root, req.Position, req.Snapshot) + }) +} + +func present(ctx context.Context, look Lookup, volRoot, rel string) error { + ok, err := Present(ctx, look, volRoot, rel) + if err != nil { + return fmt.Errorf("layout: look up %s: %w", rel, err) + } + if !ok { + return fmt.Errorf("%w: %s", ErrNotPrepared, rel) + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go new file mode 100644 index 0000000000..5a2119b002 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -0,0 +1,268 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "strings" + "testing" +) + +const volRoot = "/swblock/chunks/v1" + +// prepared writes (in the fake store) every object a commit of next needs: +// next's own chunks, its segments and its root. +func prepared(t *testing.T, f *fakeStore, next map[uint64]Ref) RootName { + t.Helper() + root, segs, err := Build(next) + if err != nil { + t.Fatal(err) + } + for i, r := range next { + if r.Owner == "v1" { + f.have[path.Join(volRoot, next[i].Chunk.Path())] = true + } + } + for n := range segs { + f.have[path.Join(volRoot, n.Path())] = true + } + rn, _, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + f.have[path.Join(volRoot, rn.Path())] = true + return rn +} + +func manifest(entries ...Ref) map[uint64]Ref { + m := map[uint64]Ref{} + for _, r := range entries { + m[r.Chunk.Index] = r + } + return m +} + +func TestCommit_Closure(t *testing.T) { + rn := RootName{Hash: Sum([]byte("new"))} + h := snapHead("s1") + next, changed, err := h.Commit(me, "s1", rn, 50, "hourly") + if err != nil || !changed || next.Activity.Kind != ActIdle || *next.Current != rn || next.Position != 50 || next.Snapshots["hourly"].Root != rn { + t.Fatalf("Commit: %+v %t %v", next, changed, err) + } + if next.Snapshots["daily"].Dependents[0] != "t1" || len(next.Snapshots) != 2 { + t.Fatalf("Commit changed other snapshots: %+v", next.Snapshots) + } + if h.Activity.Kind != ActSnap || h.Snapshots["hourly"].Root == rn { + t.Fatal("Commit changed its receiver") + } + if again, changed, err := next.Commit(me, "s1", rn, 50, "hourly"); err != nil || changed || again.Gen != next.Gen { + t.Fatalf("Commit over its applied HEAD: %+v %t %v; want a replay", again, changed, err) + } + if n2, changed, err := h.Commit(me, "s1", rn, 50, ""); err != nil || !changed || len(n2.Snapshots) != 1 { + t.Fatalf("Commit without a snapshot name: %+v %t %v", n2, changed, err) + } + full := snapHead("s1") + for i := len(full.Snapshots); i < MaxSnapshots; i++ { + full.Snapshots[fmt.Sprintf("n%03d", i)] = Snapshot{Root: rn} + } + for name, tc := range map[string]struct { + h Head + me HolderID + snapshot string + want error + }{ + "idle": {idleHead(), me, "", ErrNoSession}, + "other session": {snapHead("s2"), me, "", ErrNoSession}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "s1"}}, me, "", ErrNoSession}, + "other epoch": {h, HolderID{Epoch: 2, Holder: "srv-a"}, "", ErrNotHolder}, + "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, "", ErrNotHolder}, + "name taken": {h, me, "daily", ErrSnapshotExists}, + "snapshot limit": {full, me, "one-more", ErrTooManySnapshots}, + } { + if _, _, err := tc.h.Commit(tc.me, "s1", rn, 50, tc.snapshot); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } +} + +// commitFixture: HEAD is snap(s1) at current root = prev's root; prev and +// next share chunk 0 (unchanged), next changes chunk 3, adds chunk 10004 +// and names chunk 7 of volume "src". +func commitFixture(t *testing.T) (*fakeStore, Head, CommitRequest) { + t.Helper() + f := &fakeStore{have: map[string]bool{}} + prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) + prevRoot := prepared(t, f, prev) + next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) + prepared(t, f, next) + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &prevRoot, Position: 40} + return f, h, CommitRequest{Session: "s1", Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} +} + +func runCommit(st HeadStore, f *fakeStore, req CommitRequest) (Head, error) { + return RunCommit(context.Background(), st, f.look, volRoot, "v1", me, req) +} + +func TestRunCommit_LooksUpOnlyWhatIsNew(t *testing.T) { + f, h, req := commitFixture(t) + st := &memHead{h: &h} + f.asked = nil + got, err := runCommit(st, f, req) + if err != nil || got.Activity.Kind != ActIdle || got.Position != 50 || st.h.Gen != 8 { + t.Fatalf("RunCommit: %+v %v", got, err) + } + wantRoot, _, _ := rootOf(req.Next) + if *st.h.Current != wantRoot || st.h.Snapshots["hourly"].Root != wantRoot { + t.Fatalf("HEAD current %v snapshot %v; want %v", st.h.Current, st.h.Snapshots["hourly"], wantRoot) + } + var pool []string + for _, p := range f.asked { + if strings.Contains(p, "/"+PoolDir+"/") { + pool = append(pool, path.Base(p)) + } + } + want := []string{req.Next[3].Chunk.String(), req.Next[10004].Chunk.String()} + if strings.Join(pool, ",") != strings.Join(want, ",") { + t.Fatalf("pool lookups %v; want only the new own chunks %v (not the unchanged chunk 0, not the foreign chunk 7)", pool, want) + } +} + +func TestRunCommit_RefusesUnwrittenObjects(t *testing.T) { + for _, what := range []string{"new chunk", "segment", "root"} { + t.Run(what, func(t *testing.T) { + f, h, req := commitFixture(t) + root, segs, _ := rootOf(req.Next) + var p string + switch what { + case "new chunk": + p = req.Next[10004].Chunk.Path() + case "segment": + for n := range segs { + if n.Shard == 1 { + p = n.Path() + } + } + case "root": + p = root.Path() + } + delete(f.have, path.Join(volRoot, p)) + st := &memHead{h: &h} + if _, err := runCommit(st, f, req); !errors.Is(err, ErrNotPrepared) { + t.Fatalf("commit with its %s missing: %v; want ErrNotPrepared", what, err) + } + if st.updates != 0 || st.h.Activity.Kind != ActSnap { + t.Fatalf("HEAD written by a refused commit: %+v", st.h) + } + }) + } +} + +func TestRunCommit_StaleBaseAndLookupFailure(t *testing.T) { + f, h, req := commitFixture(t) + stale := req + stale.Prev = manifest(ref("v1", 0, "a")) // not HEAD's current root + st := &memHead{h: &h} + if _, err := runCommit(st, f, stale); !errors.Is(err, ErrStaleBase) { + t.Fatalf("commit against another base: %v; want ErrStaleBase", err) + } + empty := req + empty.Prev = nil // HEAD has a current root, so "nothing before" is stale too + if _, err := runCommit(st, f, empty); !errors.Is(err, ErrStaleBase) { + t.Fatalf("commit with no base over a current root: %v; want ErrStaleBase", err) + } + f.fail = path.Join(volRoot, req.Next[3].Chunk.Path()) + if _, err := runCommit(st, f, req); err == nil || errors.Is(err, ErrNotPrepared) { + t.Fatalf("commit with a failing lookup: %v; want an error that is not a refusal", err) + } + if st.updates != 0 { + t.Fatal("HEAD written by a refused commit") + } + // The first commit of a volume: no current root, no previous manifest. + f2 := &fakeStore{have: map[string]bool{}} + next := manifest(ref("v1", 1, "x")) + prepared(t, f2, next) + h2 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}} + if got, err := runCommit(&memHead{h: &h2}, f2, CommitRequest{Session: "s1", Next: next, Position: 5}); err != nil || got.Current == nil { + t.Fatalf("first commit: %+v %v", got, err) + } +} + +func TestRunCommit_InterruptAtEveryStep(t *testing.T) { + f, h, req := commitFixture(t) + wantRoot, _, _ := rootOf(req.Next) + interruptHead(t, h, func(st HeadStore) error { + _, err := runCommit(st, f, req) + return err + }, func(t *testing.T, got Head) { + if got.Activity.Kind != ActIdle || got.Current == nil || *got.Current != wantRoot || got.Position != 50 || got.Snapshots["hourly"].Root != wantRoot { + t.Fatalf("HEAD after Commit: %+v", got) + } + }) +} + +// An empty image is a real root: after it is published, a commit whose +// previous manifest is empty builds on it (empty -> written, and empty -> +// empty); a previous manifest that is not HEAD's current root is still +// refused. +func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { + ctx := context.Background() + f := &fakeStore{have: map[string]bool{}} + prepared(t, f, nil) + h := idleHead() + st := &memHead{h: &h} + if _, err := RunBegin(ctx, st, me, "s0"); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, CommitRequest{Session: "s0", Snapshot: "empty"}); err != nil { + t.Fatal(err) + } + if st.h.Current == nil { + t.Fatal("the empty snapshot did not publish its root") + } + if _, err := RunBegin(ctx, st, me, "s1"); err != nil { + t.Fatal(err) + } + if _, err := runCommit(st, f, CommitRequest{Session: "s1", Prev: map[uint64]Ref{}, Position: 1}); err != nil { + t.Fatalf("empty -> empty: %v", err) + } + next := manifest(ref("v1", 1, "x")) + prepared(t, f, next) + if _, err := RunBegin(ctx, st, me, "s2"); err != nil { + t.Fatal(err) + } + stale := manifest(ref("v1", 9, "z")) + if _, err := runCommit(st, f, CommitRequest{Session: "s2", Prev: stale, Next: next, Position: 2}); !errors.Is(err, ErrStaleBase) { + t.Fatalf("a non-empty previous manifest over the empty root: %v; want ErrStaleBase", err) + } + if _, err := runCommit(st, f, CommitRequest{Session: "s2", Next: next, Position: 2, Snapshot: "written"}); err != nil { + t.Fatalf("empty -> written: %v", err) + } + if want, _, _ := rootOf(next); *st.h.Current != want { + t.Fatalf("HEAD current %s; want %s", st.h.Current, want) + } + // Before any commit there is no current root: a non-empty previous + // manifest is stale there too. + h0 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s9"}} + if _, err := runCommit(&memHead{h: &h0}, f, CommitRequest{Session: "s9", Prev: next, Next: next, Position: 3}); !errors.Is(err, ErrStaleBase) { + t.Fatalf("a previous manifest before any commit: %v; want ErrStaleBase", err) + } +} + +// Abort after the session committed succeeds without a write and leaves +// the commit in place: its success says only that no activity remains. +func TestAbort_AfterCommitLeavesTheCommit(t *testing.T) { + f, h, req := commitFixture(t) + st := &memHead{h: &h} + if _, err := runCommit(st, f, req); err != nil { + t.Fatal(err) + } + committed := *st.h.Current + before := st.updates + if _, err := RunAbort(context.Background(), st, me, "s1"); err != nil { + t.Fatalf("Abort after the commit: %v", err) + } + if st.updates != before || *st.h.Current != committed || st.h.Snapshots["hourly"].Root != committed { + t.Fatalf("Abort after the commit wrote or changed HEAD: %+v", st.h) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go new file mode 100644 index 0000000000..c80a292896 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -0,0 +1,252 @@ +package layout + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" +) + +// pkgLevel is the owner of a reference outside any function body: a +// package-level var or const initializer. +const pkgLevel = "" + +// refs maps every name used in the given sources (a selector's name, as in +// st.UpdateHead, called or not, or a plain identifier, as in runTransition) +// to the functions that use it: a method value, an alias, a call and a +// package-level initializer all count. Declarations are not uses: function +// and type names, interface method names and struct field names. +func refs(t *testing.T, srcs map[string]string) map[string]map[string]bool { + t.Helper() + out := map[string]map[string]bool{} + add := func(name, owner string) { + if out[name] == nil { + out[name] = map[string]bool{} + } + out[name][owner] = true + } + visit := func(n ast.Node, owner string) { + ast.Inspect(n, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + add(x.Sel.Name, owner) + ast.Inspect(x.X, func(n ast.Node) bool { + if id, ok := n.(*ast.Ident); ok { + add(id.Name, owner) + } + return true + }) + return false + case *ast.Ident: + add(x.Name, owner) + } + return true + }) + } + for name, src := range srcs { + file, err := parser.ParseFile(token.NewFileSet(), name, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + switch d := d.(type) { + case *ast.FuncDecl: + if d.Body == nil { + continue + } + owner := d.Name.Name + if d.Recv != nil && len(d.Recv.List) == 1 { + switch x := d.Recv.List[0].Type.(type) { + case *ast.Ident: + owner = x.Name + "." + owner + case *ast.StarExpr: + owner = x.X.(*ast.Ident).Name + "." + owner + } + } + visit(d.Body, owner) + case *ast.GenDecl: + for _, s := range d.Specs { + if v, ok := s.(*ast.ValueSpec); ok { + for _, e := range v.Values { + visit(e, pkgLevel) + } + } + } + } + } + } + return out +} + +func packageSources(t *testing.T, tests bool) map[string]string { + t.Helper() + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + out := map[string]string{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") != tests { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + out[f] = string(b) + } + return out +} + +func owners(m map[string]bool) []string { + var out []string + for o := range m { + out = append(out, o) + } + sort.Strings(out) + return out +} + +// guardFindings checks the package sources against the guard and returns +// every violation. +// +// - HEAD: UpdateHead is used only in runTransition (read, one pure step, +// one conditional update): no other call, method value, alias or +// package-level use. The store has no way to create a HEAD. +// - Transitions: runTransition is used only by exported Run functions, +// each with Test_Closure and TestRun_InterruptAtEveryStep. +// - Lease, claim half: OldLeaseEnded is used only in RunClaim, and +// RunClaim, when it is declared, uses it. +// - Every declared exported Run function goes through runTransition. +// - Pool: no name starting with Delete or Remove is used yet; the +// removal that comes with cleaning must bring its lease re-check and +// its own row here. +// +// These are syntactic checks of this package's own files: they see any +// use of these names, but not a store effect reached through a name they +// do not list (for example reflection or another package's helper). +func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) []string { + var bad []string + if got := owners(code["UpdateHead"]); !reflect.DeepEqual(got, []string{"runTransition"}) { + bad = append(bad, "UpdateHead used by "+strings.Join(got, ", ")+"; want only runTransition") + } + var runs []string + for _, fn := range owners(code["runTransition"]) { + x, ok := strings.CutPrefix(fn, "Run") + if !ok { + bad = append(bad, fn+" uses runTransition; transitions are exported Run functions") + continue + } + runs = append(runs, fn) + for _, want := range []string{"Test" + x + "_Closure", "TestRun" + x + "_InterruptAtEveryStep"} { + if !tests[want] { + bad = append(bad, "transition "+fn+" has no "+want) + } + } + } + if len(runs) == 0 { + bad = append(bad, "no transition uses runTransition: the scan is broken") + } + for _, fn := range owners(code["OldLeaseEnded"]) { + if fn != "RunClaim" { + bad = append(bad, fn+" uses OldLeaseEnded; only RunClaim claims") + } + } + if decl["RunClaim"] && !code["OldLeaseEnded"]["RunClaim"] { + bad = append(bad, "RunClaim is declared and does not wait for the old lease") + } + for fn := range decl { + if strings.HasPrefix(fn, "Run") && !code["runTransition"][fn] { + bad = append(bad, fn+" is declared and does not go through runTransition") + } + } + for name, by := range code { + if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { + bad = append(bad, strings.Join(owners(by), ", ")+" uses "+name+": a store remover needs its lease re-check and its own guard row") + } + } + sort.Strings(bad) + return bad +} + +// declared returns the names of the functions the sources declare. +func declared(t *testing.T, srcs map[string]string) map[string]bool { + t.Helper() + out := map[string]bool{} + for name, src := range srcs { + file, err := parser.ParseFile(token.NewFileSet(), name, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + if fn, ok := d.(*ast.FuncDecl); ok && fn.Recv == nil { + out[fn.Name.Name] = true + } + } + } + return out +} + +func TestGuard_WritersTransitionsAndRemovers(t *testing.T) { + src := packageSources(t, false) + code := refs(t, src) + tests := declared(t, packageSources(t, true)) + if bad := guardFindings(code, declared(t, src), tests); len(bad) != 0 { + t.Fatalf("guard: %s", strings.Join(bad, "\n")) + } + st := reflect.TypeOf((*HeadStore)(nil)).Elem() + var methods []string + for i := 0; i < st.NumMethod(); i++ { + methods = append(methods, st.Method(i).Name) + } + if !reflect.DeepEqual(methods, []string{"ReadHead", "UpdateHead"}) { + t.Fatalf("HeadStore methods %v; want ReadHead and UpdateHead only (no path creates a HEAD)", methods) + } +} + +// Negative controls: each form of an extra HEAD writer, transition or +// remover, added to the package's real sources, is refused; the real +// sources alone pass (the test above). +func TestGuard_Controls(t *testing.T) { + tests := declared(t, packageSources(t, true)) + // A control with a file name replaces that real file (a changed + // claim.go); otherwise it is added beside the real sources. + for name, c := range map[string]struct{ src, want, file string }{ + "direct call": {src: `func w(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, want: "UpdateHead used by"}, + "method value alias": {src: `func w(ctx context.Context, st HeadStore, h Head) error { + update := st.UpdateHead + return update(ctx, h.Gen, h) +}`, want: "UpdateHead used by"}, + "method expression": {src: `func w(ctx context.Context, st HeadStore, h Head) error { return HeadStore.UpdateHead(st, ctx, h.Gen, h) }`, want: "UpdateHead used by"}, + "package-level var": {src: `var w = HeadStore.UpdateHead`, want: "UpdateHead used by"}, + "package-level func lit": {src: `var w = func(ctx context.Context, st HeadStore, h Head) error { return st.UpdateHead(ctx, h.Gen, h) }`, want: "UpdateHead used by"}, + "inline interface": {src: `func w(st HeadStore) { var u interface{ UpdateHead(context.Context, uint64, Head) error } = st; _ = u }`, want: "UpdateHead used by"}, + "runTransition alias": {src: `func w(ctx context.Context, st HeadStore) { f := runTransition; _, _ = f(ctx, st, nil) }`, want: "uses runTransition; transitions are exported"}, + "untested transition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, want: "has no TestZz_Closure"}, + "lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"}, + "remover": {src: `type p interface{ DeleteObject(context.Context, string) error } +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "a store remover"}, + "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) +}`, want: "does not wait for the old lease", file: "claim.go"}, + "transition not through runTransition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { h, _, err := st.ReadHead(ctx); return h, err }`, want: "does not go through runTransition"}, + "remover method value": {src: `type p interface{ RemoveName(string) } +func w(x p) { f := x.RemoveName; f("o") }`, want: "a store remover"}, + } { + srcs := packageSources(t, false) + file := c.file + if file == "" { + file = "zz_control.go" + } + srcs[file] = "package layout\n\nimport \"context\"\n\nvar _ context.Context\n\n" + c.src + "\n" + bad := guardFindings(refs(t, srcs), declared(t, srcs), tests) + if !strings.Contains(strings.Join(bad, "\n"), c.want) { + t.Errorf("control %q: findings %q; want one containing %q", name, bad, c.want) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go new file mode 100644 index 0000000000..fbf9a1b686 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -0,0 +1,305 @@ +package layout + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "unicode/utf8" +) + +// HEAD is the one mutable entry of a volume: who holds it (epoch, holder), +// the open transaction (activity), the current image and the named +// snapshots. Every change to it is one conditional update on its +// generation; nothing else is atomic. + +// Activity kinds: no transaction, a snapshot session, a cleaning session. +const ( + ActIdle = "idle" + ActSnap = "snap" + ActClean = "clean" +) + +// MaxSnapshots bounds the named snapshots one HEAD holds. +const MaxSnapshots = 100 + +// Activity is HEAD's open transaction. Session names it; a session id is +// never reused. +type Activity struct { + Kind string `json:"kind"` + Session string `json:"session,omitempty"` +} + +// Snapshot is one named snapshot: its root and the restore targets that +// still name its chunks. +type Snapshot struct { + Root RootName + Dependents []string +} + +// Head is the decoded HEAD. Gen is the generation the store holds it at; +// it is not part of the encoding. +type Head struct { + Gen uint64 + Epoch uint64 + Holder string + Activity Activity + Current *RootName // nil: no image committed yet + Position uint64 + Snapshots map[string]Snapshot +} + +type headDoc struct { + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + Activity Activity `json:"activity"` + Current string `json:"current,omitempty"` + Position uint64 `json:"position"` + Snapshots map[string]snapDoc `json:"snapshots,omitempty"` +} + +type snapDoc struct { + Root string `json:"root"` + Dependents []string `json:"dependents,omitempty"` +} + +// validName refuses a string the JSON encoding would not keep byte for +// byte: invalid UTF-8 is written as an escaped U+FFFD, which DecodeHead's +// canonical check then refuses. +func validName(field, v string) error { + if !utf8.ValidString(v) { + return fmt.Errorf("%w: %s %q is not valid UTF-8", ErrMalformed, field, v) + } + return nil +} + +func (h Head) check() error { + for field, v := range map[string]string{"holder": h.Holder, "session": h.Activity.Session} { + if err := validName(field, v); err != nil { + return err + } + } + switch h.Activity.Kind { + case ActIdle: + if h.Activity.Session != "" { + return fmt.Errorf("%w: idle activity names session %q", ErrMalformed, h.Activity.Session) + } + case ActSnap, ActClean: + if h.Activity.Session == "" { + return fmt.Errorf("%w: %s activity without a session", ErrMalformed, h.Activity.Kind) + } + default: + return fmt.Errorf("%w: activity %q", ErrMalformed, h.Activity.Kind) + } + if h.Epoch == 0 || h.Holder == "" { + return fmt.Errorf("%w: HEAD without epoch or holder", ErrMalformed) + } + if len(h.Snapshots) > MaxSnapshots { + return fmt.Errorf("%w: %d snapshots, at most %d", ErrMalformed, len(h.Snapshots), MaxSnapshots) + } + for n, s := range h.Snapshots { + if n == "" { + return fmt.Errorf("%w: unnamed snapshot", ErrMalformed) + } + if err := validName("snapshot", n); err != nil { + return err + } + for i, d := range s.Dependents { + if err := validName("dependent", d); err != nil { + return err + } + if err := checkOwner(d); err != nil { + return err + } + if i > 0 && s.Dependents[i-1] >= d { + return fmt.Errorf("%w: snapshot %q dependents not sorted and unique", ErrMalformed, n) + } + } + } + return nil +} + +// Encode returns HEAD's canonical bytes (JSON, keys in a fixed order). +func (h Head) Encode() ([]byte, error) { + if err := h.check(); err != nil { + return nil, err + } + d := headDoc{Epoch: h.Epoch, Holder: h.Holder, Activity: h.Activity, Position: h.Position} + if h.Current != nil { + d.Current = h.Current.String() + } + if len(h.Snapshots) > 0 { + d.Snapshots = map[string]snapDoc{} + for n, s := range h.Snapshots { + d.Snapshots[n] = snapDoc{Root: s.Root.String(), Dependents: s.Dependents} + } + } + return json.Marshal(d) +} + +// DecodeHead parses canonical HEAD bytes; unknown fields and non-canonical +// bytes are refused. +func DecodeHead(b []byte, gen uint64) (Head, error) { + var d headDoc + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + if err := dec.Decode(&d); err != nil { + return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err) + } + h := Head{Gen: gen, Epoch: d.Epoch, Holder: d.Holder, Activity: d.Activity, Position: d.Position} + if d.Current != "" { + rn, err := ParseRootName(d.Current) + if err != nil { + return Head{}, err + } + h.Current = &rn + } + if len(d.Snapshots) > 0 { + h.Snapshots = map[string]Snapshot{} + for n, s := range d.Snapshots { + rn, err := ParseRootName(s.Root) + if err != nil { + return Head{}, err + } + h.Snapshots[n] = Snapshot{Root: rn, Dependents: s.Dependents} + } + } + again, err := h.Encode() + if err != nil { + return Head{}, err + } + if !bytes.Equal(again, b) { + return Head{}, fmt.Errorf("%w: HEAD bytes are not canonical", ErrMalformed) + } + return h, nil +} + +// Refusals of a transition's guard. A refusal changes nothing. +var ( + ErrHeadAbsent = errors.New("layout: HEAD absent") + ErrNotHolder = errors.New("layout: not the holder at HEAD's epoch") + ErrBusy = errors.New("layout: another transaction is open") + ErrNoSession = errors.New("layout: the session is not open") +) + +// HolderID is the identity a transition acts as: the epoch of the line it was +// granted and its server. +type HolderID struct { + Epoch uint64 + Holder string +} + +func (h Head) heldBy(me HolderID) bool { return h.Epoch == me.Epoch && h.Holder == me.Holder } + +// Begin is transition 2: activity idle -> snap(session), by the holder at +// HEAD's epoch. Begin of the session already open is a replay: it returns +// HEAD unchanged and changed=false. Any other open activity is ErrBusy. +func (h Head) Begin(me HolderID, session string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: Begin needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + switch { + case h.Activity == Activity{Kind: ActSnap, Session: session}: + return h, false, nil + case h.Activity.Kind != ActIdle: + return Head{}, false, fmt.Errorf("%w: %s(%s)", ErrBusy, h.Activity.Kind, h.Activity.Session) + } + next = h.clone() + next.Activity = Activity{Kind: ActSnap, Session: session} + return next, true, nil +} + +func (h Head) clone() Head { + c := h + if h.Current != nil { + rn := *h.Current + c.Current = &rn + } + if h.Snapshots != nil { + c.Snapshots = make(map[string]Snapshot, len(h.Snapshots)) + for n, s := range h.Snapshots { + c.Snapshots[n] = Snapshot{Root: s.Root, Dependents: append([]string(nil), s.Dependents...)} + } + } + return c +} + +// ErrPrecondition is returned by HeadStore.Update when HEAD is not at the +// expected generation. +var ErrPrecondition = errors.New("layout: HEAD generation moved") + +// HeadStore is the one entry a volume's transitions write: a read, and a +// conditional update on the generation (the store's only all-or-nothing +// unit). An absent HEAD reads as found=false. +type HeadStore interface { + ReadHead(ctx context.Context) (h Head, found bool, err error) + UpdateHead(ctx context.Context, expectedGen uint64, next Head) error +} + +// RunBegin reads HEAD, applies Begin and commits it by one conditional +// update. A lost reply is resolved by a re-run with the same session: it +// finds snap(session) and returns without writing. An absent HEAD refuses +// (no path creates a HEAD here). +func RunBegin(ctx context.Context, st HeadStore, me HolderID, session string) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.Begin(me, session) }) +} + +// Abort is transition 5: activity snap(session) -> idle, by the holder at +// HEAD's epoch. Nothing it prepared is reachable, so nothing else changes. +// After its own crash a holder rolls back the session HEAD names by +// aborting it. Abort when HEAD is already idle succeeds and writes +// nothing: it means only that no activity remains (the session may have +// been aborted, committed, or never begun); whether its work was committed +// is read from HEAD's current root, never from Abort's result. Another +// open session or a cleaning is ErrNoSession. +func (h Head) Abort(me HolderID, session string) (next Head, changed bool, err error) { + if session == "" { + return Head{}, false, errors.New("layout: Abort needs a session id") + } + if !h.heldBy(me) { + return Head{}, false, fmt.Errorf("%w: HEAD epoch %d holder %q, caller epoch %d holder %q", ErrNotHolder, h.Epoch, h.Holder, me.Epoch, me.Holder) + } + switch { + case h.Activity.Kind == ActIdle: + return h, false, nil + case h.Activity != Activity{Kind: ActSnap, Session: session}: + return Head{}, false, fmt.Errorf("%w: HEAD has %s(%s), not snap(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) + } + next = h.clone() + next.Activity = Activity{Kind: ActIdle} + return next, true, nil +} + +// RunAbort reads HEAD, applies Abort and commits it by one conditional +// update. An absent HEAD refuses. +func RunAbort(ctx context.Context, st HeadStore, me HolderID, session string) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.Abort(me, session) }) +} + +// runTransition is read HEAD, apply t, and one conditional update when t +// changed it. An absent HEAD is refused: no transition creates one. +func runTransition(ctx context.Context, st HeadStore, t func(Head) (Head, bool, error)) (Head, error) { + h, found, err := st.ReadHead(ctx) + if err != nil { + return Head{}, err + } + if !found { + return Head{}, ErrHeadAbsent + } + next, changed, err := t(h) + if err != nil || !changed { + return next, err + } + if err := next.check(); err != nil { + return Head{}, err + } + if err := st.UpdateHead(ctx, h.Gen, next); err != nil { + return Head{}, err + } + next.Gen = h.Gen + 1 + return next, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go new file mode 100644 index 0000000000..a6100d3f0c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -0,0 +1,373 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" +) + +var me = HolderID{Epoch: 3, Holder: "srv-a"} + +func idleHead() Head { + return Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}} +} + +func TestHead_GoldenEncodingRoundTrip(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &rn, Position: 42, + Snapshots: map[string]Snapshot{"daily": {Root: rn, Dependents: []string{"t1", "t2"}}}} + b, err := h.Encode() + if err != nil { + t.Fatal(err) + } + want := `{"epoch":3,"holder":"srv-a","activity":{"kind":"snap","session":"s1"},"current":"` + rn.String() + + `","position":42,"snapshots":{"daily":{"root":"` + rn.String() + `","dependents":["t1","t2"]}}}` + if string(b) != want { + t.Fatalf("encoding\n got %s\nwant %s", b, want) + } + back, err := DecodeHead(b, 9) + if err != nil { + t.Fatal(err) + } + if back.Gen != 9 || back.Current == nil || *back.Current != rn || back.Snapshots["daily"].Root != rn { + t.Fatalf("decoded %+v", back) + } + if b2, _ := back.Encode(); string(b2) != want { + t.Fatal("re-encoding differs") + } +} + +func TestHead_Refusals(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + many := map[string]Snapshot{} + for i := 0; i <= MaxSnapshots; i++ { + many[fmt.Sprintf("s%03d", i)] = Snapshot{Root: rn} + } + for name, h := range map[string]Head{ + "idle with a session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle, Session: "s"}}, + "snap without a session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap}}, + "unknown activity": {Epoch: 1, Holder: "a", Activity: Activity{Kind: "open"}}, + "epoch zero": {Holder: "a", Activity: Activity{Kind: ActIdle}}, + "no holder": {Epoch: 1, Activity: Activity{Kind: ActIdle}}, + "dependents unsorted": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"b", "a"}}}}, + "dependent twice": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"a", "a"}}}}, + "bad dependent": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"a/b"}}}}, + "too many snapshots": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: many}, + } { + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: %v; want ErrMalformed", name, err) + } + } + good, _ := idleHead().Encode() + for name, b := range map[string]string{ + "unknown field": strings.Replace(string(good), `"position"`, `"extra":1,"position"`, 1), + "whitespace": strings.Replace(string(good), `,`, `, `, 1), + "bad root": strings.Replace(string(good), `"position"`, `"current":"xyz","position"`, 1), + "not json": "HEAD", + } { + if _, err := DecodeHead([]byte(b), 1); !errors.Is(err, ErrMalformed) { + t.Errorf("decode %s: %v; want ErrMalformed", name, err) + } + } +} + +// Begin's closure row: idle -> snap(s); snap(s) again is a replay; any +// other open activity, another epoch or another holder is refused and +// changes nothing. +func TestBegin_Closure(t *testing.T) { + h := idleHead() + next, changed, err := h.Begin(me, "s1") + if err != nil || !changed || next.Activity != (Activity{Kind: ActSnap, Session: "s1"}) { + t.Fatalf("Begin from idle: %+v %t %v", next, changed, err) + } + if h.Activity.Kind != ActIdle { + t.Fatal("Begin changed its receiver") + } + if again, changed, err := next.Begin(me, "s1"); err != nil || changed || again.Activity != next.Activity { + t.Fatalf("Begin of the open session: %+v %t %v; want a replay", again, changed, err) + } + for name, tc := range map[string]struct { + h Head + me HolderID + want error + }{ + "other session open": {next, me, ErrBusy}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}}, me, ErrBusy}, + "older caller epoch": {h, HolderID{Epoch: 2, Holder: "srv-a"}, ErrNotHolder}, + "newer caller epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, + "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + } { + session := "s2" + if _, _, err := tc.h.Begin(tc.me, session); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } + if _, _, err := h.Begin(me, ""); err == nil { + t.Error("Begin without a session id accepted") + } +} + +// memHead is a HEAD entry with a generation, and optional kill points: the +// n-th update dies before it applies, or applies and loses its reply. +type memHead struct { + mu sync.Mutex + h *Head + updates int + killAt int + after bool + dead bool + hook func() // runs between a read and the next update +} + +var errKilled = errors.New("process killed") + +func (m *memHead) ReadHead(context.Context) (Head, bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.dead { + return Head{}, false, errKilled + } + if m.h == nil { + return Head{}, false, nil + } + b, _ := m.h.Encode() + h, err := DecodeHead(b, m.h.Gen) + return h, true, err +} + +func (m *memHead) UpdateHead(_ context.Context, gen uint64, next Head) error { + if m.hook != nil { + hk := m.hook + m.hook = nil + hk() + } + m.mu.Lock() + defer m.mu.Unlock() + if m.dead { + return errKilled + } + m.updates++ + kill := m.updates == m.killAt + if kill && !m.after { + m.dead = true + return errKilled + } + if m.h == nil || m.h.Gen != gen { + return ErrPrecondition + } + if _, err := next.Encode(); err != nil { + return err + } + n := next.clone() + n.Gen = gen + 1 + m.h = &n + if kill { + m.dead = true + return errKilled + } + return nil +} + +func (m *memHead) restart() { m.mu.Lock(); m.dead = false; m.killAt = 0; m.mu.Unlock() } + +func TestRunBegin(t *testing.T) { + ctx := context.Background() + h := idleHead() + st := &memHead{h: &h} + got, err := RunBegin(ctx, st, me, "s1") + if err != nil || got.Activity.Session != "s1" || got.Gen != 8 || st.h.Gen != 8 { + t.Fatalf("RunBegin: %+v %v (store gen %d)", got, err, st.h.Gen) + } + if _, err := RunBegin(ctx, &memHead{}, me, "s1"); !errors.Is(err, ErrHeadAbsent) { + t.Fatalf("RunBegin over an absent HEAD: %v; want ErrHeadAbsent", err) + } + // Another writer moves HEAD between the read and the update: refused, + // nothing written by this Begin. + h2 := idleHead() + st2 := &memHead{h: &h2} + st2.hook = func() { st2.h.Gen++ } + if _, err := RunBegin(ctx, st2, me, "s1"); !errors.Is(err, ErrPrecondition) { + t.Fatalf("RunBegin racing another writer: %v; want ErrPrecondition", err) + } + if st2.h.Activity.Kind != ActIdle { + t.Fatalf("HEAD after the refused Begin: %+v", st2.h.Activity) + } +} + +// Interrupt at every step: RunBegin killed at each of its HEAD writes and +// re-run with the same session ends in snap(session). +func TestRunBegin_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, idleHead(), func(st HeadStore) error { + _, err := RunBegin(context.Background(), st, me, "s1") + return err + }, func(t *testing.T, h Head) { + if h.Activity != (Activity{Kind: ActSnap, Session: "s1"}) { + t.Fatalf("HEAD after Begin: %+v", h.Activity) + } + }) +} + +// interruptHead kills run at its one HEAD write (before it applies, and +// applied with its reply lost), re-runs it, and checks the end state: want +// at exactly start.Gen+1, and a further re-run writes nothing. Every +// transition is exactly one conditional update; a run that makes another +// number of writes fails. +func interruptHead(t *testing.T, start Head, run func(HeadStore) error, want func(*testing.T, Head)) { + t.Helper() + fresh := func() *Head { h := start.clone(); return &h } + count := &memHead{h: fresh()} + if err := run(count); err != nil { + t.Fatalf("uninterrupted: %v", err) + } + want(t, *count.h) + steps := count.updates + if steps != 1 { + t.Fatalf("the transition made %d HEAD writes; want exactly 1", steps) + } + for k := 1; k <= steps; k++ { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("write%d/after=%t", k, after), func(t *testing.T) { + st := &memHead{h: fresh(), killAt: k, after: after} + if err := run(st); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + st.restart() + if err := run(st); err != nil { + t.Fatalf("re-run: %v", err) + } + want(t, *st.h) + if st.h.Gen != start.Gen+uint64(steps) { + t.Fatalf("HEAD gen %d after the re-run; want %d", st.h.Gen, start.Gen+uint64(steps)) + } + before := st.updates + if err := run(st); err != nil || st.updates != before { + t.Fatalf("second re-run: %v, wrote %d times", err, st.updates-before) + } + }) + } + } +} + +func snapHead(session string) Head { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Activity = Activity{Kind: ActSnap, Session: session} + h.Current = &rn + h.Position = 40 + h.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: []string{"t1"}}} + return h +} + +func TestAbort_Closure(t *testing.T) { + h := snapHead("s1") + next, changed, err := h.Abort(me, "s1") + if err != nil || !changed || next.Activity != (Activity{Kind: ActIdle}) { + t.Fatalf("Abort of the open session: %+v %t %v", next, changed, err) + } + if *next.Current != *h.Current || next.Position != h.Position || len(next.Snapshots) != 1 || next.Snapshots["daily"].Dependents[0] != "t1" { + t.Fatalf("Abort changed more than activity: %+v", next) + } + if h.Activity.Kind != ActSnap { + t.Fatal("Abort changed its receiver") + } + if again, changed, err := next.Abort(me, "s1"); err != nil || changed || again.Activity.Kind != ActIdle { + t.Fatalf("Abort over idle: %+v %t %v; want a replay", again, changed, err) + } + for name, tc := range map[string]struct { + h Head + me HolderID + want error + }{ + "other session open": {snapHead("s2"), me, ErrNoSession}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "s1"}}, me, ErrNoSession}, + "other epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, + "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + } { + if _, _, err := tc.h.Abort(tc.me, "s1"); !errors.Is(err, tc.want) { + t.Errorf("%s: %v; want %v", name, err, tc.want) + } + } + if _, _, err := h.Abort(me, ""); err == nil { + t.Error("Abort without a session id accepted") + } +} + +// Abort over idle succeeds and writes nothing whatever came before: a +// session that never began, one already committed, one already aborted. +// Success means only that no activity remains; it never says whether the +// session's work was committed (that is read from HEAD's current root). +func TestAbort_IdleMeansNoActivityRemains(t *testing.T) { + for name, h := range map[string]Head{ + "never begun": idleHead(), + "already aborted": func() Head { n, _, _ := snapHead("s1").Abort(me, "s1"); return n }(), + } { + next, changed, err := h.Abort(me, "s1") + if err != nil || changed || next.Activity.Kind != ActIdle || next.Gen != h.Gen { + t.Errorf("Abort over idle (%s): %+v %t %v; want unchanged, no error", name, next, changed, err) + } + } +} + +// After its own crash a holder finds snap(s) at its epoch with nothing in +// memory: a new session beside s is refused; rolling s back by Abort, then +// Begin of a new session, succeeds. +func TestAbort_RollBackAfterOwnCrash(t *testing.T) { + ctx := context.Background() + h := snapHead("s1") + st := &memHead{h: &h} + if _, err := RunBegin(ctx, st, me, "s2"); !errors.Is(err, ErrBusy) { + t.Fatalf("a new session beside the open one: %v; want ErrBusy", err) + } + cur, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := RunAbort(ctx, st, me, cur.Activity.Session); err != nil { + t.Fatal(err) + } + got, err := RunBegin(ctx, st, me, "s2") + if err != nil || got.Activity != (Activity{Kind: ActSnap, Session: "s2"}) || st.h.Gen != h.Gen+2 { + t.Fatalf("Begin after the roll back: %+v %v gen %d", got, err, st.h.Gen) + } + if _, err := RunAbort(ctx, &memHead{}, me, "s1"); !errors.Is(err, ErrHeadAbsent) { + t.Fatalf("Abort over an absent HEAD: %v", err) + } +} + +func TestRunAbort_InterruptAtEveryStep(t *testing.T) { + interruptHead(t, snapHead("s1"), func(st HeadStore) error { + _, err := RunAbort(context.Background(), st, me, "s1") + return err + }, func(t *testing.T, h Head) { + if h.Activity != (Activity{Kind: ActIdle}) || h.Position != 40 { + t.Fatalf("HEAD after Abort: %+v", h) + } + }) +} + +// A name that is not valid UTF-8 is written by the JSON encoding as an +// escaped U+FFFD, and DecodeHead's canonical check then refuses those +// bytes: Encode would succeed with a HEAD its own decoder cannot read. +// Refused at Encode on every string field. +func TestHead_RefusesInvalidUTF8(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + bad := "a\xff" + for name, h := range map[string]Head{ + "holder": {Epoch: 1, Holder: bad, Activity: Activity{Kind: ActIdle}}, + "session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap, Session: bad}}, + "snapshot": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{bad: {Root: rn}}}, + "dependent": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{bad}}}}, + } { + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Errorf("%s %q: %v; want ErrMalformed", name, bad, err) + } + } + h := idleHead() + st := &memHead{h: &h} + if _, err := RunBegin(context.Background(), st, me, bad); err == nil || st.h.Activity.Kind != ActIdle { + t.Fatalf("Begin with an invalid UTF-8 session: %v, HEAD %+v; want refused, nothing written", err, st.h.Activity) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/session_test.go b/seaweed-block/core/frontend/chunkstore/layout/session_test.go new file mode 100644 index 0000000000..c8e89926de --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/session_test.go @@ -0,0 +1,362 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "testing" +) + +// memVolume is one volume's store: HEAD (memHead) and its objects, with +// one kill point counted over every write of either kind. +type memVolume struct { + head *memHead + objects map[string][]byte + writes []string // every write, in order + killAt int + after bool + dead bool +} + +func (v *memVolume) write(what string) (apply, die bool, err error) { + if v.dead { + return false, false, errKilled + } + v.writes = append(v.writes, what) + if len(v.writes) == v.killAt { + v.dead = true + return v.after, true, nil + } + return true, false, nil +} + +func (v *memVolume) ReadHead(ctx context.Context) (Head, bool, error) { + if v.dead { + return Head{}, false, errKilled + } + return v.head.ReadHead(ctx) +} + +func (v *memVolume) UpdateHead(ctx context.Context, gen uint64, next Head) error { + apply, die, err := v.write("update HEAD") + if err != nil { + return err + } + if apply { + if err := v.head.UpdateHead(ctx, gen, next); err != nil { + return err + } + } + if die { + return errKilled + } + return nil +} + +func (v *memVolume) look(_ context.Context, dir, name string) (bool, error) { + if v.dead { + return false, errKilled + } + _, ok := v.objects[path.Join(dir, name)] + return ok, nil +} + +// put writes an object if absent (a content name that exists is complete, +// so a present one is skipped). +func (v *memVolume) put(rel string, b []byte) error { + p := path.Join(volRoot, rel) + if v.dead { + return errKilled + } + if _, ok := v.objects[p]; ok { + return nil + } + apply, die, err := v.write("create " + rel) + if err != nil { + return err + } + if apply { + v.objects[p] = append([]byte(nil), b...) + } + if die { + return errKilled + } + return nil +} + +// snapshotSession is the whole snapshot transaction as the holder runs it +// after a (re)start: an open session of its own at HEAD's epoch is rolled +// back first (memory is empty after a crash), then Begin, write every new +// object (chunks, segments, root; present ones skipped), and Commit. +func snapshotSession(v *memVolume, session string, data map[uint64][]byte, req CommitRequest) error { + ctx := context.Background() + h, found, err := v.ReadHead(ctx) + if err != nil { + return err + } + if !found { + return ErrHeadAbsent + } + if h.Activity.Kind == ActSnap && h.heldBy(me) { + if _, err := RunAbort(ctx, v, me, h.Activity.Session); err != nil { + return err + } + } + if _, err := RunBegin(ctx, v, me, session); err != nil { + return err + } + // What is new is recomputed against HEAD's current root, never kept + // from before the crash (a commit may have applied with its reply lost). + switch cur := h.Current; { + case cur != nil && *cur == mustRoot(req.Next): + req.Prev = req.Next + case cur != nil && *cur != mustRoot(req.Prev): + return fmt.Errorf("unexpected current root %s", cur) + } + for i, r := range newOwn("v1", req.Prev, req.Next) { + if err := v.put(r.Chunk.Path(), data[i]); err != nil { + return err + } + } + root, segs, err := Build(req.Next) + if err != nil { + return err + } + for n, b := range segs { + if err := v.put(n.Path(), b); err != nil { + return err + } + } + rn, rb, err := NameRoot(root) + if err != nil { + return err + } + if err := v.put(rn.Path(), rb); err != nil { + return err + } + req.Session = session + _, err = RunCommit(ctx, v, v.look, volRoot, "v1", me, req) + return err +} + +func mustRoot(m map[uint64]Ref) RootName { + rn, _, err := rootOf(m) + if err != nil { + panic(err) + } + return rn +} + +// sessionFixture: HEAD idle at the root of prev (chunks 0 and 3, written); +// the session commits next (chunk 3 changed, chunk 10004 added, a foreign +// chunk named). +func sessionFixture(t *testing.T) (func() *memVolume, map[uint64][]byte, CommitRequest) { + t.Helper() + data := map[uint64][]byte{0: []byte("a"), 3: []byte("b2"), 10004: []byte("c")} + prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) + next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) + prevData := map[uint64][]byte{0: []byte("a"), 3: []byte("b")} + fresh := func() *memVolume { + objs := map[string][]byte{} + prevRoot := writeImage(t, objs, prev, prevData) + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40, + Snapshots: map[string]Snapshot{"daily": {Root: prevRoot}}} + return &memVolume{head: &memHead{h: &h}, objects: objs} + } + return fresh, data, CommitRequest{Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} +} + +// requireCommitted: HEAD idle at next's root with the snapshot, and every +// object next's root reaches in this volume exists, its bytes as written. +func requireCommitted(t *testing.T, v *memVolume, data map[uint64][]byte, req CommitRequest) { + t.Helper() + h := v.head.h + root, segs, _ := Build(req.Next) + rn, _, _ := NameRoot(root) + if h.Activity.Kind != ActIdle || h.Current == nil || *h.Current != rn || h.Position != 50 || h.Snapshots["hourly"].Root != rn { + t.Fatalf("HEAD after the session: %+v", h) + } + for i, r := range req.Next { + if r.Owner != "v1" { + continue + } + b, ok := v.objects[path.Join(volRoot, r.Chunk.Path())] + if !ok { + t.Fatalf("chunk %d the committed root names is missing", i) + } + if _, changed := newOwn("v1", req.Prev, req.Next)[i]; changed && string(b) != string(data[i]) { + t.Fatalf("chunk %d holds %q; want %q", i, b, data[i]) + } + } + for n := range segs { + if _, ok := v.objects[path.Join(volRoot, n.Path())]; !ok { + t.Fatalf("segment %s the committed root names is missing", n) + } + } + if _, ok := v.objects[path.Join(volRoot, rn.Path())]; !ok { + t.Fatal("the committed root is missing") + } + if err := reachableMissing(h, v.objects); err != nil { + t.Fatalf("after the session HEAD reaches a missing object: %v", err) + } +} + +// Interrupt at every step of the snapshot transaction: killed at each of +// its writes (Begin's HEAD update, every object create, Commit's HEAD +// update), before the write applies and after it applied with its reply +// lost; the restarted holder rolls back what it finds open, begins a new +// session, reuses written objects by name and commits. The end state is +// the committed image with every object it reaches present; at no point +// does HEAD name an object that is missing. +func TestSnapshotSession_InterruptAtEveryStep(t *testing.T) { + fresh, data, req := sessionFixture(t) + count := fresh() + if err := snapshotSession(count, "s1", data, req); err != nil { + t.Fatal(err) + } + requireCommitted(t, count, data, req) + steps := append([]string(nil), count.writes...) + if len(steps) < 5 { + t.Fatalf("the session made %d writes: %v", len(steps), steps) + } + t.Logf("%d step boundaries: %v", len(steps), steps) + for k := range steps { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("step%d %s/after=%t", k+1, steps[k], after), func(t *testing.T) { + v := fresh() + v.killAt, v.after = k+1, after + if err := snapshotSession(v, "s1", data, req); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + requireReachablePresent(t, v) + v.dead, v.killAt = false, 0 + if err := snapshotSession(v, "s2", data, req); err != nil { + t.Fatalf("re-run after a kill at step %d: %v", k+1, err) + } + requireCommitted(t, v, data, req) + }) + } + } +} + +// writeImage stores a manifest's own chunks (with their bytes), its +// segments and its root, and returns the root's name. +func writeImage(t *testing.T, objs map[string][]byte, m map[uint64]Ref, data map[uint64][]byte) RootName { + t.Helper() + root, segs, err := Build(m) + if err != nil { + t.Fatal(err) + } + for i, r := range m { + if r.Owner == "v1" { + objs[path.Join(volRoot, r.Chunk.Path())] = data[i] + } + } + for n, b := range segs { + objs[path.Join(volRoot, n.Path())] = b + } + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + objs[path.Join(volRoot, rn.Path())] = rb + return rn +} + +// reachableMissing walks every root HEAD names (current and every +// snapshot) through its segments to this volume's chunks, reading the +// stored bytes, and reports the first object that is missing or does not +// hash to its name. +func reachableMissing(h *Head, objs map[string][]byte) error { + roots := map[RootName]bool{} + if h.Current != nil { + roots[*h.Current] = true + } + for _, s := range h.Snapshots { + roots[s.Root] = true + } + get := func(rel string, want Hash) ([]byte, error) { + b, ok := objs[path.Join(volRoot, rel)] + if !ok { + return nil, fmt.Errorf("%s is missing", rel) + } + if Sum(b) != want { + return nil, fmt.Errorf("%s does not hash to its name", rel) + } + return b, nil + } + for rn := range roots { + rb, err := get(rn.Path(), rn.Hash) + if err != nil { + return err + } + root, err := DecodeRoot(rb) + if err != nil { + return err + } + for _, sn := range root.Segments { + sb, err := get(sn.Path(), sn.Hash) + if err != nil { + return err + } + seg, err := DecodeSegment(sb) + if err != nil { + return err + } + for _, r := range seg.Chunks { + if r.Owner != "v1" { + continue // the source's pool holds it + } + if _, err := get(r.Chunk.Path(), r.Chunk.Hash); err != nil { + return err + } + } + } + } + return nil +} + +// requireReachablePresent: every object any root in HEAD reaches in this +// volume exists with its bytes (checked after a kill, before the restart). +func requireReachablePresent(t *testing.T, v *memVolume) { + t.Helper() + if err := reachableMissing(v.head.h, v.objects); err != nil { + t.Fatalf("after the kill HEAD reaches a missing object: %v", err) + } +} + +// The reachability observer's negative controls: a reachable own chunk, +// segment or snapshot root deleted (the current root kept) is reported. +func TestReachableMissing_Controls(t *testing.T) { + fresh, _, req := sessionFixture(t) + if err := reachableMissing(fresh().head.h, fresh().objects); err != nil { + t.Fatalf("control: the fixture itself: %v", err) + } + _, segs, _ := Build(req.Prev) + var seg0 SegName + for n := range segs { + seg0 = n + } + for name, rel := range map[string]string{ + "own chunk": req.Prev[3].Chunk.Path(), + "segment": seg0.Path(), + } { + v := fresh() + delete(v.objects, path.Join(volRoot, rel)) + if err := reachableMissing(v.head.h, v.objects); err == nil { + t.Errorf("%s deleted: not reported", name) + } + } + v := fresh() + other := RootName{Hash: Sum([]byte("missing root"))} + v.head.h.Snapshots["weekly"] = Snapshot{Root: other} + if err := reachableMissing(v.head.h, v.objects); err == nil { + t.Error("a snapshot root that is missing: not reported") + } + v = fresh() + v.objects[path.Join(volRoot, req.Prev[0].Chunk.Path())] = []byte("tampered") + if err := reachableMissing(v.head.h, v.objects); err == nil { + t.Error("a chunk whose bytes do not match its name: not reported") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go new file mode 100644 index 0000000000..832a436731 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -0,0 +1,52 @@ +package layout + +import ( + "reflect" + "sort" + "testing" +) + +// Every pure transition refuses a caller that is not the holder at HEAD's +// epoch: an older epoch of the same server, and the same epoch held by +// another server, in idle, snap and clean. The table must name every +// method of Head that returns (Head, bool, error), so a new transition +// fails here until it is added. +func TestTransitions_RefuseAStaleHolder(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + steps := map[string]func(Head, HolderID) error{ + "Begin": func(h Head, c HolderID) error { _, _, err := h.Begin(c, "s"); return err }, + "Abort": func(h Head, c HolderID) error { _, _, err := h.Abort(c, "s"); return err }, + "Commit": func(h Head, c HolderID) error { _, _, err := h.Commit(c, "s", rn, 1, ""); return err }, + "BeginClean": func(h Head, c HolderID) error { _, _, err := h.BeginClean(c, "c"); return err }, + "EndClean": func(h Head, c HolderID) error { _, _, err := h.EndClean(c, "c"); return err }, + "Claim": func(h Head, c HolderID) error { _, _, err := h.Claim(c); return err }, + } + callers := map[string]HolderID{ + "older epoch, same server": {Epoch: 2, Holder: "srv-a"}, + "same epoch, another server": {Epoch: 3, Holder: "srv-b"}, + } + for name, step := range steps { + for who, c := range callers { + for _, h := range []Head{idleHead(), snapHead("s"), cleanHead("c")} { + if err := step(h, c); err == nil { + t.Errorf("%s by %s over a HEAD at epoch 3 held by srv-a (%s) succeeded", name, who, h.Activity.Kind) + } + } + } + } + headT, boolT := reflect.TypeOf(Head{}), reflect.TypeOf(false) + errT := reflect.TypeOf((*error)(nil)).Elem() + var missing []string + for i := 0; i < headT.NumMethod(); i++ { + m := headT.Method(i).Type + if m.NumOut() == 3 && m.Out(0) == headT && m.Out(1) == boolT && m.Out(2) == errT { + if _, ok := steps[headT.Method(i).Name]; !ok { + missing = append(missing, headT.Method(i).Name) + } + } + } + sort.Strings(missing) + if len(missing) != 0 { + t.Fatalf("transitions not in the stale-holder table: %v", missing) + } +} diff --git a/seaweed-block/core/frontend/durable/hold_kzhold.go b/seaweed-block/core/frontend/durable/hold_kzhold.go new file mode 100644 index 0000000000..468ac34fed --- /dev/null +++ b/seaweed-block/core/frontend/durable/hold_kzhold.go @@ -0,0 +1,30 @@ +//go:build kzhold + +package durable + +import ( + "fmt" + "os" + "time" +) + +// HoldBeforeChunkFreshRetireForTest exists only in a binary built with the +// kzhold tag, which is never released. At the attach's boundary after +// presence and before the fresh marker is retired (the attach commit), the +// provider writes reached and then waits until release exists (at most ten +// minutes), so a test can stop the process at that exact point. +func (p *DurableProvider) HoldBeforeChunkFreshRetireForTest(reached, release string) { + p.testBeforeChunkFreshRetire = func() error { + if err := os.WriteFile(reached, []byte(time.Now().UTC().Format(time.RFC3339Nano)+"\n"), 0o644); err != nil { + return fmt.Errorf("kzhold: write %s: %w", reached, err) + } + end := time.Now().Add(10 * time.Minute) + for time.Now().Before(end) { + if _, err := os.Stat(release); err == nil { + return nil + } + time.Sleep(20 * time.Millisecond) + } + return fmt.Errorf("kzhold: %s never appeared", release) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index da03a11fe6..71b0b8ea30 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -26,6 +26,7 @@ The design is described in three documents, and this one collects their machines - [M5 The cut pipeline](#m5-the-cut-pipeline) - [M6 Chunk lifecycle](#m6-chunk-lifecycle) - [M7. Host background-cut admission](#m7-host-background-cut-admission) + - [M9 Snapshot kernel: HEAD transactions over the content-named layout](#m9-snapshot-kernel-head-transactions-over-the-content-named-layout) - [Part B. Invariant ledger](#part-b-invariant-ledger) - [Part C. Change rules](#part-c-change-rules) - [Part D. Wait ownership](#part-d-wait-ownership) @@ -514,9 +515,35 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO `_RestoringIsSkippedAndCounted`, `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`. +### M9 Snapshot kernel: HEAD transactions over the content-named layout + +A library, `core/frontend/chunkstore/layout`, with no production caller yet. A volume's HEAD holds its epoch and holder, one activity (`idle`, `snap(s)` or `clean(c)`), the current root and position, and the named snapshots with their dependents. Every transition is one conditional update of HEAD through `runTransition`; no transition creates a HEAD, and an absent HEAD is refused. Objects (chunks, segments, roots) are written first under content names; the commit is the only step that makes them reachable. + +```mermaid +stateDiagram-v2 + [*] --> idle: HEAD created outside this package + idle --> snap: Begin(s) + snap --> idle: Abort(s) + snap --> idle: Commit(s, root) + idle --> idle: Claim(e) + snap --> idle: Claim(e), s void + clean --> idle: Claim(e), c void + idle --> clean: BeginClean(c) + clean --> idle: EndClean(c) +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| idle | snap(s) | caller is the holder at HEAD's epoch (epoch and server); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | +| snap(s) | idle | holder at HEAD's epoch; activity is snap(s); over idle it succeeds without a write and means only that no activity remains | head.go `Head.Abort` | `INV-SNAPK-ABORT-001` | +| snap(s) | idle, current = root | holder at HEAD's epoch; activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001` | +| any | idle at epoch e | e above HEAD's epoch (the same epoch and server is a replay); every older holder's lease has ended, checked after the read and before the update | claim.go `Head.Claim`, `RunClaim` (`LeaseWait.OldLeaseEnded`) | `INV-SNAPK-CLAIM-LEASE-001` | +| idle | clean(c) | holder at HEAD's epoch; activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | +| clean(c) | idle | holder at HEAD's epoch; activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | + ## Part B. Invariant ledger -328 rows: 257 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 313 new. +338 rows: 267 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 323 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. @@ -1052,6 +1079,25 @@ Notes: - `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. +### B.10 Snapshot kernel: content-named layout and HEAD transitions + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `Head.Commit` | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-TXN-INTERRUPT-001` | A snapshot transaction killed at any of its writes (Begin, each object, Commit), before the write or after it applied with its reply lost, never leaves HEAD reaching a missing object, and the restarted holder (roll back, new session, base recomputed from HEAD) ends at the committed image. | M9 idle → snap → idle | `core/frontend/chunkstore/layout` `head.go`, `commit.go` (the transitions above) | `TestSnapshotSession_InterruptAtEveryStep`, `TestReachableMissing_Controls`, `TestAbort_AfterCommitLeavesTheCommit` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server and the same epoch held by another server, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | + +Notes: + +- B.10 rows are enforced in a library with no production caller; they say nothing about a running volume until a caller is added and its own rows name these. + ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/scripts/run-alpha-app-demo.sh b/seaweed-block/scripts/run-alpha-app-demo.sh index 7c34edd006..ee8d21936d 100755 --- a/seaweed-block/scripts/run-alpha-app-demo.sh +++ b/seaweed-block/scripts/run-alpha-app-demo.sh @@ -33,6 +33,8 @@ BREAK_AFTER_BLOCKVOLUME_READY="${SW_BLOCK_DEMO_BREAK_AFTER_BLOCKVOLUME_READY:-}" BREAK_AFTER_BLOCKVOLUME_RESTART="${SW_BLOCK_DEMO_BREAK_AFTER_BLOCKVOLUME_RESTART:-}" FAIL_PRIMARY_BEFORE_READER="${SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER:-}" REQUIRE_PROMOTION_READY_BEFORE_FAILURE="${SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE:-0}" +EXPECT_NO_AUTO_PROMOTION="${SW_BLOCK_DEMO_EXPECT_NO_AUTO_PROMOTION:-0}" +NO_PROMOTION_HOLD_SECONDS="${SW_BLOCK_DEMO_NO_PROMOTION_HOLD_SECONDS:-30}" WRITER_TIMEOUT="${SW_BLOCK_DEMO_WRITER_TIMEOUT:-240}" DELETE_ALL_BLOCKVOLUMES="${SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES:-0}" PIN_APP_NODE="${SW_BLOCK_DEMO_PIN_APP_NODE:-1}" @@ -1004,6 +1006,72 @@ fail_primary_before_reader() { echo "old_primary_stale_io_success_count=0" >>"$recovery_marker" echo "stale_primary_fence_evidence=target_ready_replicas=${ready:-0}" >>"$recovery_marker" + if [[ "$EXPECT_NO_AUTO_PROMOTION" == "1" || "$EXPECT_NO_AUTO_PROMOTION" == "true" ]]; then + # This release claims no automatic promotion on node loss: a primary + # that cannot be read is unknown, not failed. Hold, then return the + # node and require the SAME primary to serve again. + log "hold ${NO_PROMOTION_HOLD_SECONDS}s: no automatic promotion while ${primary} is lost" + local hold_rounds=$((NO_PROMOTION_HOLD_SECONDS / 2)) + local hold_reads=0 + for _ in $(seq 1 "$hold_rounds"); do + # A round counts only when the inventory was actually read: an + # unreadable inventory shows no promotion and must not pass the hold. + if collect_ops_inventory_bundle "$after_dir" && grep -q '^replica: ' "$after_summary" 2>/dev/null; then + hold_reads=$((hold_reads + 1)) + fi + after_primary="$(inventory_primary_replica "$after_summary" 2>/dev/null || true)" + if [[ -n "$after_primary" && "$after_primary" != "$primary" ]]; then + echo "failover_status: unexpected_auto_promotion" >>"$recovery_marker" + echo "automatic promotion to ${after_primary} while the primary node was lost" >&2 + exit 1 + fi + sleep 2 + done + if (( hold_reads * 2 < hold_rounds )); then + echo "failover_status: no_auto_promotion_unproven" >>"$recovery_marker" + echo "no-promotion hold unproven: ${hold_reads} of ${hold_rounds} inventory reads succeeded" >&2 + exit 1 + fi + echo "auto_promotion_while_node_lost=none" >>"$recovery_marker" + echo "no_promotion_hold_reads=${hold_reads}/${hold_rounds}" >>"$recovery_marker" + write_control_plane_timeline_event "$timeline" "no_auto_promotion" "replica=${primary}" "hold_seconds=${NO_PROMOTION_HOLD_SECONDS}" + if [[ "$node_loss_mode" == "1" ]]; then + kubectl uncordon "$before_primary_node" | tee "$ARTIFACT_DIR/uncordon-primary-node.log" + fi + kubectl -n "$BLOCKVOLUME_NAMESPACE" scale "$deploy" --replicas=1 | tee "$ARTIFACT_DIR/scale-primary-one.log" + log "wait for the same primary ${primary} to serve again" + for _ in $(seq 1 120); do + collect_ops_inventory_bundle "$after_dir" || true + after_primary="$(inventory_primary_replica "$after_summary" 2>/dev/null || true)" + after_primary_count="$(grep -c '^replica: .* role=primary ' "$after_summary" 2>/dev/null || true)" + promoted_line="$(inventory_replica_line "$after_summary" "$primary" 2>/dev/null || true)" + # In the inventory summary 'frontend_primary_ready=true' appears only in + # the issue "non-primary ... frontend_primary_ready=true" (a replica that + # is not primary claims the frontend), so 0 means no such claim; the + # recovered primary must itself report ready: no + # "primary frontend_primary_ready=false" issue. + frontend_ready_issue_count="$(grep -c 'frontend_primary_ready=true' "$after_summary" 2>/dev/null || true)" + primary_not_ready_count="$(grep -c 'primary frontend_primary_ready=false' "$after_summary" 2>/dev/null || true)" + if [[ "$after_primary" == "$primary" && "$after_primary_count" == "1" && "$frontend_ready_issue_count" == "0" && "$primary_not_ready_count" == "0" ]]; then + { + echo "failover_status: recovered_same_primary" + echo "post_failure_primary_count=${after_primary_count}" + echo "recovered_replica=${primary}" + echo "promoted_replica=${primary}" + echo "promoted_replica_node=${before_primary_node:-unavailable}" + echo "after_publish_target_evidence=${promoted_line}" + echo "after_publish_target_frontend=$(promotion_evidence_field "$promoted_line" "frontend")" + } >>"$recovery_marker" + write_control_plane_timeline_event "$timeline" "primary_recovered" "replica=${primary}" "primary_count=${after_primary_count}" "evidence=${promoted_line}" + return 0 + fi + sleep 2 + done + echo "failover_status: recovery_timeout" >>"$recovery_marker" + echo "the primary ${primary} did not serve again after its node returned" >&2 + exit 1 + fi + log "wait for promoted primary ${candidate_replica} after controlled failure" for _ in $(seq 1 120); do if [[ -n "$required_frontier_arg" ]]; then diff --git a/seaweed-block/testops/README.md b/seaweed-block/testops/README.md index 2bab6216a4..47638a232c 100644 --- a/seaweed-block/testops/README.md +++ b/seaweed-block/testops/README.md @@ -74,6 +74,16 @@ Use the smallest gate that can prove the contract you changed. | Kernel initiator, k3s, mounted filesystem, failover, or stale-session behavior | The matching child chain, for example `nvme-p5-csi-protocol-chain` or `csi-rf1-durable-restart-chain` | These require real Linux/K8s/initiator behavior. | | Milestone readiness or cross-protocol release confidence | `swblock suite testops/suites/beta-hardening-gate.yaml` plus `swblock validate-bundle --profile beta-hardening` | Slow, evidence-heavy gate. Use for release/milestone claims, not first debugging. | +**Node loss (`node-loss-survival-rf3-reattach-chain`).** This release claims no automatic promotion on node loss: +the gate cordons the primary's node and stops it, requires that no other replica is promoted during the hold +(`auto_promotion_while_node_lost=none`), then returns the node and requires the same primary to serve the same +data. Manual failover (a `SwBlockReplicaFailback` handled by the failback executor, which calls blockmaster's admin +`ExecuteFailback`) is covered by the existing tests: `TestFailbackExecutorGRPCRuntimeUsesRealMasterService`, +`TestFailbackServiceEnabledUsesHostRuntime`, `TestHostFailbackAuthorityRuntimeUsesLivePublisher` +(`core/host/master/failback_runtime_test.go`), `TestFailbackAuthorityRuntimeAdapterRejectsStaleExpectedCurrent` +(`core/ops/failback_authority_runtime_adapter_test.go`) and `TestFailbackExecutorInvokesRuntimeWhenExplicitlyEnabled` +(`core/ops/failback_executor_controller_test.go`). + Default ownership: - Developers run unit/component tests, fast runner-native component gates, and diff --git a/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml b/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml index 9be7b67a93..be14ce5b4e 100644 --- a/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml +++ b/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml @@ -153,7 +153,7 @@ phases: timeout: 20m cmd: | cd {{ product_root }} - bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build/alpha-images.env; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/node-specs.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/demo-app-rf3.yaml SW_BLOCK_DEMO_APP_NODE_NAME="$APP_NODE" SW_BLOCK_DEMO_READER_NODE_NAME="$SURVIVOR_APP_NODE" SW_BLOCK_ALPHA_NODE_SPECS="$NODE_SPECS" SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1 SW_BLOCK_LAUNCHER_EXTERNAL_STATUS=1 SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS=1 SW_BLOCK_ISCSI_CHAP_SECRET_NAME=sw-block-node-loss-chap SW_BLOCK_ISCSI_CHAP_USERNAME=testops-node-loss SW_BLOCK_ISCSI_CHAP_SECRET=testops-node-loss-{{ run_id }} SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-node-loss-survival SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE=1 SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=cordon-node-scale-primary-to-zero SW_BLOCK_DEMO_STOP_AFTER=reader-verified SW_BLOCK_DEMO_KEEP_ON_STOP=1 bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/exit_code.txt; test "$rc" -eq 44' + bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build/alpha-images.env; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/node-specs.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/demo-app-rf3.yaml SW_BLOCK_DEMO_APP_NODE_NAME="$APP_NODE" SW_BLOCK_DEMO_READER_NODE_NAME="$SURVIVOR_APP_NODE" SW_BLOCK_ALPHA_NODE_SPECS="$NODE_SPECS" SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1 SW_BLOCK_DEMO_EXPECT_NO_AUTO_PROMOTION=1 SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS=1 SW_BLOCK_ISCSI_CHAP_SECRET_NAME=sw-block-node-loss-chap SW_BLOCK_ISCSI_CHAP_USERNAME=testops-node-loss SW_BLOCK_ISCSI_CHAP_SECRET=testops-node-loss-{{ run_id }} SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-node-loss-survival SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE=1 SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=cordon-node-scale-primary-to-zero SW_BLOCK_DEMO_STOP_AFTER=reader-verified SW_BLOCK_DEMO_KEEP_ON_STOP=1 bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/exit_code.txt; test "$rc" -eq 44' - action: grep_log node: m02 path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/run.log" @@ -238,14 +238,14 @@ phases: - action: grep_log node: m02 path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" - pattern: "failover_status: promoted" + pattern: "failover_status: recovered_same_primary" save_as: failover_promoted_count - action: assert_greater actual: "{{ failover_promoted_count }}" threshold: "0" - action: exec node: m02 - cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; promoted=$(sed -n 's/^promoted_replica=//p' \"$M\" | tail -1); failed=$(sed -n 's/^failed_replica=//p' \"$M\" | head -1); promoted_node=$(sed -n 's/^promoted_replica_node=//p' \"$M\" | tail -1); failed_node=$(sed -n 's/^failed_node=//p' \"$M\" | head -1); test -n \"$promoted\" && test \"$promoted\" != \"$failed\" && test -n \"$promoted_node\" && test \"$promoted_node\" != \"$failed_node\"" + cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; recovered=$(sed -n 's/^recovered_replica=//p' \"$M\" | tail -1); failed=$(sed -n 's/^failed_replica=//p' \"$M\" | head -1); test -n \"$recovered\" && test \"$recovered\" = \"$failed\" && grep -q '^auto_promotion_while_node_lost=none$' \"$M\"" - action: grep_log node: m02 path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" @@ -328,13 +328,13 @@ phases: threshold: "0" - action: exec node: m02 - cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; before=$(sed -n 's/^before_publish_target_frontend=//p' \"$M\" | head -1); portal=$(sed -n 's/^after_publish_target_frontend=//p' \"$M\" | tail -1); test -n \"$portal\" && test \"$portal\" != \"$before\" && ! printf '%s\n' \"$portal\" | grep -q '^127\\.0\\.0\\.1:' && grep -q \"NodeStageVolume: .* staged transport=iscsi portal=${portal}\" /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/blockcsi-node.log" + cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; before=$(sed -n 's/^before_publish_target_frontend=//p' \"$M\" | head -1); portal=$(sed -n 's/^after_publish_target_frontend=//p' \"$M\" | tail -1); test -n \"$portal\" && test \"$portal\" = \"$before\" && ! printf '%s\n' \"$portal\" | grep -q '^127\\.0\\.0\\.1:' && grep -q \"NodeStageVolume: .* staged transport=iscsi portal=${portal}\" /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/blockcsi-node.log" - action: exec node: m02 cmd: "test -s /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-boundary.txt && grep -q 'node_loss_recovery_claimed=true' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-boundary.txt" - action: exec node: m02 - cmd: "S=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-summary.txt; test -s \"$S\" && grep -q '^node_loss_recovery_summary_version=1$' \"$S\" && grep -q '^result=promoted$' \"$S\" && grep -q '^data_check_after_node_loss=reader_checksum_passed$' \"$S\"" + cmd: "S=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-summary.txt; test -s \"$S\" && grep -q '^node_loss_recovery_summary_version=1$' \"$S\" && grep -q '^result=recovered_same_primary$' \"$S\" && grep -q '^data_check_after_node_loss=reader_checksum_passed$' \"$S\"" - action: grep_log node: m02 path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/control-plane-timeline.txt" @@ -359,14 +359,6 @@ phases: - action: assert_greater actual: "{{ product_event_candidate_count }}" threshold: "0" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation/cluster-evidence.json" - pattern: "\"event_type\": \"authority_published\"" - save_as: product_event_authority_count - - action: assert_greater - actual: "{{ product_event_authority_count }}" - threshold: "0" - action: grep_log node: m02 path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation/cluster-evidence.json"