Merge remote-tracking branch 'origin/main' into docs/operator-guide

This commit is contained in:
pingqiu committed 2026-11-22 13:39:54 -08:00
commit 6c225b3936
173 files changed
+11479 -1342

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Self-test of public-text-check.sh in a throwaway repository.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
t=$(mktemp -d); trap 'rm -rf "$t"' EXIT
cd "$t"; git init -q .; git config user.email t@example.invalid; git config user.name t
echo base > a.txt; git add a.txt; git commit -q -m "base"
mb=$(git rev-parse HEAD)
: > title; : > body
run() { bash "$here/public-text-check.sh" "$@" >out 2>&1; }
expect() { # expect RC NAME
local want=$1 name=$2 rc=0
shift 2
run "$@" || rc=$?
[ "$rc" = "$want" ] || { echo "public-text-check-test: $name: exit $rc, want $want"; cat out; exit 1; }
}
echo "plain line" >> a.txt; git commit -q -am "add a plain line"
expect 0 "clean change" "$mb" HEAD title body
seat="clau""de06"; path="V:/sha""re/x"; nas="share/rd""ma/y"
echo "// asked by $seat" >> a.txt; git commit -q -am "comment"
expect 1 "seat name in an added line" "$mb" HEAD title body
grep -q "a.txt:3" out || { echo "public-text-check-test: hit does not name file and line"; cat out; exit 1; }
git reset -q --hard HEAD~1
echo "ok" >> a.txt; git commit -q -am "review by $seat"
expect 1 "seat name in a commit subject" "$mb" HEAD title body
git reset -q --hard HEAD~1
echo "see $path" > title; expect 1 "share path in the title" "$mb" HEAD title body; : > title
echo "results under $nas" > body; expect 1 "share path in the description" "$mb" HEAD title body; : > body
echo "an old line with $seat" >> a.txt; git commit -q -am "old"; mb2=$(git rev-parse HEAD)
echo "new clean line" >> a.txt; git commit -q -am "new"
expect 0 "an existing line is not this change's" "$mb2" HEAD title body
# A file line that begins with "++ " shows in the diff as "+++ ...": an added line, not a header.
printf '%s
' "++ $seat" >> a.txt; git commit -q -am "plus line"
expect 1 "an added line that looks like a diff header" "$mb2" HEAD title body
git reset -q --hard HEAD~1
bs=$(printf '\')
printf '%s
' "${bs}${bs}nas${bs}sha""re${bs}rd""ma${bs}z" > title
expect 1 "backslash form of the share path in the title" "$mb2" HEAD title body; : > title
expect 2 "a missing title file is an error, not clean" "$mb2" HEAD no-such-title body
expect 2 "a missing description file is an error, not clean" "$mb2" HEAD title no-such-body
expect 2 "an unknown commit is an error, not clean" 0000000000000000000000000000000000000000 HEAD title body
# A grep that fails (exit 2) is an error: the check must refuse and never print "clean".
mkdir -p fakebin; printf '#!/bin/sh
exit 2
' > fakebin/grep; chmod +x fakebin/grep
rc=0; PATH="$PWD/fakebin:$PATH" bash "$here/public-text-check.sh" "$mb2" HEAD title body >out 2>&1 || rc=$?
[ "$rc" = 2 ] || { echo "public-text-check-test: failing grep: exit $rc, want 2"; cat out; exit 1; }
if PATH=/usr/bin:/bin grep -q "clean" out; then echo "public-text-check-test: failing grep printed clean"; cat out; exit 1; fi
echo "public-text-check-test: ok"
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Refuses internal names in what a pull request makes public: the lines it
# adds, its commit messages, its title and its description. This repository is
# public; internal seat names and internal file-share paths do not belong in it.
#
# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE
# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage.
#
# The patterns live only here and in this check's own test; both files are
# excluded from the scan of added lines.
set -euo pipefail
[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; }
mb=$1; head=$2; title=$3; body=$4
for f in "$title" "$body"; do
[ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; }
done
git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null ||
{ echo "public-text: unknown commit $mb or $head" >&2; exit 2; }
# match: a grep error fails the check instead of reading as "no hit".
match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; }
pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation'
out=$(mktemp); trap 'rm -f "$out"' EXIT
report() { # report WHERE < matching lines
local where=$1 line
while IFS= read -r line; do
printf 'public-text: %s: %s
' "$where" "${line:0:160}" >>"$out"
done
}
# Added lines of the diff, with file and line number.
git diff --no-color --no-renames -U0 "$mb" "$head" -- . \
':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' |
awk '
/^diff --git / { hdr = 1; next }
hdr && /^\+\+\+ / { f = substr($0, 7); next }
/^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next }
!hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ }
' | match | report "added line"
# Commit messages (subjects and bodies) of the pull request.
git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message"
match "$title" | report "title"
match "$body" | report "description"
hits=$(wc -l <"$out" | tr -d ' ')
if [ "$hits" -gt 0 ]; then
cat "$out"
echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2
exit 1
fi
echo "public-text: clean"
+6
View File
@@ -43,6 +43,7 @@ jobs:
HEAD: ${{ github.event.pull_request.head.sha }}
PR: ${{ github.event.pull_request.number }}
BODY: ${{ github.event.pull_request.body }}
TITLE: ${{ github.event.pull_request.title }}
run: |
set -euo pipefail
bash .github/scripts/spec-trace-check-test.sh
@@ -60,3 +61,8 @@ jobs:
done
mkdir -p blobs
bash .github/scripts/spec-trace-check.sh body.txt blobs <changed.bin
# Internal names stay out of this public repository: added lines,
# commit messages, title and description (no PR code is run).
bash .github/scripts/public-text-check-test.sh
printf '%s' "$TITLE" >title.txt
bash .github/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt
+30 -1
View File
@@ -82,4 +82,33 @@ jobs:
fi
done
fi
go test -p=1 -short -count=1 -timeout 10m $pkgs
# 20m per package: core/storage alone took 602 s on tp04 on main
# (2026-11-22), past the old 10m, so any PR touching it failed.
go test -p=1 -short -count=1 -timeout 20m $pkgs
- name: Test planned hand-over (real binaries)
# The documented standalone planned hand-over and its refused clean
# move without the ACK (cmd/blockvolume TestStandalone*, build tags
# subprocess and chunkstore_integration, so the default pass above is
# unchanged) run real blockmaster, blockvolume and sw-block against a
# pinned SeaweedFS release. The release archive is checked against its
# sha256 before every use, also when taken from the runner's cache; a
# mismatch fails the step. Nothing else is fetched.
env:
WEED_VERSION: "4.53"
WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d
run: |
set -euo pipefail
cache="${RUNNER_TOOL_CACHE:-$RUNNER_TEMP}/seaweedfs-weed/$WEED_VERSION"
tgz="$cache/linux_amd64.tar.gz"
mkdir -p "$cache"
if ! echo "$WEED_SHA256 $tgz" | sha256sum -c --status - 2>/dev/null; then
part="$tgz.$$.part"
curl -fsSL --retry 3 -o "$part" "https://github.com/seaweedfs/seaweedfs/releases/download/$WEED_VERSION/linux_amd64.tar.gz"
echo "$WEED_SHA256 $part" | sha256sum -c - || { rm -f "$part"; exit 1; }
mv -f "$part" "$tgz"
fi
bin="$RUNNER_TEMP/weed-$WEED_VERSION"
mkdir -p "$bin"
tar -xzf "$tgz" -C "$bin" weed
CHUNKSTORE_WEED="$bin/weed" go test -tags 'subprocess chunkstore_integration' -count=1 -timeout 10m -run '^TestStandalone(PlannedHandoffToTheSameHost|CleanMoveWithoutTheACKIsRefused)$' ./cmd/blockvolume/
+3
View File
@@ -30,3 +30,6 @@ coverage.out
# MkDocs engineering wiki build output
/site/
# Windows builds of the binaries (never committed)
/*.exe
@@ -0,0 +1,94 @@
package main
import (
"fmt"
"os"
"time"
)
// workspaceStopWait is what the process's one stop waiter (waitWorkspaceStop)
// returned: the lease drain request to honour, and the lease guard's done
// channel (nil once consumed).
type workspaceStopWait struct {
leaseStop *workspaceStopRequest
leaseDone <-chan error
}
// awaitFrontendStart races the backend's first admitted I/O against the stop
// waiter (INV-FE-PRIMARY-READY-OPERATIONAL-001). serving is closed the first
// time the backend admits I/O (for a chunk volume: after its storage claim);
// nil means there is no durable backend to wait for. It returns start = true
// when the frontends may start; otherwise the stop that won, which the caller
// shuts down with exactly as after the frontends. A stop decided meanwhile by
// INV-WS-STARTUP-RETRY-001 (exit 75 or 78) ends the stop waiter too, so a
// refused claim never starts a frontend.
// servingBackend is the part of the durable backend the start gate reads.
type servingBackend interface {
FirstServing() <-chan struct{}
AdmitsIO() error
}
// frontendStartSignal is what the frontends wait for. A workspace chunk
// primary (V1-SPEC r2.37/r2.39) starts its targets only once the one "may
// serve" function (AdmitsIO) passes after the backend first admitted I/O;
// any other volume (non-chunk, or a supporting replica) starts right after
// open, as before: it never makes the claim a workspace primary waits for.
func frontendStartSignal(f flags, b servingBackend, stop <-chan struct{}) <-chan struct{} {
if f.workspaceLease && f.durableImpl == "walstore-chunk" {
out, _ := firstAdmitted(stop, b.FirstServing(), b.AdmitsIO)
return out
}
return b.FirstServing()
}
// admitRecheck bounds firstAdmitted's re-check of AdmitsIO after the backend
// first admits I/O (workspace primaries only, until first served): the
// backend has no projection-change signal.
const admitRecheck = 50 * time.Millisecond
// firstAdmitted's out is closed once first has closed (the backend first
// admitted I/O) and admits() then passes; it re-checks every admitRecheck
// until then, and ends without closing out when stop closes. done is closed
// when its goroutine has returned, on either path.
func firstAdmitted(stop <-chan struct{}, first <-chan struct{}, admits func() error) (out, done <-chan struct{}) {
o, d := make(chan struct{}), make(chan struct{})
go func() {
defer close(d)
select {
case <-first:
case <-stop:
return
}
t := time.NewTicker(admitRecheck)
defer t.Stop()
for admits() != nil {
select {
case <-t.C:
case <-stop:
return
}
}
close(o)
}()
return o, d
}
func awaitFrontendStart(serving <-chan struct{}, stopWait <-chan workspaceStopWait) (stopped *workspaceStopWait, start bool) {
if serving == nil {
return nil, true
}
select {
case <-serving:
return nil, true
default:
}
fmt.Fprintln(os.Stderr, "blockvolume: frontends wait for the storage claim: the backend admits no I/O yet")
select {
case <-serving:
fmt.Fprintln(os.Stderr, "blockvolume: backend admits I/O: starting the frontends")
return nil, true
case w := <-stopWait:
fmt.Fprintln(os.Stderr, "blockvolume: stopping before any frontend started")
return &w, false
}
}
@@ -0,0 +1,103 @@
package main
import (
"context"
"testing"
"time"
)
type gateResult struct {
stopped *workspaceStopWait
start bool
}
// gateWait bounds every receive of a gate result in these tests.
const gateWait = 5 * time.Second
// runGate runs awaitFrontendStart on serving and a stop channel it owns
// (buffered, returned for the test to send on). Its cleanup, registered
// before the worker starts, releases a gate that is still waiting with a
// stop and joins the worker within gateWait, so a failing check never
// strands it.
func runGate(t *testing.T, serving <-chan struct{}) (<-chan gateResult, chan<- workspaceStopWait) {
t.Helper()
out := make(chan gateResult, 1)
stopWait := make(chan workspaceStopWait, 1)
exited := make(chan struct{})
t.Cleanup(func() {
select {
case stopWait <- workspaceStopWait{}:
default:
}
select {
case <-exited:
case <-time.After(gateWait):
t.Errorf("the gate worker did not exit within %s of a stop", gateWait)
}
})
go func() {
defer close(exited)
s, ok := awaitFrontendStart(serving, stopWait)
out <- gateResult{s, ok}
}()
return out, stopWait
}
func receiveGate(t *testing.T, res <-chan gateResult, what string) gateResult {
t.Helper()
select {
case r := <-res:
return r
case <-time.After(gateWait):
t.Fatalf("%s: the gate did not return within %s", what, gateWait)
return gateResult{}
}
}
// INV-FE-PRIMARY-READY-OPERATIONAL-001: the frontends start only once the
// backend first admits I/O. With no durable backend, and with a backend that
// already serves, they start at once. Sampled every 10 ms while the backend
// admits no I/O (a chunk volume before its storage claim), the gate never
// releases; it releases as soon as the backend's first-serving channel closes.
func TestFrontendGateWaitsForTheStorageClaim(t *testing.T) {
served := make(chan struct{})
close(served)
for name, ch := range map[string]<-chan struct{}{"no durable backend": nil, "already serving": served} {
res, _ := runGate(t, ch)
if r := receiveGate(t, res, name); !r.start || r.stopped != nil {
t.Fatalf("%s: %+v, want the frontends started at once", name, r)
}
}
serving := make(chan struct{})
res, _ := runGate(t, serving)
for i := 0; i < 30; i++ { // 300 ms of samples while the claim is pending
select {
case r := <-res:
t.Fatalf("sample %d: the gate released (%+v) before the backend admitted I/O", i, r)
case <-time.After(10 * time.Millisecond):
}
}
close(serving) // the storage claim succeeded
if r := receiveGate(t, res, "after the claim"); !r.start {
t.Fatalf("after the claim: %+v, want the frontends started", r)
}
}
// A refused claim never closes the first-serving channel; the process's stop
// waiter then wins (a signal, the lease guard, or INV-WS-STARTUP-RETRY-001's
// latched exit 75/78) and no frontend starts: the stop is handed back for
// the ordinary shutdown, its lease drain request included.
func TestFrontendGateStopsWithoutStartingTheFrontends(t *testing.T) {
res, stopWait := runGate(t, make(chan struct{})) // fenced: never serves
select {
case r := <-res:
t.Fatalf("a backend that never serves released the gate: %+v", r)
case <-time.After(100 * time.Millisecond):
}
req := &workspaceStopRequest{ctx: context.Background()}
stopWait <- workspaceStopWait{leaseStop: req}
if r := receiveGate(t, res, "stop before serving"); r.start || r.stopped == nil || r.stopped.leaseStop != req {
t.Fatalf("stop before serving: %+v, want no frontends and the lease drain request handed back", r)
}
}
@@ -0,0 +1,107 @@
package main
import (
"errors"
"sync/atomic"
"testing"
"time"
)
type servingStub struct {
first chan struct{}
admits atomic.Bool
}
func (s *servingStub) FirstServing() <-chan struct{} { return s.first }
func (s *servingStub) AdmitsIO() error {
if s.admits.Load() {
return nil
}
return errors.New("stale primary lineage")
}
func closedWithin(ch <-chan struct{}, d time.Duration) bool {
select {
case <-ch:
return true
case <-time.After(d):
return false
}
}
// V1-SPEC r2.37/r2.39: a workspace chunk primary's targets start only once
// AdmitsIO passes after the backend first admitted I/O; the stop ends the
// wait without starting them.
func TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO(t *testing.T) {
f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"}
stop := make(chan struct{})
t.Cleanup(func() { close(stop) }) // ends the re-check goroutine on any path
b := &servingStub{first: make(chan struct{})}
sig := frontendStartSignal(f, b, stop)
if closedWithin(sig, 100*time.Millisecond) {
t.Fatal("started before the backend first admitted I/O")
}
close(b.first) // operational, but the guarded projection does not admit yet
if closedWithin(sig, 4*admitRecheck) {
t.Fatal("started while AdmitsIO refuses")
}
b.admits.Store(true)
if !closedWithin(sig, 5*time.Second) {
t.Fatal("did not start after AdmitsIO passed")
}
}
// A stop ends firstAdmitted's worker without starting the targets, both
// while it waits for the first admitted I/O and while it re-checks AdmitsIO:
// its completion is observed on its own channel, and every join is bounded.
func TestFirstAdmittedStopEndsTheWorker(t *testing.T) {
for _, served := range []bool{false, true} {
stop := make(chan struct{})
b := &servingStub{first: make(chan struct{})}
if served {
close(b.first) // re-checking AdmitsIO, which keeps refusing
}
out, done := firstAdmitted(stop, b.FirstServing(), b.AdmitsIO)
stopped := false
t.Cleanup(func() {
if !stopped {
close(stop)
}
if !closedWithin(done, 5*time.Second) {
t.Errorf("served=%v: the worker did not return within 5s of its stop (cleanup)", served)
}
})
if closedWithin(done, 2*admitRecheck) {
t.Fatalf("served=%v: the worker returned before any stop", served)
}
close(stop)
stopped = true
if !closedWithin(done, 5*time.Second) {
t.Fatalf("served=%v: the worker did not return within 5s of its stop", served)
}
select {
case <-out:
t.Fatalf("served=%v: a stopped wait started the targets", served)
default:
}
}
}
// INV-WS-SERVE-LEASE-HELD-001 scope (V1-SPEC r2.39): a non-chunk volume or a supporting
// replica starts its frontends right after open, as before: its start
// signal is the backend's first-serving channel itself, not AdmitsIO.
func TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore(t *testing.T) {
stop := make(chan struct{})
defer close(stop)
for _, f := range []flags{
{durableImpl: "walstore", volumeID: "v1"},
{durableImpl: "walstore-chunk", volumeID: "v1"}, // chunk without the workspace lease
} {
b := &servingStub{first: make(chan struct{})}
close(b.first) // open and recovered; AdmitsIO refuses (not the primary)
if !closedWithin(frontendStartSignal(f, b, stop), time.Second) {
t.Fatalf("impl=%s workspace-lease=%v: did not start right after open while AdmitsIO refuses", f.durableImpl, f.workspaceLease)
}
}
}
@@ -196,7 +196,10 @@ func startG54Volume(t *testing.T, bins l2bins, art string, o volOpts) *proc {
t.Fatalf("volume log: %v", err)
}
_ = os.MkdirAll(o.durableRoot, 0o755)
lockDir := o.durableRoot + ".locks" // one simulated host
_ = os.MkdirAll(lockDir, 0o700)
cmd := exec.Command(bins.volume,
"--volume-lock-dir-test-only", lockDir,
"--master", o.masterAddr,
"--server-id", o.serverID,
"--volume-id", "v1",
@@ -220,6 +223,7 @@ func startG54Volume(t *testing.T, bins l2bins, art string, o volOpts) *proc {
if o.replicationAck != "" {
cmd.Args = append(cmd.Args, "--replication-ack", o.replicationAck)
}
stripSystemdForTestLockDir(cmd)
cmd.Stdout = lf
cmd.Stderr = lf
if err := cmd.Start(); err != nil {
+268 -229
View File
@@ -13,12 +13,10 @@ import (
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
@@ -123,6 +121,9 @@ type flags struct {
durableBlockSize uint
durableWALMultiBlockRecords bool
durableWALRecoveryTestDisableFlusher bool
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden,
// test-only; refused under systemd).
volumeLockDirTestOnly string
// WAL retention window past checkpoint LSN. Zero = strict
// checkpoint-driven recycle. Non-zero = walstore relaxes the
@@ -157,6 +158,22 @@ type flags struct {
version bool
}
// volumeLockDirTestOnlyFlag is hidden from --help (printVisibleUsage).
const volumeLockDirTestOnlyFlag = "volume-lock-dir-test-only"
// printVisibleUsage is the default usage without the hidden test flag.
func printVisibleUsage(fs *flag.FlagSet) {
visible := flag.NewFlagSet(fs.Name(), flag.ContinueOnError)
visible.SetOutput(fs.Output())
fs.VisitAll(func(fl *flag.Flag) {
if fl.Name != volumeLockDirTestOnlyFlag {
visible.Var(fl.Value, fl.Name, fl.Usage)
}
})
fmt.Fprintf(fs.Output(), "Usage of %s:\n", fs.Name())
visible.PrintDefaults()
}
func parseFlags(args []string) (flags, error) {
var f flags
fs := flag.NewFlagSet("blockvolume", flag.ContinueOnError)
@@ -247,7 +264,9 @@ func parseFlags(args []string) (flags, error) {
"replication acknowledgement profile: \"best-effort\" (default), \"sync-quorum\", or \"sync-all\". "+
"sync-* modes fail foreground writes when required replica acknowledgement is unavailable.")
fs.BoolVar(&f.version, "version", false, "print build provenance and exit")
fs.StringVar(&f.volumeLockDirTestOnly, volumeLockDirTestOnlyFlag, "", "")
fs.SetOutput(os.Stderr)
fs.Usage = func() { printVisibleUsage(fs) }
if err := fs.Parse(args); err != nil {
return flags{}, err
}
@@ -274,6 +293,9 @@ func parseFlags(args []string) (flags, error) {
if f.version {
return f, nil
}
if f.volumeLockDirTestOnly != "" && os.Getenv("INVOCATION_ID") != "" {
return flags{}, fmt.Errorf("--%s is test-only and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
}
if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" {
return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode)
}
@@ -584,7 +606,7 @@ func durableCreateGeometry(f flags) (uint32, int, error) {
return uint32(f.durableBlocks), int(f.durableBlockSize), nil
}
func run(f flags) int {
func runVolume(f flags, exits *processExit) int {
// Diagnostics first: parseFlags validated the directory, and nothing
// has been activated yet, so a failure here leaves nothing to clean up.
stopProfile, err := startCPUProfileSignal(f.cpuProfileDir)
@@ -657,6 +679,12 @@ func run(f flags) int {
WALRetentionLSNs: f.walRetentionLSNs,
WALMultiBlockRecords: f.durableWALMultiBlockRecords,
WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher,
// V1-SPEC r2.45: one live process per volume per host.
HostVolumeLock: true,
VolumeLockDirTestOnly: f.volumeLockDirTestOnly,
}
if f.volumeLockDirTestOnly != "" {
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is a test override: the one-process-per-host guarantee does not hold\n", f.volumeLockDirTestOnly)
}
var chunkErr error
var chunk chunkWiring
@@ -678,7 +706,11 @@ func run(f flags) int {
cfg.ChunkHolder = chunkHolder(f)
cfg.ChunkStagger = true
if f.chunk.hostLimit.Directory != "" {
limiter, limitErr := hostlimit.New(f.chunk.hostLimit)
limitErr := hostlimit.CheckLaunch(f.chunk.hostLimit)
var limiter *hostlimit.Limiter
if limitErr == nil {
limiter, limitErr = hostlimit.New(f.chunk.hostLimit)
}
if limitErr != nil {
chunkErr = errors.Join(chunkErr, limitErr)
} else {
@@ -719,6 +751,10 @@ func run(f flags) int {
return 1
}
durableProv = dp
watchCtx, stopWatch := context.WithCancel(exits.parent)
defer stopWatch()
go watchChunkStartup(watchCtx, exits, f, h, dp)
go watchChunkRuntimeFence(watchCtx, exits, f, dp)
provider = dp
if status != nil {
status.SetDurableStatusSource(dp)
@@ -759,6 +795,7 @@ func run(f flags) int {
// (wal_corrupt / io_error) faults fail-closed and is reported at
// once by a primary assignment; see openAndRecoverDurable.
outcome, evidence, sErr := openAndRecoverDurable(dp, h, f.volumeID, 10*time.Second)
chooseChunkStartupExit(exits, f, h, dp)
switch outcome {
case durableStartupFatal:
fmt.Fprintln(os.Stderr, "blockvolume: durable storage open:", sErr)
@@ -772,7 +809,7 @@ func run(f flags) int {
return 1
case durableStartupFaulted:
fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", evidence)
return waitFaultedDurableRecovery(h, status, durableProv, evidence)
return waitFaultedDurableRecovery(exits.done, h, status, durableProv, evidence)
default:
fmt.Fprintln(os.Stderr, "blockvolume: durable recovered:", evidence)
}
@@ -1013,70 +1050,163 @@ func run(f flags) int {
var iscsiTarget *iscsi.Target
var frontendTargets []*control.FrontendTarget
if f.iscsiListen != "" {
prov := provider
var probeProvider iscsi.ProbeBackendProvider
if durableProv != nil {
probeProvider = &durableProbeProvider{provider: durableProv}
}
negotiation := iscsi.NegotiableConfig{}
if f.iscsiCHAPSecret != "" {
negotiation = iscsi.DefaultNegotiableConfig()
negotiation.CHAP = iscsi.CHAPConfig{
Username: f.iscsiCHAPUser,
Secret: f.iscsiCHAPSecret,
}
}
iscsiTarget = iscsi.NewTarget(iscsi.TargetConfig{
Listen: f.iscsiListen,
IQN: f.iscsiIQN,
PortalAddr: f.iscsiPortalAddr,
VolumeID: f.volumeID,
Provider: prov,
ProbeProvider: probeProvider,
Negotiation: negotiation,
DataOutTimeout: f.iscsiDataOutTTL,
Handler: iscsi.HandlerConfig{
BlockSize: frontendBlockSize,
VolumeSize: frontendVolumeSize,
ALUA: newProjectionALUAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.iscsiIQN),
},
})
iscsiAddr, err := iscsiTarget.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: iscsi target:", err)
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 1
}
_ = json.NewEncoder(os.Stdout).Encode(iscsiReadyLine{
Component: "blockvolume",
Phase: "iscsi-listening",
IscsiAddr: iscsiAddr,
IQN: f.iscsiIQN,
})
frontendTargets = append(frontendTargets, &control.FrontendTarget{
Protocol: "iscsi",
Addr: iscsiAddr,
Iqn: f.iscsiIQN,
Lun: uint32(f.iscsiLUN),
})
h.SetFrontendTargets(frontendTargets)
}
var nvmeTarget interface {
Start() (string, error)
Close() error
}
if f.nvmeListen != "" {
if f.nvmeTransport == "rdma" {
start := nvmeRDMAListenerStartDecision(true, nvmeRDMAPreflightFacts(f.nvmeListen))
if !start.allowed {
fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s\n", start.reason)
var ublkTarget *ublk.Target
// One startup order (INV-FE-PRIMARY-READY-OPERATIONAL-001 with
// INV-WS-STARTUP-RETRY-001): the workspace lease guard and the process's
// one stop waiter (waitWorkspaceStop: signal, lease drain request, lease
// end, or the latched startup outcome) run from here, before any frontend;
// the frontends start only when the backend first admits I/O, and never
// if a stop wins that race.
shutdownCtx := exits.parent
var leaseRequests <-chan workspaceStopRequest
var leaseDone <-chan error
if f.workspaceLease {
leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h)
}
stopWait := make(chan workspaceStopWait, 1)
go func(requests <-chan workspaceStopRequest, done <-chan error) {
ls, ld := waitWorkspaceStop(exits, f, h, requests, done)
stopWait <- workspaceStopWait{leaseStop: ls, leaseDone: ld}
}(leaseRequests, leaseDone)
var serving <-chan struct{} // nil: no durable backend, start at once
if durableProv != nil {
if b := durableProv.Backend(f.volumeID); b != nil {
serving = frontendStartSignal(f, b, exits.done)
}
}
stopped, startFrontends := awaitFrontendStart(serving, stopWait)
if startFrontends {
if f.iscsiListen != "" {
prov := provider
var probeProvider iscsi.ProbeBackendProvider
if durableProv != nil {
probeProvider = &durableProbeProvider{provider: durableProv}
}
negotiation := iscsi.NegotiableConfig{}
if f.iscsiCHAPSecret != "" {
negotiation = iscsi.DefaultNegotiableConfig()
negotiation.CHAP = iscsi.CHAPConfig{
Username: f.iscsiCHAPUser,
Secret: f.iscsiCHAPSecret,
}
}
iscsiTarget = iscsi.NewTarget(iscsi.TargetConfig{
Listen: f.iscsiListen,
IQN: f.iscsiIQN,
PortalAddr: f.iscsiPortalAddr,
VolumeID: f.volumeID,
Provider: prov,
ProbeProvider: probeProvider,
Negotiation: negotiation,
DataOutTimeout: f.iscsiDataOutTTL,
Handler: iscsi.HandlerConfig{
BlockSize: frontendBlockSize,
VolumeSize: frontendVolumeSize,
ALUA: newProjectionALUAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.iscsiIQN),
},
})
iscsiAddr, err := iscsiTarget.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: iscsi target:", err)
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 1
}
_ = json.NewEncoder(os.Stdout).Encode(iscsiReadyLine{
Component: "blockvolume",
Phase: "iscsi-listening",
IscsiAddr: iscsiAddr,
IQN: f.iscsiIQN,
})
frontendTargets = append(frontendTargets, &control.FrontendTarget{
Protocol: "iscsi",
Addr: iscsiAddr,
Iqn: f.iscsiIQN,
Lun: uint32(f.iscsiLUN),
})
h.SetFrontendTargets(frontendTargets)
}
if f.nvmeListen != "" {
if f.nvmeTransport == "rdma" {
start := nvmeRDMAListenerStartDecision(true, nvmeRDMAPreflightFacts(f.nvmeListen))
if !start.allowed {
fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s\n", start.reason)
if iscsiTarget != nil {
_ = iscsiTarget.Close()
}
if replListen != nil {
replListen.Stop()
}
if replVolume != nil {
_ = replVolume.Close()
}
if durableProv != nil {
_ = durableProv.Close()
}
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 1
}
blockSize := frontendBlockSize
volumeSize := frontendVolumeSize
if blockSize == 0 {
blockSize = nvme.DefaultBlockSize
}
if volumeSize == 0 {
volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize)
}
nvmeTarget = nvmerdma.NewTarget(nvmerdma.TargetConfig{
Listen: f.nvmeListen,
SubsysNQN: f.nvmeSubsysNQN,
VolumeID: f.volumeID,
NSID: uint32(f.nvmeNS),
BlockSize: blockSize,
VolumeSize: volumeSize,
Provider: provider,
})
} else {
var probeProvider nvme.ProbeBackendProvider
if durableProv != nil {
probeProvider = &durableProbeProvider{provider: durableProv}
}
nvmeTarget = nvme.NewTarget(nvme.TargetConfig{
Transport: nvme.TransportTCP,
Listen: f.nvmeListen,
SubsysNQN: f.nvmeSubsysNQN,
VolumeID: f.volumeID,
Provider: provider,
ProbeProvider: probeProvider,
ControllerID: nvmeControllerIDFromReplicaID(f.replicaID),
MaxH2CDataLength: uint32(f.nvmeMaxH2C),
Handler: nvme.HandlerConfig{
NSID: uint32(f.nvmeNS),
BlockSize: frontendBlockSize,
VolumeSize: frontendVolumeSize,
ANA: newProjectionANAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.nvmeSubsysNQN),
},
})
}
nvmeAddr, err := nvmeTarget.Start()
if err != nil {
if f.nvmeTransport == "rdma" {
fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s error=%v\n", nvmeRDMATargetStartFailureReason(err), err)
} else {
fmt.Fprintln(os.Stderr, "blockvolume: nvme target:", err)
}
if iscsiTarget != nil {
_ = iscsiTarget.Close()
}
@@ -1097,6 +1227,34 @@ func run(f flags) int {
_ = h.Close()
return 1
}
if status != nil {
status.SetNVMeListenerReady(true)
}
_ = json.NewEncoder(os.Stdout).Encode(nvmeReadyLine{
Component: "blockvolume",
Phase: "nvme-listening",
NvmeAddr: nvmeAddr,
SubsysNQN: f.nvmeSubsysNQN,
})
if shouldPublishNVMeFrontendTarget(f.nvmeTransport) {
frontendTargets = append(frontendTargets, &control.FrontendTarget{
Protocol: "nvme",
Transport: f.nvmeTransport,
Addr: nvmeAddr,
Nqn: f.nvmeSubsysNQN,
Nsid: uint32(f.nvmeNS),
})
h.SetFrontendTargets(frontendTargets)
}
if status != nil {
status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, true))
if source, ok := nvmeTarget.(interface{ Stats() nvme.Stats }); ok {
status.SetNVMeStatusSource(source)
}
}
}
if f.ublkDevice >= 0 {
blockSize := frontendBlockSize
volumeSize := frontendVolumeSize
if blockSize == 0 {
@@ -1105,166 +1263,59 @@ func run(f flags) int {
if volumeSize == 0 {
volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize)
}
nvmeTarget = nvmerdma.NewTarget(nvmerdma.TargetConfig{
Listen: f.nvmeListen,
SubsysNQN: f.nvmeSubsysNQN,
ublkTarget = ublk.NewTarget(ublk.TargetConfig{
VolumeID: f.volumeID,
NSID: uint32(f.nvmeNS),
Provider: provider,
DevID: f.ublkDevice,
BlockSize: blockSize,
VolumeSize: volumeSize,
Provider: provider,
Queues: f.ublkQueues,
QueueDepth: f.ublkQueueDepth,
})
} else {
var probeProvider nvme.ProbeBackendProvider
if durableProv != nil {
probeProvider = &durableProbeProvider{provider: durableProv}
}
nvmeTarget = nvme.NewTarget(nvme.TargetConfig{
Transport: nvme.TransportTCP,
Listen: f.nvmeListen,
SubsysNQN: f.nvmeSubsysNQN,
VolumeID: f.volumeID,
Provider: provider,
ProbeProvider: probeProvider,
ControllerID: nvmeControllerIDFromReplicaID(f.replicaID),
MaxH2CDataLength: uint32(f.nvmeMaxH2C),
Handler: nvme.HandlerConfig{
NSID: uint32(f.nvmeNS),
BlockSize: frontendBlockSize,
VolumeSize: frontendVolumeSize,
ANA: newProjectionANAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.nvmeSubsysNQN),
},
})
}
nvmeAddr, err := nvmeTarget.Start()
if err != nil {
if f.nvmeTransport == "rdma" {
fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s error=%v\n", nvmeRDMATargetStartFailureReason(err), err)
} else {
fmt.Fprintln(os.Stderr, "blockvolume: nvme target:", err)
}
if iscsiTarget != nil {
_ = iscsiTarget.Close()
}
if replListen != nil {
replListen.Stop()
}
if replVolume != nil {
_ = replVolume.Close()
}
if durableProv != nil {
_ = durableProv.Close()
ublkPath, err := ublkTarget.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: ublk device:", err)
if nvmeTarget != nil {
_ = nvmeTarget.Close()
}
if iscsiTarget != nil {
_ = iscsiTarget.Close()
}
if replListen != nil {
replListen.Stop()
}
if replVolume != nil {
_ = replVolume.Close()
}
if durableProv != nil {
_ = durableProv.Close()
}
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 1
}
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
status.SetUblkStatusSource(ublkTarget)
}
_ = h.Close()
return 1
}
if status != nil {
status.SetNVMeListenerReady(true)
}
_ = json.NewEncoder(os.Stdout).Encode(nvmeReadyLine{
Component: "blockvolume",
Phase: "nvme-listening",
NvmeAddr: nvmeAddr,
SubsysNQN: f.nvmeSubsysNQN,
})
if shouldPublishNVMeFrontendTarget(f.nvmeTransport) {
frontendTargets = append(frontendTargets, &control.FrontendTarget{
Protocol: "nvme",
Transport: f.nvmeTransport,
Addr: nvmeAddr,
Nqn: f.nvmeSubsysNQN,
Nsid: uint32(f.nvmeNS),
_ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{
Component: "blockvolume",
Phase: "ublk-ready",
Device: ublkPath,
})
h.SetFrontendTargets(frontendTargets)
}
if status != nil {
status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, true))
if source, ok := nvmeTarget.(interface{ Stats() nvme.Stats }); ok {
status.SetNVMeStatusSource(source)
}
}
}
} // startFrontends
var ublkTarget *ublk.Target
if f.ublkDevice >= 0 {
blockSize := frontendBlockSize
volumeSize := frontendVolumeSize
if blockSize == 0 {
blockSize = nvme.DefaultBlockSize
}
if volumeSize == 0 {
volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize)
}
ublkTarget = ublk.NewTarget(ublk.TargetConfig{
VolumeID: f.volumeID,
Provider: provider,
DevID: f.ublkDevice,
BlockSize: blockSize,
VolumeSize: volumeSize,
Queues: f.ublkQueues,
QueueDepth: f.ublkQueueDepth,
})
ublkPath, err := ublkTarget.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: ublk device:", err)
if nvmeTarget != nil {
_ = nvmeTarget.Close()
}
if iscsiTarget != nil {
_ = iscsiTarget.Close()
}
if replListen != nil {
replListen.Stop()
}
if replVolume != nil {
_ = replVolume.Close()
}
if durableProv != nil {
_ = durableProv.Close()
}
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 1
}
if status != nil {
status.SetUblkStatusSource(ublkTarget)
}
_ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{
Component: "blockvolume",
Phase: "ublk-ready",
Device: ublkPath,
})
// The one stop waiter has already returned if a stop won the race above.
if stopped == nil {
w := <-stopWait
stopped = &w
}
shutdownCtx, stopSignals := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stopSignals()
var leaseRequests <-chan workspaceStopRequest
var leaseDone <-chan error
if f.workspaceLease {
leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h)
}
var leaseStop *workspaceStopRequest
select {
case <-shutdownCtx.Done():
case request := <-leaseRequests:
// The lease guard fenced and asks for the drain; it logs its cause as
// "workspace lease: fenced ...". Say here that this is why we stop (#205).
fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain")
leaseStop = &request
case err := <-leaseDone:
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err)
leaseDone = nil
}
// The main goroutine owns shutdown. The lease callback waits for this
leaseStop, leaseDone := stopped.leaseStop, stopped.leaseDone
// The resource owner performs shutdown. The lease callback waits for this
// exact drain; it cannot ACK a merely requested or failed close.
h.FenceWorkspaceLease()
var drainErr error
@@ -1316,16 +1367,7 @@ func run(f flags) int {
}
leaseStop.reply <- workspaceStopResult{gen: gen, err: drainErr}
}
if leaseDone != nil {
select {
case err := <-leaseDone:
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err)
}
case <-time.After(3 * time.Second):
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline")
}
}
finishWorkspaceLease(exits, f, h, leaseDone)
if err := h.Close(); err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: close:", err)
return 1
@@ -1477,12 +1519,9 @@ func rdmaBindAddressFact(listen string) volume.FrontendTransportPreflightFact {
return volume.FrontendTransportPreflightFact{Name: "rdma_bind_address", Available: true, Reason: "rdma_bind_address_candidate", Detail: host}
}
func waitFaultedDurableRecovery(h *volume.Host, status *volume.StatusServer, durableProv *durable.DurableProvider, evidence string) int {
func waitFaultedDurableRecovery(stop <-chan struct{}, h *volume.Host, status *volume.StatusServer, durableProv *durable.DurableProvider, evidence string) int {
fmt.Fprintln(os.Stderr, "blockvolume: durable recovery faulted; status endpoint remains available and local readiness remains blocked:", evidence)
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
signal.Stop(sig)
<-stop
if durableProv != nil {
_ = durableProv.Close()
@@ -0,0 +1,47 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"os"
"path/filepath"
"strings"
"testing"
)
// #425: the procedure gate's owner-endpoint check rejects when EITHER recipient's evidence is missing, unreadable,
// has no forced-epoch delivery, or carries another host's endpoints; it passes only with positive evidence from both.
func TestWrongOwnerEndpointsNeedsPositiveEvidenceFromEachRecipient(t *testing.T) {
owner := bvHost{id: "s2", data: "127.0.0.1:2001", ctrl: "127.0.0.1:2002"}
dir := t.TempDir()
good := `blockvolume: assignment stream delivery process="X" server="s2" volume="v1" replica="r1" epoch=2 ev=1 data="127.0.0.1:2001" ctrl="127.0.0.1:2002"`
wrong := `blockvolume: assignment stream delivery process="X" server="s2" volume="v1" replica="r1" epoch=2 ev=2 data="127.0.0.1:1001" ctrl="127.0.0.1:1002"`
other := `blockvolume: assignment stream delivery process="X" server="s1" volume="v1" replica="r1" epoch=1 ev=1 data="127.0.0.1:1001" ctrl="127.0.0.1:1002"`
logOf := func(name string, lines ...string) *daemon {
p := filepath.Join(dir, name+".log")
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
return &daemon{name: name, log: p}
}
missing := &daemon{name: "gone", log: filepath.Join(dir, "does-not-exist.log")}
for _, c := range []struct {
name string
ds []*daemon
reject string // "" = must pass
}{
{"both positive", []*daemon{logOf("a1", good), logOf("b1", other, good)}, ""},
{"second unreadable", []*daemon{logOf("a2", good), missing}, "log unreadable"},
{"first has no epoch delivery", []*daemon{logOf("a3", other), logOf("b3", good)}, "no epoch delivery logged"},
{"second carries another host's endpoints", []*daemon{logOf("a4", good), logOf("b4", good, wrong)}, "127.0.0.1:1001"},
{"first empty log", []*daemon{logOf("a5"), logOf("b5", good)}, "no epoch delivery logged"},
} {
bad := wrongOwnerEndpoints(2, owner, c.ds...)
switch {
case c.reject == "" && len(bad) != 0:
t.Errorf("%s: rejected %v, want pass", c.name, bad)
case c.reject != "" && !strings.Contains(strings.Join(bad, "\n"), c.reject):
t.Errorf("%s: got %v, want a rejection naming %q", c.name, bad, c.reject)
}
}
}
@@ -0,0 +1,340 @@
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 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 {
return 0, err
}
if e2 <= e {
return 0, fmt.Errorf("clean move issued epoch %d; want above %d", e2, e)
}
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 { 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
}
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 {
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 != 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 {
if code != 1 || stdout != "" || !strings.Contains(stderr, "workspace clean move needs detached HEAD and matching revocation ACK") {
return fmt.Errorf("clean move without the ACK: exit %d, stdout %q, stderr %q; want exit 1 and the documented refusal", code, stdout, stderr)
}
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), in the refused clean move without an ACK (move-refused,
// show-revoked), and in the procedure gate's move to s2 and forced move
// (move-clean-s2, head-reopened-s2, force-move*, lost-range), 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))
ok("clean move refused", checkCleanMoveRefused("", read("move-refused.stderr"), 1))
refused("clean move refused", checkCleanMoveRefused("", read("move-refused.stderr"), 0))
refused("clean move refused", checkCleanMoveRefused(read("move-clean.stdout"), "", 0))
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")
}
// The procedure gate's two-host outputs (a planned move to s2, a forced
// move s1 -> s2 at E=1 -> E2=2 keeping gen 3, LSN 1).
if got, err := movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s2"); err != nil || got != e2 {
t.Errorf("moved epoch to s2 %d, %v; want %d", got, err, e2)
}
_, err = movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s1")
refused("clean move to s2 read as a move to s1", err)
ok("HEAD reopened by s2", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s2"))
refused("HEAD reopened by s2 read as s1's", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s1"))
if got, err := forcedEpoch(read("force-move.stdout"), e, "s1", "s2"); err != nil || got != e2 {
t.Errorf("forced epoch %d, %v; want %d", got, err, e2)
}
_, err = forcedEpoch(read("force-move.stdout"), e, "s2", "s1")
refused("forced move read the other way round", err)
_, err = forcedEpoch(read("move-clean-s2.stdout"), e, "s1", "s2")
refused("forced epoch", err)
if got, err := forcedKeptLSN(read("force-move.stdout")); err != nil || got != l {
t.Errorf("forced kept LSN %d, %v; want %d", got, err, l)
}
if !previewAdmitted(read("force-move-dry-run-admitted.stdout")) || previewAdmitted(read("force-move-dry-run-refused.stdout")) {
t.Error("the dry-run preview is not told admitted from not admitted")
}
if !strings.Contains(read("force-move-dry-run-refused.stdout"), "admissible at ") {
t.Error("the refused preview has no admissible time")
}
if !strings.Contains(read("lost-range.stdout"), "range 1 of 1: request force-v1-1, r1@") {
t.Error("lost-range does not show the forced move")
}
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")
}
}
@@ -0,0 +1,711 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"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, cluster, chunkPath, show, volArgs := startPlannedHandoff(t)
must, mustU := fatalOn(t)
const nqn = plannedHandoffNQN
// 4. blockvolume adopts the volume.
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), within the 30 s lease.
if err := vol1.wait(30 * 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)
}
}
// TestStandaloneCleanMoveWithoutTheACKIsRefused is the chapter's negative
// check N1 made deterministic: the volume is sealed, its blockvolume is
// killed (a signal sends no ACK), and the lease is revoked with the sealed
// generation while no blockvolume runs. No ACK can arrive, so the clean move
// is refused with the documented error, exit 1, and the master keeps no ACK.
func TestStandaloneCleanMoveWithoutTheACKIsRefused(t *testing.T) {
h, cluster, chunkPath, show, volArgs := startPlannedHandoff(t)
must, mustU := fatalOn(t)
vol := h.start(t, "blockvolume", h.volume, volArgs...)
e := mustU(adoptedEpoch(vol.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@")))
h.waitPrimary(t, e)
c := dialNVMe(t, h.nvmeAddr, plannedHandoffNQN)
c.write(t, 0, bytes.Repeat([]byte{0xa5}, 4096))
c.flush(t)
c.close()
out, errOut := h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", h.statusAddr, "--timeout", "120s")
g := mustU(sealedGen(out, errOut, e))
out, _ = h.command(t, "ops", "chunk", "show", "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath)
mustU(sealedHeadLSN(out, e, g)) // HEAD is sealed: only the ACK is missing
vol.kill(t)
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))
out, errOut, code := h.run(t, "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")
must(checkCleanMoveRefused(out, errOut, code))
out, _ = h.command(t, show...)
if showsAck(out, e, g) || !hasLine(out, "recorded ACK: none") {
t.Fatalf("workspace show after the refused move:\n%s\nwant recorded ACK: none", out)
}
}
const plannedHandoffNQN = "nqn.2026-11.io.seaweedfs:handoff"
// 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()
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("nodes:\n"+nodes.String()+`volumes:
- id: v1
size_bytes: 268435456
replication_factor: 1
placements:
- server_id: s1
replica_id: r1
`), 0o644))
// 2. blockmaster with the lifecycle store and the cluster spec.
mstate := filepath.Join(h.dir, "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}, 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)
}
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.
env.show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"}
out, _ := h.command(t, env.show...)
must(checkShowBeforeStart(out))
return env
}
// volArgs is the chapter's blockvolume command for one host.
func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.hosts[id]) }
// volArgsFor is the chapter's blockvolume command for b. The default
// scheduled snapshot (daily:7, at a per-volume offset) stays on, as the page
// says; a snapshot inside a test could only make a test fail, never pass.
func (env *handoffEnv) volArgsFor(b bvHost) []string {
lockDir := b.root + ".locks" // each simulated host has its own
_ = os.MkdirAll(lockDir, 0o700)
return []string{"--volume-lock-dir-test-only", lockDir, "--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", 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) {
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
return must, func(v uint64, err error) uint64 {
t.Helper()
must(err)
return v
}
}
// plannedHandoffHarness owns real binaries, loopback endpoints and process
// lifetimes.
type plannedHandoffHarness struct {
dir string
master, volume, cli string
masterAddr, dataAddr, ctrlAddr, statusAddr, nvmeAddr string
}
func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness {
t.Helper()
if os.Getenv("CHUNKSTORE_WEED") == "" {
t.Fatal("CHUNKSTORE_WEED must name the pinned real SeaweedFS binary")
}
h := &plannedHandoffHarness{dir: t.TempDir()}
suffix := ""
if isWindows() {
suffix = ".exe"
}
for _, b := range []struct {
name string
dst *string
}{
{"blockmaster", &h.master}, {"blockvolume", &h.volume}, {"sw-block", &h.cli},
} {
*b.dst = filepath.Join(h.dir, b.name+suffix)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
cmd := exec.CommandContext(ctx, "go", "build", "-o", *b.dst, "github.com/seaweedfs/seaweed-block/cmd/"+b.name)
cmd.WaitDelay = 5 * time.Second
out, err := cmd.CombinedOutput()
cancel()
if err != nil {
t.Fatalf("build %s: %v\n%s", b.name, err, out)
}
}
h.masterAddr = handoffAddress(t)
h.dataAddr = handoffAddress(t)
h.ctrlAddr = handoffAddress(t)
h.statusAddr = handoffAddress(t)
h.nvmeAddr = handoffAddress(t)
return h
}
// captureOutput writes each sw-block answer to $HANDOFF_CAPTURE_DIR, when set,
// as <test>-<n>-<verb>.stdout/.stderr: the source of testdata/planned-handoff.
func captureOutput(t *testing.T, args []string, stdout, stderr string) {
dir := os.Getenv("HANDOFF_CAPTURE_DIR")
if dir == "" || len(args) < 3 {
return
}
captureSeq++
base := filepath.Join(dir, fmt.Sprintf("%s-%02d-%s-%s", t.Name(), captureSeq, args[1], args[2]))
_ = os.WriteFile(base+".stdout", []byte(stdout), 0o644)
_ = os.WriteFile(base+".stderr", []byte(stderr), 0o644)
}
var captureSeq int
var handoffPorts struct {
sync.Mutex
used map[int]bool
}
// handoffAddress returns a free loopback address in 10000-19999: below the
// kernel's ephemeral range (32768 and up on Linux), where an outgoing
// connection can take a port while a restarted daemon waits to bind it
// again, and below the 20000-49999 range startWorkspaceWeed draws from.
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 := 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 below the ephemeral range")
return ""
}
// daemon is one started child: its log file and its exit.
type daemon struct {
name, log string
done chan struct{}
err error
cancel context.CancelFunc
proc *os.Process
}
// term sends SIGTERM, as systemctl stop or restart does, and waits for the
// child to exit.
func (d *daemon) term(t *testing.T, timeout time.Duration) {
t.Helper()
if err := d.proc.Signal(syscall.SIGTERM); err != nil {
t.Fatalf("SIGTERM %s: %v", d.name, err)
}
select {
case <-d.done:
case <-time.After(timeout):
t.Fatalf("%s did not exit within %s of SIGTERM", d.name, timeout)
}
}
// kill kills the child (no ACK is sent on a signal) and waits for it.
func (d *daemon) kill(t *testing.T) {
t.Helper()
d.cancel()
select {
case <-d.done:
case <-time.After(10 * time.Second):
t.Fatalf("%s did not exit after kill", d.name)
}
}
// start registers cancellation and a bounded join before starting a daemon.
// Each child writes to its own file, and cleanup targets only that child.
// 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 {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
cmd := stripSystemdForTestLockDir(exec.CommandContext(ctx, binary, args...))
cmd.Dir, cmd.Stdout, cmd.Stderr = h.dir, log, log
cmd.WaitDelay = 5 * time.Second
d := &daemon{name: name, log: log.Name(), done: make(chan struct{}), cancel: cancel}
started := false
t.Cleanup(func() {
cancel()
if started {
select {
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(d.log)
if len(data) > 16000 {
data = data[len(data)-16000:]
}
t.Logf("%s log:\n%s", name, data)
}
})
if err := cmd.Start(); err != nil {
t.Fatalf("start %s: %v", name, err)
}
started = true
d.proc = cmd.Process
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()
stdout, stderr, code := h.run(t, args...)
if code != 0 {
t.Fatalf("sw-block %q: exit %d\nstdout: %s\nstderr: %s", args, code, stdout, stderr)
}
return stdout, stderr
}
// run runs sw-block and returns its output and exit status; only a failure
// to run it at all (or its timeout) fails the test.
func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, string, int) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, h.cli, args...)
cmd.Dir = h.dir
cmd.WaitDelay = 5 * time.Second
var stdout, stderr strings.Builder
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
captureOutput(t, args, stdout.String(), stderr.String())
var exit *exec.ExitError
switch {
case err == nil:
return stdout.String(), stderr.String(), 0
case errors.As(err, &exit) && ctx.Err() == nil:
return stdout.String(), stderr.String(), exit.ExitCode()
}
t.Fatalf("sw-block %q: %v\nstdout: %s\nstderr: %s", args, err, stdout.String(), stderr.String())
return "", "", -1
}
// 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 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
}
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()
}
}
}
@@ -0,0 +1,596 @@
//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 blockvolume processes with distinct
// server ids (s1, and s2 where a procedure moves the volume) sharing one
// blockmaster and one SeaweedFS. The two start-time tests and the same-host
// restarts use s1 only. 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)
// Step 1: read the holder; the lease must be granted.
out, _ := h.command(t, env.show...)
must(checkShowGranted(out, e))
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")
}
// Control: a block never written reads zero, so the comparison above can
// fail.
if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) {
t.Fatal("a block never written does not read zero on s2")
}
}
// TestProcedureSameHostRestartInsideTheLease: the page's restart without a
// hand-over, `systemctl restart`: the holder gets SIGTERM, exits, and is
// started again on its host within the unit's RestartSec (5 s), inside 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, 1)
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.term(t, 30*time.Second)
env.restartServesAtOnce(t, "blockvolume-s1-again", e, block)
}
// TestProcedureSameHostCrashRestartInsideTheLease: the page's "the holder
// comes back within the lease" after a crash: the process is killed and
// started again within the unit's RestartSec (5 s). The same outcome as a
// restart.
func TestProcedureSameHostCrashRestartInsideTheLease(t *testing.T) {
env := startHandoffEnv(t, 1)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("crash-in-lease!!")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
env.restartServesAtOnce(t, "blockvolume-s1-again", e, block)
}
// restartServesAtOnce starts s1 again within 5 s of its exit and requires it
// to serve within 15 s ("at once"), as s1/r1 at the same epoch, with the
// written block.
func (env *handoffEnv) restartServesAtOnce(t *testing.T, name string, e uint64, block []byte) {
t.Helper()
must, _ := fatalOn(t)
started := time.Now()
again := env.start(t, name, "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)
}
if took := time.Since(started); took > 15*time.Second {
t.Fatalf("the restarted holder served after %s; the page says at once", took.Round(time.Second))
}
out, _ := env.h.command(t, env.show...)
must(checkShowGranted(out, e))
env.requireHeadHolder(t, e, "s1")
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)))
started := time.Now()
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 took := time.Since(started); took > 30*time.Second {
t.Fatalf("the returning holder served after %s, past its 30 s authority wait", took.Round(time.Second))
}
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))
env.requireHeadHolder(t, e, "s1")
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, and the example unit
// (Restart=on-failure, RestartSec=5s) starts it again after it exits,
// until its start limit. Each time 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; it logs a refusal and exits with status 75.
back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 75)
time.Sleep(5 * time.Second) // RestartSec of the example unit
again := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2, 75)
// Control: on a fresh local root there is no stale root, so its refusal
// is the identity check alone; it also exits 75.
fresh := env.hosts["s1"]
fresh.root = fresh.root + "-fresh"
freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 75)
// A line carries its owner and that owner's endpoints: every line
// delivered at the forced epoch, to the new owner and to each returning
// old host alike, carries s2's own endpoints, never another host's.
if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back, again, freshRoot); len(bad) > 0 {
t.Errorf("epoch-%d deliveries not proven to carry s2's endpoints (want data=%s ctrl=%s in every recipient's lines):\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, its
// process is gone before the revoke (so no process ever sends the ACK), and
// the lease is revoked with the sealed generation. The clean move is refused;
// only a forced move to another node remains, and since HEAD is sealed,
// nothing acknowledged is lost. Killing before the revoke makes the missing
// ACK certain; the page's row "Revoked, but no ACK" has the same outcome.
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.servingNow("s1") {
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")
}
// Started before the barrier, its renewals must have been refused for it
// at least once; log times have 1 s resolution.
last := lastLogTime(back, "clock-skew margin has not elapsed")
if last.IsZero() {
t.Fatal("started 40 s after the stop, the returning holder logged no renewal refused for the barrier")
}
if ready[0].Before(last.Add(time.Second)) {
t.Errorf("the returning holder served at %s, while 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 !back.has("workspace lease: re-granted after ") {
t.Error("the returning holder served without logging its re-grant")
}
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)
// Attempt 2 starts about 66 s after the stop and its wait ends about
// 96 s after it, against a barrier of at most 95 s, so attempt 2 normally
// serves; up to 4 attempts allow for scheduling on a loaded host.
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.servingNow("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 !d.has("blockvolume: exiting status=75 reason=assignment_timeout") {
t.Fatalf("attempt %d exited 75 without the reason assignment_timeout", attempt)
}
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
}
// oldHostRefuses starts the old holder b after the volume moved to epoch e2
// on another host, and returns it. While it runs it must not adopt the new
// line, report its frontend ready or listen; it must log a refusal and exit
// with wantExit.
func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 uint64, wantExit int) *daemon {
t.Helper()
d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...)
var failures []string
end := time.Now().Add(60 * time.Second)
for alive := true; alive && time.Now().Before(end); {
if l := d.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" {
failures = append(failures, "it adopted the new holder's line: "+l)
}
if env.frontendReadyAt("s1") {
failures = append(failures, "its status reports FrontendPrimaryReady")
}
if listening(b.nvme) {
failures = append(failures, "its NVMe/TCP target listens")
}
select {
case <-d.done:
alive = false
case <-time.After(500 * time.Millisecond):
}
}
if err := d.wait(5 * time.Second); exitCode(err) != wantExit {
failures = append(failures, fmt.Sprintf("it did not exit with status %d: %v", wantExit, err))
}
if !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.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("%s after the forced move: %s", name, strings.Join(failures, "; "))
}
return d
}
// servingNow reports whether the host serves: its frontend is ready or its
// NVMe/TCP target accepts connections.
func (env *handoffEnv) servingNow(id string) bool {
return env.frontendReadyAt(id) || listening(env.hosts[id].nvme)
}
// requireHeadHolder checks that HEAD is active, held by host/r1 at epoch e.
func (env *handoffEnv) requireHeadHolder(t *testing.T, e uint64, host string) {
t.Helper()
out, _ := env.h.command(t, env.chunkShow()...)
head, err := parseHead(out)
if err != nil {
t.Fatal(err)
}
if head.State != "active" || head.Epoch != e || head.Holder != host+"/r1" {
t.Fatalf("HEAD %+v; want active at epoch %d held by %s/r1", head, e, host)
}
}
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, plus an entry for each recipient whose log cannot be read or shows no epoch-e
// delivery at all (each recipient must positively have received the owner's line).
func wrongOwnerEndpoints(e uint64, owner bvHost, ds ...*daemon) []string {
var bad []string
tag := fmt.Sprintf(" epoch=%d ev=", e)
for _, d := range ds {
raw, err := os.ReadFile(d.log)
if err != nil {
bad = append(bad, d.name+": log unreadable: "+err.Error())
continue
}
seen := 0
for _, l := range strings.Split(string(raw), "\n") {
if !strings.Contains(l, "assignment stream delivery") || !strings.Contains(l, tag) {
continue
}
seen++
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))
}
}
if seen == 0 { // positive evidence per recipient: a check that saw no forced-epoch delivery proves nothing
bad = append(bad, d.name+": no epoch delivery logged")
}
}
return bad
}
@@ -0,0 +1,256 @@
package main
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/host/volume"
)
const (
exitWorkspaceRetry = 75
exitWorkspaceSuperseded = 78
// Existing post-drain ACK wait; M2 Revoking -> Revoked, Part D.
workspaceLeaseCloseoutTimeout = 3 * time.Second
)
type workspaceExit struct {
code int
reason string
// detail is the operator's cure, printed on the final exit line.
detail string
}
// INV-WS-STARTUP-RETRY-001: the first outcome is immutable. The channel is a
// single latched wakeup, not a queue of competing shutdown events.
type processExit struct {
parent context.Context
once sync.Once
done chan struct{}
decision chan workspaceExit
startupMu sync.Mutex
startupCtx context.Context
startupCancel context.CancelFunc
}
func newProcessExit(ctx context.Context) *processExit {
startupCtx, cancel := context.WithCancel(ctx)
return &processExit{parent: ctx, done: make(chan struct{}), decision: make(chan workspaceExit, 1), startupCtx: startupCtx, startupCancel: cancel}
}
// INV-WS-STARTUP-RETRY-001: once the resource owner takes shutdown, startup
// outcomes cannot arbitrate it. ACK success is still selected only after ACK.
func (e *processExit) stopChunkStartup() {
e.startupMu.Lock()
defer e.startupMu.Unlock()
e.startupCancel()
}
func (e *processExit) chooseChunkStartup(out workspaceExit) {
e.startupMu.Lock()
defer e.startupMu.Unlock()
if e.startupCtx.Err() == nil {
e.choose(out)
}
}
func (e *processExit) choose(out workspaceExit) {
e.once.Do(func() {
if e.parent.Err() != nil {
out = workspaceExit{reason: "signal"}
}
e.decision <- out // exactly one send fits the buffer without blocking under a provider lock
close(e.done)
})
}
// The original resource owner still drains everything. This outer process
// owner bounds even a stuck Close or deferred cleanup; main alone calls Exit.
func run(f flags) int {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
return superviseProcess(ctx, func(e *processExit) int { return runVolume(f, e) })
}
// INV-WS-STARTUP-RETRY-001: M2 process exit owns the cleanup bound.
func superviseProcess(ctx context.Context, work func(*processExit) int) int {
e := newProcessExit(ctx)
finished := make(chan int, 1)
go func() { finished <- work(e) }()
var out workspaceExit
select {
case code := <-finished:
select {
case out = <-e.decision:
return reportWorkspaceExit(out)
default:
return code
}
case <-ctx.Done():
e.choose(workspaceExit{reason: "signal"})
out = <-e.decision
case out = <-e.decision:
}
if out.code == 0 {
<-finished
return 0
}
timer := time.NewTimer(volume.WorkspaceDrainTimeout)
defer timer.Stop()
return finishWorkspaceExit(out, finished, timer.C)
}
func finishWorkspaceExit(out workspaceExit, finished <-chan int, deadline <-chan time.Time) int {
select {
case <-finished:
case <-deadline:
}
return reportWorkspaceExit(out)
}
func reportWorkspaceExit(out workspaceExit) int {
if out.code != 0 {
if out.detail != "" {
fmt.Fprintf(os.Stderr, "blockvolume: exiting status=%d reason=%s cure=%q\n", out.code, out.reason, out.detail)
} else {
fmt.Fprintf(os.Stderr, "blockvolume: exiting status=%d reason=%s\n", out.code, out.reason)
}
}
return out.code
}
// INV-WS-STARTUP-RETRY-001: one decision combines a newer other-replica
// authority fact and the provider's generation-bound foreign-HEAD proof.
func workspaceRetryOutcome(reason string, h *volume.Host, claimSuperseded bool) workspaceExit {
if claimSuperseded || h.IsCurrentReplicaSuperseded() {
return workspaceExit{code: exitWorkspaceSuperseded, reason: "superseded"}
}
return workspaceExit{code: exitWorkspaceRetry, reason: reason}
}
// M2 startup outcome; INV-WS-STARTUP-RETRY-001. Workspace chunk primaries only.
func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) {
if !f.workspaceLease || f.durableImpl != "walstore-chunk" {
return
}
for {
if chooseChunkStartupExit(e, f, h, p) {
return
}
select {
case <-e.startupCtx.Done():
return
case <-ctx.Done():
return
case <-e.done:
return
case <-p.ChunkStartupUpdates():
}
}
}
// chunkRuntimeFenceProvider reports a runtime HEAD fence of the attached layer.
type chunkRuntimeFenceProvider interface {
ChunkRuntimeFenced(string) bool
ChunkRuntimeFenceUpdates() <-chan struct{}
}
// watchChunkRuntimeFence: a HEAD fence after startup, while the lease may
// still be valid, ends the process with no restart (78 head_fenced): another
// holder owns HEAD (INV-FE-PRIMARY-READY-OPERATIONAL-001). Workspace chunk
// primaries only.
func watchChunkRuntimeFence(ctx context.Context, e *processExit, f flags, p chunkRuntimeFenceProvider) {
if !f.workspaceLease || f.durableImpl != "walstore-chunk" {
return
}
for {
if p.ChunkRuntimeFenced(f.volumeID) {
e.choose(workspaceExit{code: exitWorkspaceSuperseded, reason: "head_fenced"})
return
}
select {
case <-ctx.Done():
return
case <-e.done:
return
case <-p.ChunkRuntimeFenceUpdates():
}
}
}
// M2 process exit / Revoking -> Revoked; INV-WS-STARTUP-RETRY-001.
func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan workspaceStopRequest, done <-chan error) (*workspaceStopRequest, <-chan error) {
select {
case <-e.parent.Done():
e.choose(workspaceExit{reason: "signal"})
return nil, done
case <-e.done:
return nil, done
case request := <-requests:
fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain")
e.stopChunkStartup()
out := workspaceExit{reason: "revoked"}
if !h.WorkspaceLeaseRevoking() {
out = workspaceRetryOutcome("lease_expired", h, false)
}
if out.code != 0 {
e.choose(out)
}
return &request, done
case err := <-done:
e.stopChunkStartup()
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err)
e.choose(workspaceRetryOutcome("lease_expired", h, false))
return nil, nil
}
}
// An ACKed revocation completes with status zero. A failure to confirm that
// ACK is retryable; a signal observed first still retains the signal status.
// M2 Revoking -> Revoked; INV-WS-REVOKE-ACK-001, INV-WS-STARTUP-RETRY-001.
func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan error) {
if done == nil {
return
}
select {
case err := <-done:
if err == nil {
e.choose(workspaceExit{reason: "revoked"})
return
}
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err)
case <-time.After(workspaceLeaseCloseoutTimeout):
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline")
}
e.choose(workspaceExit{code: exitWorkspaceRetry, reason: "revoke_ack_unconfirmed"})
}
// The provider publishes only a generation-bound outcome and an atomic choice.
type chunkStartupOutcomeProvider interface {
ChunkStartupOutcome(string) (uint64, bool)
ChunkStartupSuperseded(string, uint64) bool
ChooseChunkStartupExit(string, uint64, func()) bool
}
func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStartupOutcomeProvider) bool {
if !f.workspaceLease || f.durableImpl != "walstore-chunk" {
return false
}
gen, failed := p.ChunkStartupOutcome(f.volumeID)
if !failed {
return false
}
// INV-WS-STARTUP-RETRY-001: one exit decision consumes both proof
// sources; the provider rechecks the claim generation below.
out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen))
if c, ok := p.(interface{ ChunkStartupCure(string, uint64) string }); ok {
out.detail = c.ChunkStartupCure(f.volumeID, gen)
}
return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) })
}
@@ -0,0 +1,492 @@
package main
import (
"bytes"
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/host/volume"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc"
"net"
"sync/atomic"
"testing"
"time"
)
type exitAssignmentStream struct {
control.UnimplementedAssignmentServiceServer
control.UnimplementedObservationServiceServer
control.UnimplementedWorkspaceServiceServer
revoke bool
ackError error
acks atomic.Int32
facts chan *control.AssignmentFact
}
func (s *exitAssignmentStream) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(30 * time.Second), Revoking: s.revoke}, nil
}
func (s *exitAssignmentStream) AckWorkspaceRevoked(_ context.Context, a *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) {
if a.GetHeadGen() != 1 {
return nil, errors.New("ACK lacks the stored detached proof")
}
s.acks.Add(1)
return &control.WorkspaceEmpty{}, s.ackError
}
func (s *exitAssignmentStream) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) {
return &control.HeartbeatAck{}, nil
}
func (s *exitAssignmentStream) SubscribeAssignments(_ *control.SubscribeRequest, stream control.AssignmentService_SubscribeAssignmentsServer) error {
for {
select {
case <-stream.Context().Done():
return stream.Context().Err()
case f := <-s.facts:
if err := stream.Send(f); err != nil {
return err
}
}
}
}
func exitAuthorityHost(t *testing.T, configure ...func(*exitAssignmentStream)) (*volume.Host, func(string, uint64)) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
stream := &exitAssignmentStream{facts: make(chan *control.AssignmentFact, 4)}
for _, f := range configure {
f(stream)
}
control.RegisterWorkspaceServiceServer(srv, stream)
control.RegisterAssignmentServiceServer(srv, stream)
control.RegisterObservationServiceServer(srv, stream)
go srv.Serve(ln)
t.Cleanup(srv.Stop)
h, err := volume.New(volume.Config{WorkspaceLease: true, MasterAddr: ln.Addr().String(), ServerID: "s", VolumeID: "v", ReplicaID: "r", DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2"})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() {
if err := h.Close(); err != nil {
t.Error(err)
}
})
return h, func(replica string, epoch uint64) {
t.Helper()
stream.facts <- &control.AssignmentFact{VolumeId: "v", ReplicaId: replica, ServerId: "s", Epoch: epoch, EndpointVersion: 1}
deadline := time.NewTimer(3 * time.Second)
defer deadline.Stop()
tick := time.NewTicker(time.Millisecond)
defer tick.Stop()
for {
ready := false
if replica == "r" {
ready = h.Adapter().Projection().Epoch == epoch
} else {
f := h.LastOtherLine()
ready = f != nil && f.ReplicaId == replica && f.Epoch == epoch
}
if ready {
return
}
select {
case <-deadline.C:
t.Fatal("assignment observation did not arrive")
case <-tick.C:
}
}
}
}
// Exercise the real Host subscription and the process stop seam, including a
// historical other-replica record retained after the master assigns us again.
func TestWorkspaceRetryUsesNewestOwnAssignment(t *testing.T) {
for _, tc := range []struct {
name string
facts []struct {
replica string
epoch uint64
}
want int
}{
{"old other then own", []struct {
replica string
epoch uint64
}{{"other", 6}, {"r", 7}}, 75},
{"own then newer other", []struct {
replica string
epoch uint64
}{{"r", 5}, {"other", 6}}, 78},
{"never assigned", []struct {
replica string
epoch uint64
}{{"other", 6}}, 75},
{"empty replica newer epoch", []struct {
replica string
epoch uint64
}{{"r", 5}, {"", 7}}, 75},
{"same replica higher epoch", []struct {
replica string
epoch uint64
}{{"r", 5}, {"r", 7}}, 75},
} {
t.Run(tc.name, func(t *testing.T) {
h, send := exitAuthorityHost(t)
for _, f := range tc.facts {
send(f.replica, f.epoch)
}
e := newProcessExit(context.Background())
done := make(chan error, 1)
done <- errors.New("lease ended")
waitWorkspaceStop(e, flags{volumeID: "v", replicaID: "r"}, h, nil, done)
if out := <-e.decision; out.code != tc.want {
t.Fatalf("lease end classified %+v, want%d", out, tc.want)
}
})
}
}
func TestWorkspaceUnconfirmedRevokeHasOwnReason(t *testing.T) {
h, _ := exitAuthorityHost(t)
e := newProcessExit(context.Background())
done := make(chan error, 1)
done <- errors.New("ACK answer lost")
finishWorkspaceLease(e, flags{volumeID: "v", replicaID: "r"}, h, done)
if out := <-e.decision; out.code != 75 || out.reason != "revoke_ack_unconfirmed" {
t.Fatalf("unconfirmed ACK classified %+v", out)
}
}
// Controlled provider outcome at its public generation/selection seam. The
// real provider deadline/retained-state boundary is tested in durable.
type exitStartupOutcome struct{ expired bool }
func (s *exitStartupOutcome) ChunkStartupSuperseded(string, uint64) bool { return false }
func (s *exitStartupOutcome) ChunkStartupOutcome(string) (uint64, bool) { return 1, s.expired }
func (s *exitStartupOutcome) ChooseChunkStartupExit(_ string, gen uint64, choose func()) bool {
if gen != 1 || !s.expired {
return false
}
choose()
return true
}
func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) {
for _, failAck := range []bool{false, true} {
t.Run(map[bool]string{false: "ACK succeeds", true: "ACK lost"}[failAck], func(t *testing.T) {
var stream *exitAssignmentStream
h, send := exitAuthorityHost(t, func(s *exitAssignmentStream) {
stream = s
s.revoke = true
if failAck {
s.ackError = errors.New("ACK answer lost")
}
})
send("r", 1)
ctx, cancel := context.WithCancel(context.Background())
doneConsumed := false
requests, done := startWorkspaceLease(ctx, h)
t.Cleanup(func() {
cancel()
if !doneConsumed {
select {
case <-done:
case <-time.After(3 * time.Second):
t.Error("lease worker did not join")
}
}
})
e := newProcessExit(ctx)
f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v", replicaID: "r"}
// The real guard sets revoked, sends its stop request, and waits for the
// resource owner's drain reply. No success is selected yet.
request, leaseDone := waitWorkspaceStop(e, f, h, requests, done)
if request == nil || !h.WorkspaceLeaseRevoking() {
t.Fatal("real planned drain not acquired")
}
// Deliver expiry only after the real guard's planned drain owns
// shutdown, while its resource-owner reply is deliberately held.
p := &exitStartupOutcome{expired: true}
chooseChunkStartupExit(e, f, h, p)
select {
case out := <-e.decision:
t.Fatalf("startup overrode the pending real drain: %+v", out)
default:
}
remote := storage.NewMemChunkRemote()
_, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Epoch: 1, Holder: "s/r", Gen: 1}})
if err != nil {
t.Fatal(err)
}
gen, err := workspaceDetachedGeneration(ctx, func(string) (storage.ChunkRemote, error) { return remote, nil }, request.id, "s/r")
if err != nil {
t.Fatal(err)
}
request.reply <- workspaceStopResult{gen: gen}
finishWorkspaceLease(e, f, h, leaseDone)
doneConsumed = true
out := <-e.decision
if stream.acks.Load() != 1 {
t.Fatal("real guard did not send proof ACK")
}
if !failAck && out.code != 0 {
t.Fatalf("ACKed stop restarted: %+v", out)
}
if failAck && (out.code != 75 || out.reason != "revoke_ack_unconfirmed") {
t.Fatalf("unconfirmed ACK: %+v", out)
}
})
}
}
// The real provider must carry the claim's filer proof to the process owner,
// even when the master stream has never reported another replica.
type claimExitView struct{ assigned atomic.Bool }
func (v *claimExitView) Projection() frontend.Projection {
if !v.assigned.Load() {
return frontend.Projection{VolumeID: "v"}
}
return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}
}
func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) {
for _, deferred := range []bool{false, true} {
for _, tc := range []struct {
name, holder string
want int
}{
{"foreign holder", "other", 78}, {"same holder higher epoch", "r", 75},
} {
t.Run(tc.name+map[bool]string{false: "/immediate", true: "/waiting"}[deferred], func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
h, _ := exitAuthorityHost(t)
remote := storage.NewMemChunkRemote()
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: tc.holder, State: storage.ChunkHeadActive}); err != nil {
t.Fatal(err)
}
view := &claimExitView{}
view.assigned.Store(!deferred)
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := p.Close(); err != nil {
t.Error(err)
}
})
if _, err = p.EnsureStorage("v"); err != nil {
t.Fatal(err)
}
_, err = p.RecoverVolume(ctx, "v")
if deferred {
if err != nil {
t.Fatal(err)
}
view.assigned.Store(true)
} else if !errors.Is(err, storage.ErrChunkLayerFenced) {
t.Fatalf("claim refusal=%v", err)
}
select {
case <-p.ChunkStartupUpdates():
case <-ctx.Done():
t.Fatal(ctx.Err())
}
if h.LastOtherLine() != nil {
t.Fatal("fixture unexpectedly supplied master supersede evidence")
}
e := newProcessExit(ctx)
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) {
t.Fatal("claim refusal did not select an exit")
}
select {
case out := <-e.decision:
if out.code != tc.want {
t.Fatalf("claim exit=%+v want %d", out, tc.want)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
head, err := remote.GetHead(ctx)
if err != nil || head.Gen != 1 || head.Holder != tc.holder || remote.Puts() != 0 {
t.Fatalf("refused claim mutated remote: %+v puts=%d err=%v", head, remote.Puts(), err)
}
for _, status := range p.DurableStatuses() {
if status.Operational {
t.Fatal("refused claim became operational")
}
}
})
}
}
}
// Unlike a move BACK to an older foreign publication, this local root's
// assignment is older than the foreign HEAD: another holder has superseded it.
func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) {
for _, deferred := range []bool{false, true} {
t.Run(map[bool]string{false: "immediate", true: "waiting"}[deferred], func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
h, _ := exitAuthorityHost(t)
root := t.TempDir()
remote := storage.NewMemChunkRemote()
view := &claimExitView{}
view.assigned.Store(true)
open := func() *durable.DurableProvider {
t.Helper()
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
if _, err := p.EnsureStorage("v"); err != nil {
t.Fatal(err)
}
return p
}
first := open()
if _, err := first.RecoverVolume(ctx, "v"); err != nil {
t.Fatal(err)
}
want := bytes.Repeat([]byte{0x73}, 4096)
if _, err := first.LogicalStorage("v").Write(0, want); err != nil {
t.Fatal(err)
}
if _, err := first.LogicalStorage("v").Sync(); err != nil {
t.Fatal(err)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
before, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "other", State: storage.ChunkHeadActive}); err != nil {
t.Fatal(err)
}
view.assigned.Store(!deferred)
second := open()
_, err = second.RecoverVolume(ctx, "v")
if deferred {
if err != nil {
t.Fatal(err)
}
view.assigned.Store(true)
select {
case <-second.ChunkStartupUpdates():
case <-ctx.Done():
t.Fatal(ctx.Err())
}
} else if !errors.Is(err, storage.ErrChunkLayerFenced) {
t.Fatalf("old root refusal=%v", err)
}
e := newProcessExit(ctx)
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, second) {
t.Fatal("foreign HEAD attach refusal retained the superseded process")
}
if out := <-e.decision; out.code != 78 {
t.Fatalf("old holder exit=%+v", out)
}
if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) {
t.Fatalf("refusal lost local acknowledged bytes: %v", err)
}
after, err := remote.GetHead(ctx)
if err != nil || after.Gen != before.Gen+1 || after.Holder != "other" || remote.Puts() != 0 {
t.Fatalf("refusal mutated HEAD/payload: %+v puts=%d err=%v", after, remote.Puts(), err)
}
})
}
}
// The real claim reads E1/A; a late E2/C wins before E3/B's CAS.
// The displaced HEAD is a fence for this attempt, not proof E3 was superseded.
type displacedClaimExitRemote struct {
storage.ChunkRemote
epoch uint64
raced bool
}
func (r *displacedClaimExitRemote) CASHead(ctx context.Context, prev storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
if !r.raced {
r.raced = true
late := storage.ChunkHead{Epoch: r.epoch, Holder: "C", State: storage.ChunkHeadActive}
if _, err := r.ChunkRemote.CASHead(ctx, prev, late); err != nil {
return 0, err
}
}
return r.ChunkRemote.CASHead(ctx, prev, next)
}
type displacedClaimExitView struct{}
func (displacedClaimExitView) Projection() frontend.Projection {
return frontend.Projection{VolumeID: "v", ReplicaID: "B", Epoch: 3, Healthy: true}
}
func TestWorkspaceDisplacedClaimUsesAssignedEpoch(t *testing.T) {
for _, tc := range []struct {
name string
epoch uint64
want int
}{
{"late lower epoch", 2, 75}, {"equal epoch foreign holder", 3, 78}, {"higher epoch foreign holder", 4, 78},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
h, _ := exitAuthorityHost(t)
base := storage.NewMemChunkRemote()
if _, err := base.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "A", State: storage.ChunkHeadActive}); err != nil {
t.Fatal(err)
}
remote := &displacedClaimExitRemote{ChunkRemote: base, epoch: tc.epoch}
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, displacedClaimExitView{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := p.Close(); err != nil {
t.Error(err)
}
})
if _, err = p.EnsureStorage("v"); err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) {
t.Fatalf("claim error=%v", err)
}
if !remote.raced {
t.Fatal("controlled CAS did not run")
}
e := newProcessExit(ctx)
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) {
t.Fatal("fenced claim did not choose an exit")
}
select {
case out := <-e.decision:
if out.code != tc.want {
t.Fatalf("displaced E%d/C at assigned E3/B chose %+v, want %d", tc.epoch, out, tc.want)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
head, err := base.GetHead(ctx)
if err != nil || head.Gen != 2 || head.Epoch != tc.epoch || head.Holder != "C" || base.Puts() != 0 {
t.Fatalf("refused claim mutated HEAD/payload: %+v puts=%d err=%v", head, base.Puts(), err)
}
for _, status := range p.DurableStatuses() {
if status.Operational {
t.Fatal("displaced claim served I/O")
}
}
})
}
}
@@ -0,0 +1,93 @@
package main
import (
"context"
"errors"
"os"
"os/exec"
"testing"
"time"
)
func TestWorkspaceExitFirstOutcomeIsLatched(t *testing.T) {
for _, first := range []workspaceExit{{code: 75, reason: "lease_expired"}, {code: 78, reason: "superseded"}, {code: 0, reason: "revoked"}} {
e := newProcessExit(context.Background())
e.choose(first)
e.choose(workspaceExit{code: 75, reason: "assignment_timeout"})
<-e.done
if got := <-e.decision; got != first {
t.Fatalf("first=%+v changed to %+v", first, got)
}
e.choose(workspaceExit{code: 78, reason: "superseded"})
select {
case got := <-e.decision:
t.Fatalf("later outcome published: %+v", got)
default:
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
e := newProcessExit(ctx)
e.choose(workspaceExit{code: 78, reason: "superseded"})
if got := <-e.decision; got.code != 0 || got.reason != "signal" {
t.Fatalf("observed signal lost: %+v", got)
}
}
func TestWorkspaceExitDoesNotWaitForBlockedFrontendClose(t *testing.T) {
finished := make(chan int) // a frontend Close that never returns
deadline := make(chan time.Time, 1)
deadline <- time.Time{}
if code := finishWorkspaceExit(workspaceExit{code: 75, reason: "lease_expired"}, finished, deadline); code != 75 {
t.Fatalf("code=%d", code)
}
// Cleanup errors do not overwrite an already selected retry/no-retry status.
done := make(chan int, 1)
done <- 1
if code := finishWorkspaceExit(workspaceExit{code: 78, reason: "superseded"}, done, make(chan time.Time)); code != 78 {
t.Fatalf("code=%d", code)
}
}
func TestWorkspacePlannedStopKeepsSuccess(t *testing.T) {
code := superviseProcess(context.Background(), func(e *processExit) int {
e.choose(workspaceExit{reason: "revoked"})
return 0 // the close/ACK owner completed normally
})
if code != 0 {
t.Fatalf("planned stop would restart: %d", code)
}
}
// A real child process contains the stuck resource owner. An injected event
// tests the select above; this witness also covers deferred-cleanup isolation.
func TestWorkspaceRetryProcessExitsWhenCloseBlocks(t *testing.T) {
if os.Getenv("GAP1_BLOCKED_CLOSE_CHILD") == "1" {
code := superviseProcess(context.Background(), func(e *processExit) int {
e.choose(workspaceExit{code: 75, reason: "lease_expired"})
select {} // the frontend/resource owner's Close never returns
})
os.Exit(code)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestWorkspaceRetryProcessExitsWhenCloseBlocks$")
cmd.Env = append(os.Environ(), "GAP1_BLOCKED_CLOSE_CHILD=1")
out, err := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 75 {
t.Fatalf("blocked close exit: %v %s", err, out)
}
}
func TestWorkspaceSignalFirstKeepsZeroAfterLaterFailure(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
code := superviseProcess(ctx, func(e *processExit) int {
e.choose(workspaceExit{code: 78, reason: "superseded"})
return 1 // a later cleanup error cannot replace the chosen signal status
})
if code != 0 {
t.Fatalf("first signal status changed to %d", code)
}
}
@@ -117,7 +117,8 @@ func TestBinaryReplicationIngressFollowsAssignedSlots(t *testing.T) {
if e != nil {
t.Fatal(e)
}
child := exec.Command(exe, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", status, "--t1-readiness", "--durable-root", root, "--durable-impl", "walstore", "--durable-blocks", "64", "--heartbeat-interval", "50ms", "--recovery-mode", mode)
child := exec.Command(exe, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", status, "--t1-readiness", "--durable-root", root, "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore", "--durable-blocks", "64", "--heartbeat-interval", "50ms", "--recovery-mode", mode)
stripSystemdForTestLockDir(child)
child.Stdout, child.Stderr = log, log
if e = child.Start(); e != nil {
t.Fatal(e)
@@ -166,7 +167,7 @@ func TestBinaryReplicationIngressFollowsAssignedSlots(t *testing.T) {
ingressRefused(t, data)
ingressRefused(t, dual)
fact := func(e uint64, peers []*control.ReplicaDescriptor) *control.AssignmentFact {
return &control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: e, EndpointVersion: e, DataAddr: data, CtrlAddr: ctrl, PeerSetGeneration: e, Peers: peers}
return &control.AssignmentFact{ServerId: "s1", VolumeId: "v1", ReplicaId: "r1", Epoch: e, EndpointVersion: e, DataAddr: data, CtrlAddr: ctrl, PeerSetGeneration: e, Peers: peers}
}
m.facts <- fact(1, nil)
ingressWait(t, "RF1 assignment not applied", func() bool { return epoch(1) })
@@ -0,0 +1,86 @@
package main
import (
"context"
"sync/atomic"
"testing"
"time"
)
type runtimeFenceStub struct {
fenced atomic.Bool
updates chan struct{}
}
func (s *runtimeFenceStub) ChunkRuntimeFenced(string) bool { return s.fenced.Load() }
func (s *runtimeFenceStub) ChunkRuntimeFenceUpdates() <-chan struct{} { return s.updates }
// runtimeFenceWait bounds every receive and join in this test.
const runtimeFenceWait = 5 * time.Second
// startRuntimeFenceWatch runs watchChunkRuntimeFence with a context it owns.
// Its cleanup, registered before the worker starts, cancels that context and
// joins the worker within runtimeFenceWait, so an earlier failed check never
// strands it. The returned channel closes when the worker returned.
func startRuntimeFenceWatch(t *testing.T, e *processExit, f flags, p chunkRuntimeFenceProvider) <-chan struct{} {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
t.Cleanup(func() {
cancel()
select {
case <-done:
case <-time.After(runtimeFenceWait):
t.Errorf("the runtime-fence watcher did not return within %s of its cancel", runtimeFenceWait)
}
})
go func() {
defer close(done)
watchChunkRuntimeFence(ctx, e, f, p)
}()
return done
}
// INV-FE-FENCE-EXIT-001: a runtime HEAD fence of a workspace chunk primary
// chooses the no-restart exit 78 head_fenced through the process owner's one
// chooser, and the watcher returns; nothing is chosen while not fenced, and a
// non-workspace volume never watches.
func TestRuntimeHeadFenceChoosesHeadFencedExit(t *testing.T) {
f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"}
e := newProcessExit(context.Background())
stub := &runtimeFenceStub{updates: make(chan struct{}, 1)}
done := startRuntimeFenceWatch(t, e, f, stub)
select {
case out := <-e.decision:
t.Fatalf("an exit was chosen while not fenced: %+v", out)
case <-time.After(100 * time.Millisecond):
}
stub.fenced.Store(true)
stub.updates <- struct{}{}
select {
case out := <-e.decision:
if out != (workspaceExit{code: exitWorkspaceSuperseded, reason: "head_fenced"}) {
t.Fatalf("exit %+v, want 78 head_fenced", out)
}
case <-time.After(runtimeFenceWait):
t.Fatal("no exit chosen after the runtime fence")
}
select {
case <-done:
case <-time.After(runtimeFenceWait):
t.Fatal("the watcher chose the exit but did not return")
}
plain := newProcessExit(context.Background())
plainDone := startRuntimeFenceWatch(t, plain, flags{volumeID: "v1"}, stub)
select {
case <-plainDone: // not a workspace chunk primary: returns at once
case <-time.After(runtimeFenceWait):
t.Fatal("a non-workspace volume kept watching")
}
select {
case out := <-plain.decision:
t.Fatalf("a non-workspace volume chose %+v", out)
default:
}
}
@@ -0,0 +1,179 @@
//go:build linux && subprocess && chunkstore_integration && systemd_integration
package main_test
import (
"bytes"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
// This small initiator uses the same exported wire types and admin/IO queue
// handshake as core/frontend/nvme/client_support_test.go. It talks only to the
// real blockvolume in this harness; no kernel device or unrelated NQN is used.
type gap1NVMe struct {
admin, io net.Conn
r *nvme.Reader
w *nvme.Writer
cid uint16
}
func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe {
t.Helper()
c := &gap1NVMe{}
t.Cleanup(c.close)
var controller uint16 = 0xffff
for q := uint16(0); q < 2; q++ {
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
t.Fatal(err)
}
if q == 0 {
c.admin = conn
} else {
c.io = conn
}
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
r, w := nvme.NewReader(conn), nvme.NewWriter(conn)
if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil {
t.Fatal(err)
}
h, err := r.Dequeue()
if err != nil || h.Type != 1 {
t.Fatalf("NVMe IC response: %+v %v", h, err)
}
var ic nvme.ICResponse
if err := r.Receive(&ic); err != nil {
t.Fatal(err)
}
c.cid++
cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16}
data := make([]byte, 1024)
(&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data)
if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil {
t.Fatal(err)
}
reply := gap1NVMeReply(t, r, c.cid)
if q == 0 {
controller = uint16(reply.DW0)
if controller == 0 {
t.Fatal("no controller assigned")
}
}
if q == 1 {
c.r, c.w = r, w
}
}
return c
}
func (c *gap1NVMe) close() {
if c.io != nil {
_ = c.io.Close()
}
if c.admin != nil {
_ = c.admin.Close()
}
}
func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse {
t.Helper()
h, err := r.Dequeue()
if err != nil || h.Type != 5 {
t.Fatalf("NVMe capsule header: %+v %v", h, err)
}
var reply nvme.CapsuleResponse
if err := r.Receive(&reply); err != nil {
t.Fatal(err)
}
if reply.CID != cid || reply.Status != 0 {
t.Fatalf("NVMe CID %d: %+v", cid, reply)
}
return reply
}
func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) {
t.Helper()
if len(payload) != 4096 {
t.Fatal("harness writes exactly one block")
}
c.cid++
cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)}
if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil {
t.Fatal(err)
}
h, err := c.r.Dequeue()
if err != nil || h.Type != 9 {
t.Fatalf("NVMe R2T: %+v %v", h, err)
}
var r2t nvme.R2THeader
if err := c.r.Receive(&r2t); err != nil {
t.Fatal(err)
}
if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) {
t.Fatalf("wrong R2T %+v", r2t)
}
data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))}
if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil {
t.Fatal(err)
}
gap1NVMeReply(t, c.r, c.cid)
c.cid++
flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1}
if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil {
t.Fatal(err)
}
gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable
}
func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) {
t.Helper()
c.cid++
cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)}
if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil {
t.Fatal(err)
}
h, err := c.r.Dequeue()
if err != nil || h.Type != 7 {
t.Fatalf("NVMe read data: %+v %v", h, err)
}
var header nvme.C2HDataHeader
if err := c.r.Receive(&header); err != nil {
t.Fatal(err)
}
if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) {
t.Fatalf("wrong read frame %+v length%d", header, c.r.Length())
}
got := make([]byte, c.r.Length())
if err := c.r.ReceiveData(got); err != nil {
t.Fatal(err)
}
gap1NVMeReply(t, c.r, c.cid)
if !bytes.Equal(got, want) {
t.Fatal("fsync-acknowledged NVMe record changed after supervised restart")
}
}
// Calibration of the witness client only, not a systemd/re-grant proof.
func TestGAP1NVMeWitnessRoundTripsAcknowledgedBlock(t *testing.T) {
backend := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1})
nqn := "nqn.2026-11.test:gap1-witness-calibration"
target := nvme.NewTarget(nvme.TargetConfig{Listen: "127.0.0.1:0", SubsysNQN: nqn, VolumeID: "v", Provider: testback.NewStaticProvider(backend), Handler: nvme.HandlerConfig{NSID: 1, BlockSize: 4096, VolumeSize: 64 * 4096}})
addr, err := target.Start()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = target.Close() })
c := gap1ConnectNVMe(t, addr, nqn)
want := bytes.Repeat([]byte{0x6d}, 4096)
c.writeFlush(t, 8, want)
c.readExact(t, 8, want)
if backend.WriteCount() != 1 || backend.SyncCount() != 1 || backend.ReadCount() != 1 {
t.Fatalf("witness bypassed backend write/flush/read: %d/%d/%d", backend.WriteCount(), backend.SyncCount(), backend.ReadCount())
}
}
@@ -0,0 +1,811 @@
//go:build linux && subprocess && chunkstore_integration && systemd_integration
package main_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Real systemd owns every restart. No test goroutine relaunches the holder.
// The first assertion is RED on GAP-1: the expired startup stays alive.
func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" {
t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof")
}
if os.Geteuid() != 0 {
t.Fatal("systemd qualification needs root")
}
if os.Getenv("CHUNKSTORE_WEED") == "" {
t.Fatal("real CHUNKSTORE_WEED binary required")
}
probeCtx, probeCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer probeCancel()
if out, err := exec.CommandContext(probeCtx, "systemctl", "show", "--property=Version").CombinedOutput(); err != nil {
t.Fatalf("real systemd unavailable: %v %s", err, out)
}
// Under systemd the test lock override is refused: the units use the
// real host lock directory, which the shipped tmpfiles.d entry makes.
if err := os.MkdirAll(durable.HostVolumeLockDir, 0o700); err != nil {
t.Fatalf("host volume lock directory: %v", err)
}
fixture := newGAP1Fixture(t)
root := fixture.root
bin := filepath.Join(root, "bin")
if err := os.Mkdir(bin, 0755); err != nil {
t.Fatal(err)
}
for _, name := range []string{"blockvolume", "blockmaster"} {
buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute)
cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name)
cmd.WaitDelay = time.Second // bound inherited child pipes after cancellation
out, err := cmd.CombinedOutput()
buildCancel()
if err != nil {
t.Fatalf("real binary build: %v %s", err, out)
}
}
cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed"))
gap1PreserveFailure(t, root, cluster.dir)
stem := fmt.Sprintf("gap1-%d", time.Now().UnixNano())
gap1ProbeTerminalSuccess(t, fixture, stem+"-policy-probe")
volume := stem
base := "/" + stem
masterAddr := leaseBinaryAddress(t)
target, masterListen := gap1TargetAddresses(t, masterAddr)
dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t)
cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n - server_id: s2\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, target.dataAddr, target.ctrlAddr, volume)
spec := filepath.Join(root, "cluster.yaml")
if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil {
t.Fatal(err)
}
fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"),
"--listen", masterListen, "--insecure-external-bind", "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"),
"--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1",
"--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base)
w4WaitTCP(t, masterAddr, 20*time.Second)
conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ws := control.NewWorkspaceServiceClient(conn)
args := []string{"--master", masterAddr, "--server-id", "s1", "--volume-id", volume, "--replica-id", "r1",
"--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr,
"--durable-root", filepath.Join(root, "store"), "--durable-impl", "walstore-chunk", "--durable-blocks", "64",
"--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease",
"--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:" + stem}
// Bootstrap is a different, non-restarting unit. Kill only this exact unit.
bootstrap := stem + "-bootstrap"
fixture.start(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...)
waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) })
// Calibrate the readiness parser on the serving source's actual /status
// response before using it for the target's negative readiness assertion.
waitGAP1(t, "source readiness control never became true", 20*time.Second, func() bool {
status, body, err := gap1StatusAt(statusAddr, volume, "/status")
if err != nil || status != http.StatusOK {
return false
}
serving, err := gap1Readiness(status, body, volume)
if err != nil {
t.Fatal(err)
}
if serving {
t.Logf("captured real readiness control: status%d body%s", status, body)
}
return serving
})
// Calibrate verdict parsing against actual binary responses BEFORE kill.
status, payload, err := gap1Status(statusAddr, volume)
t.Logf("captured real status200: status%d body%s", status, payload)
if err != nil || !gap1StatusOperational(status, payload, volume) {
t.Fatalf("real status200 parser control: %v", err)
}
missing, body404, err := gap1Status(statusAddr, volume+"-not-served")
t.Logf("captured real status404: status%d body%s", missing, body404)
if err != nil || missing != http.StatusNotFound || gap1StatusOperational(missing, body404, volume) {
t.Fatalf("real status404 parser control: %v", err)
}
want := bytes.Repeat([]byte{0x6d}, 4096)
client := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem)
client.writeFlush(t, 8, want)
t.Logf("acknowledged NVMe record: lba=8 bytes=%d sha256=%x", len(want), sha256.Sum256(want))
client.readExact(t, 8, want)
client.close()
remote := cluster.remote(t, base+"/"+volume)
before, err := gap1ReadHead(t, remote)
if err != nil || before.Gen == 0 {
t.Fatalf("bootstrap HEAD: %+v %v", before, err)
}
gap1Systemctl(t, "kill", "--signal=KILL", "--kill-who=main", bootstrap)
waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" })
// QueryWorkspace is read-only. These real binaries and this test share
// one WSL kernel wall clock. Use the reported MASTER expiry timestamp,
// not ValidForNs (which ends half a skew earlier and could renew live).
// No product barrier formula or fake master clock is introduced.
waitGAP1(t, "holder's reported validity never lapsed", 60*time.Second, func() bool {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
s, e := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume})
if e != nil || s.GetLease() == nil {
return false
}
t.Logf("captured master lease: %s", s.String())
return s.Lease.ValidForNs <= 0 && time.Now().UnixNano() >= s.Lease.ExpiresAtNs
})
unit := stem + "-returning"
fixture.start(t, unit, true, filepath.Join(bin, "blockvolume"), args...)
first := gap1Unit(t, unit)
t.Logf("captured effective restart policy: %+v", first)
firstPID := first["MainPID"]
if firstPID == "0" {
t.Fatal("returning unit did not start a real process")
}
// Existing assignment wait is30s. This is an outer failed-run guard, not
// an injected success delay or a replacement product deadline.
waitGAP1(t, "GAP-1: first startup never exited75; stayed alive non-serving", 45*time.Second, func() bool {
s := gap1Unit(t, unit)
if gap1Operational(t, statusAddr, volume) {
t.Fatal("fixture returned before the expired-grant barrier: cannot count this as a startup-timeout red")
}
if s["ExecMainStatus"] == "75" {
return true
}
if s["MainPID"] != "0" && s["MainPID"] != firstPID {
t.Fatalf("restart without captured75: %+v", s)
}
return false
})
waitGAP1(t, "systemd did not restart/regrant/attach", 100*time.Second, func() bool {
s := gap1Unit(t, unit)
n, e := strconv.Atoi(s["NRestarts"])
if e != nil {
t.Fatalf("invalid captured NRestarts: %+v", s)
}
if n > 2 {
t.Fatalf("barrier retry exceeded three total launches: %+v", s)
}
return n >= 1 && s["MainPID"] != "0" && s["MainPID"] != firstPID && gap1Operational(t, statusAddr, volume)
})
after, err := gap1ReadHead(t, remote)
if err != nil || after.Gen <= before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch {
t.Fatalf("return did not claim HEAD: before%+v after%+v err%v", before, after, err)
}
returned := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem)
returned.readExact(t, 8, want)
returned.writeFlush(t, 9, want)
returned.readExact(t, 9, want)
returned.close()
// A real control cut must pass the lease and layer gates after restart.
req, err := http.NewRequest(http.MethodPost, "http://"+statusAddr+"/chunk/cut", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"timeoutMs":3000}`, volume)))
if err != nil {
t.Fatal(err)
}
resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("post-regrant real cut status%d", resp.StatusCode)
}
s := gap1Unit(t, unit)
if s["Result"] == "start-limit-hit" {
t.Fatalf("systemd rate limit hit: %+v", s)
}
gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"])
gap1PrestartedTargetServesAfterMove(t, fixture, ws, remote, target, stem, filepath.Join(bin, "blockvolume"), args, root, volume, want)
}
// Roots are deliberately independent of testing.TempDir: unknown unit cleanup
// must never remove an executable or WAL beneath a possible surviving service.
type gap1Fixture struct {
root string
units []string
}
func newGAP1Fixture(t *testing.T) *gap1Fixture {
t.Helper()
root, err := os.MkdirTemp("", "gap1-runtime-")
if err != nil {
t.Fatal(err)
}
f := &gap1Fixture{root: root}
t.Cleanup(func() {
safe := true
for _, unit := range f.units {
state, err := gap1ReadUnit(unit)
if err != nil || !gap1UnitGone(state) {
t.Errorf("final unit absence unproved: %s state%v err%v", unit, state, err)
safe = false
}
}
if !safe || t.Failed() {
t.Logf("retained run root: %s (safe=%v failed=%v)", root, safe, t.Failed())
return
}
if err := os.RemoveAll(root); err != nil {
t.Errorf("remove confirmed idle run root: %v", err)
}
})
return f
}
func (f *gap1Fixture) start(t *testing.T, unit string, restart bool, exe string, args ...string) {
t.Helper()
f.units = append(f.units, unit)
// Persist ownership before the create, including an aggregate test crash.
ownership, err := os.OpenFile(filepath.Join(f.root, "owned-units.txt"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
t.Fatal(err)
}
_, writeErr := fmt.Fprintln(ownership, unit)
closeErr := ownership.Close()
if writeErr != nil || closeErr != nil {
t.Fatalf("record unit ownership: %v %v", writeErr, closeErr)
}
// Register BEFORE submission: systemd may create the unit even when the
// command loses its answer or times out. Every uncertain create is owned.
t.Cleanup(func() { gap1CleanupUnit(t, unit) })
policy := "no"
if restart {
policy = "on-failure"
}
shipped := gap1ShippedPolicy(t)
cmdArgs := []string{"--unit=" + unit, "--property=Type=exec", "--property=Restart=" + policy, "--property=RestartSec=" + shipped["RestartSec"], "--property=RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], "--property=TimeoutStopSec=" + shipped["TimeoutStopSec"], "--property=StartLimitIntervalSec=10s", "--property=StartLimitBurst=5", "--", exe}
cmdArgs = append(cmdArgs, args...)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if out, err := exec.CommandContext(ctx, "systemd-run", cmdArgs...).CombinedOutput(); err != nil {
t.Fatalf("systemd-run %s (creation outcome uncertain; registered cleanup owns it): %v %s", unit, err, out)
}
}
func gap1CleanupUnit(t *testing.T, unit string) {
t.Helper()
command := func(bound time.Duration, args ...string) error {
ctx, cancel := context.WithTimeout(context.Background(), bound)
defer cancel()
out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
if err != nil {
t.Logf("unit cleanup %s: %v %s", unit, err, out)
}
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=short-monotonic").CombinedOutput()
cancel()
t.Logf("real unit %s journal:\n%s", unit, journal)
_ = command(15*time.Second, "stop", unit)
state, err := gap1ReadUnit(unit)
if err != nil || !gap1UnitGone(state) {
_ = command(5*time.Second, "kill", "--kill-who=all", "--signal=KILL", unit)
_ = command(5*time.Second, "stop", unit)
}
_ = command(5*time.Second, "reset-failed", unit)
state, err = gap1ReadUnit(unit)
if err != nil || !gap1UnitGone(state) {
t.Errorf("owned unit/PID cleanup not confirmed; retain run root: %s state%v err%v", unit, state, err)
return
}
t.Logf("confirmed owned unit stopped: %s state%v", unit, state)
}
func gap1UnitGone(s map[string]string) bool {
job, hasJob := s["Job"]
return hasJob && job == "" && s["MainPID"] == "0" && s["ControlPID"] == "0" &&
(s["LoadState"] == "not-found" || s["LoadState"] == "loaded") && s["ActiveState"] == "inactive" && s["SubState"] == "dead"
}
// The absent-unit shape is captured from real systemd249. Refuse incomplete,
// contradictory, queued-job and live-process observations before removing WAL.
func TestGAP1AbsenceRequiresNoJobAndBothPIDsZero(t *testing.T) {
for _, tc := range []struct {
name, key, value string
want bool
}{
{"collected", "LoadState", "not-found", true},
{"loaded stopped", "LoadState", "loaded", true},
{"main lives", "MainPID", "123", false},
{"control lives", "ControlPID", "123", false},
{"job queued", "Job", "123", false},
{"restart pending", "SubState", "auto-restart", false},
{"contradictory active", "ActiveState", "active", false},
{"unknown load", "LoadState", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
s := map[string]string{"MainPID": "0", "ControlPID": "0", "LoadState": "not-found", "ActiveState": "inactive", "SubState": "dead", "Job": ""}
s[tc.key] = tc.value
if gap1UnitGone(s) != tc.want {
t.Fatalf("absence classification %+v want%v", s, tc.want)
}
delete(s, "Job")
if gap1UnitGone(s) {
t.Fatal("missing observation treated as absence")
}
})
}
}
func gap1ReadHead(t *testing.T, remote storage.ChunkRemote) (storage.ChunkHead, error) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return remote.GetHead(ctx)
}
func gap1Systemctl(t *testing.T, args ...string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput(); err != nil {
t.Fatalf("systemctl: %v %s", err, out)
}
}
func gap1Unit(t *testing.T, unit string) map[string]string {
t.Helper()
m, err := gap1ReadUnit(unit)
if err != nil {
t.Fatal(err)
}
t.Logf("captured unit %s: %+v", unit, m)
return m
}
func gap1ReadUnit(unit string) (map[string]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=Job,MainPID,ControlPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec,ActiveState,SubState,LoadState,InvocationID").CombinedOutput()
if err != nil {
return nil, fmt.Errorf("unit show %s: %w %s", unit, err, b)
}
m := map[string]string{}
for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") {
k, v, ok := strings.Cut(l, "=")
if ok {
m[k] = v
}
}
for _, key := range []string{"Job", "MainPID", "ControlPID", "NRestarts", "ExecMainStatus", "Result", "ExecMainStartTimestampMonotonic", "LoadState", "ActiveState", "SubState"} {
if _, ok := m[key]; !ok {
return nil, fmt.Errorf("captured systemd response lacks %s: %s", key, b)
}
}
return m, nil
}
func gap1Status(addr, volume string) (int, []byte, error) {
return gap1StatusAt(addr, volume, "/status/durable")
}
func gap1StatusAt(addr, volume, route string) (int, []byte, error) {
r, e := (&http.Client{Timeout: time.Second}).Get("http://" + addr + route + "?volume=" + volume)
if e != nil {
return 0, nil, e
}
defer r.Body.Close()
body, e := io.ReadAll(io.LimitReader(r.Body, 1<<20))
return r.StatusCode, body, e
}
// /status is a different schema from /status/durable. Presence checks make
// a wrong route or a missing field a failed oracle, not false readiness.
func gap1Readiness(status int, payload []byte, volume string) (bool, error) {
if status != http.StatusOK {
return false, fmt.Errorf("readiness HTTP status%d", status)
}
var body struct {
VolumeID string
Healthy, FrontendPrimaryReady *bool
}
if err := json.Unmarshal(payload, &body); err != nil {
return false, err
}
if body.VolumeID != volume || body.Healthy == nil || body.FrontendPrimaryReady == nil {
return false, fmt.Errorf("readiness response lacks exact volume and readiness fields: %s", payload)
}
return *body.Healthy || *body.FrontendPrimaryReady, nil
}
func TestGAP1ReadinessRejectsWrongSchema(t *testing.T) {
projection := hostvolume.StatusProjection{}
projection.VolumeID = "v"
projectionPayload := func(healthy, ready bool) []byte {
t.Helper()
projection.Healthy, projection.FrontendPrimaryReady = healthy, ready
b, err := json.Marshal(projection)
if err != nil {
t.Fatal(err)
}
return b
}
for _, tc := range []struct {
name string
status int
body []byte
serving, refused bool
}{
{"not-ready", 200, projectionPayload(false, false), false, false},
{"healthy", 200, projectionPayload(true, false), true, false},
{"frontend-ready", 200, projectionPayload(false, true), true, false},
{"durable-route", 200, []byte(`{"VolumeID":"v","Volumes":[{"VolumeID":"v","Operational":false}]}`), false, true},
{"missing-readiness", 200, []byte(`{"VolumeID":"v","Healthy":false}`), false, true},
{"wrong-volume", 200, []byte(`{"VolumeID":"other","Healthy":false,"FrontendPrimaryReady":false}`), false, true},
{"http-refusal", 404, projectionPayload(false, false), false, true},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := gap1Readiness(tc.status, tc.body, "v")
if got != tc.serving || (err != nil) != tc.refused {
t.Fatalf("serving=%v err=%v want=%v refused=%v", got, err, tc.serving, tc.refused)
}
})
}
}
func gap1StatusOperational(status int, payload []byte, volume string) bool {
if status != http.StatusOK {
return false
}
var body struct{ Volumes []durable.VolumeStatus }
if json.Unmarshal(payload, &body) != nil {
return false
}
for _, v := range body.Volumes {
if v.VolumeID == volume {
return v.Operational && v.Chunk != nil && v.Chunk.Attached && !v.Chunk.Fenced
}
}
return false
}
func gap1Operational(t *testing.T, addr, volume string) bool {
t.Helper()
status, payload, e := gap1Status(addr, volume)
return e == nil && gap1StatusOperational(status, payload, volume)
}
func waitGAP1(t *testing.T, what string, bound time.Duration, ready func() bool) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), bound)
defer cancel()
tick := time.NewTicker(200 * time.Millisecond)
defer tick.Stop()
for {
if ready() {
return
}
select {
case <-ctx.Done():
t.Fatal(what)
case <-tick.C:
}
}
}
// The transient unit exercises the shipped restart policy, not an independently
// tuned retry loop. Both deployed frontend variants must carry the same policy.
func gap1ShippedPolicy(t *testing.T) map[string]string {
t.Helper()
var first map[string]string
for _, name := range []string{"sw-blockvolume.service", "sw-blockvolume-ublk.service"} {
raw, err := os.ReadFile(filepath.Join("..", "..", "deploy", "systemd", name))
if err != nil {
t.Fatal(err)
}
fields := map[string]string{}
for _, line := range strings.Split(string(raw), "\n") {
key, value, ok := strings.Cut(strings.TrimSpace(line), "=")
if ok {
fields[key] = value
}
}
if fields["Restart"] != "on-failure" || fields["RestartPreventExitStatus"] != "78" || fields["RestartSec"] != "5s" {
t.Fatalf("shipped policy changed: %s %+v", name, fields)
}
if first != nil {
for _, key := range []string{"Restart", "RestartSec", "RestartPreventExitStatus", "TimeoutStopSec"} {
if fields[key] != first[key] {
t.Fatalf("unit policies differ at %s", key)
}
}
}
first = fields
}
return first
}
// A successful planned revoke is not a retry outcome. The master's ACK and
// systemd's terminal inactive/dead state prove no automatic restart is queued.
func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClient, unit, addr, volume string, epoch uint64, holder, restarts, invocation string) {
t.Helper()
req, err := http.NewRequest(http.MethodPost, "http://"+addr+"/chunk/detach", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"plain":true,"timeoutMs":5000}`, volume)))
if err != nil {
t.Fatal(err)
}
resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
if err != nil {
t.Fatal(err)
}
body, readErr := io.ReadAll(resp.Body)
_ = resp.Body.Close()
t.Logf("captured plain seal response: status%d body%s", resp.StatusCode, body)
if readErr != nil || resp.StatusCode != http.StatusOK {
t.Fatalf("plain seal: %v status%d", readErr, resp.StatusCode)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, err = ws.RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: volume, ReplicaId: holder, Epoch: epoch})
cancel()
if err != nil {
t.Fatal(err)
}
waitGAP1(t, "planned revoke never recorded ACK and exited normally", 20*time.Second, func() bool {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
status, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume})
if err != nil || status.GetRevocationAck() == nil {
return false
}
ack := status.GetRevocationAck()
t.Logf("captured planned-stop ACK: %s", ack.String())
if ack.GetIdentity().GetVolumeId() != volume || ack.GetIdentity().GetReplicaId() != holder || ack.GetIdentity().GetEpoch() != epoch || ack.GetHeadGen() == 0 {
t.Fatalf("wrong planned ACK: %s", ack.String())
}
state := gap1Unit(t, unit)
// systemd may unload a successful transient unit, resetting its
// counters. In that case use the exact invocation's journal proof.
if state["LoadState"] != "not-found" && state["NRestarts"] != restarts {
t.Fatalf("planned stop restarted: %+v", state)
}
if state["MainPID"] != "0" {
return false
}
if state["ExecMainStatus"] != "0" || state["ActiveState"] != "inactive" || state["SubState"] != "dead" {
t.Fatalf("planned stop is not terminal success: %+v", state)
}
starts, parseErr := strconv.Atoi(restarts)
if parseErr != nil || invocation == "" {
t.Fatalf("missing pre-stop systemd identity: starts=%q invocation=%q", restarts, invocation)
}
return gap1JournalTerminalSuccess(t, unit, invocation, starts+1)
})
}
// The host-consistency check uses the actual gRPC peer address. Model two
// registered hosts with loopback and a real non-loopback local IPv4 address;
// the target dials the master over that second address. Both processes and
// every restart still run under the same real WSL systemd (not two machines).
type gap1Target struct {
masterAddr, dataAddr, ctrlAddr string
}
func gap1TargetAddresses(t *testing.T, masterAddr string) (gap1Target, string) {
t.Helper()
_, port, err := net.SplitHostPort(masterAddr)
if err != nil {
t.Fatal(err)
}
interfaces, err := net.Interfaces()
if err != nil {
t.Fatal(err)
}
for _, iface := range interfaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addresses, err := iface.Addrs()
if err != nil {
t.Fatal(err)
}
for _, address := range addresses {
ip, _, err := net.ParseCIDR(address.String())
if err != nil || ip.To4() == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
continue
}
allocate := func() string {
ln, err := net.Listen("tcp", net.JoinHostPort(ip.String(), "0"))
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
if err := ln.Close(); err != nil {
t.Fatal(err)
}
return addr
}
return gap1Target{net.JoinHostPort(ip.String(), port), allocate(), allocate()}, net.JoinHostPort("0.0.0.0", port)
}
}
t.Fatal("qualification requires a real non-loopback IPv4 address; no skip is proof")
return gap1Target{}, ""
}
// Start the future target before a clean move is issued. It has the same
// logical r1 identity but a different server id, and no own lineage: the source
// line cannot mean it lost anything. Prove75 and automatic restart, then issue
// a real MoveWorkspace and prove lease/HEAD/data admission without touching
// the target unit again. This is not a positive78/no-restart witness.
func gap1PrestartedTargetServesAfterMove(t *testing.T, fixture *gap1Fixture, ws control.WorkspaceServiceClient, remote storage.ChunkRemote, target gap1Target, stem, exe string, args []string, root, volume string, want []byte) {
t.Helper()
changed := append([]string(nil), args...)
addr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t)
nqn := "nqn.2026-11.test:" + stem + "-prestarted-target"
replacements := map[string]string{"--master": target.masterAddr, "--server-id": "s2", "--data-addr": target.dataAddr, "--ctrl-addr": target.ctrlAddr, "--status-addr": addr, "--durable-root": filepath.Join(root, "target-store"), "--nvme-listen": nvmeAddr, "--nvme-subsysnqn": nqn}
for i := 0; i+1 < len(changed); i++ {
if value, ok := replacements[changed[i]]; ok {
changed[i+1] = value
}
}
unit := stem + "-prestarted-target"
fixture.start(t, unit, true, exe, changed...)
waitGAP1(t, "target never observed the source holder before the move", 15*time.Second, func() bool {
status, body, err := gap1StatusAt(addr, volume, "/status")
if err != nil || status != http.StatusOK {
return false
}
serving, err := gap1Readiness(status, body, volume)
if err != nil {
t.Fatal(err)
}
if serving {
t.Fatalf("future target served before the move: %s", body)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat")
cmd.WaitDelay = time.Second
journal, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("target journal: %v %s", err, journal)
}
observed := fmt.Sprintf("assignment identity refusal volume=%q replica=%q server=%q", volume, "r1", "s1")
return strings.Contains(string(journal), observed)
})
waitGAP1(t, "prestarted target did not exit75 before the move", 45*time.Second, func() bool {
s := gap1Unit(t, unit)
if s["ExecMainStatus"] == "78" {
t.Fatalf("zero-lineage target chose no-retry before its move: %+v", s)
}
return s["ExecMainStatus"] == "75"
})
waitGAP1(t, "prestarted target retry75 did not restart", 15*time.Second, func() bool {
s := gap1Unit(t, unit)
n, err := strconv.Atoi(s["NRestarts"])
if err != nil || n > 2 {
t.Fatalf("invalid or unbounded target restart count: %+v", s)
}
return n >= 1 && s["MainPID"] != "0"
})
sealed, err := gap1ReadHead(t, remote)
if err != nil || sealed.State != storage.ChunkHeadDetached || sealed.Holder != "s1/r1" || sealed.Gen == 0 {
t.Fatalf("move source not sealed by its exact holder: %+v %v", sealed, err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: stem + "-target-move", VolumeId: volume, ExpectedReplicaId: "r1", ExpectedEpoch: sealed.Epoch, TargetReplicaId: "r1", TargetServerId: "s2", TargetDataAddr: target.dataAddr, TargetCtrlAddr: target.ctrlAddr, Kind: "clean"})
cancel()
if err != nil || !grant.GetIssued() || grant.GetNewEpoch() <= sealed.Epoch || grant.GetOldHost() != "s1" || grant.GetNewHost() != "s2" || grant.GetHeadGen() != sealed.Gen {
t.Fatalf("real clean move failed: grant=%v err=%v", grant, err)
}
t.Logf("prestarted target move issued after its automatic restart: %s", grant)
waitGAP1(t, "automatically restarted target did not serve after the move", 60*time.Second, func() bool {
s := gap1Unit(t, unit)
n, err := strconv.Atoi(s["NRestarts"])
if err != nil || n < 1 || n > 2 || s["Result"] == "start-limit-hit" {
t.Fatalf("target restart bound violated after move: %+v", s)
}
return gap1Operational(t, addr, volume)
})
head, err := gap1ReadHead(t, remote)
if err != nil || head.Gen <= sealed.Gen || head.Epoch != grant.NewEpoch || head.Holder != "s2/r1" || head.State != storage.ChunkHeadActive {
t.Fatalf("target did not claim its issued HEAD: %+v %v", head, err)
}
client := gap1ConnectNVMe(t, nvmeAddr, nqn)
client.readExact(t, 8, want)
client.readExact(t, 9, want)
client.writeFlush(t, 10, want)
client.readExact(t, 10, want)
client.close()
t.Logf("prestarted target served after a real clean move without operator restart: unit=%s HEAD=%+v", unit, head)
}
// Register before the units: their exact-unit cleanup runs first, then this
// retains failed-run local state before testing.TempDir removes it. Nothing is
// deleted from the evidence directory, including a partial copy on failure.
func gap1PreserveFailure(t *testing.T, roots ...string) {
t.Helper()
destination := os.Getenv("GAP1_EVIDENCE_DIR")
if destination == "" {
return
}
t.Cleanup(func() {
if !t.Failed() {
return
}
if err := os.MkdirAll(destination, 0700); err != nil {
t.Logf("evidence mkdir: %v", err)
return
}
for i, root := range roots {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
out, err := exec.CommandContext(ctx, "cp", "-a", "--sparse=always", root, filepath.Join(destination, fmt.Sprintf("runtime-%d", i))).CombinedOutput()
cancel()
t.Logf("failed-run state retained: source=%s destination=%s err=%v output=%s", root, destination, err, out)
}
})
}
// Captured systemd249 journal records supply stable manager message IDs. The
// raw journal is logged when this witness succeeds; no fabricated PID status
// can turn an unknown unit into an ACKed successful invocation.
func gap1JournalTerminalSuccess(t *testing.T, unit, invocation string, expectedStarts int) bool {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
raw, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=json").CombinedOutput()
if err != nil {
t.Fatalf("unit journal: %v %s", err, raw)
}
starts := 0
started := map[string]bool{}
succeeded := map[string]bool{}
for _, line := range bytes.Split(raw, []byte{'\n'}) {
if len(line) == 0 {
continue
}
var entry struct {
Unit string `json:"UNIT"`
Invocation string `json:"INVOCATION_ID"`
Message string `json:"MESSAGE_ID"`
PID string `json:"_PID"`
JobResult string `json:"JOB_RESULT"`
}
if err := json.Unmarshal(line, &entry); err != nil {
t.Fatalf("captured journal JSON: %v", err)
}
if entry.Unit != unit+".service" || entry.PID != "1" {
continue
}
switch entry.Message {
case "39f53479d3a045ac8e11786248231fbf":
if entry.JobResult == "done" {
starts++
started[entry.Invocation] = true
}
case "7ad2d189f7e94e70a38c781354912448":
succeeded[entry.Invocation] = true
}
}
if starts > expectedStarts {
t.Fatalf("unexpected restart in captured unit journal: starts%d want%d", starts, expectedStarts)
}
if invocation == "" && expectedStarts == 1 {
for id := range started {
invocation = id
}
}
complete := invocation != "" && starts == expectedStarts && started[invocation] && succeeded[invocation]
if complete {
t.Logf("captured terminal-success journal for %s invocation%s: %s", unit, invocation, raw)
}
return complete
}
// Calibrate the terminal parser against the real supervisor before any holder
// is killed. Successful transient units can be collected; their journal is the
// proof, never the default zeros returned for an unknown unit.
func gap1ProbeTerminalSuccess(t *testing.T, fixture *gap1Fixture, unit string) {
t.Helper()
fixture.start(t, unit, true, "/bin/true")
waitGAP1(t, "systemd terminal-success parser preflight failed", 5*time.Second, func() bool {
return gap1JournalTerminalSuccess(t, unit, "", 1)
})
}
@@ -0,0 +1 @@
sealed HEAD generation: 3
@@ -0,0 +1 @@
{"volumeID":"v1","cutLSN":1,"headGen":3,"headEpoch":1,"lastWrittenLSN":1}
@@ -0,0 +1,4 @@
preview (advisory): at master time 2026-11-22T15:36:16.705621624Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.
forced move admitted
HEAD now: gen 3, epoch 1, holder s1/r1, remote LSN 1, published at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution)
if moved now: writes with LSN <= 1 are kept; writes acknowledged after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost
@@ -0,0 +1,3 @@
preview (advisory): at master time 2026-11-22T15:35:12.107989752Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.
forced move not admitted: workspace forced move lease expiry plus clock-skew margin has not elapsed
admissible at 2026-11-22T15:36:16.617154582Z, master clock
@@ -0,0 +1,3 @@
forced move issued: volume v1 request force-v1-1: r1@1 on s1 -> r1@2 on s2 (kept HEAD gen 3, remote LSN 1)
volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN.
next: start volume v1 on s2 (this command moved authority only)
@@ -0,0 +1 @@
{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795361693554515613,"parent":null},"head":{"gen":4,"epoch":2,"holder":"s2/r1","remoteLSN":1,"state":"active","detachedBy":null,"chunkCount":1}}
@@ -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}}
@@ -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}}
@@ -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"
@@ -0,0 +1,2 @@
range 1 of 1: request force-v1-1, r1@1 -> epoch 2, lost after LSN 1, until 2026-11-22T15:36:16.617154582Z (master clock)
volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN.
@@ -0,0 +1,2 @@
clean move issued: volume v1 request move-v1-1: r1@1 -> r1@2 on s2 (sealed HEAD gen 3, remote LSN 1)
next: start volume v1 on s2 (this command moved authority only)
@@ -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)
@@ -0,0 +1 @@
workspace move: clean move: workspace clean move needs detached HEAD and matching revocation ACK
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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: 1795338384724043516; host validity_ns at query: 19727540908
recorded ACK: none
host: unknown (not recorded by the master); issued moves and bindings below are separate facts
@@ -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"}
@@ -0,0 +1,37 @@
package main_test
import (
"os"
"os/exec"
"strings"
)
// stripSystemdForTestLockDir is the external test package's copy of the
// helper in volume_lock_env_test.go (package main_test cannot use it): a
// child started with --volume-lock-dir-test-only gets an environment without
// INVOCATION_ID, which a systemd-run test runner would otherwise pass on.
func stripSystemdForTestLockDir(cmd *exec.Cmd) *exec.Cmd {
const flag = "--volume-lock-dir-test-only"
hasFlag := false
for _, a := range cmd.Args[1:] {
if a == flag || strings.HasPrefix(a, flag+"=") {
hasFlag = true
break
}
}
if !hasFlag {
return cmd
}
env := cmd.Env
if env == nil {
env = os.Environ()
}
kept := make([]string, 0, len(env))
for _, kv := range env {
if !strings.HasPrefix(kv, "INVOCATION_ID=") {
kept = append(kept, kv)
}
}
cmd.Env = kept
return cmd
}
@@ -0,0 +1,37 @@
package main
import (
"os"
"os/exec"
"strings"
)
// stripSystemdForTestLockDir gives a blockvolume child started with
// --volume-lock-dir-test-only an environment without INVOCATION_ID.
// blockvolume refuses the test override under systemd; a test runner that is
// itself a systemd service (a CI runner unit) would otherwise pass its
// INVOCATION_ID to every child. Other children are left as they are.
func stripSystemdForTestLockDir(cmd *exec.Cmd) *exec.Cmd {
hasFlag := false
for _, a := range cmd.Args[1:] {
if a == "--"+volumeLockDirTestOnlyFlag || strings.HasPrefix(a, "--"+volumeLockDirTestOnlyFlag+"=") {
hasFlag = true
break
}
}
if !hasFlag {
return cmd
}
env := cmd.Env
if env == nil {
env = os.Environ()
}
kept := make([]string, 0, len(env))
for _, kv := range env {
if !strings.HasPrefix(kv, "INVOCATION_ID=") {
kept = append(kept, kv)
}
}
cmd.Env = kept
return cmd
}
@@ -0,0 +1,52 @@
package main
import (
"io"
"os"
"strings"
"testing"
"time"
)
// V1-SPEC r2.45: the test lock directory override is refused under systemd
// (INVOCATION_ID set), so it cannot reach a shipped unit.
func TestVolumeLockDirTestOnlyRefusedUnderSystemd(t *testing.T) {
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore", "--volume-lock-dir-test-only="+t.TempDir())
t.Setenv("INVOCATION_ID", "")
f, err := parseFlags(args)
if err != nil || f.volumeLockDirTestOnly == "" {
t.Fatalf("the test override outside systemd: %+v %v", f.volumeLockDirTestOnly, err)
}
t.Setenv("INVOCATION_ID", "0123456789abcdef")
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "refused under systemd") {
t.Fatalf("the test override was accepted under systemd: %v", err)
}
}
// The test override is hidden from --help.
func TestVolumeLockDirTestOnlyHiddenFromHelp(t *testing.T) {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
saved := os.Stderr
t.Cleanup(func() { os.Stderr = saved; _ = w.Close(); _ = r.Close() })
read := make(chan []byte, 1)
go func() { b, _ := io.ReadAll(r); read <- b }() // usage exceeds a pipe buffer
os.Stderr = w
_, parseErr := parseFlags([]string{"-h"})
os.Stderr = saved
_ = w.Close() // release the reader before joining it
var out []byte
select {
case out = <-read:
case <-time.After(10 * time.Second):
t.Fatal("usage reader did not finish")
}
if parseErr == nil || !strings.Contains(string(out), "-durable-root") {
t.Fatalf("no usage printed: %v %q", parseErr, out)
}
if strings.Contains(string(out), volumeLockDirTestOnlyFlag) {
t.Fatalf("--help lists the test override:\n%s", out)
}
}
@@ -60,13 +60,9 @@ func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (st
if err != nil {
return 0, err
}
head, err := remote.GetHead(ctx)
head, err := storage.ReadDetachedChunkHead(ctx, remote, id.Epoch, holder)
if err != nil {
return 0, err
}
proof := head.DetachedBy
if head.Gen == 0 || head.Epoch != id.Epoch || head.Holder != holder || head.State != storage.ChunkHeadDetached || proof == nil || proof.Gen != head.Gen || proof.Epoch != head.Epoch || proof.Holder != head.Holder {
return 0, fmt.Errorf("workspace shutdown has no matching stored detached HEAD")
}
return head.Gen, nil
}
@@ -106,7 +106,8 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease")
cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease")
stripSystemdForTestLockDir(cmd)
cmd.Stdout, cmd.Stderr = log, log
if err = cmd.Start(); err != nil {
t.Fatal(err)
@@ -0,0 +1,69 @@
package main
import (
"context"
"errors"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"testing"
)
type workspaceProofRemote struct {
storage.ChunkRemote
head storage.ChunkHead
err error
reads int
}
func (r *workspaceProofRemote) GetHead(context.Context) (storage.ChunkHead, error) {
r.reads++
return r.head, r.err
}
func TestWorkspaceRevocationUsesExactStoredSeal(t *testing.T) {
for _, name := range []string{"valid", "zero-epoch", "empty-holder", "active", "missing-proof", "proof-gen", "proof-epoch", "proof-holder", "foreign-holder", "foreign-epoch", "zero-gen", "read-error"} {
t.Run(name, func(t *testing.T) {
h := storage.ChunkHead{Gen: 7, Epoch: 2, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "s/r"}}
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}
holder := "s/r"
r := &workspaceProofRemote{head: h}
switch name {
case "zero-epoch":
id.Epoch = 0
r.head.Epoch = 0
r.head.DetachedBy.Epoch = 0
case "empty-holder":
holder = ""
r.head.Holder = ""
r.head.DetachedBy.Holder = ""
case "active":
r.head.State = storage.ChunkHeadActive
case "missing-proof":
r.head.DetachedBy = nil
case "zero-gen":
r.head.Gen = 0
r.head.DetachedBy.Gen = 0
case "proof-epoch":
r.head.DetachedBy.Epoch = 1
case "proof-holder":
r.head.DetachedBy.Holder = "other/r"
case "foreign-epoch":
r.head.Epoch = 1
case "proof-gen":
r.head.DetachedBy.Gen = 6
case "foreign-holder":
r.head.Holder = "other/r"
case "read-error":
r.err = errors.New("HEAD answer lost")
}
gen, err := workspaceDetachedGeneration(context.Background(), func(string) (storage.ChunkRemote, error) { return r, nil }, id, holder)
if name == "valid" {
if err != nil || gen != 7 || r.reads != 1 {
t.Fatalf("stored seal: gen%d reads%d err%v", gen, r.reads, err)
}
} else if err == nil || gen != 0 {
t.Fatalf("unproven ACK gen%d err%v", gen, err)
}
})
}
}
@@ -62,12 +62,21 @@ func w4WaitTCP(t *testing.T, addr string, d time.Duration) {
}
func startWorkspaceWeed(t *testing.T) *w4WeedCluster {
t.Helper()
return startWorkspaceWeedAt(t, t.TempDir())
}
// A caller-owned root lets process qualification retain its filer evidence
// when external-service cleanup is uncertain. Existing tests keep TempDir.
func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster {
t.Helper()
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
t.Skip("CHUNKSTORE_WEED not set")
}
dir := t.TempDir()
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
used := map[int]bool{}
mp, vp, fp := w4FreePortPair(t, used), w4FreePortPair(t, used), w4FreePortPair(t, used)
c := &w4WeedCluster{
@@ -64,7 +64,7 @@ func seedForcedVolume(t *testing.T, h *master.Host) {
t.Fatal("no authority line for vol-f")
}
}
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil {
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil {
t.Fatal(err)
}
}
@@ -45,7 +45,7 @@ func TestWorkspacePlannedHandoffAgainstRealMaster(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// This is the separate host event, never synthesized by the CLI.
_, err = control.NewWorkspaceServiceClient(conn).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}, HeadGen: 9})
_, err = control.NewWorkspaceServiceClient(conn).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}, HeadGen: 9})
if err != nil {
t.Fatal(err)
}
+4
View File
@@ -23,6 +23,10 @@ import (
// AssignmentInfo is a raw assignment from the master heartbeat.
type AssignmentInfo struct {
// ServerID is immutable for a moved authority line; an unknown moved
// owner remains empty instead of falling back to placement.
ServerID string
OwnerFromMove bool
VolumeID string
ReplicaID string
Epoch uint64
@@ -0,0 +1,26 @@
package authority
import "github.com/seaweedfs/seaweed-block/core/adapter"
// captureAssignmentOwner binds owner and line in one publication under p.mu
// (INV-AUTH-HOLDER-IDENTITY-001). Reload derives it from that same durable
// record's journal. A reserved/unissued move never permits placement fallback.
func (p *Publisher) captureAssignmentOwner(info *adapter.AssignmentInfo, issuing *WorkspaceState) {
state := issuing
if state == nil {
state = p.workspace[info.VolumeID]
}
if state == nil {
return
}
for _, move := range state.Moves {
if move.NewReplicaID == info.ReplicaID && move.NewEpoch == info.Epoch {
info.OwnerFromMove = true
info.ServerID = ""
if move.Issued {
info.ServerID = move.NewHost
}
return
}
}
}
@@ -0,0 +1,25 @@
package authority
import (
"github.com/seaweedfs/seaweed-block/core/adapter"
"testing"
)
// INV-AUTH-HOLDER-IDENTITY-001: an unissued move cannot authorize a
// placement fallback, while a published move captures its own target.
func TestAssignmentOwnerReservedAndIssuedCapture(t *testing.T) {
p := NewPublisher(nil)
state := &WorkspaceState{Moves: []WorkspaceMoveRecord{{NewReplicaID: "r1", NewEpoch: 2, NewHost: "s2"}}}
for _, issued := range []bool{false, true} {
state.Moves[0].Issued = issued
info := adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1}
p.captureAssignmentOwner(&info, state)
want := ""
if issued {
want = "s2"
}
if !info.OwnerFromMove || info.ServerID != want {
t.Fatalf("issued=%t: captured %+v", issued, info)
}
}
}
+5 -1
View File
@@ -275,7 +275,7 @@ func (p *Publisher) reloadFromStore() {
p.workspace[rec.VolumeID] = cloneWorkspace(rec.Workspace)
}
key := subKey{volumeID: rec.VolumeID, replicaID: rec.ReplicaID}
p.state[key] = assignmentState{
loaded := assignmentState{
info: adapter.AssignmentInfo{
VolumeID: rec.VolumeID,
ReplicaID: rec.ReplicaID,
@@ -286,6 +286,8 @@ func (p *Publisher) reloadFromStore() {
},
present: true,
}
p.captureAssignmentOwner(&loaded.info, rec.Workspace)
p.state[key] = loaded
if rec.WriteSeq > p.writeSeqByVolume[rec.VolumeID] {
p.writeSeqByVolume[rec.VolumeID] = rec.WriteSeq
}
@@ -586,6 +588,8 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
// sequenced after Put: on Put failure we simply return without
// touching p.state / p.writeSeqByVolume, so no rollback is
// needed. Subscribers never see a fact that isn't durable yet.
p.captureAssignmentOwner(&next, issuedWorkspace)
if p.store != nil {
// Compute the per-volume WriteSeq for this mint. Starts
// at the highest previously-persisted value for the
@@ -0,0 +1,80 @@
package authority
import (
"testing"
"time"
)
// ownerReader is the publisher view the snapshot builder reads: the line plus the server a move issued it to.
type ownerReader struct {
*fakeReaderForHost
owner map[string]PublishedLine
}
func (r ownerReader) PublishedAuthorityLine(volume string) (PublishedLine, bool) {
pl, ok := r.owner[volume]
return pl, ok
}
// #425 (V1-SPEC r2.40, INV-AUTH-HOLDER-IDENTITY-001): after a forced move s1 -> s2 the accepted topology still names
// s1 for r1. When s1 returns and reports r1 at its own endpoints, the controller's input for the line's replica must
// come from the line's owner s2, never s1: otherwise an endpoint refresh republishes the line with s1's endpoints.
func TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner(t *testing.T) {
start := time.Date(2026, 11, 22, 14, 0, 0, 0, time.UTC)
clk := newFakeClock(start)
store := NewObservationStore(FreshnessConfig{FreshnessWindow: 500 * time.Millisecond, PendingGrace: 100 * time.Millisecond}, clk.Now)
topo := AcceptedTopology{Volumes: []VolumeExpected{{VolumeID: "v1", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}}}}
at := func(addr string) SlotFact {
s := healthySlot("v1", "r1")
s.DataAddr, s.CtrlAddr = addr+":1", addr+":2"
return s
}
_ = ingest(t, store, serverObs("s2", start, at("owner-s2")))
_ = ingest(t, store, serverObs("s1", start, at("old-s1"))) // the old host, back with its own endpoints
reader := ownerReader{fakeReaderForHost: newFakeReaderForHost(), owner: map[string]PublishedLine{
"v1": {ReplicaID: "r1", Epoch: 2, IssuedHost: "s2", OwnerFromMove: true}}}
reader.SetVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, DataAddr: "owner-s2:1", CtrlAddr: "owner-s2:2"})
v, ok := findSupported(BuildSnapshot(store.Snapshot(), topo, reader), "v1")
if !ok {
t.Fatal("v1 not supported")
}
r1, ok := candidateByReplica(v, "r1")
if !ok || r1.ServerID != "s2" || r1.DataAddr != "owner-s2:1" || r1.CtrlAddr != "owner-s2:2" {
t.Fatalf("line replica candidate %+v ok=%v, want the owner s2 at owner-s2:1/2 (never the old host s1)", r1, ok)
}
// a move minted the line but its owner is unknown: NO server supplies the replica's facts, so the returning
// placement server's fresh report changes nothing (no endpoint change, hence no refresh)
unknown := ownerReader{fakeReaderForHost: reader.fakeReaderForHost, owner: map[string]PublishedLine{"v1": {ReplicaID: "r1", Epoch: 2, OwnerFromMove: true}}}
// exact outcome: the volume is not supported, or the replica is the no-observation placeholder (no server, the
// line's own endpoints, nothing reachable/ready/eligible): neither s1's nor s2's report may supply it
if v, ok := findSupported(BuildSnapshot(store.Snapshot(), topo, unknown), "v1"); ok {
want := ReplicaCandidate{ReplicaID: "r1", DataAddr: "owner-s2:1", CtrlAddr: "owner-s2:2"}
if r1, _ := candidateByReplica(v, "r1"); r1 != want {
t.Fatalf("unknown owner: candidate %+v, want exactly the no-observation placeholder %+v (no server's facts)", r1, want)
}
}
// without a move-named owner the accepted topology stands (control)
plain := ownerReader{fakeReaderForHost: reader.fakeReaderForHost, owner: map[string]PublishedLine{"v1": {ReplicaID: "r1", Epoch: 2}}}
v, _ = findSupported(BuildSnapshot(store.Snapshot(), topo, plain), "v1")
if r1, _ := candidateByReplica(v, "r1"); r1.ServerID != "s1" || r1.DataAddr != "old-s1:1" {
t.Fatalf("control: no move-named owner, candidate %+v, want the topology's s1", r1)
}
}
// TERM-HOLDER-001's single owner decision: the three outcomes of PublishedLine.Owner.
func TestPublishedLineOwnerOutcomes(t *testing.T) {
for _, c := range []struct {
pl PublishedLine
server string
fromMove bool
}{
{PublishedLine{IssuedHost: "s2", OwnerFromMove: true}, "s2", true},
{PublishedLine{IssuedHost: "s2"}, "s2", true},
{PublishedLine{OwnerFromMove: true}, "", true},
{PublishedLine{}, "", false},
} {
if server, fromMove := c.pl.Owner(); server != c.server || fromMove != c.fromMove {
t.Fatalf("%+v.Owner() = %q, %v; want %q, %v", c.pl, server, fromMove, c.server, c.fromMove)
}
}
}
@@ -98,6 +98,9 @@ func BuildSnapshot(store storeSnapshot, topology AcceptedTopology, reader Author
if reader != nil {
basis, hasLine = reader.VolumeAuthorityLine(vid)
}
if hasLine {
expected = expectOwnerForLine(expected, vid, basis, reader)
}
verdict := evaluateVolume(vid, expected, freshSlotsByVolume[vid], store, basis, hasLine)
switch verdict.state {
@@ -473,3 +476,37 @@ func assembleVolumeTopology(
Slots: slots,
}
}
// lineOwnerReader is the publisher's view of a line's owner (the server a move issued it to).
type lineOwnerReader interface {
PublishedAuthorityLine(volume string) (PublishedLine, bool)
}
// expectOwnerForLine binds the expected slot of the line's replica to the line's owner (PublishedLine.Owner) when a
// move minted the line (#425, V1-SPEC r2.40, INV-AUTH-HOLDER-IDENTITY-001): a line carries its owner and that owner's
// endpoints, so its replica's facts (health, endpoints, and any endpoint refresh) come only from that server, never
// from the placement or topology server it was moved away from. A move-minted line whose owner is unknown is bound to
// NO server (no fact from anyone, so no refresh) until the owner is known. Only a line no move minted keeps the
// accepted topology.
func expectOwnerForLine(expected VolumeExpected, volumeID string, line AuthorityBasis, reader AuthorityBasisReader) VolumeExpected {
r, ok := reader.(lineOwnerReader)
if !ok {
return expected
}
pl, ok := r.PublishedAuthorityLine(volumeID)
if !ok || pl.ReplicaID != line.ReplicaID || pl.Epoch != line.Epoch {
return expected
}
server, fromMove := pl.Owner()
if !fromMove {
return expected
}
out := VolumeExpected{VolumeID: expected.VolumeID, Slots: make([]ExpectedSlot, len(expected.Slots))}
copy(out.Slots, expected.Slots)
for i := range out.Slots {
if out.Slots[i].ReplicaID == line.ReplicaID {
out.Slots[i].ServerID = server // "" for an unknown owner: no server supplies this replica's facts
}
}
return out
}
+3 -2
View File
@@ -277,8 +277,9 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.HeadGen == 0 || s == nil || s.Lease == nil || !s.Lease.Revoking {
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
}
now := p.workspaceNow()
if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.leaseDeadlineLocked(volume)) {
lease := *s.Lease
lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano())
if p.WorkspaceLeaseValidity(lease) == 0 {
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
}
if s.Ack != nil && *s.Ack != ack {
@@ -12,18 +12,19 @@ import (
// p.mu -> leaseMu at every point where an input changes, so that whenever
// p.mu is released the view equals derive(published) (INV-LEASE-VIEW-001).
type leaseDerived struct {
bound bool // an authority line exists for the volume
replica string
epoch uint64
issuedHost string // NewHost of the issued move that minted the line; "" if none
leasePresent bool
revoking bool
movePending bool // the last workspace move is reserved, not issued
uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001)
storeless bool
horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant
maxSkewNS int64
lease WorkspaceLease // the published (durable) lease
bound bool // an authority line exists for the volume
replica string
epoch uint64
ownerFromMove bool
issuedHost string // NewHost of the issued move that minted the line; "" if none
leasePresent bool
revoking bool
movePending bool // the last workspace move is reserved, not issued
uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001)
storeless bool
horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant
maxSkewNS int64
lease WorkspaceLease // the published (durable) lease
}
// leaseView is one volume's renewal state. Guarded by Publisher.leaseMu.
@@ -43,14 +44,10 @@ func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived {
d := leaseDerived{uncertain: p.workspaceUncertain[volume], storeless: p.store == nil, maxSkewNS: int64(p.workspaceSkew(nil))}
if _, line, ok := p.workspaceLineLocked(volume); ok {
d.bound, d.replica, d.epoch = true, line.info.ReplicaID, line.info.Epoch
d.issuedHost, d.ownerFromMove = line.info.ServerID, line.info.OwnerFromMove
}
if s := p.workspace[volume]; s != nil {
d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued
for _, r := range s.Moves {
if d.bound && r.Issued && r.NewReplicaID == d.replica && r.NewEpoch == d.epoch {
d.issuedHost = r.NewHost
}
}
if s.Lease != nil {
d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease
d.maxSkewNS = int64(p.workspaceSkew(s.Lease))
@@ -147,6 +144,18 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
return l, true
}
// WorkspaceLeaseValidity reports host validity on the publisher clock, with
// the configured TTL and the larger configured/persisted skew bound.
// M2 grant/revoke ACK; INV-WS-FORCED-MOVE-HALF-SKEW-001.
func (p *Publisher) WorkspaceLeaseValidity(l WorkspaceLease) time.Duration {
return p.workspaceLeaseValidityAt(l, p.workspaceNow())
}
func (p *Publisher) workspaceLeaseValidityAt(l WorkspaceLease, now time.Time) time.Duration {
remaining := time.Unix(0, l.ExpiresAtNS).Add(-p.workspaceSkew(&l) / 2).Sub(now)
return max(0, min(remaining, p.workspaceTTL))
}
// PublishedLine is a volume's committed authority line as the lease view
// publishes it.
type PublishedLine struct {
@@ -154,7 +163,37 @@ type PublishedLine struct {
Epoch uint64
// IssuedHost is the target host of the issued move that minted this line;
// "" when no issued move did (a placement or static topology line).
IssuedHost string
IssuedHost string
OwnerFromMove bool
}
// Owner is TERM-HOLDER-001's single owner decision for a line (INV-AUTH-HOLDER-IDENTITY-001), shared by the master's
// workspaceLineOwner and the snapshot builder. Three outcomes:
// - fromMove, server != "": a move minted the line on server;
// - fromMove, server == "": a move minted it but its owner is unknown: no server may supply its facts;
// - !fromMove: no move minted it; the caller uses placement / the accepted topology.
func (pl PublishedLine) Owner() (server string, fromMove bool) {
if pl.OwnerFromMove || pl.IssuedHost != "" {
return pl.IssuedHost, true
}
return "", false
}
// The snapshot builder binds a moved line's replica to its owner through this method; the production reader must
// provide it (a refactor dropping it is a build error, not a silent return to placement).
var _ lineOwnerReader = (*Publisher)(nil)
// PublishedAuthorityLine reads one committed line under leaf leaseMu. Identity
// checks on renewal must not wait for p.mu, which spans authority store I/O
// (INV-LEASE-VIEW-001, INV-WS-RENEW-NONBLOCKING-001).
func (p *Publisher) PublishedAuthorityLine(volume string) (PublishedLine, bool) {
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
lv := p.leaseViews[volume]
if lv == nil || !lv.d.bound {
return PublishedLine{}, false
}
return PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost, OwnerFromMove: lv.d.ownerFromMove}, true
}
// PublishedAuthorityLines returns the committed authority line of every
@@ -168,7 +207,7 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
out := make(map[string]PublishedLine, len(p.leaseViews))
for volume, lv := range p.leaseViews {
if lv.d.bound {
out[volume] = PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost}
out[volume] = PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost, OwnerFromMove: lv.d.ownerFromMove}
}
}
return out
@@ -234,7 +273,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
// A grant without positive host validity (expiry minus half the skew
// bound, leaseFact) would make the host fence on an invalid reply and lose
// its remaining validity; refuse with an error instead.
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 {
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
summary := p.leaseStats.summaryDue(now)
p.leaseMu.Unlock()
+12 -1
View File
@@ -86,7 +86,18 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) {
if err != nil || again != r {
t.Fatal("grant replay changed", again, err)
}
final := NewPublisher(nil, WithStore(disk)).WorkspaceState("v")
finalPublisher := NewPublisher(nil, WithStore(disk))
for name, publisher := range map[string]*Publisher{"issued": loaded, "reloaded": finalPublisher} {
line, ok := publisher.LastPublished("v", "old")
if !ok || line.ServerID != "new-node" || !line.OwnerFromMove {
t.Fatalf("%s lost captured moved owner: %+v", name, line)
}
published, _ := publisher.PublishedAuthorityLine("v")
if published.IssuedHost != line.ServerID || !published.OwnerFromMove {
t.Fatalf("%s lease and stream owners differ: %+v / %+v", name, published, line)
}
}
final := finalPublisher.WorkspaceState("v")
if final == nil || len(final.Moves) != 1 || !final.Moves[0].Issued {
t.Fatal("issued epoch lost journal", final)
}
@@ -0,0 +1,61 @@
package authority
import (
"context"
"testing"
"time"
)
func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) {
for _, tc := range []struct {
name string
elapsed time.Duration
allowed bool
restart bool
}{
{"before", 28*time.Second - time.Nanosecond, true, false},
{"at", 28 * time.Second, false, false},
{"after", 29 * time.Second, false, false},
{"horizon-before", 43*time.Second - time.Nanosecond, true, true},
{"horizon-at", 43 * time.Second, false, true},
{"horizon-after", 44 * time.Second, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
disk, _ := newTempStore(t)
start := time.Unix(1000, 0)
now := start
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second))
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
ctx := context.Background()
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if tc.restart {
// Reopening at +20s gives a restart deadline of +50s, beyond
// the persisted +45s horizon. ACK must stop at +43s.
now = start.Add(20 * time.Second)
p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second))
p.mu.Lock()
deadline := p.leaseDeadlineLocked("v")
horizon := p.workspace["v"].Lease.ExpiresAtNS
p.mu.Unlock()
if !deadline.After(time.Unix(0, horizon)) {
t.Fatal("fixture deadline does not exceed persisted horizon")
}
}
now = start.Add(tc.elapsed)
err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7})
if (err == nil) != tc.allowed {
t.Fatalf("ACK allowed=%t, want %t: %v", err == nil, tc.allowed, err)
}
if (p.WorkspaceState("v").Ack != nil) != tc.allowed {
t.Fatal("ACK persistence differs from admission")
}
})
}
}
+62 -6
View File
@@ -145,6 +145,13 @@ func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool,
if resp == nil {
return PublishTarget{}, false
}
if fronts, tagged := primaryOwnedFrontends(resp, rejectLoopback); tagged {
if len(fronts) == 0 {
return PublishTarget{}, false
}
resp = &control.StatusResponse{VolumeId: resp.GetVolumeId(), ReplicaId: resp.GetReplicaId(), Epoch: resp.GetEpoch(),
EndpointVersion: resp.GetEndpointVersion(), Assigned: resp.GetAssigned(), Frontends: fronts}
}
base := PublishTarget{
VolumeID: resp.GetVolumeId(),
ReplicaID: resp.GetReplicaId(),
@@ -161,20 +168,23 @@ func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool,
if ft.GetProtocol() != string(ProtocolISCSI) || ft.GetAddr() == "" || ft.GetIqn() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback) {
continue
}
if _, ok := iscsiByIQN[ft.GetIqn()]; !ok {
iscsiOrder = append(iscsiOrder, ft.GetIqn())
// one multipath target is one IQN AND LUN: paths to another LUN of the same IQN are another unit
// (INV-AUTH-HOLDER-IDENTITY-001)
key := ft.GetIqn() + "\x00" + strconv.FormatUint(uint64(ft.GetLun()), 10)
if _, ok := iscsiByIQN[key]; !ok {
iscsiOrder = append(iscsiOrder, key)
}
iscsiByIQN[ft.GetIqn()] = append(iscsiByIQN[ft.GetIqn()], ft)
iscsiByIQN[key] = append(iscsiByIQN[key], ft)
}
for _, iqn := range iscsiOrder {
frontends := iscsiByIQN[iqn]
for _, key := range iscsiOrder {
frontends := iscsiByIQN[key]
if len(frontends) == 0 {
continue
}
out := base
out.Protocol = ProtocolISCSI
out.ISCSIAddr = frontends[0].GetAddr()
out.IQN = iqn
out.IQN = frontends[0].GetIqn()
out.LUN = frontends[0].GetLun()
if len(frontends) > 1 {
out.Multipath = true
@@ -247,6 +257,52 @@ func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool,
return PublishTarget{}, false
}
// primaryOwnedFrontends applies INV-AUTH-HOLDER-IDENTITY-001 when the master tags each frontend with its replica: the
// usable frontends of the primary replica come first, and another replica's frontend is kept only as an extra path to a
// target the primary itself serves (same IQN and LUN, or same NQN/NSID/transport). No usable primary frontend: none at all, so
// a supporting replica is never published under the primary identity. An untagged (older) response is returned as is.
func primaryOwnedFrontends(resp *control.StatusResponse, rejectLoopback bool) ([]*control.FrontendTarget, bool) {
tagged := false
for _, ft := range resp.GetFrontends() {
if ft != nil && ft.GetReplicaId() != "" {
tagged = true
}
}
if !tagged {
return nil, false
}
key := func(ft *control.FrontendTarget) (string, bool) {
switch {
case ft.GetAddr() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback):
return "", false
case ft.GetProtocol() == string(ProtocolISCSI) && ft.GetIqn() != "":
return "iscsi\x00" + ft.GetIqn() + "\x00" + strconv.FormatUint(uint64(ft.GetLun()), 10), true // IQN AND LUN
case ft.GetProtocol() == string(ProtocolNVMe) && ft.GetNqn() != "":
return "nvme\x00" + ft.GetNqn() + "\x00" + strconv.FormatUint(uint64(ft.GetNsid()), 10) + "\x00" +
string(normalizeFrontendTransport(ProtocolNVMe, FrontendTransport(ft.GetTransport()))), true
}
return "", false
}
var out []*control.FrontendTarget
served := map[string]bool{}
for _, ft := range resp.GetFrontends() {
if ft != nil && ft.GetReplicaId() == resp.GetReplicaId() {
if k, ok := key(ft); ok {
served[k] = true
out = append(out, ft)
}
}
}
for _, ft := range resp.GetFrontends() {
if ft != nil && ft.GetReplicaId() != resp.GetReplicaId() {
if k, ok := key(ft); ok && served[k] {
out = append(out, ft)
}
}
}
return out, true
}
func rejectFrontendAddr(addr string, rejectLoopback bool) bool {
if !rejectLoopback {
return false
@@ -0,0 +1,67 @@
package csi
import (
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// INV-AUTH-HOLDER-IDENTITY-001: with replica-tagged frontends, a target is published only when the primary replica has a
// usable frontend; another replica's frontend is at most an extra path to the primary's own target. Untagged responses
// (an older master) keep the previous first-usable behaviour.
func TestPublishTargetIsPrimaryOwned(t *testing.T) {
ft := func(replica, addr, iqn string) *control.FrontendTarget {
return &control.FrontendTarget{Protocol: string(ProtocolISCSI), Addr: addr, Iqn: iqn, ReplicaId: replica}
}
status := func(fronts ...*control.FrontendTarget) *control.StatusResponse {
return &control.StatusResponse{VolumeId: "v1", Assigned: true, ReplicaId: "r1", Epoch: 3, Frontends: fronts}
}
// the primary's only frontend is one CSI rejects (loopback): the supporting replica's must not stand in
if got, ok := publishTargetFromStatus(status(ft("r1", "127.0.0.1:3260", "iqn.v1"), ft("r2", "192.0.2.2:3260", "iqn.v1")), false, true); ok {
t.Fatalf("rejected primary frontend: published %+v, want no target", got)
}
if got, ok := publishTargetFromStatus(status(ft("r1", "127.0.0.1:3260", "iqn.v1"), ft("r2", "192.0.2.2:3260", "iqn.v1")), true, true); ok {
t.Fatalf("rejected primary frontend (multipath): published %+v, want no target", got)
}
// primary first; a supporting path to the SAME target joins only as a multipath path
got, ok := publishTargetFromStatus(status(ft("r2", "192.0.2.2:3260", "iqn.v1"), ft("r1", "192.0.2.1:3260", "iqn.v1")), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || !got.Multipath || len(got.ISCSIAddrs) != 2 || got.ISCSIAddrs[0] != "192.0.2.1:3260" {
t.Fatalf("multipath: %+v ok=%v, want the primary first with the supporting path", got, ok)
}
// a supporting frontend of ANOTHER target never joins
got, ok = publishTargetFromStatus(status(ft("r1", "192.0.2.1:3260", "iqn.v1"), ft("r2", "192.0.2.2:3260", "iqn.other")), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || got.Multipath || got.IQN != "iqn.v1" {
t.Fatalf("foreign target: %+v ok=%v, want only the primary's", got, ok)
}
// iSCSI paths match on both IQN and LUN: a supporting q/LUN2 is another target, not a path to the primary's q/LUN1.
lun := func(replica, addr string, n uint32) *control.FrontendTarget {
return &control.FrontendTarget{Protocol: string(ProtocolISCSI), Addr: addr, Iqn: "iqn.q", Lun: n, ReplicaId: replica}
}
got, ok = publishTargetFromStatus(status(lun("r1", "192.0.2.1:3260", 1), lun("r2", "192.0.2.2:3260", 2)), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || got.LUN != 1 || got.Multipath || len(got.ISCSIAddrs) != 0 {
t.Fatalf("LUN mismatch: %+v ok=%v, want only the primary's q/LUN1 (no multipath)", got, ok)
}
got, ok = publishTargetFromStatus(status(lun("r1", "192.0.2.1:3260", 1), lun("r2", "192.0.2.2:3260", 1)), true, false)
if !ok || got.LUN != 1 || !got.Multipath || len(got.ISCSIAddrs) != 2 || got.ISCSIAddrs[0] != "192.0.2.1:3260" {
t.Fatalf("nonzero LUN match: %+v ok=%v, want multipath primary-first at LUN 1", got, ok)
}
// two PRIMARY-owned units of one IQN (q/LUN1 at A, q/LUN2 at B) are two targets, never one multipath target with
// LUN1 for both: the final grouping also binds IQN and LUN.
got, ok = publishTargetFromStatus(status(lun("r1", "192.0.2.1:3260", 1), lun("r1", "192.0.2.2:3260", 2)), true, false)
if !ok || got.ISCSIAddr != "192.0.2.1:3260" || got.LUN != 1 || got.Multipath || len(got.ISCSIAddrs) != 0 {
t.Fatalf("two primary units: %+v ok=%v, want q/LUN1 at 192.0.2.1 alone (no multipath with LUN2's path)", got, ok)
}
got, ok = publishTargetFromStatus(status(lun("", "192.0.2.1:3260", 1), lun("", "192.0.2.2:3260", 2)), true, false)
if !ok || got.LUN != 1 || got.Multipath {
t.Fatalf("untagged two units: %+v ok=%v, want q/LUN1 alone", got, ok)
}
// no primary frontend at all, supporting present: no target
if got, ok := publishTargetFromStatus(status(ft("r2", "192.0.2.2:3260", "iqn.v1")), false, false); ok {
t.Fatalf("no primary frontend: published %+v, want no target", got)
}
// untagged (older master): unchanged first-usable selection
got, ok = publishTargetFromStatus(status(ft("", "192.0.2.2:3260", "iqn.v1")), false, false)
if !ok || got.ISCSIAddr != "192.0.2.2:3260" {
t.Fatalf("untagged: %+v ok=%v, want the first usable frontend", got, ok)
}
}
@@ -0,0 +1,36 @@
package durable_test
import (
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// V1-SPEC r2.39: AdmitsIO is the one "may serve" function, the I/O gate
// itself: an operational backend whose guarded projection is not this
// lineage's healthy primary does not admit, nor does a backend that is not
// operational; both together admit.
func TestStorageBackend_AdmitsIOIsTheIOGate(t *testing.T) {
for _, f := range logicalStorageFactories() {
f := f
t.Run(f.name, func(t *testing.T) {
b, view, _ := newTestBackend(t, f, 4, 4096)
if err := b.AdmitsIO(); err != nil {
t.Fatalf("healthy and operational: %v, want nil", err)
}
p := view.Projection()
p.Healthy = false
view.set(p)
if err := b.AdmitsIO(); !errors.Is(err, frontend.ErrStalePrimary) {
t.Fatalf("operational, projection not healthy: %v, want ErrStalePrimary", err)
}
p.Healthy = true
view.set(p)
b.SetOperational(false, "test: attach pending")
if err := b.AdmitsIO(); !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("healthy, not operational: %v, want ErrNotReady", err)
}
})
}
}
@@ -0,0 +1,91 @@
package durable_test
import (
"bytes"
"context"
"runtime"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// casObservedRemote counts HEAD reads and CAS attempts; onGetHead runs
// before each HEAD read (n counts from 1), onCAS right after each successful
// HEAD CAS.
type casObservedRemote struct {
storage.ChunkRemote
onCAS func(next storage.ChunkHead)
onGetHead func(n int)
reads, cass int
}
func (r *casObservedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
r.reads++
if r.onGetHead != nil {
r.onGetHead(r.reads)
}
return r.ChunkRemote.GetHead(ctx)
}
func (r *casObservedRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
r.cass++
gen, err := r.ChunkRemote.CASHead(ctx, expected, next)
if err == nil && r.onCAS != nil {
r.onCAS(next)
}
return gen, err
}
// V1-SPEC r2.45 (2) rests on this: a cut publishes only an LSN its root has
// already made durable (the barrier sync before the HEAD CAS), so a crash
// right after the CAS leaves a root at or above HEAD's remote_lsn. The
// root's crash image taken at the CAS reattaches under that HEAD and serves
// the cut's data.
func TestCutPublishesOnlyLocallyDurableLSN(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the open store's byte-range lock keeps its files unreadable for the crash image")
}
ctx := context.Background()
inner := storage.NewMemChunkRemote()
root, crash := t.TempDir(), t.TempDir()
var ws *storage.WALStore
var images int
remote := &casObservedRemote{ChunkRemote: inner}
remote.onCAS = func(next storage.ChunkHead) {
if ws == nil || next.RemoteLSN == 0 {
return
}
if durable, _, _ := ws.Boundaries(); durable < next.RemoteLSN {
t.Errorf("HEAD CAS published remote_lsn %d above the root's durable LSN %d", next.RemoteLSN, durable)
}
copyRootFiles(t, root, crash) // the root as a crash right after this CAS leaves it
images++
}
a := chunkProvider(t, root, remote, v1View(), 0)
s := openRecovered(t, a)
ws = s.(*storage.WALStore)
for lba := uint32(0); lba < 3; lba++ {
if _, err := s.Write(lba, block(byte(lba+1))); err != nil {
t.Fatal(err)
}
}
if _, err := a.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if images == 0 {
t.Fatal("no cut published a HEAD")
}
head, _ := inner.GetHead(ctx)
b := chunkProvider(t, crash, inner, v1View(), 0)
got := openRecovered(t, b) // the refusal must not fire on the crash image
for lba := uint32(0); lba < 3; lba++ {
buf, err := got.Read(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf, block(byte(lba+1))) {
t.Fatalf("crash image under HEAD remote_lsn %d lost block %d", head.RemoteLSN, lba)
}
}
}
@@ -0,0 +1,49 @@
package durable_test
import (
"context"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// INV-FE-PRIMARY-READY-OPERATIONAL-001: a non-chunk durable volume admits I/O
// right after open and recovery (the role, primary or supporting, does not
// enter), so its first-serving channel is already closed and its frontends
// start at once, as before the gate. A later loss of readiness does not
// reopen the channel (the process exit owns that window).
func TestDurableProvider_NonChunkVolumeServesRightAfterOpen(t *testing.T) {
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64,
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { p.Close() })
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
b := p.Backend("v1")
if b == nil {
t.Fatal("no backend after EnsureStorage")
}
select {
case <-b.FirstServing():
t.Fatal("first-serving closed before recovery")
default:
}
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
select {
case <-b.FirstServing():
default:
t.Fatal("a recovered non-chunk volume has not admitted I/O: its frontends would wait")
}
b.SetOperational(false, "test: readiness lost")
select {
case <-b.FirstServing():
default:
t.Fatal("a later loss of readiness reopened the first-serving channel")
}
}
@@ -0,0 +1,137 @@
package durable_test
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// lockedProvider is a chunk provider whose host volume-lock directory is dir.
func lockedProvider(t *testing.T, root, lockDir string, remote storage.ChunkRemote) *durable.DurableProvider {
t.Helper()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: root,
HostVolumeLock: true, VolumeLockDirTestOnly: lockDir,
BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatalf("NewDurableProvider: %v", err)
}
t.Cleanup(func() { _ = p.Close() })
return p
}
// V1-SPEC r2.45 (1): one live process per volume per host. A second
// provider for the same volume id on the same host (another storage root,
// the same host lock directory) is refused before its store opens; once the
// first closes, the volume can be opened again.
func TestOneLiveProcessPerVolumePerHost(t *testing.T) {
remote := storage.NewMemChunkRemote()
lockDir := t.TempDir()
a := lockedProvider(t, t.TempDir(), lockDir, remote)
if _, err := a.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
held, err := os.Stat(filepath.Join(lockDir, "v1.lock"))
if err != nil {
t.Fatal(err)
}
bRoot := t.TempDir()
b := lockedProvider(t, bRoot, lockDir, remote)
if _, err := b.EnsureStorage("v1"); !errors.Is(err, storage.ErrWALStoreLocked) {
t.Fatalf("a second provider for the same volume on this host opened: %v; want %v", err, storage.ErrWALStoreLocked)
}
if left, err := os.ReadDir(bRoot); err != nil || len(left) != 0 {
t.Fatalf("the refused second provider touched its root: %v %v", left, err)
}
other := lockedProvider(t, t.TempDir(), lockDir, remote)
if _, err := other.EnsureStorage("v2"); err != nil {
t.Fatalf("another volume was refused by v1's lock: %v", err)
}
if err := a.Close(); err != nil {
t.Fatal(err)
}
c := lockedProvider(t, t.TempDir(), lockDir, remote)
if _, err := c.EnsureStorage("v1"); err != nil {
t.Fatalf("the volume could not be opened after its first owner closed: %v", err)
}
// Released, never unlinked: the next owner locks the same file.
if again, err := os.Stat(filepath.Join(lockDir, "v1.lock")); err != nil || !os.SameFile(held, again) {
t.Fatalf("the lock file was replaced between owners: %v", err)
}
}
// V1-SPEC r2.45 (1): the provider creates a missing lock directory (0700)
// and refuses, with the operator's cure, only when it cannot create it.
func TestHostVolumeLockDirectoryCreatedOrRefused(t *testing.T) {
newProvider := func(dir string) (*durable.DurableProvider, error) {
return durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks,
HostVolumeLock: true, VolumeLockDirTestOnly: dir,
}, v1View())
}
missing := filepath.Join(t.TempDir(), "sw-block", "locks")
p, err := newProvider(missing)
if err != nil {
t.Fatalf("a missing lock directory was not created: %v", err)
}
_ = p.Close()
if fi, err := os.Stat(missing); err != nil || !fi.IsDir() {
t.Fatalf("lock directory %s: %v", missing, err)
}
blocked := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(blocked, nil, 0o600); err != nil {
t.Fatal(err)
}
p, err = newProvider(filepath.Join(blocked, "locks"))
if err == nil {
_ = p.Close()
}
if !errors.Is(err, durable.ErrVolumeLockDirUnavailable) || !strings.Contains(err.Error(), "install the tmpfiles.d entry") || !strings.Contains(err.Error(), "chown the directory and its lock files") {
t.Fatalf("an uncreatable lock directory: %v; want the refusal with its cure", err)
}
}
// A lock path that exists but is not a directory refuses, as before the
// lock directory was laid out by the provider.
func TestHostVolumeLockRefusesNonDirectoryLockPath(t *testing.T) {
locks := filepath.Join(t.TempDir(), "locks")
if err := os.WriteFile(locks, nil, 0o600); err != nil {
t.Fatal(err)
}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks,
HostVolumeLock: true, VolumeLockDirTestOnly: locks,
}, v1View())
if err == nil {
_ = p.Close()
}
if !errors.Is(err, durable.ErrVolumeLockDirUnavailable) {
t.Fatalf("a regular file as the lock directory was accepted: %v", err)
}
}
// A lock file this process cannot write (one another user created, as the
// root ublk unit does) is still taken: the lock opens it read-only.
func TestHostVolumeLockTakesReadOnlyLockFile(t *testing.T) {
remote := storage.NewMemChunkRemote()
lockDir := t.TempDir()
path := filepath.Join(lockDir, "v1.lock")
if err := os.WriteFile(path, nil, 0o444); err != nil {
t.Fatal(err)
}
a := lockedProvider(t, t.TempDir(), lockDir, remote)
if _, err := a.EnsureStorage("v1"); err != nil {
t.Fatalf("a read-only lock file refused the volume: %v", err)
}
b := lockedProvider(t, t.TempDir(), lockDir, remote)
if _, err := b.EnsureStorage("v1"); !errors.Is(err, storage.ErrWALStoreLocked) {
t.Fatalf("a second provider on a read-only lock file: %v; want %v", err, storage.ErrWALStoreLocked)
}
}
+150 -16
View File
@@ -159,6 +159,18 @@ type ProviderConfig struct {
// ChunkHolder names this node in HEAD; blockvolume sets
// <server-id>/<replica-id>. Zero: the replica ID (tests).
ChunkHolder string
// HostVolumeLock makes the provider hold an exclusive, nonblocking lock
// on HostVolumeLockDir/<volume id>.lock from before the volume's store
// opens until Close: one host runs at most one live process per volume
// (V1-SPEC r2.45). NewDurableProvider creates the directory (0700) when
// missing and refuses when it cannot create or use it; the tmpfiles.d
// entry in deploy/systemd creates it for the unit's user. blockvolume
// sets this.
HostVolumeLock bool
// VolumeLockDirTestOnly replaces HostVolumeLockDir for tests and test
// harnesses (blockvolume --volume-lock-dir-test-only); the one-process-
// per-host guarantee then holds only among processes sharing it.
VolumeLockDirTestOnly string
// Zero uses immediate HEAD confirmation for the supported single-filer
// topology. Nonzero cooling is reserved for explicit topology experiments.
ChunkHeadCoolingWindow time.Duration
@@ -233,10 +245,12 @@ type DurableProvider struct {
cfg ProviderConfig
view frontend.ProjectionView
mu sync.Mutex
volumes map[string]*volHandle // keyed by volumeID
opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create
closed bool
mu sync.Mutex
volumes map[string]*volHandle // keyed by volumeID
opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create
closed bool
startupUpdates chan struct{} // wake only; the generation-bound result stays on the handle
fenceUpdates chan struct{} // wake only; runtimeFenced stays on the handle
// testAfterChunkResolve, test-only, runs in CutVolume right after the
// volume's handle and layer are resolved.
@@ -260,7 +274,8 @@ type DurableProvider struct {
// walstore-chunk: closeCtx ends with Close and cancels in-flight
// remote attachment; inflight counts RecoverVolume calls admitted
// before Close, which Close waits for before closing any store.
// before Close, and each attached layer's fence watcher, which Close
// waits for before closing any store.
closeCtx context.Context
closeCancel context.CancelFunc
inflight sync.WaitGroup
@@ -272,6 +287,11 @@ type volHandle struct {
path string
impl ImplName // the resolved implementation, never ImplAuto
// hostLock is the volume's host lock (HostVolumeLock), held while open.
hostLock *os.File
// startupCure is the operator's cure of a stale-root startup end.
startupCure string
// ImplWALStoreChunk. fresh: the local volume is new and starts from
// the remote HEAD. It mirrors the durable fresh marker beside the
// volume file, written before the file is created and removed only
@@ -284,10 +304,13 @@ type volHandle struct {
// wait, 0 if none: a recovered volume whose layer waits for master
// authority. A wait only acts while its generation is still the
// latest recovery's.
recoverGen uint64
waitGen uint64
chunk storage.ChunkLayer // after RecoverVolume
chunkLineage chunkLineage // immutable authority captured by this attachment
recoverGen uint64
waitGen uint64
startupSuperseded bool // exact foreign-holder claim proof for startupEnded; guarded by p.mu
startupEnded uint64 // recovery generation with a terminal startup outcome; guarded by p.mu
runtimeFenced bool // the attached layer fenced after startup (HEAD has another owner); guarded by p.mu
chunk storage.ChunkLayer // after RecoverVolume
chunkLineage chunkLineage // immutable authority captured by this attachment
// Private until the owner commit succeeds; retained for attach retry.
chunkPending storage.ChunkLayer
// chunkDetach is set (under attachMu) when DetachVolume starts and
@@ -378,6 +401,14 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura
if cfg.ChunkSnapshotPeriod < 0 || (cfg.ChunkSnapshotPeriod > 0 && cfg.ChunkScheduledSnapshot == nil) {
return nil, fmt.Errorf("durable: a chunk snapshot period must not be negative and requires its callback")
}
if cfg.HostVolumeLock {
if cfg.VolumeLockDirTestOnly == "" {
cfg.VolumeLockDirTestOnly = HostVolumeLockDir
}
if err := makeVolumeLockDir(cfg.VolumeLockDirTestOnly); err != nil {
return nil, fmt.Errorf("%w %s: %w; %s", ErrVolumeLockDirUnavailable, cfg.VolumeLockDirTestOnly, err, volumeLockCure)
}
}
if cfg.ChunkBlocks == 0 {
cfg.ChunkBlocks = defaultChunkBlocks
}
@@ -392,12 +423,14 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura
}
closeCtx, closeCancel := context.WithCancel(context.Background())
return &DurableProvider{
cfg: cfg,
view: view,
volumes: map[string]*volHandle{},
opening: map[string]*sync.Mutex{},
closeCtx: closeCtx,
closeCancel: closeCancel,
cfg: cfg,
view: view,
volumes: map[string]*volHandle{},
opening: map[string]*sync.Mutex{},
closeCtx: closeCtx,
closeCancel: closeCancel,
startupUpdates: make(chan struct{}, 1),
fenceUpdates: make(chan struct{}, 1),
}, nil
}
@@ -489,25 +522,113 @@ func (p *DurableProvider) ensureHandle(volumeID string) (*volHandle, error) {
}
p.mu.Unlock()
h, err := p.openOrCreate(volumeID)
// V1-SPEC r2.45: the host lock is taken before the store opens.
hostLock, err := p.lockVolumeOnHost(volumeID)
if err != nil {
return nil, err
}
h, err := p.openOrCreate(volumeID)
if err != nil {
closeHostLock(hostLock)
return nil, err
}
h.hostLock = hostLock
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
_ = h.storage.Close()
closeHostLock(h.hostLock)
return nil, fmt.Errorf("durable: provider closed")
}
if existing, ok := p.volumes[volumeID]; ok {
_ = h.storage.Close()
closeHostLock(h.hostLock)
return existing, nil
}
p.volumes[volumeID] = h
return h, nil
}
// HostVolumeLockDir is the one fixed host-local directory of the volume
// host locks (HostVolumeLock).
const HostVolumeLockDir = "/run/sw-block/locks"
// ErrVolumeLockDirUnavailable refuses a provider with HostVolumeLock whose
// lock directory or lock file it cannot create or open.
var ErrVolumeLockDirUnavailable = errors.New("durable: host volume lock directory unavailable")
// volumeLockCure names the operator's cure. A directory or lock file a root
// process created is root-owned: an unprivileged unit then cannot use it.
const volumeLockCure = "install the tmpfiles.d entry (deploy/systemd/sw-block.tmpfiles.conf), or make its parent directory traversable (0755) and chown the directory and its lock files to this process's user"
// makeVolumeLockDir lays out a missing lock directory as the tmpfiles.d
// entry does: its parent 0755 (traversable by the unit's user even when root
// created it) and the directory itself 0700. Only a directory this call
// creates is chmod'ed (the umask cannot narrow it); one that exists, or that
// another process creates meanwhile, keeps its mode. An existing lock path
// that is not a directory refuses.
func makeVolumeLockDir(dir string) error {
parent := filepath.Dir(dir)
if err := os.MkdirAll(filepath.Dir(parent), 0o755); err != nil {
return err
}
if err := os.Mkdir(parent, 0o755); err == nil {
if err := os.Chmod(parent, 0o755); err != nil {
return err
}
} else if !errors.Is(err, os.ErrExist) {
return err
}
if err := os.Mkdir(dir, 0o700); err == nil {
return os.Chmod(dir, 0o700)
} else if !errors.Is(err, os.ErrExist) {
return err
}
fi, err := os.Lstat(dir)
if err != nil {
return err
}
if !fi.IsDir() {
return fmt.Errorf("%s exists and is not a directory", dir)
}
return nil
}
// lockVolumeOnHost takes the volume's host lock (nil without
// HostVolumeLock). A second live process for the volume on this host gets
// storage.ErrWALStoreLocked.
func (p *DurableProvider) lockVolumeOnHost(volumeID string) (*os.File, error) {
if !p.cfg.HostVolumeLock {
return nil, nil
}
dir := p.cfg.VolumeLockDirTestOnly
if volumeID == "" || volumeID == "." || volumeID == ".." || strings.ContainsAny(volumeID, "/\\") {
return nil, fmt.Errorf("durable: volume id %q is not a plain path element", volumeID)
}
path := filepath.Join(dir, volumeID+".lock")
// Read-only, 0644: a lock file another user created (the root ublk unit)
// stays lockable by the plain unit; the 0700 directory keeps others out.
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
f, err = os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0o644)
}
if err != nil {
return nil, fmt.Errorf("%w: volume lock %s: %w; %s", ErrVolumeLockDirUnavailable, path, err, volumeLockCure)
}
if err := storage.LockWALStoreFile(f); err != nil {
_ = f.Close()
return nil, fmt.Errorf("durable: volume %s already has a live process on this host (lock %s held): %w", volumeID, path, err)
}
return f, nil
}
func closeHostLock(f *os.File) {
if f != nil {
_ = f.Close()
}
}
// EnsureStorage opens (or creates) the on-disk LogicalStorage for
// volumeID WITHOUT waiting for the projection to flip Healthy. This
// is the binary-path entry point used by G5-4 to construct per-volume
@@ -550,6 +671,16 @@ func (p *DurableProvider) LogicalStorage(volumeID string) storage.LogicalStorage
// G5-4 binary wiring to install SetWriteObserver eagerly (before
// any frontend bind) — the same backend instance is returned by
// the future dp.Open() call when a frontend asks.
// AdmitsIO is StorageBackend.AdmitsIO for an open volume; ErrVolumeNotOpen
// for any other (fail closed).
func (p *DurableProvider) AdmitsIO(volumeID string) error {
b := p.Backend(volumeID)
if b == nil {
return fmt.Errorf("%w: %s", ErrVolumeNotOpen, volumeID)
}
return b.AdmitsIO()
}
func (p *DurableProvider) Backend(volumeID string) *StorageBackend {
p.mu.Lock()
defer p.mu.Unlock()
@@ -947,6 +1078,8 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R
p.mu.Lock()
h.recoverGen++ // any earlier recovery's authority wait is now stale
gen = h.recoverGen
h.startupEnded = 0
h.startupSuperseded = false
p.mu.Unlock()
}
report := Recover(h.storage, volumeID)
@@ -1004,6 +1137,7 @@ func (p *DurableProvider) Close() error {
if err := h.storage.Close(); err != nil && firstErr == nil {
firstErr = fmt.Errorf("durable: close storage: %w", err)
}
closeHostLock(h.hostLock) // after the store closes
}
return firstErr
}
@@ -56,8 +56,9 @@ var (
var ErrChunkStaleLocalRoot = errors.New("durable: local volume predates a HEAD published by another holder")
var (
errProviderClosed = errors.New("durable: provider closed")
errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer")
errProviderClosed = errors.New("durable: provider closed")
errChunkForeignClaim = errors.New("durable: HEAD claim refused by another holder")
errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer")
)
const (
@@ -124,6 +125,9 @@ func (p *DurableProvider) recoverChunk(ctx context.Context, volumeID string, h *
p.startChunkAuthorityWait(volumeID, h, gen)
return false, nil
}
if errors.Is(err, storage.ErrChunkLayerFenced) && (!errors.Is(err, ErrChunkStaleLocalRoot) || errors.Is(err, errChunkForeignClaim)) {
p.endChunkStartup(h, gen, err)
}
return err == nil, err
}
@@ -161,10 +165,11 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
defer func() {
log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended)
}()
retained := false // this generation already chose sealed replay or diagnostics
waitCtx, endWait := context.WithTimeout(p.closeCtx, limit)
defer endWait()
defer func() {
if !errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
if retained || !errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
return
}
// The old wait must not overwrite a newer recovery's readiness.
@@ -173,6 +178,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
if p.current(h, gen) && h.chunk == nil {
ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID))
h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error())
p.endChunkStartup(h, gen, nil)
}
}()
defer func() {
@@ -228,15 +234,25 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
case errors.Is(err, errProviderClosed):
ended = "provider closed"
return
case errors.Is(err, storage.ErrChunkLayerDetached):
// INV-WS-STARTUP-RETRY-001: an assigned sealed incarnation stays
// non-serving for exact seal replay; restarting cannot unseal it.
retained = true
ended = "sealed assignment, retained for replay"
h.backend.SetOperational(false, "sealed assignment; replay only")
return
case errors.Is(err, storage.ErrChunkLayerFenced):
ended = "fenced, not serving"
log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err)
if errors.Is(err, ErrChunkStaleLocalRoot) {
if errors.Is(err, ErrChunkStaleLocalRoot) && !errors.Is(err, errChunkForeignClaim) {
retained = true
h.attachMu.Lock()
if p.current(h, gen) && h.chunk == nil {
h.backend.SetOperational(false, "chunk layer attach refused: "+err.Error())
}
h.attachMu.Unlock()
} else {
p.endChunkStartup(h, gen, err)
}
return
case errors.Is(err, errChunkNoAuthority):
@@ -320,6 +336,8 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
h.backend.chunkFenced = layer.Fenced
h.backend.mu.Unlock()
p.startChunkLoop(volumeID, h, layer)
p.inflight.Add(1) // under p.mu with closed false: Close joins the watcher
go p.watchChunkFence(volumeID, h, layer)
}
return nil
}
@@ -434,10 +452,28 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
if head.Gen != 0 && head.Holder != holder {
err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD",
ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder)
// INV-WS-STARTUP-RETRY-001: at or above this assignment,
// the foreign holder is a supersede proof. A lower epoch is
// the existing move-back/stale-root diagnostic, never 78.
if claimHeadSupersedes(head, cfg) {
err = fmt.Errorf("%w: %w", err, errChunkForeignClaim)
}
log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)",
volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder)
return err
}
// V1-SPEC r2.45: HEAD names this holder, but a root whose local
// durable LSN is below HEAD's remote_lsn is a rolled-back copy
// (a backup taken before a later cut). Restarting cannot cure it.
// A crash cannot cause it: a cut syncs its LSN locally before the
// HEAD CAS publishes it (storage chunkLayer capture: the barrier
// syncWithPhases result is next.RemoteLSN).
if durableLSN, _, _ := ws.Boundaries(); head.Gen != 0 && durableLSN < head.RemoteLSN {
log.Printf("durable: refusing to attach volume=%s root=%s: local durable LSN %d is below HEAD gen=%d remote_lsn=%d (remove or quarantine the local root)",
volumeID, h.path, durableLSN, head.Gen, head.RemoteLSN)
return fmt.Errorf("%w: %w: %w: volume %s local root %s, local durable LSN %d below HEAD gen %d remote_lsn %d; remove or quarantine the local root to attach fresh from HEAD",
ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, errChunkForeignClaim, volumeID, h.path, durableLSN, head.Gen, head.RemoteLSN)
}
return nil
}
if err := cfg.PrepareRestore(head); err != nil {
@@ -485,6 +521,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder)
head, err := storage.ClaimChunkHead(ctx, remote, cfg)
if err != nil {
// INV-WS-STARTUP-RETRY-001: only the claim's exact foreign-holder
// proof permits no-retry; a higher epoch of our own holder retries.
if errors.Is(err, storage.ErrChunkLayerFenced) && claimHeadSupersedes(head, cfg) {
err = errors.Join(err, errChunkForeignClaim)
}
log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err)
return nil, fmt.Errorf("durable: restore HEAD claim: %w", err)
}
@@ -1473,3 +1514,9 @@ func (w *cutWaitSlot) status(cutSeq uint64) CutScheduleStatus {
}
return st
}
// INV-WS-STARTUP-RETRY-001: a displaced lower-epoch claim fences this
// attempt, but cannot prove the assigned holder was superseded.
func claimHeadSupersedes(head storage.ChunkHead, cfg storage.ChunkLayerConfig) bool {
return head.Gen != 0 && head.Holder != "" && head.Holder != cfg.Holder && head.Epoch >= cfg.Epoch
}
@@ -0,0 +1,141 @@
package durable
import (
"errors"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// ChunkStartupUpdates wakes the process owner when a startup wait ends. It is
// not an event queue: the owner must read ChunkStartupOutcome for its volume.
// INV-WS-STARTUP-RETRY-001 keeps stale recoveries from terminating a newer one.
func (p *DurableProvider) ChunkStartupUpdates() <-chan struct{} { return p.startupUpdates }
// ChunkStartupOutcome is a latched, generation-bound startup failure. A new
// recovery or Close invalidates it; reading it does not consume it. It grants
// no assignment and makes no claim about whether this holder was superseded.
func (p *DurableProvider) ChunkStartupOutcome(volumeID string) (uint64, bool) {
p.mu.Lock()
defer p.mu.Unlock()
h := p.volumes[volumeID]
if p.closed || h == nil || h.startupEnded == 0 || h.startupEnded != h.recoverGen {
return 0, false
}
return h.startupEnded, true
}
// ChunkStartupSuperseded reports only a proven foreign-holder claim refusal
// for this exact recovery. Selection still rechecks gen under the provider lock.
func (p *DurableProvider) ChunkStartupSuperseded(volumeID string, gen uint64) bool {
p.mu.Lock()
defer p.mu.Unlock()
h := p.volumes[volumeID]
return !p.closed && h != nil && gen != 0 && h.recoverGen == gen && h.startupEnded == gen && h.startupSuperseded
}
func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed || gen != h.recoverGen || h.startupEnded != 0 {
return
}
h.startupEnded = gen
h.startupSuperseded = errors.Is(cause, errChunkForeignClaim)
h.startupCure = ""
if errors.Is(cause, ErrChunkStaleLocalRoot) {
h.startupCure = ChunkStaleLocalRootCure
}
select {
case p.startupUpdates <- struct{}{}:
default:
}
}
// ChunkStaleLocalRootCure is the operator's cure of a stale local root.
const ChunkStaleLocalRootCure = "remove or quarantine the local root to attach fresh from HEAD"
// ChunkStartupCure is the operator's cure of this exact recovery's startup
// end ("" when none), for the process's final exit line.
func (p *DurableProvider) ChunkStartupCure(volumeID string, gen uint64) string {
p.mu.Lock()
defer p.mu.Unlock()
h := p.volumes[volumeID]
if p.closed || h == nil || gen == 0 || h.recoverGen != gen || h.startupEnded != gen {
return ""
}
return h.startupCure
}
// ChooseChunkStartupExit validates and selects an outcome in one provider-lock
// section, so recovery cannot change generation between observation and choice.
// choose must only latch the process outcome; it must not block or call back
// into the provider. No remote work or resource cleanup belongs in this call.
func (p *DurableProvider) ChooseChunkStartupExit(volumeID string, gen uint64, choose func()) bool {
p.mu.Lock()
defer p.mu.Unlock()
h := p.volumes[volumeID]
if p.closed || h == nil || h.startupEnded != gen || gen == 0 || h.recoverGen != gen {
return false
}
choose()
return true
}
// chunkFenceWatchInterval bounds how long after a runtime fence the backend
// reports not operational and the process owner is woken. I/O is refused
// from the fence itself (readyCheck reads the layer's latched flag).
const chunkFenceWatchInterval = 50 * time.Millisecond
// watchChunkFence waits for the attached layer to fence after startup (its
// publication found HEAD owned by another holder or epoch: the layer latches
// fenced only on supersede or owner change, never on a clean detach), then
// latches the backend not operational with that evidence and marks the
// volume runtime-fenced (INV-FE-PRIMARY-READY-OPERATIONAL-001). It ends when
// the provider closes or the layer is no longer this volume's; Close joins it
// through p.inflight (counted when it starts) after cancelling closeCtx.
func (p *DurableProvider) watchChunkFence(volumeID string, h *volHandle, layer storage.ChunkLayer) {
defer p.inflight.Done()
t := time.NewTicker(chunkFenceWatchInterval)
defer t.Stop()
for {
select {
case <-p.closeCtx.Done():
return
case <-t.C:
}
p.mu.Lock()
current := !p.closed && p.volumes[volumeID] == h && h.chunk == layer
p.mu.Unlock()
if !current {
return
}
if !layer.Fenced() {
continue
}
h.backend.SetOperational(false, "chunk layer fenced after startup: HEAD has another publication owner")
p.mu.Lock()
if !p.closed && p.volumes[volumeID] == h && h.chunk == layer {
h.runtimeFenced = true
select {
case p.fenceUpdates <- struct{}{}:
default:
}
}
p.mu.Unlock()
return
}
}
// ChunkRuntimeFenceUpdates wakes the process owner when a volume's attached
// layer fenced after startup; read ChunkRuntimeFenced for the volume.
func (p *DurableProvider) ChunkRuntimeFenceUpdates() <-chan struct{} { return p.fenceUpdates }
// ChunkRuntimeFenced reports a latched runtime fence of the volume's
// attached layer (HEAD has another publication owner).
func (p *DurableProvider) ChunkRuntimeFenced(volumeID string) bool {
p.mu.Lock()
defer p.mu.Unlock()
h := p.volumes[volumeID]
return !p.closed && h != nil && h.runtimeFenced
}
@@ -0,0 +1,57 @@
package durable
import "testing"
func TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake(t *testing.T) {
h := &volHandle{recoverGen: 1}
p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)}
p.endChunkStartup(h, 1, nil)
h.recoverGen = 2
h.startupEnded = 0 // RecoverVolume invalidates the old generation under p.mu.
p.endChunkStartup(h, 1, nil)
if _, ok := p.ChunkStartupOutcome("v"); ok {
t.Fatal("stale wait ended the new recovery")
}
p.endChunkStartup(h, 2, nil) // full wake channel must not discard the current latched result
<-p.ChunkStartupUpdates()
if gen, ok := p.ChunkStartupOutcome("v"); !ok || gen != 2 {
t.Fatalf("current result lost: %d %v", gen, ok)
}
p.endChunkStartup(h, 1, nil)
if gen, ok := p.ChunkStartupOutcome("v"); !ok || gen != 2 {
t.Fatal("late old completion overwrote the current result")
}
}
func TestChunkStartupExitRechecksGenerationBeforeChoice(t *testing.T) {
h := &volHandle{recoverGen: 2, startupEnded: 2}
p := &DurableProvider{volumes: map[string]*volHandle{"v": h}}
calls := 0
if p.ChooseChunkStartupExit("v", 1, func() { calls++ }) || calls != 0 {
t.Fatal("stale observation selected process exit")
}
if !p.ChooseChunkStartupExit("v", 2, func() { calls++ }) || calls != 1 {
t.Fatal("current result was not selectable")
}
p.closed = true
if p.ChooseChunkStartupExit("v", 2, func() { calls++ }) || calls != 1 {
t.Fatal("closed provider selected exit")
}
}
func TestChunkStartupForeignProofIsGenerationBound(t *testing.T) {
h := &volHandle{recoverGen: 1}
p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)}
p.endChunkStartup(h, 1, errChunkForeignClaim)
if !p.ChunkStartupSuperseded("v", 1) || p.ChunkStartupSuperseded("other", 1) || p.ChunkStartupSuperseded("v", 2) {
t.Fatal("foreign proof escaped volume or generation")
}
h.recoverGen = 2
h.startupEnded = 0
h.startupSuperseded = false
p.endChunkStartup(h, 1, errChunkForeignClaim)
p.endChunkStartup(h, 2, nil)
if p.ChunkStartupSuperseded("v", 2) {
t.Fatal("old foreign proof poisoned current retry")
}
}
@@ -0,0 +1,160 @@
package durable_test
import (
"context"
"errors"
"reflect"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// INV-WS-STARTUP-RETRY-001: a bounded authority wait must expose a latched
// outcome to its process owner, rather than merely leaving status not-ready.
func TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome(t *testing.T) {
logs := &lockedLog{}
captureWriteLogs(t, logs)
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64,
BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Millisecond,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) {
t.Error("remote reached without authority")
return storage.NewMemChunkRemote(), nil
},
}, v)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
v.active.Store(true)
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
waitLog(t, logs, "assignment unavailable, not serving")
outcomes, ok := any(p).(interface{ ChunkStartupOutcome(string) (uint64, bool) })
if !ok {
t.Fatal("assignment wait ended without a process-owner outcome; process stays up forever")
}
gen, failed := outcomes.ChunkStartupOutcome("v1")
if !failed || gen != 1 {
t.Fatalf("timeout outcome = generation %d, failed %v; want current generation 1", gen, failed)
}
if again, ok := outcomes.ChunkStartupOutcome("v1"); !ok || again != gen {
t.Fatal("outcome was consumed rather than latched")
}
if _, ok := outcomes.ChunkStartupOutcome("other"); ok {
t.Fatal("outcome escaped its volume")
}
if err := p.Close(); err != nil {
t.Fatal(err)
}
if _, ok := outcomes.ChunkStartupOutcome("v1"); ok {
t.Fatal("closed provider retained an actionable outcome")
}
}
func TestChunkStartupSealedAssignmentStaysForReplay(t *testing.T) {
logs := &lockedLog{}
captureWriteLogs(t, logs)
ctx := hangGuard(t)
remote := storage.NewMemChunkRemote()
root := t.TempDir()
first := chunkProvider(t, root, remote, v1View(), 0)
openRecovered(t, first)
sealed, _, err := first.DetachVolumePlain(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
view := v1View()
assigned := view.Projection()
waiting := assigned
waiting.Epoch = 0
waiting.Healthy = false
view.set(waiting)
second := chunkProvider(t, root, remote, view, 0)
if _, err := second.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := second.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
view.set(assigned)
waitLog(t, logs, "sealed assignment, retained for replay")
if _, failed := second.ChunkStartupOutcome("v1"); failed {
t.Fatal("sealed assignment became a process retry")
}
replay, _, err := second.DetachVolumePlain(ctx, "v1")
if err != nil || !reflect.DeepEqual(replay.Head, sealed.Head) {
t.Fatalf("sealed replay changed: %+v %v", replay, err)
}
for _, status := range second.DurableStatuses() {
if status.Operational {
t.Fatal("sealed restart served")
}
}
}
// The attach check returns a retained disposition only AFTER its context's
// deadline. This makes the timeout-defer boundary causal, not a scheduler race.
func TestChunkStartupRetainedDispositionWinsExpiredAttachContext(t *testing.T) {
for _, tc := range []struct {
name string
err error
}{
{"sealed", storage.ErrChunkLayerDetached},
{"stale local root", errors.Join(storage.ErrChunkLayerFenced, durable.ErrChunkStaleLocalRoot)},
} {
t.Run(tc.name, func(t *testing.T) {
logs := &lockedLog{}
captureWriteLogs(t, logs)
view := v1View()
assigned := view.Projection()
waiting := assigned
waiting.Epoch = 0
waiting.Healthy = false
view.set(waiting)
var entered atomic.Bool
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
ChunkAssignmentTimeout: 250 * time.Millisecond,
ChunkAttachCheck: func(ctx context.Context, _ string, _ durable.ChunkGeometry) error {
entered.Store(true)
<-ctx.Done()
return tc.err
},
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) {
t.Error("retained attach reached remote")
return storage.NewMemChunkRemote(), nil
},
}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
if _, err = p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
view.set(assigned)
waitLog(t, logs, "chunk authority wait for volume=v1 ended")
if !entered.Load() {
t.Fatal("fixture deadline elapsed before attach check entered; not a retained-disposition witness")
}
if _, failed := p.ChunkStartupOutcome("v1"); failed {
t.Fatal("deadline defer replaced retained attach disposition with process retry")
}
})
}
}
@@ -0,0 +1,188 @@
package durable_test
import (
"bytes"
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// copyRootFiles copies a provider's storage root (files only) to dst.
func copyRootFiles(t *testing.T, src, dst string) {
t.Helper()
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(src, path)
target := filepath.Join(dst, rel)
if info.IsDir() {
return os.MkdirAll(target, 0o755)
}
in, err := os.Open(path)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
})
if err != nil {
t.Fatal(err)
}
}
// V1-SPEC r2.45 (2): an existing root whose HEAD names this holder attaches
// only if its local durable LSN reaches HEAD's remote_lsn. A rolled-back
// copy of the root (a backup taken before the last cut) is refused with the
// stale-root refusal, as a no-retry (superseded) startup outcome, with the
// operator's cure; it makes no claim, never serves and is left as it was. An
// exact copy of the root at HEAD, and the root's own restart, attach.
func TestRolledBackCopyBelowHeadLSNIsRefused(t *testing.T) {
ctx := context.Background()
remote := storage.NewMemChunkRemote()
root := t.TempDir()
a := chunkProvider(t, root, remote, v1View(), 0)
s := openRecovered(t, a)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
if _, err := a.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
copyLSN, _, _ := s.(*storage.WALStore).Boundaries()
if err := a.Close(); err != nil {
t.Fatal(err)
}
backup := t.TempDir()
copyRootFiles(t, root, backup) // durable LSN at the first cut
a = chunkProvider(t, root, remote, v1View(), 0)
s = openRecovered(t, a) // the root's own restart
if _, err := s.Write(2, block(2)); err != nil {
t.Fatal(err)
}
if _, err := a.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if err := a.Close(); err != nil {
t.Fatal(err)
}
head, _ := remote.GetHead(ctx)
exact := t.TempDir()
copyRootFiles(t, root, exact) // durable LSN at HEAD
puts := remote.Puts()
observed := &casObservedRemote{ChunkRemote: remote}
b := chunkProvider(t, backup, observed, v1View(), 0)
bs, err := b.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
_, err = b.RecoverVolume(ctx, "v1")
if !errors.Is(err, durable.ErrChunkStaleLocalRoot) || !strings.Contains(err.Error(), "remove or quarantine the local root") {
t.Fatalf("a rolled-back copy attached under HEAD remote_lsn %d: %v; want the stale-root refusal", head.RemoteLSN, err)
}
gen, ended := b.ChunkStartupOutcome("v1")
if !ended || !b.ChunkStartupSuperseded("v1", gen) {
t.Fatalf("the rolled-back copy's startup: ended=%t superseded=%t, want a no-retry outcome", ended, b.ChunkStartupSuperseded("v1", gen))
}
if cure := b.ChunkStartupCure("v1", gen); cure != durable.ChunkStaleLocalRootCure {
t.Fatalf("the startup end carries cure %q, want %q for the final exit line", cure, durable.ChunkStaleLocalRootCure)
}
if after, _ := remote.GetHead(ctx); after.Gen != head.Gen || after.Epoch != head.Epoch || after.Holder != head.Holder || remote.Puts() != puts {
t.Fatalf("the refused copy claimed or wrote: HEAD gen %d -> %d, PUTs %d -> %d", head.Gen, after.Gen, puts, remote.Puts())
}
if observed.cass != 0 {
t.Fatalf("the refused copy attempted %d HEAD CASes, want none", observed.cass)
}
if err := b.Backend("v1").AdmitsIO(); err == nil {
t.Fatal("the refused copy admits I/O")
}
// The refused root is left as it was: its data and durable LSN are those
// of the copy (no seed, replay or rewrite toward HEAD).
ws := bs.(*storage.WALStore)
if r, _, _ := ws.Boundaries(); r != copyLSN {
t.Fatalf("the refused root's durable LSN moved: %d -> %d", copyLSN, r)
}
for lba, want := range map[uint32][]byte{1: block(1), 2: make([]byte, 4096)} {
got, err := ws.Read(lba)
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("the refused root's block %d changed: %v", lba, err)
}
}
if err := b.Close(); err != nil {
t.Fatal(err)
}
x := chunkProvider(t, exact, remote, v1View(), 0)
if _, err := x.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := x.RecoverVolume(ctx, "v1"); err != nil {
t.Fatalf("an exact copy at HEAD remote_lsn %d was refused: %v", head.RemoteLSN, err)
}
if err := x.Close(); err != nil {
t.Fatal(err)
}
c := chunkProvider(t, root, remote, v1View(), 0)
if _, err := c.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := c.RecoverVolume(ctx, "v1"); err != nil {
t.Fatalf("the root's own restart after its last cut was refused: %v", err)
}
// The recheck on the exact claim image: HEAD advances at the same epoch
// and holder between the preliminary HEAD read and the claim's read
// (the original root cut again). An exact copy that passed the first
// read is then below HEAD and refused, with no CAS.
race := t.TempDir()
copyRootFiles(t, exact, race)
raced := &casObservedRemote{ChunkRemote: remote}
var advanced storage.ChunkHead
raced.onGetHead = func(n int) {
if n != 2 {
return
}
cur, err := remote.GetHead(ctx)
if err != nil {
t.Error(err)
return
}
next := cur
next.RemoteLSN = cur.RemoteLSN + 1
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil {
t.Error(err)
}
advanced, _ = remote.GetHead(ctx)
}
y := chunkProvider(t, race, raced, v1View(), 0)
if _, err := y.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := y.RecoverVolume(ctx, "v1"); !errors.Is(err, durable.ErrChunkStaleLocalRoot) {
t.Fatalf("HEAD advanced to remote_lsn %d (epoch %d) after the preliminary read; the claim recheck attached: %v", advanced.RemoteLSN, advanced.Epoch, err)
}
if advanced.Gen == 0 || advanced.Epoch != head.Epoch || advanced.Holder != head.Holder || raced.cass != 0 {
t.Fatalf("race control: advanced HEAD %+v (want same epoch %d, holder %q), CAS attempts %d (want 0)", advanced, head.Epoch, head.Holder, raced.cass)
}
if err := y.Close(); err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,89 @@
package durable_test
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// INV-FE-PRIMARY-READY-OPERATIONAL-001 (condition A): a HEAD fence after
// startup, while the lease would still be valid, refuses I/O from the fence,
// latches the backend not operational with its evidence and marks the volume
// runtime-fenced with a wakeup, so the process owner chooses the no-restart
// exit. Another holder claims HEAD at a newer epoch, or at the same epoch
// under another holder string; this holder's next publication fences.
func TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational(t *testing.T) {
for _, tc := range []struct {
name string
epoch func(uint64) uint64
holder string
}{
{"newer epoch", func(e uint64) uint64 { return e + 1 }, "s2/r1"},
{"same epoch, other holder", func(e uint64) uint64 { return e }, "s2/r1"},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
remote := storage.NewMemChunkRemote()
p := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
s := openRecovered(t, p)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if p.ChunkRuntimeFenced("v1") {
t.Fatal("runtime-fenced while serving")
}
backend, err := p.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
head, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
next := head
next.Epoch, next.Holder = tc.epoch(head.Epoch), tc.holder
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next); err != nil {
t.Fatal(err)
}
if _, err := s.Write(2, block(2)); err != nil {
t.Fatal(err)
}
if _, err := p.CaptureVolume(ctx, "v1"); err == nil {
t.Fatal("a capture over another holder's HEAD succeeded")
}
// From the fence on, no I/O is admitted (before the watcher runs).
if n, err := backend.Write(ctx, 3*4096, block(3)); err == nil || n != 0 {
t.Fatalf("a write after the fence: n=%d err=%v, want refused", n, err)
}
select {
case <-p.ChunkRuntimeFenceUpdates():
case <-time.After(5 * time.Second):
t.Fatal("no runtime-fence wakeup within the cleanup bound")
}
if !p.ChunkRuntimeFenced("v1") {
t.Fatal("woken but not runtime-fenced")
}
var st *durable.VolumeStatus
for _, v := range p.DurableStatuses() {
if v.VolumeID == "v1" {
v := v
st = &v
}
}
if st == nil || st.Operational || st.Evidence != "chunk layer fenced after startup: HEAD has another publication owner" {
t.Fatalf("durable status after a runtime fence: %+v, want not operational with the fence evidence", st)
}
if _, err := backend.Write(ctx, 3*4096, block(3)); err == nil {
t.Fatal("a write after the runtime fence was admitted")
}
})
}
}
@@ -181,6 +181,11 @@ type StorageBackend struct {
readyChanged chan struct{}
operational atomic.Bool
opEvidence atomic.Value // string
// firstServing is closed the first time the backend admits I/O (under
// mu); it never reopens. INV-FE-PRIMARY-READY-OPERATIONAL-001: the
// frontends start on it.
firstServing chan struct{}
served bool // under mu: firstServing is closed
// ioMu is the I/O admission boundary: every Read, Write and Sync holds
// its read side for the whole operation, gate included, so StopIO can
@@ -221,10 +226,11 @@ type StorageBackend struct {
// impl changes it mid-session).
func NewStorageBackend(s storage.LogicalStorage, view frontend.ProjectionView, id frontend.Identity) *StorageBackend {
b := &StorageBackend{
storage: s,
view: view,
id: id,
blockSize: s.BlockSize(),
storage: s,
view: view,
id: id,
blockSize: s.BlockSize(),
firstServing: make(chan struct{}),
}
b.opEvidence.Store("awaiting first SetOperational")
// operational.Store(false) is zero-value default; be explicit.
@@ -488,11 +494,23 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) {
b.mu.Unlock()
}
// FirstServing is closed the first time the backend admits I/O (for a chunk
// volume: after its storage claim succeeded) and never reopens. A later loss
// of readiness does not reopen it: the process exit of
// INV-WS-STARTUP-RETRY-001 owns that window.
func (b *StorageBackend) FirstServing() <-chan struct{} { return b.firstServing }
// The caller owns mu; publication never calls the store or waits for I/O.
func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) {
flipped := !ok && b.operational.Load()
b.opEvidence.Store(evidence)
b.operational.Store(ok)
if ok && !b.served {
b.served = true
if b.firstServing != nil { // nil only for a backend built without NewStorageBackend
close(b.firstServing)
}
}
if flipped {
b.stopFlipAt = time.Now() // after the store: no gate after this instant admits
}
@@ -882,6 +900,13 @@ func (b *StorageBackend) gate() error {
return b.lineageCheck()
}
// AdmitsIO is the one deciding function for "may serve" (V1-SPEC r2.39):
// nil exactly when a Read, Write or Sync arriving now passes the I/O gate,
// i.e. the backend admits I/O (open, operational, not chunk-fenced, no
// pre-copy pause) AND the guarded projection names this backend's lineage as
// the healthy primary. /status FrontendPrimaryReady reads it.
func (b *StorageBackend) AdmitsIO() error { return b.gate() }
// readyCheck is the gate without the lineage check: closed, then
// operational.
func (b *StorageBackend) readyCheck() error {
@@ -0,0 +1,88 @@
//go:build unix
package durable_test
import (
"os"
"path/filepath"
"syscall"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// V1-SPEC r2.45 (1), as the tmpfiles.d entry lays it out: a lock directory
// the provider creates gets a traversable parent (0755) and is itself 0700,
// whatever the umask. A 0700 parent created by root would keep the unit's
// user out even after the locks directory is chowned to it.
func TestHostVolumeLockCreatesParent0755AndLocks0700(t *testing.T) {
old := syscall.Umask(0o077) // a strict umask must not narrow the parent
defer syscall.Umask(old)
parent := filepath.Join(t.TempDir(), "sw-block")
locks := filepath.Join(parent, "locks")
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks,
HostVolumeLock: true, VolumeLockDirTestOnly: locks,
}, v1View())
if err != nil {
t.Fatal(err)
}
_ = p.Close()
for path, want := range map[string]os.FileMode{parent: 0o755, locks: 0o700} {
fi, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if got := fi.Mode().Perm(); got != want {
t.Fatalf("%s created %v, want %v", path, got, want)
}
}
}
// newLockProvider opens a provider whose host lock directory is locks.
func newLockProvider(t *testing.T, locks string) {
t.Helper()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks,
HostVolumeLock: true, VolumeLockDirTestOnly: locks,
}, v1View())
if err != nil {
t.Fatal(err)
}
_ = p.Close()
}
func wantPerm(t *testing.T, path string, want os.FileMode) {
t.Helper()
fi, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if got := fi.Mode().Perm(); got != want {
t.Fatalf("%s is %v, want %v", path, got, want)
}
}
// Directories the provider did not create keep their modes: an existing
// parent with a missing lock directory, and both existing.
func TestHostVolumeLockKeepsExistingDirectoryModes(t *testing.T) {
parent := filepath.Join(t.TempDir(), "sw-block")
if err := os.Mkdir(parent, 0o711); err != nil {
t.Fatal(err)
}
if err := os.Chmod(parent, 0o711); err != nil {
t.Fatal(err)
}
locks := filepath.Join(parent, "locks")
newLockProvider(t, locks)
wantPerm(t, parent, 0o711)
wantPerm(t, locks, 0o700)
if err := os.Chmod(locks, 0o750); err != nil {
t.Fatal(err)
}
newLockProvider(t, locks)
wantPerm(t, parent, 0o711)
wantPerm(t, locks, 0o750)
}
@@ -0,0 +1,99 @@
package frontend
import (
"context"
"errors"
"log"
"reflect"
"sync"
"syscall"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// BackendErrorClass is independent of transport status (INV-FE-ERROR-RETRY-CLASS-001).
type BackendErrorClass uint8
const (
BackendErrorPermanent BackendErrorClass = iota
BackendErrorNotReady
BackendErrorBusy
BackendErrorStale
BackendErrorClosed
)
var unclassifiedBackendErrorTypes sync.Map // reflect.Type -> struct{}
// ClassifyBackendError implements INV-FE-ERROR-RETRY-CLASS-001 and V1-SPEC r2.42.
// Call only for a non-nil backend error. Known permanent causes win across the
// entire wrapped/joined tree. Deliberate frontend markers decide otherwise;
// a marker-free unknown error stays permanent and is logged once per leaf type.
func ClassifyBackendError(ctx context.Context, err error) BackendErrorClass {
// M1 I/O error completion: inspect permanent causes before any retry marker.
if hasPermanentBackendCause(err) {
return BackendErrorPermanent
}
switch {
case errors.Is(err, ErrBackendBusy):
return BackendErrorBusy
case errors.Is(err, ErrStalePrimary):
return BackendErrorStale
case errors.Is(err, ErrBackendClosed):
return BackendErrorClosed
case errors.Is(err, ErrNotReady), IsWriteDeadline(ctx, err):
return BackendErrorNotReady
default:
// M1 marker-free completion: amended V1-SPEC r2.42 retains the
// permanent default. Backend owners must classify types seen in gates.
logUnclassifiedBackendError(err)
return BackendErrorPermanent
}
}
func hasPermanentBackendCause(err error) bool {
// M1 permanent precedence: visit every envelope. errors.As alone returns
// the first RecoveryFailure, which may have a non-permanent kind while a
// later sibling or nested envelope carries the latched store fault.
if joined, ok := err.(interface{ Unwrap() []error }); ok {
for _, cause := range joined.Unwrap() {
if hasPermanentBackendCause(cause) {
return true
}
}
} else if cause := errors.Unwrap(err); cause != nil && hasPermanentBackendCause(cause) {
return true
}
var failure *storage.RecoveryFailure
if errors.As(err, &failure) && (failure.Kind == storage.StorageRecoveryFailureSubstrateIO ||
failure.Kind == storage.StorageRecoveryFailureWALIntegrity) {
return true
}
// errors.Is traverses every child of joins, so neither an outer transient
// wrapper nor a sibling deadline can hide a typed storage/media failure.
for _, cause := range []error{syscall.EIO, syscall.ENOSPC, syscall.EROFS,
storage.ErrCounterExhausted, storage.ErrWALIntegrityFault, storage.ErrFsyncFailed,
storage.ErrAppendFailed, storage.ErrMapInvalid} {
if errors.Is(err, cause) {
return true
}
}
return false
}
// Wrapper types are not backend error types: inspect each unknown leaf so one
// fmt wrapper cannot suppress the first diagnostic for a different cause type.
func logUnclassifiedBackendError(err error) {
if joined, ok := err.(interface{ Unwrap() []error }); ok && len(joined.Unwrap()) != 0 {
for _, cause := range joined.Unwrap() {
logUnclassifiedBackendError(cause)
}
return
}
if cause := errors.Unwrap(err); cause != nil {
logUnclassifiedBackendError(cause)
return
}
if _, logged := unclassifiedBackendErrorTypes.LoadOrStore(reflect.TypeOf(err), struct{}{}); !logged {
log.Printf("frontend: unclassified backend error type=%T: %v", err, err)
}
}
@@ -0,0 +1,193 @@
package iscsi_test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"syscall"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type classifiedErrorBackend struct {
frontend.Backend
err error
}
func (b classifiedErrorBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err }
func (b classifiedErrorBackend) Write(context.Context, int64, []byte) (int, error) { return 0, b.err }
func (b classifiedErrorBackend) Sync(context.Context) error { return b.err }
// INV-FE-ERROR-RETRY-CLASS-001: transient backend errors must never become a media failure. Both
// protocol handlers consume the same backend condition; neither returns data.
func TestBackendErrorClassesAcrossFrontends(t *testing.T) {
for _, tc := range []struct {
name string
err error
status, key, asc, ascq, sct, sc uint8
deadline bool
}{
{name: "wal-pressure", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrWALPressureTimeout), status: 0x08, sct: 0, sc: 0x82},
{name: "hydration-pending", err: fmt.Errorf("%w: %w", frontend.ErrBackendBusy, storage.ErrChunkHydrationPending), status: 0x08, sct: 0, sc: 0x82},
{name: "observer-deadline", err: fmt.Errorf("%w: %w: %w", frontend.ErrBackendBusy, durable.ErrReplicationAckUnavailable, context.DeadlineExceeded), status: 0x08, sct: 0, sc: 0x82, deadline: true},
{name: "unknown", err: errors.New("unrecognized backend cause"), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "pressure-without-busy-marker", err: storage.ErrWALPressureTimeout, status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "hydration-without-busy-marker", err: storage.ErrChunkHydrationPending, status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "observer-deadline-without-busy-marker", err: errors.Join(durable.ErrReplicationAckUnavailable, context.DeadlineExceeded), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "unknown-with-busy", err: errors.Join(errors.New("unrecognized backend cause"), frontend.ErrBackendBusy), status: 0x08, sct: 0, sc: 0x82},
{name: "unknown-with-not-ready", err: errors.Join(errors.New("unrecognized backend cause"), frontend.ErrNotReady), status: 0x02, key: 0x02, asc: 0x04, ascq: 0x01, sct: 0, sc: 0x82},
{name: "unknown-with-stale", err: errors.Join(errors.New("unrecognized backend cause"), frontend.ErrStalePrimary), status: 0x02, key: 0x02, asc: 0x04, ascq: 0x0a, sct: 3, sc: 3},
{name: "unknown-with-closed", err: errors.Join(errors.New("unrecognized backend cause"), frontend.ErrBackendClosed), status: 0x02, key: 0x02, asc: 0x04, ascq: 0x03, sct: 3, sc: 2},
{name: "unknown-with-physical", err: errors.Join(errors.New("unrecognized backend cause"), syscall.EIO), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "latched-arbitrary-io", err: errors.Join(frontend.ErrBackendBusy, storage.NewSubstrateIOFailure(errors.New("map persist failed"), "latched store")),
status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "latched-arbitrary-integrity", err: errors.Join(frontend.ErrBackendBusy, storage.NewWALIntegrityFailure(errors.New("descriptor corrupt"), "latched store")),
status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "counter-exhausted", err: errors.Join(frontend.ErrBackendBusy, storage.ErrCounterExhausted),
status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "local-short-read", err: errors.Join(frontend.ErrBackendBusy, storage.NewWALIntegrityFailure(io.ErrUnexpectedEOF, "local file read")),
status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "unknown-recovery-kind", err: errors.Join(frontend.ErrBackendBusy, &storage.RecoveryFailure{Kind: storage.StorageRecoveryFailureUnknown, Cause: errors.New("unknown recovery cause")}),
status: 0x08, sct: 0, sc: 0x82},
{name: "recycled-recovery-kind", err: errors.Join(frontend.ErrBackendBusy, storage.NewWALRecycledFailure(errors.New("recycled"), "history")),
status: 0x08, sct: 0, sc: 0x82},
{name: "latched-after-nonpermanent-envelope", err: errors.Join(frontend.ErrNotReady,
&storage.RecoveryFailure{Kind: storage.StorageRecoveryFailureUnknown},
storage.NewSubstrateIOFailure(errors.New("map persistence latched"), "store")),
status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "latched-under-nonpermanent-envelope", err: errors.Join(frontend.ErrNotReady,
&storage.RecoveryFailure{Kind: storage.StorageRecoveryFailureUnknown,
Cause: storage.NewWALIntegrityFailure(errors.New("descriptor latched"), "store")}),
status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "fsync-fault", err: errors.Join(frontend.ErrBackendBusy, storage.ErrFsyncFailed), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "append-fault", err: errors.Join(frontend.ErrBackendBusy, storage.ErrAppendFailed), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "integrity-fault", err: errors.Join(frontend.ErrBackendBusy, storage.ErrWALIntegrityFault), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "invalid-map", err: errors.Join(frontend.ErrBackendBusy, storage.ErrMapInvalid), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "no-space", err: errors.Join(frontend.ErrBackendBusy, syscall.ENOSPC), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "read-only", err: errors.Join(frontend.ErrBackendBusy, syscall.EROFS), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "hydration-short-remote-body", err: errors.Join(frontend.ErrBackendBusy, storage.ErrChunkHydrationPending, io.ErrUnexpectedEOF), status: 0x08, sct: 0, sc: 0x82},
{name: "not-ready", err: frontend.ErrNotReady, status: 0x02, key: 0x02, asc: 0x04, ascq: 0x01, sct: 0, sc: 0x82},
{name: "busy", err: frontend.ErrBackendBusy, status: 0x08, sct: 0, sc: 0x82},
{name: "stale", err: frontend.ErrStalePrimary, status: 0x02, key: 0x02, asc: 0x04, ascq: 0x0a, sct: 3, sc: 3},
{name: "closed", err: frontend.ErrBackendClosed, status: 0x02, key: 0x02, asc: 0x04, ascq: 0x03, sct: 3, sc: 2},
{name: "permanent", err: syscall.EIO, status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6},
{name: "deadline", err: context.DeadlineExceeded, status: 0x02, key: 0x02, asc: 0x04, ascq: 0x01, sct: 0, sc: 0x82, deadline: true},
{name: "deadline-and-physical", err: errors.Join(context.DeadlineExceeded, syscall.EIO), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "deadline-and-busy", err: errors.Join(context.DeadlineExceeded, frontend.ErrBackendBusy), status: 0x08, sct: 0, sc: 0x82, deadline: true},
{name: "deadline-busy-physical-last", err: errors.Join(context.DeadlineExceeded, frontend.ErrBackendBusy, syscall.EIO), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "deadline-busy-physical-first", err: errors.Join(syscall.EIO, frontend.ErrBackendBusy, context.DeadlineExceeded), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "deadline-busy-nested-physical", err: errors.Join(frontend.ErrBackendBusy, fmt.Errorf("durability: %w", errors.Join(context.DeadlineExceeded, syscall.EIO))), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "deadline-and-not-ready", err: errors.Join(context.DeadlineExceeded, frontend.ErrNotReady), status: 0x02, key: 0x02, asc: 0x04, ascq: 0x01, sct: 0, sc: 0x82, deadline: true},
{name: "deadline-not-ready-physical-last", err: errors.Join(context.DeadlineExceeded, frontend.ErrNotReady, syscall.EIO), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "deadline-not-ready-physical-first", err: errors.Join(syscall.EIO, frontend.ErrNotReady, context.DeadlineExceeded), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
{name: "deadline-not-ready-nested-physical", err: errors.Join(frontend.ErrNotReady, fmt.Errorf("durability: %w", errors.Join(context.DeadlineExceeded, syscall.EIO))), status: 0x02, key: 0x03, asc: 0x11, sct: 0, sc: 6, deadline: true},
} {
for _, op := range []string{"read", "write", "sync"} {
t.Run(tc.name+"/"+op, func(t *testing.T) {
ctx := context.Background()
if tc.deadline {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, time.Now().Add(-time.Second))
defer cancel()
}
b := classifiedErrorBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v"}), err: fmt.Errorf("backend: %w", tc.err)}
sh := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: b})
nh := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b})
var cdb [16]byte
var payload []byte
nc := nvme.IOCommand{NSID: 1, NLB: 1}
switch op {
case "read":
cdb[0] = iscsi.ScsiRead10
cdb[8] = 1
nc.Opcode = 2
case "write":
cdb[0] = iscsi.ScsiWrite10
cdb[8] = 1
payload = make([]byte, 512)
nc.Opcode = 1
nc.Data = payload
case "sync":
cdb[0] = iscsi.ScsiSyncCache10
nc.Opcode = 0
}
got := sh.HandleCommand(ctx, cdb, payload)
ng := nh.Handle(ctx, nc)
asc := tc.asc
if op == "sync" && tc.key == 0x03 {
asc = 0x0c
}
if got.Status != tc.status || got.SenseKey != tc.key || got.ASC != asc || got.ASCQ != tc.ascq {
t.Errorf("SCSI got status/key/ASC/ASCQ %02x/%02x/%02x/%02x want %02x/%02x/%02x/%02x", got.Status, got.SenseKey, got.ASC, got.ASCQ, tc.status, tc.key, asc, tc.ascq)
}
if ng.SCT != tc.sct || ng.SC != tc.sc {
t.Errorf("NVMe got %x/%x want %x/%x", ng.SCT, ng.SC, tc.sct, tc.sc)
}
if len(got.Data) != 0 || len(ng.Data) != 0 {
t.Fatal("error returned data")
}
if tc.name == "not-ready" || tc.name == "busy" {
if got.SenseKey == iscsi.SenseMediumError || ng.SCT != nvme.SCTGeneric || ng.SC != nvme.SCNamespaceNotReady {
t.Fatal("transient condition is not retryable on both protocols")
}
}
})
}
}
}
type unknownCompletionError struct{ message string }
func (e unknownCompletionError) Error() string { return e.message }
type otherUnknownCompletionError struct{}
func (otherUnknownCompletionError) Error() string { return "unknown completion B" }
// INV-FE-ERROR-RETRY-CLASS-001 / amended V1-SPEC r2.42: no marker means
// permanent. Unknown leaf types are logged once across wrappers and protocols.
func TestUnclassifiedBackendErrorIsPermanentAndLoggedOncePerType(t *testing.T) {
// The log-once cache is process-wide; give each test repetition a fresh
// process rather than exposing an implementation-only reset operation.
if os.Getenv("FRONTEND_UNCLASSIFIED_LOG_CHILD") != "1" {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestUnclassifiedBackendErrorIsPermanentAndLoggedOncePerType$", "-test.count=1")
cmd.Env = append(os.Environ(), "FRONTEND_UNCLASSIFIED_LOG_CHILD=1")
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("log-once child: %v\n%s", err, output)
}
return
}
var logs bytes.Buffer
previous := log.Writer()
log.SetOutput(&logs)
t.Cleanup(func() { log.SetOutput(previous) })
for _, cause := range []error{
fmt.Errorf("wrapped: %w", unknownCompletionError{"unknown completion A"}),
errors.Join(unknownCompletionError{"same type, other value"}, otherUnknownCompletionError{}),
} {
b := classifiedErrorBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v"}), err: cause}
scsi := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: b}).HandleCommand(context.Background(), [16]byte{iscsi.ScsiSyncCache10}, nil)
nv := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b}).Handle(context.Background(), nvme.IOCommand{NSID: 1})
if scsi.Status != 0x02 || scsi.SenseKey != 0x03 || scsi.ASC != 0x0c || nv.SCT != 0 || nv.SC != 6 {
t.Fatalf("marker-free completion not permanent: SCSI=%+v NVMe=%+v", scsi, nv)
}
}
if strings.Count(logs.String(), "frontend: unclassified backend error type=") != 2 || !strings.Contains(logs.String(), "unknown completion A") || !strings.Contains(logs.String(), "unknown completion B") {
t.Fatalf("expected one log for each leaf type across both frontends: %q", logs.String())
}
}
+20 -43
View File
@@ -5,7 +5,6 @@ import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"log"
@@ -215,13 +214,7 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [
log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE handler entry opcode=0x%02x", cdb[0])
if err := h.backend.Sync(ctx); err != nil {
log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync FAILED: %v", err)
return SCSIResult{
Status: StatusCheckCondition,
SenseKey: SenseMediumError,
ASC: ASCWriteError,
ASCQ: 0x00,
Reason: fmt.Sprintf("SYNC_CACHE: backend sync: %v", err),
}
return mapBackendError(ctx, err, "sync")
}
log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync ok")
return SCSIResult{Status: StatusGood}
@@ -278,7 +271,7 @@ func (h *SCSIHandler) doRead(ctx context.Context, lba uint64, transferLen uint32
buf := make([]byte, byteLen)
_, err := h.backend.Read(ctx, int64(lba)*int64(h.blockSize), buf)
if err != nil {
return mapBackendError(err, "read")
return mapBackendError(ctx, err, "read")
}
return SCSIResult{Status: StatusGood, Data: buf}
}
@@ -307,7 +300,7 @@ func (h *SCSIHandler) doWrite(ctx context.Context, lba uint64, transferLen uint3
_, err := h.backend.Write(ctx, int64(lba)*int64(h.blockSize), dataOut[:expectedBytes])
if err != nil {
log.Printf("iscsi: SCSI WRITE backend.Write FAILED lba=%d: %v", lba, err)
return mapBackendError(err, "write")
return mapBackendError(ctx, err, "write")
}
log.Printf("iscsi: SCSI WRITE backend.Write ok lba=%d", lba)
return SCSIResult{Status: StatusGood}
@@ -688,41 +681,25 @@ func (h *SCSIHandler) reportLuns(cdb [16]byte) SCSIResult {
// --- helpers ---
// mapBackendError translates a frontend.Backend error into the
// SCSI status/sense tuple. ErrStalePrimary is the load-bearing
// case (test-spec §4 T2.L0.i2/i3): stale WRITE must not
// acknowledge success, stale READ must not return stale bytes.
// Both map to CHECK CONDITION + NOT READY + stale-lineage ASC.
//
// Other backend errors surface as CHECK CONDITION / MEDIUM
// ERROR — conservative fail-closed; real-backend-specific
// mapping lands with T3.
func mapBackendError(err error, op string) SCSIResult {
if errors.Is(err, frontend.ErrStalePrimary) {
return SCSIResult{
Status: StatusCheckCondition,
SenseKey: SenseNotReady,
ASC: ASCStaleLineage,
ASCQ: ASCQStaleLineage,
Reason: "stale primary lineage on " + op,
// mapBackendError only maps the shared retry class to SCSI status/sense.
func mapBackendError(ctx context.Context, err error, op string) SCSIResult {
result := SCSIResult{Status: StatusCheckCondition, SenseKey: SenseNotReady, ASC: ASCNotReady, Reason: "backend error on " + op + ": " + err.Error()}
switch frontend.ClassifyBackendError(ctx, err) {
case frontend.BackendErrorBusy:
return SCSIResult{Status: StatusBusy, Reason: result.Reason}
case frontend.BackendErrorNotReady:
result.ASCQ = 0x01 // LOGICAL UNIT IS IN PROCESS OF BECOMING READY (T10 ASC list).
case frontend.BackendErrorStale:
result.ASC, result.ASCQ = ASCStaleLineage, ASCQStaleLineage
case frontend.BackendErrorClosed:
result.ASCQ = ASCNotReadyManualIntv
default:
result.SenseKey, result.ASC = SenseMediumError, 0x11
if op == "sync" {
result.ASC = ASCWriteError
}
}
if errors.Is(err, frontend.ErrBackendClosed) {
return SCSIResult{
Status: StatusCheckCondition,
SenseKey: SenseNotReady,
ASC: ASCNotReady,
ASCQ: ASCNotReadyManualIntv,
Reason: "backend closed on " + op,
}
}
return SCSIResult{
Status: StatusCheckCondition,
SenseKey: SenseMediumError,
ASC: 0x11, // Unrecovered read error (or generic medium error)
ASCQ: 0x00,
Reason: "backend error on " + op + ": " + err.Error(),
}
return result
}
func illegalRequest(asc, ascq uint8, reason string) SCSIResult {
@@ -0,0 +1,111 @@
package nvme
import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
"github.com/seaweedfs/seaweed-block/core/storage"
"syscall"
"testing"
"time"
)
type retryClassBackend struct {
frontend.Backend
err error
}
func (b retryClassBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err }
func (b retryClassBackend) Write(context.Context, int64, []byte) (int, error) { return 0, b.err }
func (b retryClassBackend) Sync(context.Context) error { return b.err }
// INV-FE-ERROR-RETRY-CLASS-001: validate the completion encoding, not only the handler's status code.
func TestBackendRetryClassClearsWireDNR(t *testing.T) {
for _, tc := range []struct {
name string
err error
dnr bool
}{
{"not-ready", frontend.ErrNotReady, false},
{"unknown", errors.New("unrecognized backend cause"), true},
{"busy", frontend.ErrBackendBusy, false},
{"permanent", syscall.EIO, true},
{"deadline-busy", errors.Join(context.DeadlineExceeded, frontend.ErrBackendBusy), false},
{"deadline-not-ready", errors.Join(context.DeadlineExceeded, frontend.ErrNotReady), false},
{"deadline-busy-physical", errors.Join(context.DeadlineExceeded, frontend.ErrBackendBusy, syscall.EIO), true},
{"deadline-not-ready-physical", errors.Join(context.DeadlineExceeded, frontend.ErrNotReady, syscall.EIO), true},
} {
for _, op := range []uint8{ioRead, ioWrite, ioFlush} {
t.Run(tc.name+string(rune('0'+op)), func(t *testing.T) {
h := NewIOHandler(HandlerConfig{Backend: retryClassBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v"}), err: tc.err}})
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
result := h.Handle(ctx, IOCommand{Opcode: op, NSID: 1, NLB: 1, Data: make([]byte, 512)})
if dnr := result.completionStatus()&(1<<15) != 0; dnr != tc.dnr {
t.Fatalf("DNR=%t want %t, result=%+v", dnr, tc.dnr, result)
}
})
}
}
}
type durabilityClassBackend struct {
frontend.Backend
err error
writes, syncs int
}
func (b *durabilityClassBackend) Write(_ context.Context, _ int64, p []byte) (int, error) {
b.writes++
return len(p), nil
}
func (b *durabilityClassBackend) Sync(context.Context) error {
b.syncs++
return b.err
}
// INV-FE-ERROR-RETRY-CLASS-001 / amended V1-SPEC r2.42: a failed durability
// operation's latched permanent cause wins even beneath a deliberate busy marker.
func TestSyncAndFUALatchedFaultOverridesBusy(t *testing.T) {
for _, fua := range []bool{false, true} {
for _, fault := range []struct {
name string
err error
}{
{name: "no-latch"},
{name: "fsync-sentinel", err: storage.ErrFsyncFailed},
{name: "arbitrary-substrate-latch", err: storage.NewSubstrateIOFailure(errors.New("map persist failed"), "store")},
{name: "arbitrary-integrity-latch", err: storage.NewWALIntegrityFailure(errors.New("descriptor corrupt"), "store")},
{name: "counter-exhausted", err: storage.ErrCounterExhausted},
} {
t.Run(fmt.Sprintf("fua=%t/%s", fua, fault.name), func(t *testing.T) {
cause := errors.Join(frontend.ErrBackendBusy, errors.New("untyped durability cause"))
if fault.err != nil {
cause = errors.Join(cause, fault.err)
}
b := &durabilityClassBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v"}), err: cause}
cmd := IOCommand{Opcode: ioFlush, NSID: 1}
if fua {
cmd = IOCommand{Opcode: ioWrite, NSID: 1, NLB: 1, Data: make([]byte, 512), FUA: true}
}
got := NewIOHandler(HandlerConfig{Backend: b}).Handle(context.Background(), cmd)
want := MakeStatusField(SCTGeneric, SCNamespaceNotReady, false)
if fault.err != nil {
want = MakeStatusField(SCTGeneric, SCInternalError, true)
}
if got.completionStatus() != want {
t.Fatalf("completion=%#x want %#x", got.completionStatus(), want)
}
writes := 0
if fua {
writes = 1
}
if b.writes != writes || b.syncs != 1 {
t.Fatalf("durability seam not reached once: writes=%d syncs=%d", b.writes, b.syncs)
}
})
}
}
}
+15 -45
View File
@@ -17,7 +17,6 @@ package nvme
import (
"context"
"errors"
"fmt"
"time"
@@ -214,7 +213,7 @@ func (h *IOHandler) Handle(ctx context.Context, cmd IOCommand) (result IOResult)
// SC=0x06) — stop rule §3.6 (error-faithful) forbids
// swallowing to Success.
if err := h.backend.Sync(ctx); err != nil {
return mapBackendError(err, "flush")
return mapBackendError(ctx, err, "flush")
}
return IOResult{SCT: SCTGeneric, SC: SCSuccess}
default:
@@ -257,7 +256,7 @@ func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult {
buf := make([]byte, byteLen)
_, err := h.backend.Read(ctx, int64(cmd.SLBA)*int64(h.blockSize), buf)
if err != nil {
return mapBackendError(err, "read")
return mapBackendError(ctx, err, "read")
}
return IOResult{SCT: SCTGeneric, SC: SCSuccess, Data: buf}
}
@@ -283,58 +282,29 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
start := time.Now()
n, err := h.backend.Write(ctx, int64(cmd.SLBA)*int64(h.blockSize), cmd.Data[:expectedBytes])
if err != nil {
return mapWriteBudgetError(ctx, err, "write")
return mapBackendError(ctx, err, "write")
}
if rec, ok := h.backend.(targetWriteRecorder); ok {
rec.RecordTargetWrite(n, time.Since(start))
}
if cmd.FUA {
if err := h.backend.Sync(ctx); err != nil {
return mapWriteBudgetError(ctx, err, "FUA sync")
return mapBackendError(ctx, err, "FUA sync")
}
}
return IOResult{SCT: SCTGeneric, SC: SCSuccess}
}
// Only a pure command-deadline cause is transient. A joined physical error
// must retain its terminal mapping even when the command deadline also passed.
func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult {
if frontend.IsWriteDeadline(ctx, err) {
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true, Reason: "command deadline on " + op + ": " + err.Error()}
}
return mapBackendError(err, op)
}
// mapBackendError translates frontend errors into NVMe CQE
// status tuples. ErrStalePrimary → ANA Transition;
// ErrBackendClosed → ANA Inaccessible; ErrNotReady → retryable Namespace
// Not Ready; anything else → Internal
// Error (fail-closed; real-backend-specific mapping lands with
// T3).
func mapBackendError(err error, op string) IOResult {
if errors.Is(err, frontend.ErrBackendBusy) {
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "local admission pressure on " + op + ": " + err.Error(), retryable: true}
}
if errors.Is(err, frontend.ErrStalePrimary) {
return IOResult{
SCT: SCTPathRelated,
SC: SCPathAsymAccessTransition,
Reason: "stale primary lineage on " + op,
}
}
if errors.Is(err, frontend.ErrBackendClosed) {
return IOResult{
SCT: SCTPathRelated,
SC: SCPathAsymAccessInaccessible,
Reason: "backend closed on " + op,
}
}
if errors.Is(err, frontend.ErrNotReady) {
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "backend not ready on " + op + ": " + err.Error(), retryable: true}
}
return IOResult{
SCT: SCTGeneric,
SC: SCInternalError,
Reason: "backend error on " + op + ": " + err.Error(),
// mapBackendError only maps the shared retry class to NVMe protocol status.
func mapBackendError(ctx context.Context, err error, op string) IOResult {
switch frontend.ClassifyBackendError(ctx, err) {
case frontend.BackendErrorBusy, frontend.BackendErrorNotReady:
return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true, Reason: "backend temporarily unavailable on " + op + ": " + err.Error()}
case frontend.BackendErrorStale:
return IOResult{SCT: SCTPathRelated, SC: SCPathAsymAccessTransition, Reason: "stale primary lineage on " + op}
case frontend.BackendErrorClosed:
return IOResult{SCT: SCTPathRelated, SC: SCPathAsymAccessInaccessible, Reason: "backend closed on " + op}
default:
return IOResult{SCT: SCTGeneric, SC: SCInternalError, Reason: "backend error on " + op + ": " + err.Error()}
}
}
@@ -0,0 +1,28 @@
package master
import (
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
"testing"
)
// INV-AUTH-HOLDER-IDENTITY-001 / TERM-HOLDER-001: fault injection at the
// stream encoder, not a claim that publisher ordering can emit an unissued
// line. The captured E2 publication is available while its journal is not.
func TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal(t *testing.T) {
h := &Host{boot: &bootstrap.DurableAuthorityBootstrap{Publisher: authority.NewPublisher(authority.NewStaticDirective(nil))}, topo: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{VolumeID: "v", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}}}}}
for _, owner := range []string{"s2", ""} {
t.Run("owner="+owner, func(t *testing.T) {
info := adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, ServerID: owner, OwnerFromMove: true}
fact := (&services{host: h}).assignmentFact(info)
if fact.ServerId != owner {
t.Fatalf("captured owner %q relabelled %q from placement while journal unavailable", owner, fact.ServerId)
}
})
}
initial := adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
if got := (&services{host: h}).assignmentFact(initial).ServerId; got != "s1" {
t.Fatalf("move-less initial placement owner: %q", got)
}
}
@@ -42,7 +42,7 @@ func (r *isolationRig) issueMove(t *testing.T, vol, requestID string) (*control.
if line.Epoch != 1 || line.ReplicaID != "r1" {
t.Fatalf("fixture authority line: %+v", line)
}
id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: vol, ReplicaId: "r1", Epoch: 1}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatal(err)
}
@@ -311,8 +311,8 @@ func TestStatusReportsExtensionWriteLatency(t *testing.T) {
reviewLegacyBind(t, h, c, ctx, "vol-b")
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
svc := &services{host: h}
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
t.Fatal(err) // first grant: not an extension
}
get := func() map[string]any {
@@ -329,7 +329,7 @@ func TestStatusReportsExtensionWriteLatency(t *testing.T) {
t.Fatalf("before any extension: %v", b)
}
time.Sleep(8 * time.Second)
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
t.Fatal(err)
}
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) {
@@ -122,7 +122,8 @@ func (h *Host) observationVolume(volumeID string, rec lifecycle.VolumeRecord, pl
volume.Replicas = replicas
volume.ObservedReplicas = countObservedReplicas(replicas)
if volume.PrimaryReplica != "" {
volume.PrimaryNode = serverForReplica(placement, volume.PrimaryReplica)
// the server on the authority line (issued holder), not placement (INV-AUTH-HOLDER-IDENTITY-001)
volume.PrimaryNode = h.workspaceSourceHost(volumeID, line.ReplicaID, line.Epoch)
volume.PublishTarget = publishTargetForReplica(replicas, volume.PrimaryReplica)
}
@@ -230,7 +231,15 @@ func (h *Host) observationReplicas(volumeID string, placement lifecycle.Placemen
replica.Role = "primary"
replica.ReplicationRole = "primary"
}
if fact, ok := h.ObservationHost().Store().SlotFact(volumeID, replicaID); ok {
fact, ok := h.ObservationHost().Store().SlotFact(volumeID, replicaID)
if hasLine && line.Assigned && replicaID == line.ReplicaID {
// the whole primary row is the line's server: its identity, evidence and frontend
// (INV-AUTH-HOLDER-IDENTITY-001); never placement's server carrying the holder's frontend
var holder string
holder, fact, ok = h.holderSlotFact(volumeID, replicaID, line.Epoch)
replica.ServerID, replica.KubernetesNode = holder, holder
}
if ok {
replica.Observed = true
replica.CandidateReady = fact.ReadyForPrimary
replica.CandidateReadyReason = candidateReason(fact.ReadyForPrimary)
@@ -0,0 +1,106 @@
package master
import (
"context"
"fmt"
"net"
"strings"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/peer"
)
// addrHost is the host part of a host:port (or bare host) address.
func addrHost(addr string) string {
if h, _, err := net.SplitHostPort(addr); err == nil {
return h
}
return strings.TrimSpace(addr)
}
// registryHosts is the host set the node registry records for serverID (data, ctrl and plain addresses) and the host
// named in refusals; ok is false when serverID has no registry record.
func (h *Host) registryHosts(serverID string) (hosts map[string]bool, named string, ok bool) {
if h.lifecycle == nil || h.lifecycle.Nodes == nil || serverID == "" {
return nil, "", false
}
reg, ok := h.lifecycle.Nodes.GetNodeSnapshot(serverID) // committed snapshot: never the store mutex (INV-WS-RENEW-NONBLOCKING-001)
if !ok {
return nil, "", false
}
hosts = map[string]bool{}
for _, a := range []string{reg.DataAddr, reg.CtrlAddr, reg.Addr} {
if a != "" {
hosts[addrHost(a)] = true
}
}
named = addrHost(reg.DataAddr)
if named == "" {
named = addrHost(reg.Addr)
}
return hosts, named, true
}
// refuseServerIDFromOtherHost is the observation half of INV-AUTH-HOLDER-IDENTITY-001: a heartbeat whose slot addresses
// are on a host other than the one registered for its server id is refused before its slots reach the observations.
// Only the host part is compared (each volume process listens on its own ports); several server ids on one host stay
// allowed; an id with no registry record is not checked here (no first-seen binding in v1.0: host addresses change).
func (h *Host) refuseServerIDFromOtherHost(r *control.HeartbeatReport) error {
hosts, named, ok := h.registryHosts(r.ServerId)
if !ok || len(hosts) == 0 {
return nil
}
for _, s := range r.Slots {
for _, a := range []string{s.DataAddr, s.CtrlAddr} {
if a != "" && !hosts[addrHost(a)] {
return fmt.Errorf("heartbeat: server id %s is registered on host %s but advertises %s (volume %s replica %s): advertise the registered address, or register the node by the address it uses, in the cluster spec",
r.ServerId, named, addrHost(a), s.VolumeId, s.ReplicaId)
}
}
}
return nil
}
// peerHost is the host part of a gRPC call's network peer; "" when the call carries none.
func peerHost(ctx context.Context) string {
p, ok := peer.FromContext(ctx)
if !ok || p.Addr == nil {
return ""
}
return addrHost(p.Addr.String())
}
// refuseWorkspaceHolderHost is the holder half of INV-AUTH-HOLDER-IDENTITY-001 for workspace volumes (lease renew, ACK,
// assignment stream): the server id must be registered (no first-seen binding), and the call's network peer must be on
// the host the registry records for it. Limits: it trusts the network peer address (no NAT or proxy between volume and
// master in OSS), and it is not authentication. Every refusal is logged.
func (h *Host) refuseWorkspaceHolderHost(ctx context.Context, rpc, server string) error {
hosts, named, ok := h.registryHosts(server)
var err error
switch ph := peerHost(ctx); {
case !ok:
err = fmt.Errorf("%s: server id %q is not registered; a workspace holder's server id must be", rpc, server)
case ph == "" || !hosts[ph]:
if ph == "" {
ph = "an unknown peer"
}
err = fmt.Errorf("%s: server id %s is registered on host %s but connects from %s: register the node by the address it connects from (not loopback) in the cluster spec", rpc, server, named, ph)
}
if err != nil {
h.log.Print(err)
}
return err
}
// holderSlotFact is the slot fact of replica on the server the authority line names (workspaceSourceHost); a
// same-replica claim from any other server, however fresh, is never used (INV-AUTH-HOLDER-IDENTITY-001).
// No resolvable holder: no fact (fail closed).
func (h *Host) holderSlotFact(volumeID, replicaID string, epoch uint64) (string, authority.SlotFact, bool) {
holder := h.workspaceSourceHost(volumeID, replicaID, epoch)
if holder == "" || h.obs == nil {
return holder, authority.SlotFact{}, false
}
fact, ok := h.obs.Store().SlotFactOnServer(holder, volumeID, replicaID)
return holder, fact, ok
}
@@ -0,0 +1,463 @@
package master
import (
"context"
"errors"
"fmt"
"net"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/csi"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// INV-AUTH-HOLDER-IDENTITY-001: after an issued workspace move the authority line is on the new host while the placement
// slot may still name the old one. The displayed primary node, its publish target and the CSI portal follow the ISSUED
// holder; the old host, still reporting the replica id with a newer observation, wins none of them.
func TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot(t *testing.T) {
heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}}
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }})
if err != nil {
t.Fatal(err)
}
m.Start()
defer closeTestMaster(t, m)
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
ws, lc, obs := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn), control.NewObservationServiceClient(conn)
for _, n := range []struct{ id, d, c string }{{"node-a", "127.0.0.1:19101", "127.0.0.1:19102"}, {"node-b", "127.0.0.1:19301", "127.0.0.1:19302"}} {
if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: n.d, CtrlAddr: n.c}); err != nil {
t.Fatal(err)
}
}
if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "a2", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "a2", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "a2", ServerID: "node-b", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if _, err := obs.ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "a2", ReplicaId: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}}}); err != nil {
t.Fatal(err)
}
if _, err := m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
a2 := waitAuthorityLine(t, m.Publisher(), "a2")
id := &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "to-a", VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch,
TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: "127.0.0.1:19111", TargetCtrlAddr: "127.0.0.1:19112", Kind: "clean"})
if err != nil || !g.Issued || g.NewHost != "node-a" {
t.Fatalf("move to node-a: %+v %v", g, err)
}
line, _ := m.Publisher().VolumeAuthorityLine("a2")
if p, ok := m.Lifecycle().Placements.GetPlacementSnapshot("a2"); ok {
t.Logf("placement after the move: %+v (the displayed primary must not depend on it)", p.Slots)
}
fact := func(server, host string, at time.Time) authority.Observation {
return authority.Observation{ServerID: server, ObservedAt: at, Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{VolumeID: "a2", ReplicaID: "r1", DataAddr: host + ":19111", CtrlAddr: host + ":19112",
Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 10,
Frontends: []authority.FrontendTargetFact{{Protocol: "iscsi", Addr: host + ":3260", IQN: "iqn.2026-05.io.seaweedfs:a2", LUN: 1}}}}}
}
now := time.Now().UTC()
if holder := m.workspaceSourceHost("a2", line.ReplicaID, line.Epoch); holder != "node-a" {
t.Fatalf("issued holder %q, want node-a (line %+v)", holder, line)
}
lookup := csi.NewControlStatusLookup(control.NewEvidenceServiceClient(conn))
// only the old host reports the replica: no primary evidence from the issued holder, so no portal at all
if err := m.ObservationHost().Ingest(fact("node-b", "192.0.2.9", now.Add(time.Second))); err != nil {
t.Fatal(err)
}
if target, err := lookup.LookupPublishTarget(ctx, "a2", ""); !errors.Is(err, csi.ErrPublishTargetNotFound) {
t.Fatalf("CSI lookup with only the old host's claim: target %+v err %v, want ErrPublishTargetNotFound", target, err)
}
if err := m.ObservationHost().Ingest(fact("node-a", "127.0.0.1", now)); err != nil {
t.Fatal(err)
}
if target, err := lookup.LookupPublishTarget(ctx, "a2", ""); err != nil || !strings.Contains(fmt.Sprintf("%+v", target), "127.0.0.1:3260") || strings.Contains(fmt.Sprintf("%+v", target), "192.0.2.9") {
t.Fatalf("CSI lookup: target %+v err %v, want the issued holder's 127.0.0.1:3260", target, err)
}
var vol *struct{ node, target, rowServer, rowNode, rowFrontend string }
for _, v := range m.ObservationSnapshot(time.Now().UTC()).Volumes {
if v.VolumeID == "a2" {
vol = &struct{ node, target, rowServer, rowNode, rowFrontend string }{node: v.PrimaryNode, target: v.PublishTarget}
for _, r := range v.Replicas {
if r.ReplicaID == line.ReplicaID {
vol.rowServer, vol.rowNode, vol.rowFrontend = r.ServerID, r.KubernetesNode, r.FrontendAddr
}
}
}
}
// The whole primary row names the issued holder, never placement's node-b carrying node-a's frontend.
if vol == nil || vol.node != "node-a" || vol.target != "127.0.0.1:3260" || vol.rowServer != "node-a" || vol.rowNode != "node-a" || vol.rowFrontend != "127.0.0.1:3260" {
t.Fatalf("displayed primary %+v, want node-a at 127.0.0.1:3260 in the volume and its primary row (the issued holder, not the placement slot or the old host)", vol)
}
resp, err := newServices(m).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "a2"})
if err != nil || len(resp.Frontends) == 0 || resp.Frontends[0].Addr != "127.0.0.1:3260" {
t.Fatalf("CSI portal %v %v, want the issued holder's 127.0.0.1:3260", resp.GetFrontends(), err)
}
}
// heartbeatFrom sends a heartbeat for server whose slot addresses are on host.
func (r *isolationRig) heartbeatFrom(server, host string) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-" + server, ReplicaId: "r-" + server, DataAddr: host + ":19611", CtrlAddr: host + ":19612"}}})
return err
}
// INV-AUTH-HOLDER-IDENTITY-001: OSS has no host authentication, so a server id names a host only if the master
// refuses that id from any host other than the one registered for it. Two processes started with the same --server-id
// on different hosts: the one on the registered host is accepted, the other is refused, and it never enters the
// observations (a copied config cannot borrow the registered host's holder identity).
func TestServerIDRefusedFromAHostOtherThanItsRegisteredOne(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) // node-a is registered on 127.0.0.1
if err := r.heartbeatFrom("node-a", "127.0.0.1"); err != nil {
t.Fatalf("heartbeat from node-a's registered host refused: %v", err)
}
// The peer is the registered host; only the advertised slot address is wrong.
obs := control.NewObservationServiceClient(r.dialFrom(t, "127.0.0.1"))
_, err := obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-node-a", ReplicaId: "r-node-a", DataAddr: "127.0.0.2:19611", CtrlAddr: "127.0.0.2:19612"}}})
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1") {
t.Fatalf("same --server-id from a second host: %v, want FailedPrecondition naming the registered host", err)
}
want := "registered on host 127.0.0.1 but advertises 127.0.0.2 (volume hb-node-a replica r-node-a): advertise the registered address, or register the node by the address it uses, in the cluster spec"
if !strings.Contains(status.Convert(err).Message(), want) {
t.Fatalf("heartbeat refusal lacks the cure or slot detail: %v", err)
}
if slot, ok := r.m.ObservationHost().Store().SlotFactOnServer("node-a", "hb-node-a", "r-node-a"); !ok || !strings.HasPrefix(slot.DataAddr, "127.0.0.1:") {
t.Fatalf("refused heartbeat reached the observations: %+v ok=%v", slot, ok)
}
}
// INV-AUTH-HOLDER-IDENTITY-001: the CSI portal (QueryVolumeStatus frontends) and the displayed primary
// (ClusterStatus primary node and publish target) come from the server on the volume's authority line, never from
// whichever host sent the freshest heartbeat for the same replica id. A stale old host that still reports the
// primary's replica, even more recently, changes neither.
func TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
seedObservationSnapshotVolume(t, h)
seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01")
ingestObservationSnapshotRF3(t, h, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
line := waitAuthorityLine(t, h.Publisher(), "pvc-a")
holder := h.workspaceSourceHost("pvc-a", line.ReplicaID, line.Epoch)
own, ok := h.ObservationHost().Store().SlotFactOnServer(holder, "pvc-a", line.ReplicaID)
if holder == "" || !ok || len(own.Frontends) == 0 {
t.Fatalf("line %+v names holder %q with no observed frontend", line, holder)
}
holderAddr := own.Frontends[0].Addr
stale := ""
for _, server := range []string{"m01", "m02", "tp01"} { // the fixture's placement servers
if server != holder {
stale = server
break
}
}
// the stale host reports the primary's replica id with a newer observation than the holder's
if err := h.ObservationHost().Ingest(authority.Observation{ServerID: stale, ObservedAt: time.Now().UTC().Add(time.Second),
Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{VolumeID: "pvc-a", ReplicaID: line.ReplicaID, DataAddr: "192.0.2.9:19101", CtrlAddr: "192.0.2.9:19102",
Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 99,
Frontends: []authority.FrontendTargetFact{{Protocol: "iscsi", Addr: "192.0.2.9:3260", IQN: "iqn.2026-05.io.seaweedfs:pvc-a", LUN: 1}}}}}); err != nil {
t.Fatalf("ingest stale host: %v", err)
}
resp, err := newServices(h).QueryVolumeStatus(context.Background(), &control.StatusRequest{VolumeId: "pvc-a"})
if err != nil {
t.Fatalf("status: %v", err)
}
if len(resp.Frontends) == 0 || resp.Frontends[0].Addr != holderAddr {
t.Fatalf("CSI portal: frontends=%v, want the line server %s's %s first (stale host %s must not win)", resp.Frontends, holder, holderAddr, stale)
}
for _, ft := range resp.Frontends {
if ft.Addr == "192.0.2.9:3260" {
t.Fatalf("CSI portal lists the stale host's frontend: %v", resp.Frontends)
}
}
vol := h.ObservationSnapshot(time.Now().UTC()).Volumes[0]
if vol.PrimaryNode != holder || vol.PublishTarget != holderAddr {
t.Fatalf("displayed primary node=%q target=%q, want %q %q (line server, not the stale host %s)", vol.PrimaryNode, vol.PublishTarget, holder, holderAddr, stale)
}
}
// dialFrom opens a client connection to the rig's master whose source address is host (a real loopback address).
func (r *isolationRig) dialFrom(t *testing.T, host string) *grpc.ClientConn {
t.Helper()
d := net.Dialer{LocalAddr: &net.TCPAddr{IP: net.ParseIP(host)}}
conn, err := grpc.NewClient(r.m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) { return d.DialContext(ctx, "tcp", addr) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return conn
}
// INV-AUTH-HOLDER-IDENTITY-001, workspace path: two processes with the same --server-id on two real loopback hosts. The
// one not on the registered host (127.0.0.2) is refused at lease renew, at the revocation ACK and at the assignment
// stream (so it never receives the line to adopt), and each refusal is logged; an unregistered server id is refused at
// its first renew; the registered host is unaffected. The check trusts the network peer address (no NAT or proxy
// between volume and master in OSS); it is not authentication.
func TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) // node-a registered on 127.0.0.1
r.createVolume(t, "w1")
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "w1", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "w1", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "w1", ReplicaId: "r1", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"}}}); err != nil {
t.Fatal(err)
}
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, r.m.Publisher(), "w1")
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "w1", ReplicaId: "r1", Epoch: line.Epoch}
other := r.dialFrom(t, "127.0.0.2")
wsOther, asnOther := control.NewWorkspaceServiceClient(other), control.NewAssignmentServiceClient(other)
refusedFrom2 := func(what string, err error) {
t.Helper()
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "registered on host 127.0.0.1 but connects from 127.0.0.2") {
t.Fatalf("%s from 127.0.0.2 as node-a: %v, want the host refusal", what, err)
}
if !strings.Contains(status.Convert(err).Message(), "register the node by the address it connects from (not loopback) in the cluster spec") {
t.Fatalf("%s refusal has no registration cure: %v", what, err)
}
}
_, err := wsOther.RenewWorkspaceLease(r.ctx, id)
refusedFrom2("renew", err)
_, err = wsOther.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9})
refusedFrom2("ACK", err)
stream, err := asnOther.SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w1", ReplicaId: "r1", ServerId: "node-a"})
if err == nil {
_, err = stream.Recv()
}
refusedFrom2("assignment stream", err)
if n := strings.Count(r.logs.String(), "connects from 127.0.0.2"); n < 3 {
t.Fatalf("refusals logged %d times, want 3:\n%s", n, r.logs.String())
}
// the registered host is unaffected: it renews and receives the line
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatalf("renew from the registered host: %v", err)
}
own, err := control.NewAssignmentServiceClient(r.dialFrom(t, "127.0.0.1")).SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w1", ReplicaId: "r1", ServerId: "node-a"})
if err != nil {
t.Fatal(err)
}
if fact, err := own.Recv(); err != nil || fact.GetEpoch() != line.Epoch {
t.Fatalf("assignment stream from the registered host: %+v %v", fact, err)
}
// an unregistered server id is refused at its first renew; a stream naming no server id is refused too
_, err = r.ws.RenewWorkspaceLease(r.ctx, &control.WorkspaceIdentity{ServerId: "node-z", VolumeId: "w1", ReplicaId: "r1", Epoch: line.Epoch})
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), `server id "node-z" is not registered`) {
t.Fatalf("renew by an unregistered server id: %v, want the not-registered refusal", err)
}
anon := r.dialFrom(t, "127.0.0.1")
s2, err := control.NewAssignmentServiceClient(anon).SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w1", ReplicaId: "r1"})
if err == nil {
_, err = s2.Recv()
}
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), `server id "" is not registered`) {
t.Fatalf("assignment stream with no server id: %v, want the not-registered refusal", err)
}
}
// loopbackPeer is ctx as an RPC from 127.0.0.1 arrives at the master (in-process service calls carry no peer).
func loopbackPeer(ctx context.Context) context.Context {
return peer.NewContext(ctx, &peer.Peer{Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 40000}})
}
// registerWorkspaceHolder registers server on 127.0.0.1 (a workspace holder must be registered).
func registerWorkspaceHolder(t *testing.T, h *Host, server string) {
t.Helper()
if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:19901", CtrlAddr: "127.0.0.1:19902"}); err != nil {
t.Fatal(err)
}
}
// A CSI client takes the first frontend as the primary. When the primary's evidence (from the line's server)
// is missing, the status lists NO frontend, even though supporting replicas report theirs; without the rule a
// supporting replica's frontend would be published under the primary identity.
func TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing(t *testing.T) {
obs := authority.NewObservationHost(authority.ObservationHostConfig{})
for _, r := range []struct{ server, replica, host string }{{"node-b", "r2", "127.0.0.2"}, {"node-c", "r3", "127.0.0.3"}} {
if err := obs.IngestHeartbeat(authority.HeartbeatMessage{ServerID: r.server, SentAt: time.Now().UTC(), Reachable: true, Eligible: true,
Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: r.replica, DataAddr: r.host + ":9201", CtrlAddr: r.host + ":9101",
Frontends: []authority.FrontendTargetFact{{Protocol: "iscsi", Addr: r.host + ":3260", IQN: "iqn.2026-05.example:v1"}}}}}); err != nil {
t.Fatal(err)
}
}
noPrimary := func(replicaID string) (authority.SlotFact, bool) {
if replicaID == "r1" {
return authority.SlotFact{}, false // the line's server has no evidence for the primary
}
return obs.Store().SlotFact("v1", replicaID)
}
if got := statusFrontendsFor(obs, "v1", []string{"r1", "r2", "r3"}, true, "r1", noPrimary); len(got) != 0 {
t.Fatalf("primary evidence missing: frontends %v, want none (a supporting replica must not stand in for the primary)", got)
}
if got := statusFrontendsFor(obs, "v1", []string{"r1", "r2", "r3"}, true, "", noPrimary); len(got) != 2 {
t.Fatalf("control: without the primary rule the supporting frontends are listed (%v): the hazard this test pins", got)
}
}
// inProcEvidence is the CSI lookup's EvidenceService client wired straight to the master's QueryVolumeStatus.
type inProcEvidence struct{ s *services }
func (e inProcEvidence) QueryVolumeStatus(ctx context.Context, in *control.StatusRequest, _ ...grpc.CallOption) (*control.StatusResponse, error) {
return e.s.QueryVolumeStatus(ctx, in)
}
// Through the real CSI ControlStatusLookup, with supporting replicas reporting usable frontends, no
// target is published when the primary's slot (on the line's server) exists but carries no frontend, or when its only
// frontend is one CSI rejects (loopback, with loopback targets rejected). Control: the same lookup without the loopback
// rejection publishes the primary's own frontend.
func TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
seedObservationSnapshotVolume(t, h)
seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01")
ingestObservationSnapshotRF3(t, h, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
line := waitAuthorityLine(t, h.Publisher(), "pvc-a")
holder := h.workspaceSourceHost("pvc-a", line.ReplicaID, line.Epoch)
reprimary := func(fronts []authority.FrontendTargetFact, at time.Time) {
t.Helper()
if err := h.ObservationHost().Ingest(authority.Observation{ServerID: holder, ObservedAt: at, Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{VolumeID: "pvc-a", ReplicaID: line.ReplicaID, DataAddr: "192.0.2.1:19101", CtrlAddr: "192.0.2.1:19102",
Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 30, Frontends: fronts}}}); err != nil {
t.Fatal(err)
}
}
svc := newServices(h)
plain := csi.NewControlStatusLookup(inProcEvidence{svc})
noLoopback := csi.NewControlStatusLookupWithOptions(inProcEvidence{svc}, csi.WithLoopbackPublishTargetsRejected())
ctx := context.Background()
// (a) the primary slot exists on the holder but carries no frontend
reprimary(nil, time.Now().UTC().Add(time.Second))
if resp, err := svc.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "pvc-a"}); err != nil || len(resp.Frontends) != 0 {
t.Fatalf("primary slot without a frontend: status frontends %v err %v, want none", resp.GetFrontends(), err)
}
if target, err := plain.LookupPublishTarget(ctx, "pvc-a", ""); !errors.Is(err, csi.ErrPublishTargetNotFound) {
t.Fatalf("primary slot without a frontend: CSI target %+v err %v, want ErrPublishTargetNotFound", target, err)
}
// (b) the primary's only frontend is loopback, which this CSI lookup rejects; supporting replicas are usable
reprimary([]authority.FrontendTargetFact{{Protocol: "iscsi", Addr: "127.0.0.1:3260", IQN: "iqn.2026-05.io.seaweedfs:pvc-a", LUN: 1}}, time.Now().UTC().Add(2*time.Second))
if target, err := noLoopback.LookupPublishTarget(ctx, "pvc-a", ""); !errors.Is(err, csi.ErrPublishTargetNotFound) {
t.Fatalf("rejected primary frontend: CSI target %+v err %v, want ErrPublishTargetNotFound (no supporting stand-in)", target, err)
}
if target, err := plain.LookupPublishTarget(ctx, "pvc-a", ""); err != nil || target.ISCSIAddr != "127.0.0.1:3260" || target.ReplicaID != line.ReplicaID {
t.Fatalf("control: CSI target %+v err %v, want the primary's own 127.0.0.1:3260", target, err)
}
}
// A workspace volume being deleted is still a workspace volume: its assignment stream keeps the holder
// host check (a deletion reservation must not open a bypass).
func TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "w2")
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "w2", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "w2", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if len(r.m.replicaSlotsFor("w2")) == 0 {
t.Fatal("fixture: w2 has no replica slot, the stream would fail before the host check")
}
if _, err := r.m.Lifecycle().Deletions.Admit("w2", "del-1"); err != nil {
t.Fatal(err)
}
stream, err := control.NewAssignmentServiceClient(r.dialFrom(t, "127.0.0.2")).SubscribeAssignments(r.ctx, &control.SubscribeRequest{VolumeId: "w2", ReplicaId: "r1", ServerId: "node-a"})
if err == nil {
_, err = stream.Recv()
}
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "connects from 127.0.0.2") {
t.Fatalf("deletion-reserved workspace volume, stream from another host: %v, want the host refusal", err)
}
}
// INV-WS-RENEW-NONBLOCKING-001: a live lease renewal through holderMatches, whose host check reads the
// node registry, completes while a registration write is held (the store mutex RegisterNode keeps across file I/O). The
// hold is proven real: a concurrent RegisterNode does not finish until it is released.
func TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir()) // node-a registered on 127.0.0.1
r.createVolume(t, "w3")
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "w3", DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{VolumeID: "w3", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{VolumeId: "w3", ReplicaId: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil {
t.Fatal(err)
}
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, r.m.Publisher(), "w3")
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "w3", ReplicaId: "r1", Epoch: line.Epoch}
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
t.Fatalf("first grant: %v", err)
}
release := r.m.Lifecycle().Nodes.HoldWritesForTest()
writer := make(chan struct{})
t.Cleanup(func() {
release()
select {
case <-writer:
case <-time.After(5 * time.Second):
t.Error("held registration writer did not join")
}
})
go func() {
defer close(writer)
_, _ = r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-c", DataAddr: "127.0.0.1:19501", CtrlAddr: "127.0.0.1:19502"})
}()
ctx, cancel := context.WithTimeout(r.ctx, time.Second)
defer cancel()
if _, err := r.ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatalf("live renewal during a held registration write: %v (it must not wait on the registry store)", err)
}
select {
case <-writer:
t.Fatal("control: the registration write was not actually held")
default:
}
release()
select {
case <-writer:
case <-time.After(5 * time.Second):
t.Fatal("registration write did not finish after the release")
}
}
+63 -20
View File
@@ -292,6 +292,10 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.refuseColocatedHeartbeat(r.ServerId, storeident.Identity{MachineID: r.GetMachineId(), Dev: r.GetDurableRootDev(), FSID: r.GetDurableRootFsid()}); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
// INV-AUTH-HOLDER-IDENTITY-001: one server id names one host.
if err := s.host.refuseServerIDFromOtherHost(r); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
msg := heartbeatFromWire(r)
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
@@ -387,6 +391,13 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
if len(slots) == 0 {
return fmt.Errorf("subscribe: volume %q not in accepted topology", req.VolumeId)
}
// INV-AUTH-HOLDER-IDENTITY-001: a workspace volume's line is delivered only to a registered server id streaming
// from its registered host, so a second host with a copied --server-id never receives (never adopts) it.
if s.isWorkspaceVolume(req.VolumeId) {
if err := s.host.refuseWorkspaceHolderHost(ctx, "assignment stream", req.GetServerId()); err != nil {
return status.Error(codes.FailedPrecondition, err.Error())
}
}
type recv struct {
ch <-chan adapter.AssignmentInfo
@@ -461,24 +472,7 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
lastEpoch = info.Epoch
lastEV = info.EndpointVersion
sentAny = true
fact := &control.AssignmentFact{
VolumeId: info.VolumeID,
ReplicaId: info.ReplicaID,
Epoch: info.Epoch,
EndpointVersion: info.EndpointVersion,
DataAddr: info.DataAddr,
CtrlAddr: info.CtrlAddr,
}
// Populate the peer set from publisher LastPublished
// queries for every non-self replica slot in this volume's
// topology. peer_set_generation is derived
// from the authoritative line's (Epoch, EndpointVersion)
// packed into one uint64 as (epoch<<32 | ev). Assertion
// above guarantees each fits in uint32 so no aliasing.
// Monotonic across process lifetimes because Epoch/EV are
// durable authority facts preserved across master restart.
fact.Peers = s.collectPeers(req.VolumeId, info)
fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion
fact := s.assignmentFact(info)
if err := stream.Send(fact); err != nil {
return err
}
@@ -508,7 +502,15 @@ func (s *services) QueryVolumeStatus(ctx context.Context, req *control.StatusReq
replicaIDs = []string{line.ReplicaID}
}
replicaIDs = primaryFirstReplicaIDs(replicaIDs, line.ReplicaID)
resp.Frontends = statusFrontendsForAssignedVolume(s.host.obs, req.VolumeId, replicaIDs, line.Assigned)
// the primary's portal comes from the server on the line, never a fresher same-replica claim elsewhere
// (INV-AUTH-HOLDER-IDENTITY-001)
resp.Frontends = statusFrontendsFor(s.host.obs, req.VolumeId, replicaIDs, line.Assigned, line.ReplicaID, func(replicaID string) (authority.SlotFact, bool) {
if replicaID == line.ReplicaID {
_, fact, ok := s.host.holderSlotFact(req.VolumeId, replicaID, line.Epoch)
return fact, ok
}
return s.host.obs.Store().SlotFact(req.VolumeId, replicaID)
})
resp.UnhealthyReplicas = statusUnhealthyReplicas(s.host.obs, req.VolumeId, replicaIDs)
}
if ev, ok := ctrl.LastUnsupported(req.VolumeId); ok {
@@ -552,20 +554,37 @@ func primaryFirstReplicaIDs(replicaIDs []string, primaryReplicaID string) []stri
}
func statusFrontendsForAssignedVolume(obs *authority.ObservationHost, volumeID string, replicaIDs []string, assigned bool) []*control.FrontendTarget {
return statusFrontendsFor(obs, volumeID, replicaIDs, assigned, "", nil)
}
// statusFrontendsFor lists the frontends of replicaIDs in order; slotOf selects each replica's slot fact (nil: the
// freshest claim for that replica). When primary is set and its slot fact is missing, nothing is listed: a CSI client
// takes the first frontend as the primary, so a supporting replica's frontend must never stand in for it
// (INV-AUTH-HOLDER-IDENTITY-001, fail closed).
func statusFrontendsFor(obs *authority.ObservationHost, volumeID string, replicaIDs []string, assigned bool, primary string, slotOf func(replicaID string) (authority.SlotFact, bool)) []*control.FrontendTarget {
if !assigned || obs == nil {
return nil
}
if slotOf == nil {
slotOf = func(replicaID string) (authority.SlotFact, bool) { return obs.Store().SlotFact(volumeID, replicaID) }
}
if primary != "" {
if f, ok := slotOf(primary); !ok || len(f.Frontends) == 0 {
return nil // no primary evidence, or a primary slot with no frontend: nothing to publish
}
}
out := make([]*control.FrontendTarget, 0, len(replicaIDs))
seen := map[string]struct{}{}
for _, replicaID := range replicaIDs {
if replicaID == "" {
continue
}
slot, ok := obs.Store().SlotFact(volumeID, replicaID)
slot, ok := slotOf(replicaID)
if !ok {
continue
}
for _, ft := range frontendTargetsToWire(slot.Frontends) {
ft.ReplicaId = replicaID // CSI selects only a primary-owned target (INV-AUTH-HOLDER-IDENTITY-001)
key := frontendTargetKey(ft)
if _, ok := seen[key]; ok {
continue
@@ -931,3 +950,27 @@ func (h *Host) ingestHeartbeatRecordingHealth(msg authority.HeartbeatMessage) er
}
return nil
}
// assignmentFact encodes one captured publication at the stream boundary.
func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.AssignmentFact {
fact := &control.AssignmentFact{
VolumeId: info.VolumeID,
ReplicaId: info.ReplicaID,
ServerId: s.host.workspaceLineOwner(authority.PublishedLine{ReplicaID: info.ReplicaID, Epoch: info.Epoch, IssuedHost: info.ServerID, OwnerFromMove: info.OwnerFromMove}, info.VolumeID, info.ReplicaID, info.Epoch),
Epoch: info.Epoch,
EndpointVersion: info.EndpointVersion,
DataAddr: info.DataAddr,
CtrlAddr: info.CtrlAddr,
}
// Populate the peer set from publisher LastPublished
// queries for every non-self replica slot in this volume's
// topology. peer_set_generation is derived
// from the authoritative line's (Epoch, EndpointVersion)
// packed into one uint64 as (epoch<<32 | ev). Assertion
// above guarantees each fits in uint32 so no aliasing.
// Monotonic across process lifetimes because Epoch/EV are
// durable authority facts preserved across master restart.
fact.Peers = s.collectPeers(info.VolumeID, info)
fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion
return fact
}
@@ -65,18 +65,55 @@ func (h *Host) workspaceEndpointsAvailable(b lifecycle.WorkspaceBinding) error {
return nil
}
// workspaceSourceHost resolves explicit holder membership for
// INV-AUTH-HOLDER-IDENTITY-001; endpoints never select a server.
func (h *Host) workspaceSourceHost(volume, replica string, epoch uint64) string {
current, _ := h.Publisher().PublishedAuthorityLine(volume)
return h.workspaceLineOwner(current, volume, replica, epoch)
}
// workspaceLineOwner is TERM-HOLDER-001's single owner decision function
// (INV-AUTH-HOLDER-IDENTITY-001). A captured current line never takes the
// publisher's store-write lock (INV-WS-RENEW-NONBLOCKING-001); only historical
// lines need the move journal. Endpoints never identify a server.
func (h *Host) workspaceLineOwner(current authority.PublishedLine, volume, replica string, epoch uint64) string {
if current.ReplicaID == replica && current.Epoch == epoch {
if server, fromMove := current.Owner(); fromMove { // the single owner decision (PublishedLine.Owner)
return server
}
return h.placementSourceHost(volume, replica)
}
if state := h.Publisher().WorkspaceState(volume); state != nil {
for _, r := range state.Moves {
if r.Issued && r.NewReplicaID == replica && r.NewEpoch == epoch {
return r.NewHost
}
if r.Issued && r.OldReplicaID == replica && r.OldEpoch == epoch {
return r.OldHost
}
}
}
if p, ok := h.lifecycle.Placements.GetPlacement(volume); ok {
for _, slot := range p.Slots {
if slot.ReplicaID == replica {
return slot.ServerID
return h.placementSourceHost(volume, replica)
}
// placementSourceHost uses committed membership, never endpoint inference
// (INV-AUTH-HOLDER-IDENTITY-001, INV-WS-RENEW-NONBLOCKING-001).
func (h *Host) placementSourceHost(volume, replica string) string {
if h.lifecycle != nil {
if p, ok := h.lifecycle.Placements.GetPlacementSnapshot(volume); ok {
for _, slot := range p.Slots {
if slot.ReplicaID == replica {
return slot.ServerID
}
}
}
}
for _, v := range h.topo.Volumes {
if v.VolumeID == volume {
for _, slot := range v.Slots {
if slot.ReplicaID == replica {
return slot.ServerID
}
}
}
}
@@ -88,7 +88,7 @@ func TestWorkspaceBindingLegacyMoveCannotTakePreparedReservation(t *testing.T) {
if _, e := client.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "prepared", ServerId: "node-b", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); e != nil {
t.Fatal(e)
}
id := &control.WorkspaceIdentity{VolumeId: "legacy", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "legacy", ReplicaId: "r1", Epoch: 1}
if _, e := client.RenewWorkspaceLease(ctx, id); e != nil {
t.Fatal(e)
}
@@ -114,7 +114,7 @@ func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) {
if _, e := client.RegisterWorkspaceBinding(ctx, b); e != nil {
t.Fatal(e)
}
if _, e := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1}); e != nil {
if _, e := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "live", ReplicaId: "r1", Epoch: 1}); e != nil {
t.Fatal(e)
}
if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "live"}); e == nil {
@@ -126,7 +126,7 @@ func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) {
if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("live"); e != nil || !bound {
t.Fatal("refused deletion removed binding", bound, e)
}
id := &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "live", ReplicaId: "r1", Epoch: 1}
if _, e := client.RevokeWorkspace(ctx, id); e != nil {
t.Fatal(e)
}
@@ -255,7 +255,7 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) {
})
reviewLegacyBind(t, h, c, ctx, "ack")
client := control.NewWorkspaceServiceClient(c)
id := &control.WorkspaceIdentity{VolumeId: "ack", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "ack", ReplicaId: "r1", Epoch: 1}
if _, e := client.RenewWorkspaceLease(ctx, id); e != nil {
t.Fatal(e)
}
@@ -120,7 +120,7 @@ func workspaceBindingsMove(t *testing.T, forced bool) {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), vol)
id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: line.Epoch}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: vol, ReplicaId: "r1", Epoch: line.Epoch}
lease, e := client.RenewWorkspaceLease(ctx, id)
if e != nil {
t.Fatal(e)
@@ -78,7 +78,7 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
t.Fatal(err)
}
oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a")
oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
oldID := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch}
if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil {
t.Fatal(err)
}
@@ -188,7 +188,7 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) {
}
// The new holder detaches cleanly and ACKs; the delete is then admitted.
newID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch}
newID := &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, newID); err != nil {
t.Fatal(err)
}
@@ -0,0 +1,145 @@
package master
import (
"context"
"github.com/seaweedfs/seaweed-block/core/authority"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"reflect"
"sync/atomic"
"testing"
"time"
)
func leaseHolderIdentity(t *testing.T, epoch uint64, server string) *control.WorkspaceIdentity {
t.Helper()
q := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: epoch}
b, err := proto.Marshal(q)
if err != nil {
t.Fatal(err)
}
if server != "" {
b = protowire.AppendTag(b, 4, protowire.BytesType)
b = protowire.AppendString(b, server)
}
if err = proto.Unmarshal(b, q); err != nil {
t.Fatal(err)
}
return q
}
func TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant(t *testing.T) {
var nowNS atomic.Int64
nowNS.Store(time.Now().UnixNano())
h, conn, _ := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) {
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
}, func(h *Host) {
authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })(h.Publisher())
})
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
t.Cleanup(cancel)
reviewCreate(t, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
t.Fatal(err)
}
reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "v")
refuse := func(stage string, epoch uint64) {
t.Helper()
for _, server := range []string{"", "node-b"} {
before := h.Publisher().WorkspaceState("v")
if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, epoch, server)); err == nil {
t.Errorf("%s accepted lease for server %q", stage, server)
}
after := h.Publisher().WorkspaceState("v")
if !reflect.DeepEqual(before, after) {
t.Errorf("%s refused identity changed lease", stage)
}
}
}
refuse("first grant", line.Epoch)
id := leaseHolderIdentity(t, line.Epoch, "node-a")
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal("matching server grant", err)
}
refuse("renew", line.Epoch)
nowNS.Add(int64(2 * time.Minute)) // beyond both the old horizon and clock-skew barrier
refuse("expired re-grant", line.Epoch)
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal("matching server expired re-grant", err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
g, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "same-host", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"})
if err != nil {
t.Fatal(err)
}
refuse("re-grant", g.NewEpoch)
if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, g.NewEpoch, "node-a")); err != nil {
t.Fatal("matching server re-grant", err)
}
}
// INV-AUTH-HOLDER-IDENTITY-001: an ACK licenses a clean move, so only the
// primary server/replica pair may record it, not another host of the same r1.
func TestWorkspaceRevocationACKRequiresHolderServer(t *testing.T) {
for _, server := range []string{"", "node-b"} {
t.Run("server="+server, func(t *testing.T) {
h, conn, ctx := reviewBindingHost(t)
reviewCreate(t, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
t.Fatal(err)
}
reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "v")
own := leaseHolderIdentity(t, line.Epoch, "node-a")
if _, err := ws.RenewWorkspaceLease(ctx, own); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, own); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: leaseHolderIdentity(t, line.Epoch, server), HeadGen: 9}); err == nil {
t.Errorf("ACK accepted server %q with the right replica/epoch", server)
}
recorded, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "v"})
if err != nil {
t.Fatal(err)
}
if recorded.GetRevocationAck() != nil {
t.Errorf("foreign ACK recorded: %v", recorded.GetRevocationAck())
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: own, HeadGen: 9}); err != nil {
t.Fatal("own ACK refused", err)
}
recorded, err = ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "v"})
if err != nil || recorded.GetRevocationAck().GetHeadGen() != 9 {
t.Fatal("own ACK not recorded", recorded, err)
}
})
}
}
@@ -55,7 +55,7 @@ func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) {
t.Cleanup(func() { releaseOnce.Do(func() { close(stall.release) }) }) // runs first: unblock the extender
var stops atomic.Int32
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}},
deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1},
deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1},
func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil)
if err != nil {
t.Fatal(err)
@@ -112,8 +112,8 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
reviewLegacyBind(t, h, c, ctx, "vol-b")
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
svc := &services{host: h}
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
first, err := svc.RenewWorkspaceLease(ctx, id)
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
first, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id)
if err != nil {
t.Fatal(err)
}
@@ -129,7 +129,7 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
if err != nil || !rv.Revoking || rv.ExpiresAtNs != first.ExpiresAtNs {
t.Fatalf("RevokeWorkspace must report the grant %d, got %+v %v", first.ExpiresAtNs, rv, err)
}
if _, err := svc.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
if _, err := svc.AckWorkspaceRevoked(loopbackPeer(ctx), &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
deletions := h.Lifecycle().Deletions
@@ -148,6 +148,9 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
}()
renewed := make(chan *control.WorkspaceLeaseFact, 1)
renewErr := make(chan error, 1)
ownerResult := make(chan string, 1)
ownerJoined := make(chan struct{})
ownerStarted := false
renewStarted := false
t.Cleanup(func() { // bounded: release, settle both workers, then clear the hook
releaseHook()
@@ -158,6 +161,14 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
settled = false
t.Error("held reservation write did not settle")
}
if ownerStarted {
select {
case <-ownerJoined:
case <-time.After(5 * time.Second):
settled = false
t.Error("owner lookup did not settle")
}
}
if renewStarted {
select {
case <-renewErr:
@@ -175,9 +186,25 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("reservation write of vol-b never reached the store")
}
// TERM-HOLDER-001: current-line facts and lease admission resolve the
// same committed owner without entering the publisher's store-write lock.
ownerStarted = true
go func() {
defer close(ownerJoined)
ownerResult <- h.workspaceSourceHost("vol-b", line.ReplicaID, line.Epoch)
}()
select {
case owner := <-ownerResult:
matches, matchErr := svc.holderMatches(loopbackPeer(ctx), "vol-b", line.ReplicaID, owner, line.Epoch)
if owner != "node-a" || !matches || matchErr != nil {
t.Fatalf("fact and lease owner differ under held writer: %q", owner)
}
case <-time.After(time.Second):
t.Fatal("current owner lookup waited for publisher store write")
}
renewStarted = true
go func() {
f, err := svc.RenewWorkspaceLease(ctx, id)
f, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id)
renewed <- f
renewErr <- err
}()
@@ -201,7 +228,7 @@ func TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("mark deleting did not finish")
}
if _, err := svc.RenewWorkspaceLease(ctx, id); err == nil || !strings.Contains(err.Error(), "being deleted") {
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err == nil || !strings.Contains(err.Error(), "being deleted") {
t.Fatalf("renewal after the reservation was published: %v; want refused as being deleted", err)
}
}
@@ -0,0 +1,74 @@
package master
import (
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"testing"
)
// TERM-HOLDER-001 / INV-AUTH-HOLDER-IDENTITY-001: current facts, leases and
// move-source history share the owner rule; placement does not override a move.
func TestWorkspaceLineOwnerIssuedAndHistorical(t *testing.T) {
h, conn, ctx := reviewBindingHost(t)
reviewLegacyBind(t, h, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
id := leaseHolderIdentity(t, 1, "node-a")
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
target := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-b", DataAddr: "127.0.0.1:20000", CtrlAddr: "127.0.0.1:20001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, target); err != nil {
t.Fatal(err)
}
grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "owner-move", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"})
if err != nil {
t.Fatal(err)
}
if !grant.Issued || grant.NewEpoch != 2 {
t.Fatal("move did not issue", grant)
}
svc := &services{host: h}
matches := func(server string) bool {
t.Helper()
ok, err := svc.holderMatches(loopbackPeer(ctx), "v", "r1", server, 2)
if err != nil {
t.Fatal(err)
}
return ok
}
if got := h.placementSourceHost("v", "r1"); got != "node-a" {
t.Fatal("fixture placement no longer differs from issued owner", got)
}
// Both consumers must prefer the issued owner to the old placement.
if got := h.workspaceSourceHost("v", "r1", 2); got != "node-b" || !matches(got) || matches("node-a") {
t.Fatal("fact/lease issued owner mismatch", got)
}
stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(ctx, &control.SubscribeRequest{VolumeId: "v", ReplicaId: "r1", ServerId: "node-b"})
if err != nil {
t.Fatal(err)
}
fact, err := stream.Recv()
if err != nil || fact.GetServerId() != "node-b" || fact.GetEpoch() != 2 {
t.Fatal("wrong produced fact", fact, err)
}
if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, 2, "node-b")); err != nil {
t.Fatal("issued owner lease refused", err)
}
// Change only desired-placement metadata. It must not rewrite the owner of
// the historical e1 line retained in the actual issued move journal.
if _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "v", ServerID: "node-c", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if got := h.workspaceSourceHost("v", "r1", 1); got != "node-a" {
t.Fatal("historical line guessed from current placement", got)
}
if got := h.workspaceSourceHost("v", "r1", 2); got != "node-b" || !matches(got) {
t.Fatal("issued owner changed with placement", got)
}
}
@@ -97,7 +97,7 @@ func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceS
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-f")
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
t.Fatal(err)
}
return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1",
@@ -80,7 +80,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
}
defer conn.Close()
client := control.NewWorkspaceServiceClient(conn)
id := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
lease, err := client.RenewWorkspaceLease(ctx, id)
if err != nil {
t.Fatal(err)
@@ -75,7 +75,7 @@ func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) {
t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2)
}
// a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD.
id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
id := &control.WorkspaceIdentity{ServerId: "node-b", VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
@@ -159,7 +159,7 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) {
// The grantee renews (its guard is valid), then pauses before its claim.
guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}}, skewLeaseClient{p},
&control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow })
&control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow })
if err != nil {
t.Fatal(err)
}
@@ -65,7 +65,7 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) {
p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, masterNS.Load()) }), authority.WithWorkspaceMaxClockSkew(4*time.Second))
seedSkewPublisher(t, p, dir)
client := &heldSkewLeaseClient{skewLeaseClient: skewLeaseClient{p}, entered: make(chan *control.WorkspaceLeaseFact, 1), release: make(chan struct{})}
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return time.Unix(0, hostNS.Load()) })
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, client, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return time.Unix(0, hostNS.Load()) })
if err != nil {
t.Fatal(err)
}
@@ -112,7 +112,7 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro
done <- result{err: err}
return
}
done <- result{fact: leaseFact(id.VolumeId, l)}
done <- result{fact: leaseFact(c.p, id.VolumeId, l)}
}()
select {
case r := <-done:
@@ -150,11 +150,11 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil))
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
seedSkewPublisher(t, p, dir)
var stops atomic.Int32
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}},
deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1},
deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r", Epoch: 1},
func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil)
if err != nil {
t.Fatal(err)
@@ -166,7 +166,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
cancel()
<-runDone // Run returns on cancel; the go test timeout bounds a hang
})
t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins
t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins
for !g.Projection().Healthy { // progress: the first grant
time.Sleep(20 * time.Millisecond)
}
@@ -215,8 +215,8 @@ func TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite(t *testing.T) {
reviewLegacyBind(t, h, c, ctx, "vol-b")
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
svc := &services{host: h}
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
t.Fatal(err) // first grant
}
deletions := h.Lifecycle().Deletions
@@ -266,7 +266,7 @@ func TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite(t *testing.T) {
}
start := time.Now()
renewStarted = true
go func() { _, err := svc.RenewWorkspaceLease(ctx, id); renewed <- err }()
go func() { _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); renewed <- err }()
select {
case err := <-renewed:
renewed <- err // keep it for the cleanup join
@@ -27,7 +27,7 @@ func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) {
if line := waitAuthorityLine(t, h.Publisher(), "v"); line.Epoch != 1 {
t.Fatal(line)
}
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1}
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r1", Epoch: 1}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more