diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go new file mode 100644 index 0000000000..82b6dd78f3 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go @@ -0,0 +1,254 @@ +package main_test + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "testing" +) + +// The checks below read the product's own output for each step of the +// planned hand-over (docs/volume-lifecycle.md). The binary test applies +// them to live output; TestPlannedHandoffChecksReadCapturedProductOutput +// applies them to output captured from the real binaries +// (testdata/planned-handoff), so they run in every default test run. + +func checkShowBeforeStart(out string) error { + return wantLines(out, "volume: v1 (query snapshot, not authority to serve)", "replica: none", "recorded ACK: none") +} + +func checkShowGranted(out string, e uint64) error { + return wantLines(out, "replica: r1", fmt.Sprintf("epoch: %d", e), "lease state: granted", + fmt.Sprintf("holder: r1@%d (logical replica)", e), "recorded ACK: none") +} + +// adoptedEpoch reads E from blockvolume's adoption line. +func adoptedEpoch(line string) (uint64, error) { + e, err := matchUint(regexp.MustCompile(`blockvolume: volume v1 adopted as PRIMARY at r1@(\d+) `), line) + if err == nil && e == 0 { + err = fmt.Errorf("adopted at epoch 0: %q", line) + } + return e, err +} + +// sealedGen reads G from a plain detach: one JSON object on stdout and +// exactly the sealed-generation line on stderr. +func sealedGen(stdout, stderr string, e uint64) (uint64, error) { + var a struct { + VolumeID string `json:"volumeID"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + LastWrittenLSN uint64 `json:"lastWrittenLSN"` + } + if err := json.Unmarshal([]byte(stdout), &a); err != nil { + return 0, fmt.Errorf("plain detach stdout is not the JSON answer: %v: %q", err, stdout) + } + if a.VolumeID != "v1" || a.HeadGen == 0 || a.HeadEpoch != e || a.CutLSN == 0 || a.LastWrittenLSN == 0 { + return 0, fmt.Errorf("plain detach answer %+v; want v1, a generation, epoch %d and both LSNs after a write", a, e) + } + if strings.TrimSpace(stderr) != fmt.Sprintf("sealed HEAD generation: %d", a.HeadGen) { + return 0, fmt.Errorf("plain detach stderr %q; want exactly the sealed generation line", stderr) + } + return a.HeadGen, nil +} + +type detachedBy struct { + Holder string `json:"holder"` + Epoch uint64 `json:"epoch"` + Gen uint64 `json:"gen"` +} + +type headRecord struct { + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + State string `json:"state"` + RemoteLSN uint64 `json:"remoteLSN"` + DetachedBy *detachedBy `json:"detachedBy"` +} + +func parseHead(out string) (headRecord, error) { + var shown struct { + Head *headRecord `json:"head"` + } + if err := json.Unmarshal([]byte(out), &shown); err != nil || shown.Head == nil { + return headRecord{}, fmt.Errorf("chunk show stdout has no head: %v: %q", err, out) + } + return *shown.Head, nil +} + +// sealedHeadLSN checks HEAD after the seal and returns its remote LSN (L). +func sealedHeadLSN(out string, e, g uint64) (uint64, error) { + h, err := parseHead(out) + if err != nil { + return 0, err + } + if h.Gen != g || h.Epoch != e || h.Holder != "s1/r1" || h.State != "detached" || + h.DetachedBy == nil || *h.DetachedBy != (detachedBy{Holder: "s1/r1", Epoch: e, Gen: g}) { + return 0, fmt.Errorf("HEAD after the seal %+v; want gen %d epoch %d holder s1/r1 detached by itself", h, g, e) + } + return h.RemoteLSN, nil +} + +func checkRevoke(out string, e, g uint64) error { + if !strings.HasPrefix(out, fmt.Sprintf("revocation requested: volume v1 holder r1@%d expiry_ns ", e)) { + return fmt.Errorf("revoke stdout %q", out) + } + return wantLines(out, fmt.Sprintf("operator-stated sealed HEAD generation: %d (not verified); workspace show must report ACK at this generation before move --clean", g)) +} + +func showsAck(out string, e, g uint64) bool { + return hasLine(out, fmt.Sprintf("recorded ACK: r1@%d HEAD generation %d", e, g)) +} + +// movedEpoch reads E2 from the clean move's answer. +func movedEpoch(out string, e, g, l uint64) (uint64, error) { + issued := regexp.MustCompile(fmt.Sprintf(`^clean move issued: volume v1 request move-v1-1: r1@%d -> r1@(\d+) on s1 \(sealed HEAD gen %d, remote LSN %d\)$`, e, g, l)) + first, _, _ := strings.Cut(out, "\n") + e2, err := matchUint(issued, strings.TrimRight(first, "\r")) + if err != nil { + return 0, err + } + if e2 <= e { + return 0, fmt.Errorf("clean move issued epoch %d; want above %d", e2, e) + } + return e2, wantLines(out, "next: start volume v1 on s1 (this command moved authority only)") +} + +func checkClaimDone(line string, e2 uint64) error { + if !strings.Contains(line, "durable: HEAD claim for volume=v1 done in") || !strings.Contains(line, fmt.Sprintf(`epoch=%d holder="s1/r1"`, e2)) { + return fmt.Errorf("HEAD claim %q; want done at epoch %d holder s1/r1", line, e2) + } + return nil +} + +func checkShowMoved(out string, e, e2, g, l uint64) error { + return wantLines(out, fmt.Sprintf("epoch: %d", e2), "lease state: granted", + fmt.Sprintf("holder: r1@%d (logical replica)", e2), "recorded ACK: none", + fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s1/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l)) +} + +func checkHeadReopened(out string, e2, g, l uint64) error { + h, err := parseHead(out) + if err != nil { + return err + } + if h.State != "active" || h.Epoch != e2 || h.Holder != "s1/r1" || h.Gen <= g || h.RemoteLSN != l || h.DetachedBy != nil { + return fmt.Errorf("HEAD after the reopen %+v; want active, epoch %d, holder s1/r1, gen above %d, remote LSN %d, not detached", h, e2, g, l) + } + return nil +} + +// statusPrimary reports whether a /status?volume=v1 body shows a healthy +// primary at epoch. +func statusPrimary(body []byte, epoch uint64) bool { + var st struct { + Epoch uint64 + Healthy bool + AuthorityRole string + } + return json.Unmarshal(body, &st) == nil && st.Epoch == epoch && st.Healthy && st.AuthorityRole == "primary" +} + +func hasLine(out, want string) bool { + for _, l := range strings.Split(out, "\n") { + if strings.TrimRight(l, "\r") == want { + return true + } + } + return false +} + +func wantLines(out string, want ...string) error { + for _, w := range want { + if !hasLine(out, w) { + return fmt.Errorf("no line %q in:\n%s", w, out) + } + } + return nil +} + +func matchUint(re *regexp.Regexp, s string) (uint64, error) { + m := re.FindStringSubmatch(s) + if m == nil { + return 0, fmt.Errorf("%q does not match %s", s, re) + } + return strconv.ParseUint(m[1], 10, 64) +} + +// TestPlannedHandoffChecksReadCapturedProductOutput runs every check on the +// output the real binaries printed in one passing hand-over (E=1, G=3, L=1, +// E2=2), and each check on an output of another step, which it must refuse. +func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) { + read := func(name string) string { + b, err := os.ReadFile(filepath.Join("testdata", "planned-handoff", name)) + if err != nil { + t.Fatal(err) + } + return strings.ReplaceAll(string(b), "\r\n", "\n") + } + logLine := func(s string) string { + for _, l := range strings.Split(read("logs.txt"), "\n") { + if strings.Contains(l, s) { + return l + } + } + t.Fatalf("logs.txt has no line with %q", s) + return "" + } + ok := func(what string, err error) { + t.Helper() + if err != nil { + t.Errorf("%s: %v", what, err) + } + } + refused := func(what string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s: accepted the output of another step", what) + } + } + const e, g, l, e2 = 1, 3, 1, 2 + + ok("show before start", checkShowBeforeStart(read("show-before-start.stdout"))) + refused("show before start", checkShowBeforeStart(read("show-granted.stdout"))) + if got, err := adoptedEpoch(logLine("adopted as PRIMARY at r1@1 ")); err != nil || got != e { + t.Errorf("adopted epoch %d, %v; want %d", got, err, e) + } + ok("show granted", checkShowGranted(read("show-granted.stdout"), e)) + refused("show granted", checkShowGranted(read("show-acked.stdout"), e)) + if got, err := sealedGen(read("detach-plain.stdout"), read("detach-plain.stderr"), e); err != nil || got != g { + t.Errorf("sealed gen %d, %v; want %d", got, err, g) + } + _, err := sealedGen(read("detach-plain.stdout"), "", e) + refused("sealed gen without its stderr line", err) + if got, err := sealedHeadLSN(read("head-sealed.stdout"), e, g); err != nil || got != l { + t.Errorf("sealed HEAD LSN %d, %v; want %d", got, err, l) + } + _, err = sealedHeadLSN(read("head-reopened.stdout"), e, g) + refused("sealed HEAD", err) + ok("revoke", checkRevoke(read("revoke.stdout"), e, g)) + refused("revoke", checkRevoke(read("move-clean.stdout"), e, g)) + if !showsAck(read("show-acked.stdout"), e, g) || showsAck(read("show-granted.stdout"), e, g) { + t.Error("the ACK line is not told apart from a show without it") + } + if got, err := movedEpoch(read("move-clean.stdout"), e, g, l); err != nil || got != e2 { + t.Errorf("moved epoch %d, %v; want %d", got, err, e2) + } + _, err = movedEpoch(read("move-clean.stdout"), e, g+1, l) + refused("clean move at another generation", err) + ok("claim done", checkClaimDone(logLine(`gen=4 epoch=2 holder="s1/r1"`), e2)) + refused("claim done", checkClaimDone(logLine(`gen=2 epoch=1 holder="s1/r1"`), e2)) + ok("show moved", checkShowMoved(read("show-moved.stdout"), e, e2, g, l)) + refused("show moved", checkShowMoved(read("show-granted.stdout"), e, e2, g, l)) + ok("HEAD reopened", checkHeadReopened(read("head-reopened.stdout"), e2, g, l)) + refused("HEAD reopened", checkHeadReopened(read("head-sealed.stdout"), e2, g, l)) + if !statusPrimary([]byte(read("status-primary.json")), e2) || statusPrimary([]byte(read("status-primary.json")), e) { + t.Error("status check does not read the epoch of a healthy primary") + } +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 7627a59ca5..e7270fa060 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -3,18 +3,177 @@ package main_test import ( + "bytes" "context" + "crypto/sha256" + "fmt" + "io" + "net" + "net/http" "os" "os/exec" "path/filepath" "strings" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" ) +// TestStandalonePlannedHandoffToTheSameHost runs the planned hand-over back +// to the same host with the commands of docs/volume-lifecycle.md, in its +// order and form, against real blockmaster, blockvolume, sw-block and +// SeaweedFS processes on loopback: cluster spec, start, write, plain detach, +// revoke with the sealed generation, the old process acknowledges and exits +// by itself, show the ACK, clean move to the same host, start again, and the +// written block reads back unchanged. +func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) { + h := newPlannedHandoffHarness(t) + cluster := startWorkspaceWeed(t) + chunkPath := fmt.Sprintf("/handoff-%d", time.Now().UnixNano()) + const nqn = "nqn.2026-11.io.seaweedfs:handoff" + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + mustU := func(v uint64, err error) uint64 { + t.Helper() + must(err) + return v + } + + // 1. The cluster spec. + spec := filepath.Join(h.dir, "cluster-spec.yaml") + must(os.WriteFile(spec, []byte(fmt.Sprintf(`nodes: + - server_id: s1 + data_addr: %s + ctrl_addr: %s +volumes: + - id: v1 + size_bytes: 268435456 + replication_factor: 1 + placements: + - server_id: s1 + replica_id: r1 +`, h.dataAddr, h.ctrlAddr)), 0o644)) + + // 2. blockmaster with the lifecycle store and the cluster spec. + 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://"+cluster.filerHTTP+chunkPath) + if l := master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded="); !strings.Contains(l, "listen="+h.masterAddr) { + t.Fatalf("blockmaster start line %q does not name listen=%s", l, h.masterAddr) + } + if master.has("blockmaster: WARNING: --topology not supplied or empty") { + t.Fatal("blockmaster warned about a missing topology although the cluster spec gives it") + } + + // 3. The setup answers before any blockvolume runs. + show := []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"} + out, _ := h.command(t, show...) + must(checkShowBeforeStart(out)) + + // 4. blockvolume adopts the volume. + volArgs := []string{"--master", h.masterAddr, "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", + "--data-addr", h.dataAddr, "--ctrl-addr", h.ctrlAddr, "--status-addr", h.statusAddr, + "--durable-root", filepath.Join(h.dir, "vol"), "--durable-impl", "walstore-chunk", + "--durable-blocks", "65536", "--durable-blocksize", "4096", + "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath, "--chunk-control-endpoint", + "--workspace-lease", "--nvme-listen", h.nvmeAddr, "--nvme-subsysnqn", nqn} + vol1 := h.start(t, "blockvolume-1", h.volume, volArgs...) + e := mustU(adoptedEpoch(vol1.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) + vol1.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in") + h.waitPrimary(t, e) + + // 5. The lease. + out, _ = h.command(t, show...) + must(checkShowGranted(out, e)) + + // 6, 7. Write a known block and flush it, then disconnect the writer. + block := bytes.Repeat([]byte("planned-handoff!"), 4096/16) + want := sha256.Sum256(block) + c := dialNVMe(t, h.nvmeAddr, nqn) + c.write(t, 0, block) + c.flush(t) + c.close() + + // 8. Seal with a plain detach. + out, errOut := h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", h.statusAddr, "--timeout", "120s") + g := mustU(sealedGen(out, errOut, e)) + + // 9. The seal is in the object store. + chunkShow := []string{"ops", "chunk", "show", "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath} + out, _ = h.command(t, chunkShow...) + l := mustU(sealedHeadLSN(out, e, g)) + + // 10. Revoke with the sealed generation. + out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g)) + must(checkRevoke(out, e, g)) + + // 11. The old blockvolume acknowledges and exits by itself (a signal + // would suppress the ACK). + if err := vol1.wait(45 * time.Second); err != nil { + t.Fatalf("blockvolume after the revocation: %v; want a clean exit by itself", err) + } + if !vol1.has(fmt.Sprintf("workspace lease: fenced volume=v1 replica=r1 epoch=%d: revoked by the master", e)) || + !vol1.has("blockvolume: stopping: the workspace lease guard fenced and requested the drain") { + t.Fatal("blockvolume log does not show the revocation fence and drain") + } + if vol1.has("blockvolume: workspace lease closeout:") { + t.Fatal("blockvolume reported a closeout error") + } + + // 12. The master recorded the ACK at the sealed generation. + poll(t, 30*time.Second, fmt.Sprintf("workspace show never reported the ACK of r1@%d at generation %d", e, g), func() bool { + out, _ := h.command(t, show...) + return showsAck(out, e, g) + }) + + // 13. Clean move to the same host; a rerun replays the issued move. + move := []string{"ops", "workspace", "move", "--clean", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--target-host", "s1", "--target-data", h.dataAddr, "--target-ctrl", h.ctrlAddr, + "--request-id", "move-v1-1"} + moved, _ := h.command(t, move...) + e2 := mustU(movedEpoch(moved, e, g, l)) + if again, _ := h.command(t, move...); again != moved { + t.Fatalf("clean move rerun answered %q; want the issued move again %q", again, moved) + } + + // 14. Start again with the same root, within the new lease (30 s). + vol2 := h.start(t, "blockvolume-2", h.volume, volArgs...) + vol2.waitLog(t, 60*time.Second, fmt.Sprintf(`durable: HEAD claim for volume=v1 starting: target epoch=%d holder="s1/r1"`, e2)) + must(checkClaimDone(vol2.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2)) + vol2.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume v1 adopted as PRIMARY at r1@%d", e2)) + for _, bad := range []string{"refusing to attach volume=v1", "assignment unavailable, not serving"} { + if vol2.has(bad) { + t.Fatalf("the restarted blockvolume logged %q", bad) + } + } + h.waitPrimary(t, e2) + + // 15. The new lease and the move record. + out, _ = h.command(t, show...) + must(checkShowMoved(out, e, e2, g, l)) + + // 16. The new epoch claimed HEAD. + out, _ = h.command(t, chunkShow...) + must(checkHeadReopened(out, e2, g, l)) + + // 17. The block written before the hand-over reads back unchanged. + c = dialNVMe(t, h.nvmeAddr, nqn) + defer c.close() + if got := sha256.Sum256(c.read(t, 0, 4096)); got != want { + t.Fatalf("block 0 after the hand-over has sha256 %x; want %x", got, want) + } +} + // plannedHandoffHarness owns real binaries, loopback endpoints and process -// lifetimes. The lifecycle test will use the commands and observables supplied -// with docs/volume-lifecycle.md; this scaffold makes no hand-over claim yet. +// lifetimes. type plannedHandoffHarness struct { dir string master, volume, cli string @@ -55,9 +214,18 @@ func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness { return h } +// daemon is one started child: its log file and its exit. +type daemon struct { + name, log string + done chan struct{} + err error +} + // start registers cancellation and a bounded join before starting a daemon. // Each child writes to its own file, and cleanup targets only that child. -func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args ...string) { +// Cancellation kills the child; a test that needs a child to exit by itself +// waits for it with wait. +func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args ...string) *daemon { t.Helper() log, err := os.Create(filepath.Join(h.dir, name+".log")) if err != nil { @@ -67,20 +235,20 @@ func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args .. cmd := exec.CommandContext(ctx, binary, args...) cmd.Dir, cmd.Stdout, cmd.Stderr = h.dir, log, log cmd.WaitDelay = 5 * time.Second - done := make(chan error, 1) + d := &daemon{name: name, log: log.Name(), done: make(chan struct{})} started := false t.Cleanup(func() { cancel() if started { select { - case <-done: + case <-d.done: case <-time.After(10 * time.Second): t.Errorf("%s did not exit after cancellation", name) } } _ = log.Close() if t.Failed() { - data, _ := os.ReadFile(log.Name()) + data, _ := os.ReadFile(d.log) if len(data) > 16000 { data = data[len(data)-16000:] } @@ -91,14 +259,64 @@ func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args .. t.Fatalf("start %s: %v", name, err) } started = true - go func() { done <- cmd.Wait() }() + go func() { d.err = cmd.Wait(); close(d.done) }() + return d +} + +// wait waits up to timeout for the child to exit by itself and returns its +// exit error (nil: status 0). +func (d *daemon) wait(timeout time.Duration) error { + select { + case <-d.done: + return d.err + case <-time.After(timeout): + return fmt.Errorf("%s still running after %s", d.name, timeout) + } +} + +// line returns the first log line containing s ("" if none). +func (d *daemon) line(s string) string { + data, _ := os.ReadFile(d.log) + for _, l := range strings.Split(string(data), "\n") { + if strings.Contains(l, s) { + return l + } + } + return "" +} + +func (d *daemon) has(s string) bool { return d.line(s) != "" } + +// waitLog waits for a log line containing s and returns it. A child that +// exits first fails the test at once. +func (d *daemon) waitLog(t *testing.T, timeout time.Duration, s string) string { + t.Helper() + end := time.Now().Add(timeout) + for { + if l := d.line(s); l != "" { + return l + } + select { + case <-d.done: + if l := d.line(s); l != "" { + return l + } + t.Fatalf("%s exited (%v) before logging %q", d.name, d.err, s) + default: + } + if time.Now().After(end) { + t.Fatalf("%s did not log %q within %s", d.name, s, timeout) + } + time.Sleep(100 * time.Millisecond) + } } // command keeps stdout separate from stderr: detach stdout remains JSON while // its sealed-generation line is read from stderr by the documented sequence. +// The bound covers the detach's own --timeout 120s. func (h *plannedHandoffHarness) command(t *testing.T, args ...string) (string, string) { t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) defer cancel() cmd := exec.CommandContext(ctx, h.cli, args...) cmd.Dir = h.dir @@ -110,3 +328,188 @@ func (h *plannedHandoffHarness) command(t *testing.T, args ...string) (string, s } return stdout.String(), stderr.String() } + +// waitPrimary polls the status endpoint until the volume serves as a +// healthy primary at epoch. +func (h *plannedHandoffHarness) waitPrimary(t *testing.T, epoch uint64) { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + poll(t, 60*time.Second, fmt.Sprintf("status never showed a healthy primary at epoch %d", epoch), func() bool { + resp, err := c.Get("http://" + h.statusAddr + "/status?volume=v1") + if err != nil { + return false + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return statusPrimary(b, epoch) + }) +} + +func poll(t *testing.T, timeout time.Duration, what string, fn func() bool) { + t.Helper() + end := time.Now().Add(timeout) + for !fn() { + if time.Now().After(end) { + t.Fatal(what) + } + time.Sleep(time.Second) + } +} + +// nvmeInitiator is the smallest NVMe/TCP host the test needs: one admin and +// one IO queue, Write, Flush and Read of namespace 1. It runs in the test +// process, so the test needs neither root nor the kernel's nvme_tcp. +type nvmeInitiator struct { + admin, io net.Conn + r *nvme.Reader + w *nvme.Writer + cid uint16 +} + +func dialNVMe(t *testing.T, addr, subNQN string) *nvmeInitiator { + t.Helper() + c := &nvmeInitiator{} + cd := nvme.ConnectData{HostID: [16]byte{0x5e, 0xa1}, SubNQN: subNQN, HostNQN: "nqn.2026-11.io.seaweedfs:handoff-test"} + var cntlID uint16 + for qid := uint32(0); qid <= 1; qid++ { + conn, err := net.DialTimeout("tcp", addr, 5*time.Second) + if err != nil { + t.Fatalf("nvme dial %s: %v", addr, err) + } + _ = conn.SetDeadline(time.Now().Add(60 * time.Second)) + r, w := nvme.NewReader(conn), nvme.NewWriter(conn) + if err := w.SendHeaderOnly(0x0, &nvme.ICRequest{PDUMaxR2T: 1}, 120); err != nil { + t.Fatalf("nvme ICReq: %v", err) + } + if ch, err := r.Dequeue(); err != nil || ch.Type != 0x1 { + t.Fatalf("nvme ICResp: type %v err %v", ch, err) + } + if err := r.Receive(&nvme.ICResponse{}); err != nil { + t.Fatalf("nvme ICResp body: %v", err) + } + // The admin queue asks for a controller; the IO queue names it. + cd.CNTLID = 0xFFFF + if qid == 1 { + cd.CNTLID = cntlID + } + buf := make([]byte, 1024) + cd.Marshal(buf) + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 0x7F, FCType: 0x01, CID: c.cid, D10: qid << 16} + if err := w.SendWithData(0x4, 0, &cmd, 64, buf); err != nil { + t.Fatalf("nvme Connect qid %d: %v", qid, err) + } + resp := nvmeResponse(t, r) + if resp.Status != 0 { + t.Fatalf("nvme Connect qid %d status 0x%04x", qid, resp.Status) + } + if qid == 0 { + c.admin, cntlID = conn, uint16(resp.DW0&0xFFFF) + } else { + c.io, c.r, c.w = conn, r, w + } + } + return c +} + +func nvmeResponse(t *testing.T, r *nvme.Reader) nvme.CapsuleResponse { + t.Helper() + ch, err := r.Dequeue() + if err != nil || ch.Type != 0x5 { + t.Fatalf("nvme response: type %v err %v", ch, err) + } + var resp nvme.CapsuleResponse + if err := r.Receive(&resp); err != nil { + t.Fatalf("nvme response body: %v", err) + } + return resp +} + +func (c *nvmeInitiator) ioCmd(op uint8, lba uint64, blocks int) nvme.CapsuleCommand { + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: op, CID: c.cid, NSID: 1} + if blocks > 0 { + cmd.D10, cmd.D11, cmd.D12 = uint32(lba), uint32(lba>>32), uint32(blocks-1) + } + return cmd +} + +func (c *nvmeInitiator) write(t *testing.T, lba uint64, data []byte) { + t.Helper() + cmd := c.ioCmd(0x01, lba, len(data)/4096) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatalf("nvme Write: %v", err) + } + ch, err := c.r.Dequeue() + if err != nil || ch.Type != 0x9 { + t.Fatalf("nvme Write: want R2T, got type %v err %v", ch, err) + } + var r2t nvme.R2THeader + if err := c.r.Receive(&r2t); err != nil { + t.Fatalf("nvme R2T: %v", err) + } + h2c := nvme.H2CDataHeader{CCCID: cmd.CID, TAG: r2t.TAG, DATAL: uint32(len(data))} + if err := c.w.SendWithData(0x6, 0, &h2c, 16, data); err != nil { + t.Fatalf("nvme H2CData: %v", err) + } + if resp := nvmeResponse(t, c.r); resp.Status != 0 { + t.Fatalf("nvme Write status 0x%04x", resp.Status) + } +} + +func (c *nvmeInitiator) flush(t *testing.T) { + t.Helper() + cmd := c.ioCmd(0x00, 0, 0) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatalf("nvme Flush: %v", err) + } + if resp := nvmeResponse(t, c.r); resp.Status != 0 { + t.Fatalf("nvme Flush status 0x%04x", resp.Status) + } +} + +func (c *nvmeInitiator) read(t *testing.T, lba uint64, n int) []byte { + t.Helper() + cmd := c.ioCmd(0x02, lba, n/4096) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatalf("nvme Read: %v", err) + } + var data []byte + for { + ch, err := c.r.Dequeue() + if err != nil { + t.Fatalf("nvme Read: %v", err) + } + if ch.Type == 0x5 { + var resp nvme.CapsuleResponse + if err := c.r.Receive(&resp); err != nil || resp.Status != 0 { + t.Fatalf("nvme Read status 0x%04x err %v", resp.Status, err) + } + break + } + if ch.Type != 0x7 { + t.Fatalf("nvme Read: unexpected PDU type 0x%x", ch.Type) + } + var dh nvme.C2HDataHeader + if err := c.r.Receive(&dh); err != nil { + t.Fatalf("nvme C2HData: %v", err) + } + part := make([]byte, c.r.Length()) + if err := c.r.ReceiveData(part); err != nil { + t.Fatalf("nvme C2HData payload: %v", err) + } + data = append(data, part...) + } + if len(data) != n { + t.Fatalf("nvme Read returned %d bytes; want %d", len(data), n) + } + return data +} + +func (c *nvmeInitiator) close() { + for _, conn := range []net.Conn{c.io, c.admin} { + if conn != nil { + _ = conn.Close() + } + } +} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stderr b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stderr new file mode 100644 index 0000000000..cf507d69b7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stderr @@ -0,0 +1 @@ +sealed HEAD generation: 3 diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stdout new file mode 100644 index 0000000000..4bc78cc8be --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","cutLSN":1,"headGen":3,"headEpoch":1,"lastWrittenLSN":1} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened.stdout new file mode 100644 index 0000000000..747b6e56dc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795337541307771858,"parent":null},"head":{"gen":4,"epoch":2,"holder":"s1/r1","remoteLSN":1,"state":"active","detachedBy":null,"chunkCount":1}} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-sealed.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-sealed.stdout new file mode 100644 index 0000000000..af1de786d9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-sealed.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795337541307771858,"parent":null},"head":{"gen":3,"epoch":1,"holder":"s1/r1","remoteLSN":1,"state":"detached","detachedBy":{"holder":"s1/r1","epoch":1,"gen":3},"chunkCount":1}} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/logs.txt b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/logs.txt new file mode 100644 index 0000000000..3645c7a9f4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/logs.txt @@ -0,0 +1,9 @@ +2026/11/22 00:52:20 blockmaster: lock acquired, reloaded=0, listen=127.0.0.1:44358 +2026/11/22 00:52:21 blockvolume: volume v1 adopted as PRIMARY at r1@1 (EV=1) +2026/11/22 00:52:21 durable: HEAD claim for volume=v1 starting: target epoch=1 holder="s1/r1" +2026/11/22 00:52:21 durable: HEAD claim for volume=v1 done in 2.250367ms: gen=2 epoch=1 holder="s1/r1" +2026/11/22 00:52:21 workspace lease: fenced volume=v1 replica=r1 epoch=1: revoked by the master +blockvolume: stopping: the workspace lease guard fenced and requested the drain +2026/11/22 00:52:22 blockvolume: volume v1 adopted as PRIMARY at r1@2 (EV=1) +2026/11/22 00:52:22 durable: HEAD claim for volume=v1 starting: target epoch=2 holder="s1/r1" +2026/11/22 00:52:22 durable: HEAD claim for volume=v1 done in 3.597902ms: gen=4 epoch=2 holder="s1/r1" diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean.stdout new file mode 100644 index 0000000000..94de184444 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean.stdout @@ -0,0 +1,2 @@ +clean move issued: volume v1 request move-v1-1: r1@1 -> r1@2 on s1 (sealed HEAD gen 3, remote LSN 1) +next: start volume v1 on s1 (this command moved authority only) diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/revoke.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/revoke.stdout new file mode 100644 index 0000000000..d8f6e00f41 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/revoke.stdout @@ -0,0 +1,2 @@ +revocation requested: volume v1 holder r1@1 expiry_ns 1795337571673280526 +operator-stated sealed HEAD generation: 3 (not verified); workspace show must report ACK at this generation before move --clean diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-acked.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-acked.stdout new file mode 100644 index 0000000000..8eae3b9488 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-acked.stdout @@ -0,0 +1,8 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 1 +lease state: revoking +holder: r1@1 (logical replica) +lease expiry_ns: 1795337571673280526; host validity_ns at query: 19706858270 +recorded ACK: r1@1 HEAD generation 3 +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-before-start.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-before-start.stdout new file mode 100644 index 0000000000..284ab8c607 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-before-start.stdout @@ -0,0 +1,7 @@ +volume: v1 (query snapshot, not authority to serve) +replica: none +epoch: none +lease state: none +holder: none +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-granted.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-granted.stdout new file mode 100644 index 0000000000..71488987f4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-granted.stdout @@ -0,0 +1,8 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 1 +lease state: granted +holder: r1@1 (logical replica) +lease expiry_ns: 1795337571294082097; host validity_ns at query: 19891253918 +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-moved.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-moved.stdout new file mode 100644 index 0000000000..40e1fe5ca0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-moved.stdout @@ -0,0 +1,9 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 2 +lease state: granted +holder: r1@2 (logical replica) +lease expiry_ns: 1795337572110285858; host validity_ns at query: 19885280122 +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts +move: request=move-v1-1 kind=clean issued=true s1/r1@1 -> s1/r1@2 HEAD generation 3 remote LSN 1 diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/status-primary.json b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/status-primary.json new file mode 100644 index 0000000000..f33bc5ac9a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/status-primary.json @@ -0,0 +1 @@ +{"VolumeID":"v1","ReplicaID":"r1","Epoch":2,"EndpointVersion":1,"Healthy":true,"Memory":{"HeapAllocBytes":1520736,"HeapInuseBytes":3547136,"HeapSysBytes":7503872,"HeapReleasedBytes":3194880,"SoftLimitBytes":268435456,"RSSBytes":21516288,"AnonymousRSSBytes":5230592},"FrontendPrimaryReady":true,"AuthorityRole":"primary","ReplicationRole":"none"}