test: #425 red: the forced move's epoch-2 lines carry the new owner's endpoints (procedure gate)

Brings the two-process procedure gate (origin/test/procedure-gate, its three test
files) onto main and adds the assertion to TestProcedureForcedMoveWithTheOldHostReturning:
every assignment line delivered at the forced epoch, to s2 and to the returning s1, carries
s2's own data and control endpoints (V1-SPEC r2.40, INV-AUTH-HOLDER-IDENTITY-001).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-22 06:00:00 -08:00
1 parent 0218544115
commit d73acc54e9
3 files changed
+634 -38

No files matched your search

@@ -106,9 +106,12 @@ 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))
// movedEpoch reads E2 from the clean move's answer to s1.
func movedEpoch(out string, e, g, l uint64) (uint64, error) { return movedEpochTo(out, e, g, l, "s1") }
// movedEpochTo reads E2 from the clean move's answer to the target host.
func movedEpochTo(out string, e, g, l uint64, target string) (uint64, error) {
issued := regexp.MustCompile(fmt.Sprintf(`^clean move issued: volume v1 request move-v1-1: r1@%d -> r1@(\d+) on %s \(sealed HEAD gen %d, remote LSN %d\)$`, e, regexp.QuoteMeta(target), g, l))
first, _, _ := strings.Cut(out, "\n")
e2, err := matchUint(issued, strings.TrimRight(first, "\r"))
if err != nil {
@@ -117,12 +120,14 @@ func movedEpoch(out string, e, g, l uint64) (uint64, error) {
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)")
return e2, wantLines(out, fmt.Sprintf("next: start volume v1 on %s (this command moved authority only)", target))
}
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)
func checkClaimDone(line string, e2 uint64) error { return checkClaimDoneBy(line, e2, "s1") }
func checkClaimDoneBy(line string, e2 uint64, host string) error {
if !strings.Contains(line, "durable: HEAD claim for volume=v1 done in") || !strings.Contains(line, fmt.Sprintf(`epoch=%d holder="%s/r1"`, e2, host)) {
return fmt.Errorf("HEAD claim %q; want done at epoch %d holder %s/r1", line, e2, host)
}
return nil
}
@@ -134,16 +139,48 @@ func checkShowMoved(out string, e, e2, g, l uint64) error {
}
func checkHeadReopened(out string, e2, g, l uint64) error {
return checkHeadReopenedBy(out, e2, g, l, "s1")
}
func checkHeadReopenedBy(out string, e2, g, l uint64, host string) 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)
if h.State != "active" || h.Epoch != e2 || h.Holder != host+"/r1" || h.Gen <= g || h.RemoteLSN != l || h.DetachedBy != nil {
return fmt.Errorf("HEAD after the reopen %+v; want active, epoch %d, holder %s/r1, gen above %d, remote LSN %d, not detached", h, e2, host, g, l)
}
return nil
}
// forcedEpoch reads E2 from a forced move's answer (`forced move issued:
// ... r1@E on FROM -> r1@E2 on TO (kept HEAD gen N, remote LSN L)`).
func forcedEpoch(out string, e uint64, from, to string) (uint64, error) {
re := regexp.MustCompile(fmt.Sprintf(`(?m)^forced move issued: volume v1 request \S+: r1@%d on %s -> r1@(\d+) on %s \(kept HEAD gen \d+, remote LSN \d+\)$`, e, regexp.QuoteMeta(from), regexp.QuoteMeta(to)))
e2, err := matchUint(re, out)
if err == nil && e2 <= e {
err = fmt.Errorf("forced move issued epoch %d; want above %d", e2, e)
}
return e2, err
}
// forcedKeptLSN reads the remote LSN a forced move kept.
func forcedKeptLSN(out string) (uint64, error) {
return matchUint(regexp.MustCompile(`(?m)^forced move issued: .*\(kept HEAD gen \d+, remote LSN (\d+)\)$`), out)
}
// previewAdmitted reports whether a force-move --dry-run says admitted.
func previewAdmitted(out string) bool {
return regexp.MustCompile(`(?m)^forced move admitted(: .*)?$`).MatchString(out)
}
// frontendReady reports whether a /status?volume=v1 body says the frontend
// is ready to serve as primary.
func frontendReady(body []byte) bool {
var st struct{ FrontendPrimaryReady bool }
return json.Unmarshal(body, &st) == nil && st.FrontendPrimaryReady
}
// checkCleanMoveRefused checks a clean move refused for a missing ACK: exit
// 1 (a failed precondition), nothing on stdout, the documented error.
func checkCleanMoveRefused(stdout, stderr string, code int) error {
@@ -265,6 +302,9 @@ func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) {
if r := read("show-revoked.stdout"); showsAck(r, e, g) || !hasLine(r, "recorded ACK: none") {
t.Error("the revoked show without an ACK is read as acknowledged")
}
if !frontendReady([]byte(read("status-primary.json"))) || frontendReady([]byte(`{"FrontendPrimaryReady":false,"Healthy":true}`)) {
t.Error("the frontend-ready check does not read FrontendPrimaryReady")
}
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")
}
@@ -9,12 +9,14 @@ import (
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -159,37 +161,67 @@ func TestStandaloneCleanMoveWithoutTheACKIsRefused(t *testing.T) {
const plannedHandoffNQN = "nqn.2026-11.io.seaweedfs:handoff"
// startPlannedHandoff runs the chapter's steps 1-3: a weed cluster, the
// cluster spec, blockmaster with the lifecycle store, and the setup check.
// It returns the blockvolume arguments of step 4 and the show command.
// startPlannedHandoff runs the chapter's steps 1-3 for one host, s1, and
// returns the blockvolume arguments of step 4 and the show command.
func startPlannedHandoff(t *testing.T) (h *plannedHandoffHarness, cluster *w4WeedCluster, chunkPath string, show, volArgs []string) {
t.Helper()
h = newPlannedHandoffHarness(t)
cluster = startWorkspaceWeed(t)
chunkPath = fmt.Sprintf("/handoff-%d", time.Now().UnixNano())
env := startHandoffEnv(t, 1)
return env.h, env.cluster, env.chunkPath, env.show, env.volArgs("s1")
}
// handoffEnv is a running setup: weed, blockmaster with the cluster spec
// naming every host, and the hosts' blockvolume endpoints. The volume starts
// on s1.
type handoffEnv struct {
h *plannedHandoffHarness
cluster *w4WeedCluster
chunkPath string
show []string
hosts map[string]bvHost
}
// bvHost is one host's blockvolume: its server id, endpoints and local root.
type bvHost struct {
id, data, ctrl, status, nvme, root string
}
// startHandoffEnv runs the chapter's steps 1-3: a weed cluster, the cluster
// spec with hosts s1..sN, blockmaster with the lifecycle store (and
// masterArgs), and the setup check.
func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv {
t.Helper()
h := newPlannedHandoffHarness(t)
env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
must, _ := fatalOn(t)
env.hosts["s1"] = bvHost{id: "s1", data: h.dataAddr, ctrl: h.ctrlAddr, status: h.statusAddr, nvme: h.nvmeAddr, root: filepath.Join(h.dir, "vol")}
for i := 2; i <= n; i++ {
id := fmt.Sprintf("s%d", i)
env.hosts[id] = bvHost{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)}
}
cluster, chunkPath := env.cluster, env.chunkPath
// 1. The cluster spec.
var nodes strings.Builder
for i := 1; i <= n; i++ {
b := env.hosts[fmt.Sprintf("s%d", i)]
fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", b.id, b.data, b.ctrl)
}
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:
must(os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+`volumes:
- id: v1
size_bytes: 268435456
replication_factor: 1
placements:
- server_id: s1
replica_id: r1
`, h.dataAddr, h.ctrlAddr)), 0o644))
`), 0o644))
// 2. blockmaster with the lifecycle store and the cluster spec.
mstate := filepath.Join(h.dir, "master")
master := h.start(t, "blockmaster", h.master,
master := h.start(t, "blockmaster", h.master, append([]string{
"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
"--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+chunkPath)
"--workspace-rpc", "--workspace-head-base-url", "http://" + cluster.filerHTTP + chunkPath}, masterArgs...)...)
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)
}
@@ -198,17 +230,21 @@ volumes:
}
// 3. The setup answers before any blockvolume runs.
show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"}
out, _ := h.command(t, show...)
env.show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"}
out, _ := h.command(t, env.show...)
must(checkShowBeforeStart(out))
return env
}
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",
// volArgs is the chapter's blockvolume command for one host.
func (env *handoffEnv) volArgs(id string) []string {
b := env.hosts[id]
return []string{"--master", env.h.masterAddr, "--server-id", b.id, "--volume-id", "v1", "--replica-id", "r1",
"--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status,
"--durable-root", b.root, "--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", plannedHandoffNQN}
return h, cluster, chunkPath, show, volArgs
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--chunk-control-endpoint",
"--workspace-lease", "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN}
}
func fatalOn(t *testing.T) (func(error), func(uint64, error) uint64) {
@@ -259,14 +295,46 @@ func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness {
t.Fatalf("build %s: %v\n%s", b.name, err, out)
}
}
h.masterAddr = leaseBinaryAddress(t)
h.dataAddr = leaseBinaryAddress(t)
h.ctrlAddr = leaseBinaryAddress(t)
h.statusAddr = leaseBinaryAddress(t)
h.nvmeAddr = leaseBinaryAddress(t)
h.masterAddr = handoffAddress(t)
h.dataAddr = handoffAddress(t)
h.ctrlAddr = handoffAddress(t)
h.statusAddr = handoffAddress(t)
h.nvmeAddr = handoffAddress(t)
return h
}
var handoffPorts struct {
sync.Mutex
used map[int]bool
}
// handoffAddress returns a free loopback address below the kernel's
// ephemeral range (32768 and up on Linux). A daemon restarted minutes later
// binds it again, and an outgoing connection may take any ephemeral port in
// between; ports below the range are never handed out that way.
func handoffAddress(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 := 21000 + rand.Intn(11000)
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 below the ephemeral range")
return ""
}
// daemon is one started child: its log file and its exit.
type daemon struct {
name, log string
@@ -414,10 +482,17 @@ func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, strin
// 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()
h.waitPrimaryAt(t, h.statusAddr, epoch)
}
// waitPrimaryAt polls one host's status endpoint until the volume serves
// there as a healthy primary at epoch.
func (h *plannedHandoffHarness) waitPrimaryAt(t *testing.T, statusAddr string, 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")
poll(t, 60*time.Second, fmt.Sprintf("status at %s never showed a healthy primary at epoch %d", statusAddr, epoch), func() bool {
resp, err := c.Get("http://" + statusAddr + "/status?volume=v1")
if err != nil {
return false
}
@@ -0,0 +1,481 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"strings"
"testing"
"time"
)
// The procedure gate: every operator procedure of docs/volume-lifecycle.md
// runs as written, with real binaries, on two blockvolume processes with
// distinct server ids (s1 and s2) sharing one blockmaster and one SeaweedFS.
// The planned return to the same host is TestStandalonePlannedHandoffToTheSameHost.
// TestProcedurePlannedHandoffToAnotherHost: the planned hand-over from s1 to
// s2. The new holder starts with no local copy, claims the sealed HEAD at the
// new epoch and serves the written block.
func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) {
env := startHandoffEnv(t, 2)
must, mustU := fatalOn(t)
h := env.h
old := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, old, "s1")
block := pattern("to-another-host!")
env.writeBlock(t, "s1", 0, block)
g := env.seal(t, "s1", e)
l := env.sealedLSN(t, e, g)
env.revoke(t, e, g)
if err := old.wait(30 * time.Second); err != nil {
t.Fatalf("s1 after the revocation: %v; want a clean exit by itself", err)
}
env.waitAck(t, e, g)
moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...)
e2 := mustU(movedEpochTo(moved, e, g, l, "s2"))
nw := env.start(t, "blockvolume-s2", "s2")
must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2"))
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("s2 adopted at epoch %d; want %d", got, e2)
}
out, _ := h.command(t, env.show...)
must(wantLines(out, fmt.Sprintf("holder: r1@%d (logical replica)", e2),
fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s2/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l)))
out, _ = h.command(t, env.chunkShow()...)
must(checkHeadReopenedBy(out, e2, g, l, "s2"))
if !bytes.Equal(env.readBlock(t, "s2", 0), block) {
t.Fatal("the block written on s1 does not read back on s2")
}
}
// TestProcedureSameHostRestartInsideTheLease: the holder's process dies and is
// started again on its host within the 30 s lease. It keeps holder and epoch
// and serves again at once from its local WAL.
func TestProcedureSameHostRestartInsideTheLease(t *testing.T) {
env := startHandoffEnv(t, 2)
must, _ := fatalOn(t)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("restart-in-lease")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
again := env.start(t, "blockvolume-s1-again", "s1")
if got := env.adopt(t, again, "s1"); got != e {
t.Fatalf("the restarted holder adopted epoch %d; want the same epoch %d", got, e)
}
out, _ := env.h.command(t, env.show...)
must(checkShowGranted(out, e))
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the restart does not read back")
}
}
// TestProcedureReturnAfterALapsedLease: the holder's process dies and stays
// down past its lease. Started again 65 s after it stopped (the page's
// bound with default flags), it is granted again at the same epoch, reclaims
// HEAD and serves its local WAL.
func TestProcedureReturnAfterALapsedLease(t *testing.T) {
env := startHandoffEnv(t, 2)
must, _ := fatalOn(t)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("after-lapsed-ttl")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
stopped := time.Now()
time.Sleep(time.Until(stopped.Add(65 * time.Second)))
back := env.start(t, "blockvolume-s1-back", "s1")
if got := env.adopt(t, back, "s1"); got != e {
t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e)
}
if back.has("assignment unavailable, not serving") {
t.Fatal("started 65 s after the stop, the holder still logged the not-serving line")
}
out, _ := env.h.command(t, env.show...)
must(checkShowGranted(out, e))
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the lapse does not read back")
}
}
// TestProcedureForcedMoveWithTheOldHostReturning: the holder on s1 dies and
// never comes back in time. A forced move to s2, admitted after the barrier,
// restores the last HEAD: a block cut before the crash is kept, one written
// after the cut is lost, as the lost range says. The old s1 process then
// returns with its old local root and must not serve; s2 keeps serving.
func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) {
env := startHandoffEnv(t, 2)
must, mustU := fatalOn(t)
h := env.h
old := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, old, "s1")
kept, lost := pattern("cut-before-crash"), pattern("after-the-cut!!!")
env.writeBlock(t, "s1", 0, kept)
h.command(t, "ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status)
env.writeBlock(t, "s1", 8, lost)
old.kill(t)
out := env.forceMove(t, e, "s2", "force-v1-1")
e2, keptLSN := mustU(forcedEpoch(out, e, "s1", "s2")), mustU(forcedKeptLSN(out))
must(wantLines(out, "next: start volume v1 on s2 (this command moved authority only)"))
if !strings.Contains(out, fmt.Sprintf("writes with LSN <= %d are preserved", keptLSN)) {
t.Fatalf("the forced move printed no lost range at LSN %d:\n%s", keptLSN, out)
}
ranges, _ := h.command(t, "ops", "workspace", "lost-range", "--master", h.masterAddr, "--volume", "v1")
if !strings.Contains(ranges, "range 1 of 1: request force-v1-1, r1@") {
t.Fatalf("lost-range does not show the forced move:\n%s", ranges)
}
nw := env.start(t, "blockvolume-s2", "s2")
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("s2 adopted at epoch %d; want %d", got, e2)
}
if !bytes.Equal(env.readBlock(t, "s2", 0), kept) {
t.Fatal("the block cut before the crash is not on s2")
}
if got := env.readBlock(t, "s2", 8); !bytes.Equal(got, make([]byte, 4096)) {
t.Fatal("the block written after the last cut reads back on s2; the page says it is lost")
}
// The old host returns with its old local root. It must not take s2's
// line as its own (a holder is server and replica), report its frontend
// ready, or listen for I/O; the page says it does not serve.
back := env.start(t, "blockvolume-s1-back", "s1")
var failures []string
end := time.Now().Add(40 * time.Second)
for time.Now().Before(end) && len(failures) == 0 {
if l := back.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" {
failures = append(failures, "it adopted s2's line: "+l)
}
if env.frontendReadyAt("s1") {
failures = append(failures, "its status reports FrontendPrimaryReady")
}
if listening(env.hosts["s1"].nvme) {
failures = append(failures, "its NVMe/TCP target listens")
}
time.Sleep(time.Second)
}
if !back.has("refusing to attach volume=v1") && !back.has("workspace lease: stale authority") && !back.has("is not this process") && !back.has("foreign assignment") {
failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)")
}
if len(failures) > 0 {
t.Errorf("the returning old host after the forced move: %s", strings.Join(failures, "; "))
}
// #425 (V1-SPEC r2.40: a line carries its owner and that owner's endpoints): every line delivered at the forced
// epoch, to the new owner and to the returning old host alike, carries s2's own endpoints, never another host's.
if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back); len(bad) > 0 {
t.Errorf("an epoch-%d line was delivered with another host's endpoints (want s2's data=%s ctrl=%s):\n%s",
e2, env.hosts["s2"].data, env.hosts["s2"].ctrl, strings.Join(bad, "\n"))
}
env.h.waitPrimaryAt(t, env.hosts["s2"].status, e2)
if !bytes.Equal(env.readBlock(t, "s2", 0), kept) {
t.Fatal("s2 no longer serves the kept block after the old host returned")
}
}
// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed and
// revoked, but its process dies before it sends the ACK. The clean move is
// refused; only a forced move to another node remains, and since HEAD is
// sealed, nothing acknowledged is lost.
func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) {
env := startHandoffEnv(t, 2)
must, mustU := fatalOn(t)
h := env.h
old := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, old, "s1")
block := pattern("sealed-no-ack!!!")
env.writeBlock(t, "s1", 0, block)
g := env.seal(t, "s1", e)
l := env.sealedLSN(t, e, g)
old.kill(t)
env.revoke(t, e, g)
o, eo, code := h.run(t, env.moveClean(e, "s2", "move-v1-1")...)
must(checkCleanMoveRefused(o, eo, code))
out := env.forceMove(t, e, "s2", "force-v1-1")
e2 := mustU(forcedEpoch(out, e, "s1", "s2"))
if got := mustU(forcedKeptLSN(out)); got != l {
t.Fatalf("the forced move kept LSN %d; want the sealed HEAD's %d", got, l)
}
nw := env.start(t, "blockvolume-s2", "s2")
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("s2 adopted at epoch %d; want %d", got, e2)
}
if !bytes.Equal(env.readBlock(t, "s2", 0), block) {
t.Fatal("the sealed block does not read back on s2")
}
}
// TestProcedureStartInsideTheBarrierWaitIsReGranted: the holder's process
// dies and is started again 40 s later: its lease has ended, the re-grant
// barrier (at least 50 s and at most 65 s after the stop, default flags) has
// not passed, and it passes within the process's 30 s authority wait. It must not
// serve while its renewals are still refused for the barrier; once
// re-granted it serves its local WAL at the same epoch.
func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) {
env := startHandoffEnv(t, 1)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("inside-the-wait!")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
time.Sleep(40 * time.Second)
back := env.start(t, "blockvolume-s1-back", "s1")
var ready []time.Time
end := time.Now().Add(90 * time.Second)
for time.Now().Before(end) {
if env.frontendReadyAt("s1") || listening(env.hosts["s1"].nvme) {
ready = append(ready, time.Now())
if len(ready) >= 5 {
break
}
}
time.Sleep(200 * time.Millisecond)
}
if len(ready) == 0 {
t.Fatal("the returning holder never served within 90 s")
}
if last := lastLogTime(back, "clock-skew margin has not elapsed"); !last.IsZero() && ready[0].Before(last) {
t.Errorf("the returning holder served at %s, before its renewal was still refused for the barrier at %s: it served without a lease",
ready[0].Format("15:04:05.000"), last.Format("15:04:05"))
}
if got := env.adopt(t, back, "s1"); got != e {
t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e)
}
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the stop does not read back")
}
}
// TestProcedureStartTooEarlyExitsAndARestartServes: with
// --workspace-max-clock-skew 50s the barrier is at most 95 s after the stop.
// A holder started 31 s after the stop ends its 30 s authority wait before
// the barrier: it does not serve and exits with status 75, so a supervisor
// (Restart=on-failure, RestartSec=5s) starts it again; a start that waits
// past the barrier is re-granted and serves at the same epoch.
func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) {
env := startHandoffEnv(t, 1, "--workspace-max-clock-skew", "50s")
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("start-too-early!")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
time.Sleep(31 * time.Second)
for attempt := 1; ; attempt++ {
d := env.start(t, fmt.Sprintf("blockvolume-s1-try%d", attempt), "s1")
served := false
end := time.Now().Add(45 * time.Second)
for time.Now().Before(end) {
if env.frontendReadyAt("s1") {
served = true
break
}
select {
case <-d.done:
end = time.Now()
default:
time.Sleep(200 * time.Millisecond)
}
}
if served {
if attempt == 1 {
t.Fatal("started before the barrier with its wait ending first, the holder served")
}
if got := env.adopt(t, d, "s1"); got != e {
t.Fatalf("attempt %d adopted epoch %d; want the same epoch %d", attempt, got, e)
}
break
}
if err := d.wait(5 * time.Second); exitCode(err) != 75 {
t.Fatalf("attempt %d did not serve and did not exit 75: %v", attempt, err)
}
if attempt == 4 {
t.Fatal("four supervised starts never served")
}
time.Sleep(5 * time.Second)
}
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the stop does not read back")
}
}
// lastLogTime is the time of the last log line containing s (second
// resolution, the log's local time), or zero.
func lastLogTime(d *daemon, s string) time.Time {
data, _ := os.ReadFile(d.log)
var last time.Time
for _, l := range strings.Split(string(data), "\n") {
if strings.Contains(l, s) && len(l) >= 19 {
if ts, err := time.ParseInLocation("2006/01/02 15:04:05", l[:19], time.Local); err == nil {
last = ts
}
}
}
return last
}
// exitCode is a child's exit status (-1 when it did not exit with one).
func exitCode(err error) int {
var exit *exec.ExitError
if err == nil {
return 0
}
if errors.As(err, &exit) {
return exit.ExitCode()
}
return -1
}
func pattern(s string) []byte { return bytes.Repeat([]byte(s), 4096/len(s)) }
func (env *handoffEnv) start(t *testing.T, name, id string) *daemon {
t.Helper()
return env.h.start(t, name, env.h.volume, env.volArgs(id)...)
}
// adopt waits for the process to adopt v1 as primary and its host to report
// it healthy, and returns the epoch.
func (env *handoffEnv) adopt(t *testing.T, d *daemon, id string) uint64 {
t.Helper()
_, mustU := fatalOn(t)
e := mustU(adoptedEpoch(d.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@")))
env.h.waitPrimaryAt(t, env.hosts[id].status, e)
return e
}
// frontendReadyAt reports whether the host's status shows v1's frontend
// ready to serve.
func (env *handoffEnv) frontendReadyAt(id string) bool {
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get("http://" + env.hosts[id].status + "/status?volume=v1")
if err != nil {
return false
}
defer resp.Body.Close()
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
return frontendReady(b)
}
// listening reports whether something accepts TCP connections at addr.
func listening(addr string) bool {
c, err := net.DialTimeout("tcp", addr, time.Second)
if err != nil {
return false
}
c.Close()
return true
}
func (env *handoffEnv) writeBlock(t *testing.T, id string, lba uint64, data []byte) {
t.Helper()
c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN)
defer c.close()
c.write(t, lba, data)
c.flush(t)
}
func (env *handoffEnv) readBlock(t *testing.T, id string, lba uint64) []byte {
t.Helper()
c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN)
defer c.close()
return c.read(t, lba, 4096)
}
func (env *handoffEnv) seal(t *testing.T, id string, e uint64) uint64 {
t.Helper()
_, mustU := fatalOn(t)
out, errOut := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", env.hosts[id].status, "--timeout", "120s")
return mustU(sealedGen(out, errOut, e))
}
func (env *handoffEnv) chunkShow() []string {
return []string{"ops", "chunk", "show", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
}
func (env *handoffEnv) sealedLSN(t *testing.T, e, g uint64) uint64 {
t.Helper()
_, mustU := fatalOn(t)
out, _ := env.h.command(t, env.chunkShow()...)
return mustU(sealedHeadLSN(out, e, g))
}
func (env *handoffEnv) revoke(t *testing.T, e, g uint64) {
t.Helper()
must, _ := fatalOn(t)
out, _ := env.h.command(t, "ops", "workspace", "revoke", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1",
"--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g))
must(checkRevoke(out, e, g))
}
func (env *handoffEnv) waitAck(t *testing.T, e, g uint64) {
t.Helper()
poll(t, 30*time.Second, fmt.Sprintf("workspace show never reported the ACK of r1@%d at generation %d", e, g), func() bool {
out, _ := env.h.command(t, env.show...)
return showsAck(out, e, g)
})
}
func (env *handoffEnv) moveClean(e uint64, target, request string) []string {
b := env.hosts[target]
return []string{"ops", "workspace", "move", "--clean", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1",
"--epoch", fmt.Sprint(e), "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, "--request-id", request}
}
// forceMove runs the page's forced move: --dry-run until it says admitted
// (the barrier: at most 65 s after the holder stopped, with defaults, plus a
// margin), then the move itself, whose stdout it returns.
func (env *handoffEnv) forceMove(t *testing.T, e uint64, target, request string) string {
t.Helper()
b := env.hosts[target]
args := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1",
"--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl,
"--request-id", request, "--confirm-forced", fmt.Sprintf("v1@%d", e)}
first, _ := env.h.command(t, append(args, "--dry-run")...)
if !previewAdmitted(first) && !strings.Contains(first, "admissible at ") {
t.Fatalf("a refused preview does not say when the move is admissible:\n%s", first)
}
poll(t, 90*time.Second, "the forced move was never admitted", func() bool {
out, _ := env.h.command(t, append(args, "--dry-run")...)
return previewAdmitted(out)
})
out, _ := env.h.command(t, args...)
return out
}
// wrongOwnerEndpoints returns every "assignment stream delivery" log line at epoch e (in any of ds) whose data or control
// endpoint is not owner's (#425).
func wrongOwnerEndpoints(e uint64, owner bvHost, ds ...*daemon) []string {
var bad []string
tag := fmt.Sprintf(" epoch=%d ev=", e)
for _, d := range ds {
raw, _ := os.ReadFile(d.log)
for _, l := range strings.Split(string(raw), "\n") {
if !strings.Contains(l, "assignment stream delivery") || !strings.Contains(l, tag) {
continue
}
if !strings.Contains(l, fmt.Sprintf("data=%q", owner.data)) || !strings.Contains(l, fmt.Sprintf("ctrl=%q", owner.ctrl)) {
bad = append(bad, d.name+": "+strings.TrimSpace(l))
}
}
}
return bad
}