mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge pull request #432 from seaweedfs/train/20261122-24
Train 24 (P0 train B): start-time retry exits, listen/ready gate, runtime HEAD-fence exit
This commit is contained in:
commit
f9ebc99749
38 files changed
+3743
-293
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -584,7 +582,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)
|
||||
@@ -723,6 +721,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)
|
||||
@@ -763,6 +765,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)
|
||||
@@ -776,7 +779,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)
|
||||
}
|
||||
@@ -1017,70 +1020,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()
|
||||
}
|
||||
@@ -1101,6 +1197,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 {
|
||||
@@ -1109,166 +1233,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
|
||||
@@ -1320,16 +1337,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
|
||||
@@ -1481,12 +1489,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,247 @@
|
||||
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
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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{exitWorkspaceSuperseded, "superseded"}
|
||||
}
|
||||
return workspaceExit{exitWorkspaceRetry, 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{exitWorkspaceSuperseded, "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{exitWorkspaceRetry, "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))
|
||||
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{{75, "lease_expired"}, {78, "superseded"}, {0, "revoked"}} {
|
||||
e := newProcessExit(context.Background())
|
||||
e.choose(first)
|
||||
e.choose(workspaceExit{75, "assignment_timeout"})
|
||||
<-e.done
|
||||
if got := <-e.decision; got != first {
|
||||
t.Fatalf("first=%+v changed to %+v", first, got)
|
||||
}
|
||||
e.choose(workspaceExit{78, "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{78, "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{75, "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{78, "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{75, "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{78, "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)
|
||||
}
|
||||
}
|
||||
@@ -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{exitWorkspaceSuperseded, "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,806 @@
|
||||
//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)
|
||||
}
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -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{
|
||||
|
||||
@@ -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,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")
|
||||
}
|
||||
}
|
||||
@@ -233,10 +233,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 +262,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
|
||||
@@ -284,10 +287,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
|
||||
@@ -392,12 +398,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
|
||||
}
|
||||
|
||||
@@ -550,6 +558,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 +965,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)
|
||||
|
||||
@@ -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,6 +452,12 @@ 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
|
||||
@@ -485,6 +509,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 +1502,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,122 @@
|
||||
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)
|
||||
select {
|
||||
case p.startupUpdates <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// 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,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 {
|
||||
|
||||
@@ -176,8 +176,7 @@ type Host struct {
|
||||
workspaceLeaseStarted atomic.Bool
|
||||
// Guard installation and terminal host fencing share this lock. Order:
|
||||
// workspaceLeaseMu -> guard.mu; never hold either across RPC or drain.
|
||||
workspaceLeaseMu sync.Mutex
|
||||
workspaceLeaseFenced bool
|
||||
workspaceLeaseMu sync.Mutex
|
||||
// workspaceStopPending is the guard's stop-pending mode, kept here for a
|
||||
// guard installed later; workspaceStopAttempt numbers detach attempts so
|
||||
// only the latest one's resume clears it.
|
||||
@@ -204,6 +203,9 @@ type Host struct {
|
||||
otherMu sync.Mutex
|
||||
lastOther *control.AssignmentFact
|
||||
|
||||
ownAssignmentMu sync.RWMutex
|
||||
ownAssignmentEpoch, ownAssignmentEV uint64
|
||||
|
||||
frontendMu sync.RWMutex
|
||||
frontendTargets []*control.FrontendTarget
|
||||
}
|
||||
@@ -521,29 +523,21 @@ func (h *Host) getReplication() replicaSetUpdater {
|
||||
return h.replication
|
||||
}
|
||||
|
||||
// IsSuperseded gates a newer foreign replica line, or a same-replica foreign
|
||||
// server identity strictly newer than an adopted local lineage. An explicitly
|
||||
// matching self identity remains an ordinary adapter update.
|
||||
// IsSuperseded is the one foreign-holder comparison. Callers supply the
|
||||
// named lineage: adopted engine state for fencing, observed own assignment
|
||||
// for exit classification. Zero lineage selects neither fencing nor exit78
|
||||
// (INV-AUTH-HOLDER-IDENTITY-001; INV-WS-STARTUP-RETRY-001).
|
||||
func (h *Host) IsSuperseded(selfReplicaID string, selfEpoch, selfEV uint64) bool {
|
||||
h.otherMu.Lock()
|
||||
defer h.otherMu.Unlock()
|
||||
if h.lastOther == nil || selfEpoch == 0 {
|
||||
other := h.lastOther
|
||||
if selfEpoch == 0 || other == nil || other.ReplicaId == "" || other.VolumeId != h.cfg.VolumeID {
|
||||
return false
|
||||
}
|
||||
other := h.lastOther
|
||||
if other.ReplicaId == selfReplicaID {
|
||||
if h.assignmentNamesSelf(other) {
|
||||
return false
|
||||
}
|
||||
return other.Epoch > selfEpoch || other.Epoch == selfEpoch && other.EndpointVersion > selfEV
|
||||
if other.ReplicaId == selfReplicaID && h.assignmentNamesSelf(other) {
|
||||
return false
|
||||
}
|
||||
if other.Epoch > selfEpoch {
|
||||
return true
|
||||
}
|
||||
if other.Epoch == selfEpoch && other.EndpointVersion > selfEV {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return other.Epoch > selfEpoch || other.Epoch == selfEpoch && other.EndpointVersion > selfEV
|
||||
}
|
||||
|
||||
// ProjectionView returns the AdapterProjectionView that bridges
|
||||
@@ -861,6 +855,7 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
|
||||
return
|
||||
}
|
||||
|
||||
h.recordSelfAssignment(fact)
|
||||
h.reportAssignmentEndpoints(fact)
|
||||
|
||||
// The recovery watchdog runs from the primary assignment, before any
|
||||
|
||||
@@ -124,6 +124,16 @@ func (v *AdapterProjectionView) projectionWithSupersede() (frontend.Projection,
|
||||
return result, superseded
|
||||
}
|
||||
|
||||
// workspaceLeaseNotHeld: a workspace primary whose lease guard is not
|
||||
// installed yet, or does not hold a granted lease now (the guard decides).
|
||||
func (v *AdapterProjectionView) workspaceLeaseNotHeld() bool {
|
||||
if !v.workspaceRequired {
|
||||
return false
|
||||
}
|
||||
g := v.workspaceGuard.Load()
|
||||
return g == nil || !g.Held()
|
||||
}
|
||||
|
||||
func (v *AdapterProjectionView) supportingReplicaReady(selfEpoch, selfEV uint64) bool {
|
||||
if v == nil || v.probe == nil {
|
||||
return false
|
||||
|
||||
@@ -89,6 +89,9 @@ type peerStatusSource interface {
|
||||
|
||||
type durableStatusSource interface {
|
||||
DurableStatuses() []durable.VolumeStatus
|
||||
// AdmitsIO is the one deciding function for "may serve" of an open
|
||||
// volume (StorageBackend.AdmitsIO); an error for any other.
|
||||
AdmitsIO(volumeID string) error
|
||||
}
|
||||
|
||||
type nvmeStatusSource interface {
|
||||
@@ -187,8 +190,16 @@ type StatusProjection struct {
|
||||
// Memory is the process's memory use at the time of the request.
|
||||
Memory ProcessMemoryStatus
|
||||
// FrontendPrimaryReady: this replica is the healthy, non-superseded
|
||||
// primary and may serve guest I/O.
|
||||
// primary, its local durable backend admits I/O, and it may serve guest
|
||||
// I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001).
|
||||
FrontendPrimaryReady bool
|
||||
// NotReadyReason says why FrontendPrimaryReady is false, first match: a
|
||||
// workspace primary holds no granted lease now (NotReadyLeaseNotHeld); the
|
||||
// local durable backend admits no I/O (its evidence: attach pending,
|
||||
// fenced, detached) or has no status for the volume; the frontend target
|
||||
// is not listening yet; this replica is not the healthy primary. Empty
|
||||
// when ready.
|
||||
NotReadyReason string `json:",omitempty"`
|
||||
// AuthorityRole is primary, superseded or unknown.
|
||||
AuthorityRole string
|
||||
// ReplicationRole is none (a primary), recovering, not_ready,
|
||||
@@ -483,19 +494,53 @@ func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request)
|
||||
_ = json.NewEncoder(w).Encode(NVMeStatus{VolumeID: p.VolumeID, Stats: src.Stats()})
|
||||
}
|
||||
|
||||
// NotReadyLeaseNotHeld: a workspace primary without a granted lease holds at
|
||||
// the gate (no claim, no listen, not ready); V1-SPEC r2.37.
|
||||
const NotReadyLeaseNotHeld = "lease_not_held"
|
||||
|
||||
func (s *StatusServer) statusProjection() StatusProjection {
|
||||
p := s.authorityProjection()
|
||||
authorityReady := p.FrontendPrimaryReady
|
||||
s.mu.Lock()
|
||||
p.Healthy = p.Healthy && !s.nvmePending
|
||||
p.FrontendPrimaryReady = p.FrontendPrimaryReady && !s.nvmePending
|
||||
nvmePending := s.nvmePending
|
||||
p.Healthy = p.Healthy && !nvmePending
|
||||
p.FrontendPrimaryReady = p.FrontendPrimaryReady && !nvmePending
|
||||
src := s.durableSource
|
||||
s.mu.Unlock()
|
||||
// INV-FE-PRIMARY-READY-OPERATIONAL-001: not FrontendPrimaryReady while the
|
||||
// local backend admits no I/O (before the storage claim of a chunk volume,
|
||||
// after a refused claim: fenced, after a detach), and not when there is no
|
||||
// durable status for the volume at all (fail closed). The authority view
|
||||
// alone (the adapter's PublishHealthy) is not readiness; Healthy stays that
|
||||
// view. Whenever FrontendPrimaryReady is false, NotReadyReason says why.
|
||||
backendReason := ""
|
||||
if src != nil { // outside s.mu: the provider takes its own lock
|
||||
for _, st := range src.DurableStatuses() {
|
||||
if st.VolumeID == p.VolumeID {
|
||||
p.Warnings = append(p.Warnings, st.Warnings...)
|
||||
}
|
||||
}
|
||||
// V1-SPEC r2.39: the backend's one "may serve" function decides; an
|
||||
// unopened volume fails closed.
|
||||
if err := src.AdmitsIO(p.VolumeID); err != nil {
|
||||
backendReason = "durable backend admits no I/O: " + err.Error()
|
||||
}
|
||||
}
|
||||
leaseNotHeld := s.view.workspaceLeaseNotHeld()
|
||||
if backendReason != "" || leaseNotHeld {
|
||||
p.FrontendPrimaryReady = false
|
||||
}
|
||||
if !p.FrontendPrimaryReady {
|
||||
switch {
|
||||
case leaseNotHeld:
|
||||
p.NotReadyReason = NotReadyLeaseNotHeld
|
||||
case backendReason != "":
|
||||
p.NotReadyReason = backendReason
|
||||
case nvmePending:
|
||||
p.NotReadyReason = "frontend target not listening yet"
|
||||
case !authorityReady:
|
||||
p.NotReadyReason = "not the healthy primary: authority role " + p.AuthorityRole + ", replication role " + p.ReplicationRole
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
|
||||
@@ -957,6 +959,21 @@ func (s stubDurableStatusSource) DurableStatuses() []durable.VolumeStatus {
|
||||
return append([]durable.VolumeStatus(nil), s.vols...)
|
||||
}
|
||||
|
||||
// AdmitsIO models StorageBackend.AdmitsIO from the stub's statuses: an open
|
||||
// operational volume admits; a non-operational one refuses with its evidence;
|
||||
// an unknown one fails closed.
|
||||
func (s stubDurableStatusSource) AdmitsIO(volumeID string) error {
|
||||
for _, v := range s.vols {
|
||||
if v.VolumeID == volumeID {
|
||||
if !v.Operational {
|
||||
return fmt.Errorf("%w: %s", frontend.ErrNotReady, v.Evidence)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%w: %s", durable.ErrVolumeNotOpen, volumeID)
|
||||
}
|
||||
|
||||
func TestStatusServer_DurableStatusEndpoint_Disabled_Returns404(t *testing.T) {
|
||||
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
|
||||
addr, err := s.Start("127.0.0.1:0")
|
||||
@@ -1183,3 +1200,89 @@ func TestStatusServer_UblkStatusEndpoint(t *testing.T) {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// INV-FE-PRIMARY-READY-OPERATIONAL-001: a healthy primary authority view is
|
||||
// not readiness. While the volume's local durable backend admits no I/O
|
||||
// (a chunk volume awaiting its attach, a refused claim: fenced, a detach),
|
||||
// /status does not report FrontendPrimaryReady and says why (NotReadyReason),
|
||||
// while Healthy stays the authority view; once the backend admits I/O,
|
||||
// readiness follows the authority view again. A status for another
|
||||
// volume does not count.
|
||||
func TestStatusServer_ReadyOnlyWhileBackendOperational(t *testing.T) {
|
||||
p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 2}}
|
||||
s := NewStatusServer(NewAdapterProjectionView(p, "v1", "r1", nil))
|
||||
addr, err := s.Start("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
defer func() { _ = s.Close(context.Background()) }()
|
||||
read := func() StatusProjection {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://" + addr + "/status?volume=v1")
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var body StatusProjection
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
vols []durable.VolumeStatus
|
||||
want bool
|
||||
}{
|
||||
{"attach pending", []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "recovered; chunk layer awaiting master authority"}}, false},
|
||||
{"fenced", []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "chunk layer attach refused: HEAD holder h1/r1 is not this holder"}}, false},
|
||||
{"other volume not operational", []durable.VolumeStatus{{VolumeID: "v2", Operational: false}, {VolumeID: "v1", Operational: true}}, true},
|
||||
{"no status for the volume (fail closed)", []durable.VolumeStatus{{VolumeID: "v2", Operational: true}}, false},
|
||||
{"operational", []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}, true},
|
||||
} {
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: tc.vols})
|
||||
body := read()
|
||||
if !body.Healthy || body.FrontendPrimaryReady != tc.want || (body.NotReadyReason == "") != tc.want {
|
||||
t.Errorf("%s: Healthy=%v FrontendPrimaryReady=%v NotReadyReason=%q, want Healthy (the authority view), ready=%v, a reason exactly when not ready", tc.name, body.Healthy, body.FrontendPrimaryReady, body.NotReadyReason, tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
// The NVMe listener mask does not hide the backend's reason: with the
|
||||
// target not yet listening AND the backend fenced, the reason is the
|
||||
// backend's; with only the listener pending, it says so.
|
||||
s.SetNVMeListenerReady(false)
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: false, Evidence: "chunk layer attach refused"}}})
|
||||
if body := read(); body.FrontendPrimaryReady || body.NotReadyReason != "durable backend admits no I/O: frontend: volume not ready: chunk layer attach refused" {
|
||||
t.Errorf("listener pending + fenced: ready=%v reason=%q, want the backend's reason", body.FrontendPrimaryReady, body.NotReadyReason)
|
||||
}
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}})
|
||||
if body := read(); body.FrontendPrimaryReady || body.NotReadyReason != "frontend target not listening yet" {
|
||||
t.Errorf("listener pending only: ready=%v reason=%q", body.FrontendPrimaryReady, body.NotReadyReason)
|
||||
}
|
||||
s.SetNVMeListenerReady(true)
|
||||
}
|
||||
|
||||
// INV-FE-PRIMARY-READY-OPERATIONAL-001: whenever FrontendPrimaryReady is
|
||||
// false, NotReadyReason is set, also when the authority view itself is not a
|
||||
// healthy primary (an observed process before its assignment).
|
||||
func TestStatusServer_NotReadyAlwaysHasAReason(t *testing.T) {
|
||||
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
|
||||
addr, err := s.Start("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
defer func() { _ = s.Close(context.Background()) }()
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}})
|
||||
resp, err := http.Get("http://" + addr + "/status?volume=v1")
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var body StatusProjection
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if body.FrontendPrimaryReady || body.NotReadyReason == "" {
|
||||
t.Fatalf("not-ready authority view: ready=%v reason=%q, want not ready with a reason", body.FrontendPrimaryReady, body.NotReadyReason)
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func statusWarningsCase(t *testing.T, view *AdapterProjectionView, wantHealthy b
|
||||
t.Fatalf("before the warning: healthy=%t ready=%t; want %t", before.Healthy, before.FrontendPrimaryReady, wantHealthy)
|
||||
}
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{
|
||||
VolumeID: "v1", Impl: "walstore", Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1,
|
||||
VolumeID: "v1", Impl: "walstore", Operational: true, Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1,
|
||||
}}})
|
||||
after := get()
|
||||
if len(after.Warnings) != 1 || after.Warnings[0][:18] != "wal_hole_suspected" {
|
||||
|
||||
@@ -46,6 +46,9 @@ type WorkspaceLeaseGuard struct {
|
||||
// Run from its sleep.
|
||||
stopPending bool
|
||||
kick chan struct{}
|
||||
// refusedBeforeGrant counts failed renewals before the first grant
|
||||
// (under mu), for the one grant log line.
|
||||
refusedBeforeGrant int
|
||||
// after schedules Run's sleep between renewals (time.After; tests
|
||||
// replace it before Run starts to observe the delays chosen).
|
||||
after func(time.Duration) <-chan time.Time
|
||||
@@ -57,6 +60,10 @@ type WorkspaceLeaseGuard struct {
|
||||
// revocation to its ACK also includes that renewal, the drain and the ACK.
|
||||
const stopPendingPoll = 250 * time.Millisecond
|
||||
|
||||
// WorkspaceDrainTimeout is the existing fail-closed lease drain bound.
|
||||
// INV-WS-STARTUP-RETRY-001 also bounds the process cleanup by this duration.
|
||||
const WorkspaceDrainTimeout = 5 * time.Second
|
||||
|
||||
// StopPending records that a graceful stop of this workspace has begun (the
|
||||
// chunk layer is being detached) and wakes Run to renew at once; while it
|
||||
// stays pending Run sleeps at most stopPendingPoll between renewals.
|
||||
@@ -156,10 +163,23 @@ func (g *WorkspaceLeaseGuard) Projection() frontend.Projection {
|
||||
func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.heldLocked() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch
|
||||
}
|
||||
|
||||
// Held reports whether the lease is granted and valid now (the lease term of
|
||||
// permits, without the projection identity). Never call with mu held.
|
||||
func (g *WorkspaceLeaseGuard) Held() bool {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.heldLocked()
|
||||
}
|
||||
|
||||
// heldLocked latches the expiry fence; the caller owns mu.
|
||||
func (g *WorkspaceLeaseGuard) heldLocked() bool {
|
||||
if !g.until.IsZero() && !g.now().Before(g.until) {
|
||||
g.fenceLocked(fmt.Sprintf("lease expired at %s without a successful renewal", g.until.UTC().Format(time.RFC3339Nano)))
|
||||
}
|
||||
return !g.fenced && !g.until.IsZero() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch
|
||||
return !g.fenced && !g.until.IsZero()
|
||||
}
|
||||
|
||||
// Refresh anchors validity to the request START. Reply latency can only shorten
|
||||
@@ -193,6 +213,9 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
|
||||
elapsed := end.Sub(start).Round(time.Millisecond)
|
||||
hit := renewalLimitHit(start, end, until)
|
||||
g.mu.Lock()
|
||||
if g.until.IsZero() {
|
||||
g.refusedBeforeGrant++
|
||||
}
|
||||
expired := !g.until.IsZero() && !end.Before(g.until)
|
||||
if expired {
|
||||
g.fenceLocked(fmt.Sprintf("lease expired after a failed renewal (renewal failed after %s, %s: %v)", elapsed, hit, err))
|
||||
@@ -231,6 +254,8 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
|
||||
case rpcCtx.Err() != nil:
|
||||
g.fenceLocked(fmt.Sprintf("renewal reply arrived after the renewal call's context ended (renewal took %s; lease still valid until %s)", g.now().Sub(start).Round(time.Millisecond), g.until.UTC().Format(time.RFC3339Nano)))
|
||||
}
|
||||
firstGrant := !g.fenced && g.until.IsZero()
|
||||
refused := g.refusedBeforeGrant
|
||||
if !g.fenced {
|
||||
g.until = start.Add(time.Duration(reply.ValidForNs))
|
||||
}
|
||||
@@ -240,6 +265,18 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
|
||||
}
|
||||
closed := g.fenced
|
||||
g.mu.Unlock()
|
||||
if firstGrant && !closed {
|
||||
// Once per guard: the first grant, or the re-grant after refused
|
||||
// renewals (a restart before the forced-move barrier); unix_ms is the
|
||||
// request start, which the lease validity is anchored to. A first
|
||||
// reply that revokes (or arrives fenced) grants nothing: no line.
|
||||
what := "granted"
|
||||
if refused > 0 {
|
||||
what = fmt.Sprintf("re-granted after %d refused renewal(s)", refused)
|
||||
}
|
||||
log.Printf("workspace lease: %s volume=%s replica=%s epoch=%d valid for %s at unix_ms=%d",
|
||||
what, g.id.VolumeId, g.id.ReplicaId, g.id.Epoch, time.Duration(reply.ValidForNs), start.UnixMilli())
|
||||
}
|
||||
if closed {
|
||||
g.logFence()
|
||||
return g.drain(ctx, reply.Revoking)
|
||||
@@ -280,7 +317,7 @@ func (g *WorkspaceLeaseGuard) drainAfterFence(ctx context.Context, err error) er
|
||||
|
||||
func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error {
|
||||
if !g.stopped {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), WorkspaceDrainTimeout)
|
||||
gen, err := g.stop(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
// V1-SPEC r2.37: renewals refused before the first grant (a restart before the
|
||||
// forced-move barrier) leave the lease not held; the first successful renewal
|
||||
// is logged as a re-grant after the refused ones, with its time.
|
||||
func TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals(t *testing.T) {
|
||||
logs := captureLog(t)
|
||||
now := time.Unix(1000, 0)
|
||||
calls := 0
|
||||
client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) {
|
||||
calls++
|
||||
if calls <= 2 {
|
||||
return nil, errors.New("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second)}, nil
|
||||
}}
|
||||
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := g.Refresh(context.Background()); err == nil {
|
||||
t.Fatal("a refused renewal was not reported")
|
||||
}
|
||||
if g.Held() || g.Projection().Healthy {
|
||||
t.Fatal("the lease is held before any grant")
|
||||
}
|
||||
}
|
||||
if strings.Contains(logs.String(), "granted") {
|
||||
t.Fatalf("a grant was logged before any grant; log=%q", logs.String())
|
||||
}
|
||||
// One successful renewal: with the fake clock a second one would run
|
||||
// against a real-time context deadline in 1970.
|
||||
if err := g.Refresh(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !g.Held() || !g.Projection().Healthy {
|
||||
t.Fatal("the granted lease is not held")
|
||||
}
|
||||
out := logs.String()
|
||||
if n := strings.Count(out, "granted"); n != 1 || !strings.Contains(out, "workspace lease: re-granted after 2 refused renewal(s) volume=v replica=r epoch=1 valid for 10s at unix_ms=1000000") {
|
||||
t.Fatalf("want exactly one re-grant line with its time, got %d; log=%q", n, out)
|
||||
}
|
||||
now = now.Add(11 * time.Second)
|
||||
if g.Held() {
|
||||
t.Fatal("an expired lease is still held")
|
||||
}
|
||||
}
|
||||
|
||||
// A first reply that revokes grants nothing: after refused renewals, a valid
|
||||
// first reply with Revoking set fences the guard, is never held and logs no
|
||||
// grant line (the line is a readiness timing witness).
|
||||
func TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant(t *testing.T) {
|
||||
logs := captureLog(t)
|
||||
now := time.Unix(1000, 0)
|
||||
calls := 0
|
||||
client := workspaceTestClient{
|
||||
renew: func() (*control.WorkspaceLeaseFact, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return nil, errors.New("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second), Revoking: true}, nil
|
||||
},
|
||||
ack: func() error { return nil },
|
||||
}
|
||||
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = g.Refresh(context.Background())
|
||||
_ = g.Refresh(context.Background())
|
||||
if g.Held() || g.Projection().Healthy {
|
||||
t.Fatal("a revoking first reply left the lease held")
|
||||
}
|
||||
if out := logs.String(); strings.Contains(out, "granted") || !strings.Contains(out, "revoked by the master") {
|
||||
t.Fatalf("want no grant line and the revocation fence; log=%q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// V1-SPEC r2.37: a workspace primary reports NotReadyReason=lease_not_held,
|
||||
// first, while its guard is missing or holds no granted lease, even with the
|
||||
// backend admitting I/O; ready once the lease is held; lease_not_held again
|
||||
// after the guard fences.
|
||||
func TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}}
|
||||
view := NewAdapterProjectionView(p, "v1", "r1", nil)
|
||||
view.workspaceRequired = true
|
||||
s := NewStatusServer(view)
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}})
|
||||
check := func(name string, wantReady bool) {
|
||||
t.Helper()
|
||||
got := s.statusProjection()
|
||||
if got.FrontendPrimaryReady != wantReady || (!wantReady && got.NotReadyReason != NotReadyLeaseNotHeld) || (wantReady && got.NotReadyReason != "") {
|
||||
t.Errorf("%s: ready=%v reason=%q, want ready=%v (reason %q when not ready)", name, got.FrontendPrimaryReady, got.NotReadyReason, wantReady, NotReadyLeaseNotHeld)
|
||||
}
|
||||
}
|
||||
check("no guard installed", false)
|
||||
g, err := NewWorkspaceLeaseGuard(view, workspaceTestClient{}, &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return now })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view.workspaceGuard.Store(g)
|
||||
check("guard without a grant", false)
|
||||
g.mu.Lock()
|
||||
g.until = now.Add(10 * time.Second)
|
||||
g.mu.Unlock()
|
||||
check("lease held", true)
|
||||
g.mu.Lock()
|
||||
g.fenceLocked("test: revoked")
|
||||
g.mu.Unlock()
|
||||
check("guard fenced", false)
|
||||
}
|
||||
@@ -43,7 +43,14 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
|
||||
h.workspaceLeaseMu.Lock()
|
||||
// The guard is not yet shared: publish it already fenced if a
|
||||
// synchronous shutdown won the race with this installer.
|
||||
guard.fenced = h.workspaceLeaseFenced || ctx.Err() != nil
|
||||
if prior := h.view.workspaceGuard.Load(); prior != nil {
|
||||
// Before this one-shot install, only FenceWorkspaceLease can
|
||||
// publish a guard: its terminal cause must survive installation.
|
||||
guard.fenceLocked(prior.FenceCause())
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
guard.fenceLocked("shutdown requested (context cancelled)")
|
||||
}
|
||||
guard.stopPending = h.workspaceStopPending
|
||||
h.view.workspaceGuard.Store(guard)
|
||||
h.workspaceLeaseMu.Unlock()
|
||||
@@ -103,10 +110,26 @@ func (h *Host) WorkspaceStopResumed(volumeID string, attempt uint64) {
|
||||
func (h *Host) FenceWorkspaceLease() {
|
||||
h.workspaceLeaseMu.Lock()
|
||||
defer h.workspaceLeaseMu.Unlock()
|
||||
h.workspaceLeaseFenced = true
|
||||
if g := h.view.workspaceGuard.Load(); g != nil {
|
||||
g.mu.Lock()
|
||||
g.fenced = true
|
||||
g.mu.Unlock()
|
||||
// INV-WS-STARTUP-RETRY-001: the guard owns the only terminal latch,
|
||||
// including shutdown before its runtime installation.
|
||||
g := h.view.workspaceGuard.Load()
|
||||
if g == nil {
|
||||
g = &WorkspaceLeaseGuard{}
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.fenceLocked("host shutdown requested")
|
||||
g.mu.Unlock()
|
||||
h.view.workspaceGuard.Store(g)
|
||||
}
|
||||
|
||||
// WorkspaceLeaseRevoking distinguishes the ACK-owning planned drain from a
|
||||
// retryable fence without interpreting an error string (M2 Revoking -> Revoked).
|
||||
func (h *Host) WorkspaceLeaseRevoking() bool {
|
||||
g := h.view.workspaceGuard.Load()
|
||||
if g == nil {
|
||||
return false
|
||||
}
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.revoked
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package volume
|
||||
|
||||
import control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
|
||||
// INV-WS-STARTUP-RETRY-001: remember the newest assignment observed for us,
|
||||
// including one whose local readiness admission subsequently refuses.
|
||||
func (h *Host) recordSelfAssignment(f *control.AssignmentFact) {
|
||||
if f.VolumeId != h.cfg.VolumeID {
|
||||
return
|
||||
}
|
||||
h.ownAssignmentMu.Lock()
|
||||
defer h.ownAssignmentMu.Unlock()
|
||||
if f.Epoch > h.ownAssignmentEpoch || f.Epoch == h.ownAssignmentEpoch && f.EndpointVersion > h.ownAssignmentEV {
|
||||
h.ownAssignmentEpoch, h.ownAssignmentEV = f.Epoch, f.EndpointVersion
|
||||
}
|
||||
}
|
||||
|
||||
// IsCurrentReplicaSuperseded reuses the authority predicate with the newest
|
||||
// observed own lineage, zero before any own assignment. Keep that lineage
|
||||
// stable through the comparison; a historical other line alone cannot mean78.
|
||||
// This is exit classification only: frontend admission keeps its own lineage.
|
||||
func (h *Host) IsCurrentReplicaSuperseded() bool {
|
||||
h.ownAssignmentMu.RLock()
|
||||
defer h.ownAssignmentMu.RUnlock()
|
||||
return h.IsSuperseded(h.cfg.ReplicaID, h.ownAssignmentEpoch, h.ownAssignmentEV)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWorkspaceExitLineageIncludesBlockedOwnAssignment(t *testing.T) {
|
||||
h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{})
|
||||
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "other", Epoch: 6, EndpointVersion: 1})
|
||||
// Zero observed-own lineage inherits the fencing predicate's zero rule:
|
||||
// a never-assigned process retries75; it has no own incarnation to supersede.
|
||||
if h.IsCurrentReplicaSuperseded() {
|
||||
t.Fatal("never-assigned process must retry75 despite a foreign line")
|
||||
}
|
||||
h.BlockLocalReadiness("local recovery pending")
|
||||
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 7, EndpointVersion: 1})
|
||||
if h.IsCurrentReplicaSuperseded() {
|
||||
t.Fatal("blocked own assignment left historical other line current for exit")
|
||||
}
|
||||
// Exit classification must not change frontend admission at its old lineage.
|
||||
if !h.IsSuperseded("r", 5, 1) {
|
||||
t.Fatal("exit observation weakened serving supersede predicate")
|
||||
}
|
||||
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 4, EndpointVersion: 1})
|
||||
if h.IsCurrentReplicaSuperseded() {
|
||||
t.Fatal("older own delivery lowered the exit lineage")
|
||||
}
|
||||
h.recordOtherLine(&control.AssignmentFact{VolumeId: "other-volume", ReplicaId: "other", Epoch: 99})
|
||||
if h.IsCurrentReplicaSuperseded() {
|
||||
t.Fatal("another volume produced a no-retry outcome")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceEmptyOtherReplicaNeverSelectsNoRetry(t *testing.T) {
|
||||
h, _, _ := newStubbedHost(t, "v", "r", &orderingRecorder{})
|
||||
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "r", Epoch: 5, EndpointVersion: 1})
|
||||
h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v", ReplicaId: "", Epoch: 7, EndpointVersion: 1})
|
||||
if h.IsCurrentReplicaSuperseded() {
|
||||
t.Fatal("empty replica id is not another holder; must retry")
|
||||
}
|
||||
}
|
||||
|
||||
// The two Part T facts are intentionally different: a validated assignment can
|
||||
// be observed while local recovery prevents the engine from adopting it.
|
||||
func TestWorkspaceExitAndFenceUseNamedLineages(t *testing.T) {
|
||||
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "self", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = h.Close() })
|
||||
fencer := &holderFenceCounter{}
|
||||
if err := h.SetSelfFence(fencer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.BlockLocalReadiness("local recovery pending")
|
||||
foreign := holderAssignment(t, "other")
|
||||
foreign.Epoch = 6
|
||||
h.applyFact(foreign)
|
||||
if h.IsCurrentReplicaSuperseded() || h.IsSuperseded("r1", 0, 0) || fencer.calls.Load() != 0 {
|
||||
t.Fatal("foreign same-replica server must select retry75 and no fence before any own assignment")
|
||||
}
|
||||
own := holderAssignment(t, "self")
|
||||
own.Epoch = 7
|
||||
h.applyFact(own)
|
||||
if h.view.EngineProjection().Epoch != 0 || h.IsCurrentReplicaSuperseded() || fencer.calls.Load() != 0 {
|
||||
t.Fatal("observed own7 must suppress historical foreign6 for exit while adopted lineage stays zero")
|
||||
}
|
||||
foreign.Epoch = 8
|
||||
h.applyFact(foreign)
|
||||
if !h.IsCurrentReplicaSuperseded() || h.IsSuperseded("r1", 0, 0) || fencer.calls.Load() != 0 {
|
||||
t.Fatal("foreign8 must supersede observed own7 without changing the unadopted fencing rule")
|
||||
}
|
||||
}
|
||||
|
||||
// Check at the adoption handoff, not just after applyFact: moving observation
|
||||
// after adapter adoption must fail even when the eventual snapshots match.
|
||||
type observationCheckedAdoption struct {
|
||||
assignmentConsumer
|
||||
before func(adapter.AssignmentInfo)
|
||||
}
|
||||
|
||||
func (a observationCheckedAdoption) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog {
|
||||
a.before(info)
|
||||
return a.assignmentConsumer.OnAssignment(info)
|
||||
}
|
||||
|
||||
func TestWorkspaceObservedLineageNeverTrailsAdoption(t *testing.T) {
|
||||
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "self", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = h.Close() })
|
||||
check := func(epoch, ev uint64) {
|
||||
t.Helper()
|
||||
h.ownAssignmentMu.RLock()
|
||||
defer h.ownAssignmentMu.RUnlock()
|
||||
if h.ownAssignmentEpoch < epoch || h.ownAssignmentEpoch == epoch && h.ownAssignmentEV < ev {
|
||||
t.Fatalf("observation trails adoption handoff: observed=%d/%d adopted=%d/%d", h.ownAssignmentEpoch, h.ownAssignmentEV, epoch, ev)
|
||||
}
|
||||
}
|
||||
adoptions := 0
|
||||
h.adpt = observationCheckedAdoption{h.adpt, func(info adapter.AssignmentInfo) {
|
||||
check(info.Epoch, info.EndpointVersion)
|
||||
adoptions++
|
||||
}}
|
||||
assertAdopted := func(epoch, ev uint64) {
|
||||
t.Helper()
|
||||
p := h.view.EngineProjection()
|
||||
if p.Epoch != epoch || p.EndpointVersion != ev {
|
||||
t.Fatalf("adopted=%d/%d want=%d/%d", p.Epoch, p.EndpointVersion, epoch, ev)
|
||||
}
|
||||
check(p.Epoch, p.EndpointVersion)
|
||||
}
|
||||
own := holderAssignment(t, "self")
|
||||
own.Epoch = 3
|
||||
h.applyFact(own)
|
||||
assertAdopted(3, 1)
|
||||
h.BlockLocalReadiness("local recovery pending")
|
||||
own.Epoch = 7
|
||||
h.applyFact(own)
|
||||
own.EndpointVersion = 2
|
||||
h.applyFact(own)
|
||||
check(7, 2)
|
||||
assertAdopted(3, 1)
|
||||
h.ClearLocalReadinessBlock()
|
||||
h.replayLocalReadinessFactIfReady()
|
||||
assertAdopted(7, 2)
|
||||
foreign := holderAssignment(t, "other")
|
||||
foreign.Epoch = 8
|
||||
h.applyFact(foreign)
|
||||
assertAdopted(7, 2)
|
||||
own.Epoch = 9
|
||||
h.applyFact(own)
|
||||
assertAdopted(9, 2)
|
||||
own.Epoch = 7
|
||||
h.applyFact(own)
|
||||
assertAdopted(9, 2)
|
||||
if adoptions != 3 {
|
||||
t.Fatalf("adoption handoffs=%d want3 (initial, readiness replay, move back)", adoptions)
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,9 @@ func TestWorkspaceFenceBeforeHeldInstallIsTerminal(t *testing.T) {
|
||||
_ = runtimeDone(t, done)
|
||||
t.Fatal("fenced installer did not settle")
|
||||
}
|
||||
if g := h.view.workspaceGuard.Load(); g == nil || g.FenceCause() != "host shutdown requested" {
|
||||
t.Fatal("installation lost the synchronous fence cause")
|
||||
}
|
||||
if stops.Load() != 1 || h.ProjectionView().Projection().Healthy {
|
||||
t.Fatal("fence failed to stop installed guard", stops.Load())
|
||||
}
|
||||
@@ -76,3 +79,41 @@ func TestWorkspaceCanceledReplyCannotPublishGrant(t *testing.T) {
|
||||
t.Error("canceled reply published a serving grant")
|
||||
}
|
||||
}
|
||||
|
||||
// A synchronous host fence must use the guard's first-cause latch even
|
||||
// before runtime publication; installation must carry that terminal cause.
|
||||
func TestWorkspaceHostFencePublishesOneTerminalCause(t *testing.T) {
|
||||
h := workspaceRuntimeHost(t, runtimeWire(t, &runtimeLeaseServer{ttl: time.Second}), true)
|
||||
h.FenceWorkspaceLease()
|
||||
g := h.view.workspaceGuard.Load()
|
||||
if g == nil {
|
||||
t.Fatal("host fence has no guard-owned terminal cause")
|
||||
}
|
||||
first := g.FenceCause()
|
||||
if first == "" {
|
||||
t.Fatal("host fence bypassed the guard first-cause latch")
|
||||
}
|
||||
h.FenceWorkspaceLease()
|
||||
if g.FenceCause() != first || h.ProjectionView().Projection().Healthy {
|
||||
t.Fatal("repeated fence changed cause or reopened admission")
|
||||
}
|
||||
}
|
||||
func TestWorkspaceInstalledHostFenceRecordsCause(t *testing.T) {
|
||||
wire := &runtimeLeaseServer{ttl: time.Second}
|
||||
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
t.Cleanup(func() { cancel(); _ = runtimeDone(t, done) })
|
||||
go func() {
|
||||
done <- h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 7, nil })
|
||||
}()
|
||||
runtimeAwait(t, "installed serving lease", func() bool { return h.ProjectionView().Projection().Healthy })
|
||||
g := h.view.workspaceGuard.Load()
|
||||
h.FenceWorkspaceLease()
|
||||
if g.FenceCause() == "" {
|
||||
t.Error("installed host fence bypassed fenceLocked")
|
||||
}
|
||||
if h.ProjectionView().Projection().Healthy {
|
||||
t.Error("host fence still admits I/O")
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
// persist lazy-read absence before exposing the local volume for I/O.
|
||||
// No WALStore, layer-state or provider-map lock is held across remote calls;
|
||||
// the provider may hold its per-volume attach serialization lock.
|
||||
// On a proven owner fence, the returned HEAD is the exact observed proof;
|
||||
// it is not an installed claim and must never be used to serve I/O.
|
||||
func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfig) (ChunkHead, error) {
|
||||
if remote == nil || cfg.Epoch == 0 || cfg.Holder == "" {
|
||||
return ChunkHead{}, errors.New("storage: HEAD claim needs master epoch and holder")
|
||||
@@ -35,7 +37,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi
|
||||
return ChunkHead{}, err
|
||||
}
|
||||
if head.Epoch > cfg.Epoch || (head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder != cfg.Holder) {
|
||||
return ChunkHead{}, ErrChunkLayerFenced
|
||||
return copyHead(head), ErrChunkLayerFenced
|
||||
}
|
||||
// INV-WS-SEALED-REOPEN-001: the sealing incarnation cannot reopen its
|
||||
// committed handoff proof. A higher-epoch takeover remains a separate claim.
|
||||
@@ -113,7 +115,7 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi
|
||||
}
|
||||
// A foreign publication is a fence, not permission to clean our roots.
|
||||
if current.Gen != 0 && (current.Epoch != head.Epoch || current.Holder != head.Holder) {
|
||||
return ChunkHead{}, fmt.Errorf("storage: HEAD claim displaced: %w", ErrChunkLayerFenced)
|
||||
return copyHead(current), fmt.Errorf("storage: HEAD claim displaced: %w", ErrChunkLayerFenced)
|
||||
}
|
||||
settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen
|
||||
return ChunkHead{}, fmt.Errorf("storage: HEAD claim not installed: %w", casErr)
|
||||
|
||||
@@ -39,7 +39,8 @@ SWB_MASTER_WORKSPACE_HEAD_BASE_URL=
|
||||
# --workspace-max-clock-skew (default 20s; must be >0 and <60s). Host leases
|
||||
# shorten by half of it; forced moves wait the full bound.
|
||||
SWB_MASTER_WORKSPACE_MAX_CLOCK_SKEW=20s
|
||||
# Extra blockmaster flags, split on spaces. The --launcher-*, --lifecycle-*,
|
||||
# --cluster-spec, --failback-runtime-rpc and --frontend-publication-runtime-*
|
||||
# flags belong to the Kubernetes path and are set by the Helm chart.
|
||||
# Extra blockmaster flags, split on spaces.
|
||||
# A standalone workspace volume (lease, planned hand-over) needs --cluster-spec,
|
||||
# --lifecycle-store and the --workspace-* flags here: see docs/volume-lifecycle.md.
|
||||
# Kubernetes launcher/runtime flags are configured separately by the Helm chart.
|
||||
SWB_MASTER_EXTRA_ARGS=
|
||||
@@ -69,6 +69,7 @@ ExecStart=/usr/local/bin/blockvolume \
|
||||
KillSignal=SIGTERM
|
||||
TimeoutStopSec=30s
|
||||
Restart=on-failure
|
||||
RestartPreventExitStatus=78
|
||||
RestartSec=5s
|
||||
|
||||
NoNewPrivileges=true
|
||||
|
||||
@@ -68,6 +68,7 @@ ExecStart=/usr/local/bin/blockvolume \
|
||||
KillSignal=SIGTERM
|
||||
TimeoutStopSec=30s
|
||||
Restart=on-failure
|
||||
RestartPreventExitStatus=78
|
||||
RestartSec=5s
|
||||
|
||||
NoNewPrivileges=true
|
||||
|
||||
@@ -479,3 +479,61 @@ stateDiagram-v2
|
||||
```
|
||||
|
||||
Guest I/O never acquires a slot. An unavailable pool skips background cuts; urgent and named seals may use per-process fallback with an alarm. Active coordinated reservations exclude orphaned crash spill. Upload pacing debt survives leases in one process, but a new process starts fresh, so arbitrary process turnover has no fixed host-rate bound.
|
||||
|
||||
### Workspace primary supervisor retry
|
||||
|
||||
A workspace chunk primary that exhausts its existing assignment wait, or whose
|
||||
lease fences while serving, exits 75 after fail-closed cleanup bounded by the
|
||||
existing five-second lease-drain limit. systemd restarts on failure with
|
||||
RestartSec=5s. A newer master fact naming another replica or a refused claim proving another
|
||||
HEAD holder permits exit 78;
|
||||
RestartPreventExitStatus=78 suppresses automatic restarts until an operator
|
||||
explicitly starts the unit. A higher epoch for the same replica retries.
|
||||
A HEAD fence after the target listens (the attached chunk layer finds HEAD owned
|
||||
by another publisher while the lease may still be valid) is independent of the
|
||||
lease and exits 78 `head_fenced` (INV-FE-FENCE-EXIT-001).
|
||||
An ACKed planned revocation and a signal stop retain their normal exit status.
|
||||
Sealed same-epoch recovery stays non-serving for seal replay after assignment.
|
||||
Local-root, WAL-corruption and I/O diagnostics retain their existing wait.
|
||||
No restart bypasses the master barrier, durable re-grant, or HEAD claim.
|
||||
See M2 and INV-WS-STARTUP-RETRY-001 in the invariant ledger.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> AwaitingAssignment
|
||||
AwaitingAssignment --> Serving: grant and HEAD claim
|
||||
AwaitingAssignment --> Exit75: assignment wait exhausted
|
||||
Serving --> Exit75: lease fence
|
||||
AwaitingAssignment --> Exit78: newer other-replica fact or exact foreign-holder HEAD claim proof
|
||||
Serving --> Exit78: lease fence and newer other-replica fact
|
||||
Serving --> Exit78: runtime HEAD fence (another publication owner), head_fenced
|
||||
Exit75 --> AwaitingAssignment: supervisor starts new process
|
||||
Exit78 --> AwaitingAssignment: explicit operator start
|
||||
AwaitingAssignment --> SealedReplay: assigned same-epoch sealed HEAD
|
||||
SealedReplay --> Exit75: lease fence
|
||||
SealedReplay --> [*]: signal
|
||||
AwaitingAssignment --> Draining: planned revoke owns shutdown; retire startup watcher
|
||||
Serving --> Draining: planned revoke owns shutdown
|
||||
SealedReplay --> Draining: planned revoke owns shutdown
|
||||
Draining --> [*]: stored detached proof and revoke ACK
|
||||
Draining --> Exit75: ACK unconfirmed
|
||||
Serving --> [*]: signal
|
||||
```
|
||||
|
||||
GAP-1 exit classification compares a newer other-replica fact with the newest own assignment this process observed, including a locally blocked assignment; historical other facts do not suppress restart. The shared `Host.IsSuperseded` predicate is reused without changing frontend admission. An unconfirmed revocation ACK exits75 with `revoke_ack_unconfirmed`. Restart can retry ACK only while the original revoking lease remains valid; after expiry the revoking/recorded-ACK re-grant guards still refuse, so restart alone cannot resolve that case and operator recovery is required.
|
||||
|
||||
Once the resource owner accepts a stop request, startup-monitor cancellation and startup exit choice serialize on the process owner's startup mutex. A delayed startup deadline cannot replace planned drain ownership; success remains unselected until the real guard confirms the stored detached proof's ACK. A wait that already chose sealed replay or stale-local-root diagnostics keeps that disposition even if its context expires at return.
|
||||
|
||||
A refused HEAD claim returns its exact observed image as failure evidence, never
|
||||
an installed claim. Only a nonempty foreign holder in that fenced image permits
|
||||
no-retry independently of the assignment stream. Higher epochs of the same
|
||||
holder and fences without that proof retain retry75. Provider generation checks
|
||||
and planned-stop arbitration still apply; no readiness or listen gate changes
|
||||
belong to this classification fix.
|
||||
|
||||
The existing-local-root precheck uses the same distinction: another holder at
|
||||
or above the assigned epoch is positive supersede evidence; an older foreign
|
||||
publication remains the existing move-back diagnostic. Neither path serves or
|
||||
publishes the local WAL, which remains on disk for diagnosis.
|
||||
|
||||
Part T ownership: the lease guard alone holds the terminal fence and its first cause. A host shutdown before runtime installation publishes only a fenced, zero-validity guard; installation carries that cause into the valid-identity guard and never renews it. Startup and runtime exit callers both use workspaceRetryOutcome; only startup can supply a generation-bound refused-claim HEAD proof.
|
||||
@@ -46,7 +46,8 @@ The local storage engine and the durable backend in front of it. Diagrams in the
|
||||
stateDiagram-v2
|
||||
[*] --> Opened: OpenWALStore / CreateWALStore
|
||||
Opened --> Recovering: RecoverVolume
|
||||
Recovering --> Serving: Recover ok, backend operational
|
||||
Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready
|
||||
Serving --> Closed: runtime HEAD fence, exit 78 head_fenced
|
||||
Recovering --> RecoveryFailed: Recover error (typed reason)
|
||||
Serving --> Serving: map prepare refused (prior root released, no latch, retry)
|
||||
Serving --> FaultLatched: fsync or WAL append fails
|
||||
@@ -60,13 +61,14 @@ stateDiagram-v2
|
||||
|---|---|---|---|---|
|
||||
| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` |
|
||||
| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` |
|
||||
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001` |
|
||||
| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001` |
|
||||
| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` |
|
||||
| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` |
|
||||
| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` |
|
||||
| Serving | Serving (map prepare refused) | a map preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) captured prior and a publication released it before the prepare's live-set snapshot: the prepare reuses no page, writes nothing, refuses with `prior_released` without latching, counts it, and the caller's next cycle prepares from the current root | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3` | `INV-WAL-V3-MAP-PRIOR-LIVE-001` |
|
||||
| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` |
|
||||
| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` |
|
||||
| Serving | Closed (process exit 78 `head_fenced`) | workspace chunk primary: the attached layer fenced after startup (HEAD has another publication owner); I/O is refused from the fence, the backend latches not operational with the evidence, and the process owner chooses the no-restart exit | `core/frontend/durable/provider_startup.go` `watchChunkFence`; `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` | `INV-FE-FENCE-EXIT-001` |
|
||||
| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — |
|
||||
|
||||
The v2 writer, scanner, checkpoint path, C11 codec/reconciler and in-place converter are retired. Native map and descriptor rules remain enforced; v2 inputs refuse open without mutation. `TestNativeReplacementLegacyBytesRefusedWithoutMutation` and `TestChunkAttachRefusesAnUnmappedNativeStore` cover these admission boundaries. The receiver session bitmap is separate and unchanged.
|
||||
@@ -135,6 +137,7 @@ a pre-issued publication.
|
||||
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` |
|
||||
| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` |
|
||||
| Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
|
||||
| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait or lease fence exits 75 after bounded cleanup; a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` |
|
||||
| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
|
||||
| Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
|
||||
|
||||
@@ -224,7 +227,7 @@ stateDiagram-v2
|
||||
| From | To | Guard | Enforced in | Protects |
|
||||
|---|---|---|---|---|
|
||||
| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001` |
|
||||
| Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` |
|
||||
| NoLease, Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, the lease is revoking, or synchronous host shutdown fences through the guard; first cause is kept and a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh`, `fenceLocked`; `core/host/volume/workspace_runtime.go` `FenceWorkspaceLease` | `INV-WS-LEASE-001` |
|
||||
| Valid | StopPending | a chunk detach of this volume starts (before its drain); the guard renews at once. Scheduling only: StopPending admits, fences and ACKs exactly as Valid | `core/frontend/durable/provider_chunk.go` `DetachVolume`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`; `core/host/volume/workspace_lease.go` `StopPending` | `INV-WS-STOP-PENDING-001` |
|
||||
| StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` |
|
||||
| StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` |
|
||||
@@ -446,7 +449,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
|
||||
|
||||
## Part B. Invariant ledger
|
||||
|
||||
308 rows: 237 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 293 new.
|
||||
312 rows: 241 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 297 new.
|
||||
|
||||
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
|
||||
|
||||
@@ -460,6 +463,9 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
|
||||
| `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE |
|
||||
| `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE |
|
||||
| `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 after the start-time wait. | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and `FrontendPrimaryReady`); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; V1-SPEC r2.39); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`) | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore`, `TestFirstAdmittedStopEndsTheWorker` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE |
|
||||
| `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE |
|
||||
| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE |
|
||||
| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE |
|
||||
@@ -713,6 +719,15 @@ Notes:
|
||||
| `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_chunk.go` `claimHeadSupersedes`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE |
|
||||
|
||||
- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process.
|
||||
- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal.
|
||||
- Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75.
|
||||
- Part T fence ownership: `Host.FenceWorkspaceLease` uses `WorkspaceLeaseGuard.fenceLocked`, including before runtime publication; the zero-validity terminal guard preserves the first cause through installation and can grant no I/O. No second host fence latch exists. `TestWorkspaceHostFencePublishesOneTerminalCause`, `TestWorkspaceInstalledHostFenceRecordsCause`, `TestWorkspaceFenceBeforeHeldInstallIsTerminal` (`core/host/volume/workspace_terminal_test.go`).
|
||||
- Startup arbitration: sealed-replay/stale-local-root dispositions suppress the same wait's deadline defer (`TestChunkStartupRetainedDispositionWinsExpiredAttachContext`, `core/frontend/durable/provider_startup_outcome_test.go`). A stop request retires startup monitoring and its atomic-choice callback before resource cleanup; success is chosen only after the guard's ACK (`TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck`, `cmd/blockvolume/process_exit_authority_test.go`). Provider-validated startup selection briefly takes the process startup mutex; cancellation takes only that mutex. No reverse provider-lock acquisition or remote call occurs.
|
||||
|
||||
- ACK closeout: the guard sets `revoked` under its mutex before calling `drain` and invoking the stop callback. After a drain reply, its ACK call is bounded by the original lease deadline and 2 s RPC timeout. The existing 3 s closeout wait therefore expires before a newly selected retry's 5 s supervisor bound starts; a prior nonzero decision remains immutable. A restart can ACK the sealed HEAD only while the original revoking lease is still valid. Once it expires, re-grant refuses revoking/ACKed leases: repeated 75 is not recovery of an unconfirmed ACK, and operator recovery is required; no lease or ACK gate is bypassed.
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -969,6 +984,12 @@ One row per wait in the data and control paths. Guest-visible rows on one path m
|
||||
| Site | Waits for | Bound | Owner that ends it | On expiry | Lock held while waiting | Guest-visible |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) |
|
||||
| `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) |
|
||||
| `cmd/blockvolume/frontend_gate.go` `firstAdmitted` (one goroutine from `runVolume`, workspace chunk primaries only) | the backend's first admitted I/O (`FirstServing`), then `AdmitsIO` passing, re-checked every 50 ms (the backend has no projection-change signal) | until first served or the process outcome (`e.done`), whichever comes first | the process exit owner (`superviseProcess`) through `e.done` | none: it ends without starting the frontends | none | no (no target listens yet) |
|
||||
| `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` (one goroutine from `runVolume`, started with the workspace lease guard before the frontends) | a signal, the lease guard's drain request or end, or the latched process outcome (startup, or a runtime HEAD fence) | the process lifetime | the process exit owner (`superviseProcess`, `INV-WS-STARTUP-RETRY-001`) | the chosen exit status (0 revoked/signal, 75 retry, 78 superseded or `head_fenced`) | none | no |
|
||||
| `cmd/blockvolume/main.go` `runVolume`, the receive of `stopWait` after the frontends started (when `awaitFrontendStart` released on first serving) | the one result of the `waitWorkspaceStop` goroutine (its only producer, a channel of capacity one it sends to exactly once) | the process lifetime, as `waitWorkspaceStop` | the process exit owner (`superviseProcess`) | shutdown with the handed-back lease drain request | none | no (the targets serve until the stop) |
|
||||
| `core/frontend/durable/provider_startup.go` `watchChunkFence` (one goroutine per attached chunk layer, started when the layer attaches) | the 50 ms ticker (then reads the layer's latched fence flag) or provider close (`closeCtx`) | the attached layer's lifetime: it returns at provider close, when the layer is no longer the volume's, or after publishing a fence; Close joins it (`p.inflight`) | `DurableProvider.Close` (cancels `closeCtx`, then waits `p.inflight`) | none: the ticker is its poll, not a deadline; a HEAD fence is published at most 50 ms after the layer latches it (I/O is refused from the latch) | none while waiting (`p.mu` only briefly to check the handle and publish) | no |
|
||||
| `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (one goroutine from `runVolume`, workspace chunk primaries) | the provider's runtime-fence wakeup (capacity one, `ChunkRuntimeFenceUpdates`), the process outcome (`e.done`) or the watch context | the process lifetime: it returns after choosing 78 `head_fenced`, when another outcome is chosen, or when `runVolume` cancels its watch context | the process exit owner (`superviseProcess`) | none | none | no |
|
||||
|
||||
Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step.
|
||||
|
||||
@@ -988,6 +1009,8 @@ Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed sc
|
||||
|
||||
| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work |
|
||||
|---|---|---|---|---|
|
||||
| Workspace revocation ACK closeout | M2 Revoking → Revoked; `INV-WS-STARTUP-RETRY-001` | Existing `workspaceLeaseCloseoutTimeout` (3 s), after the resource owner replies to the guard | `finishWorkspaceLease` owns the wait. ACK success selects normal exit; error/expiry selects 75 with `revoke_ack_unconfirmed`. The 5 s supervisor cleanup clock starts only after a nonzero outcome is selected. | No provider/storage lock held. |
|
||||
| Workspace primary retry cleanup | M2 restart; `INV-WS-STARTUP-RETRY-001` | Existing `WorkspaceDrainTimeout` (5 s) after retry/no-retry outcome selection | Process supervisor owns the deadline and returns 75 or 78 even if resource-owner cleanup blocks; first outcome stays latched. Signal and ACKed revocation retain normal exit. | Provider latches by recovery generation under p.mu; wake is nonblocking; the supervisor holds no provider/storage lock. |
|
||||
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
|
||||
| Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. |
|
||||
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
|
||||
|
||||
@@ -27,7 +27,8 @@ The volume's authority and health projection. Go type `volume.StatusProjection`.
|
||||
| `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) |
|
||||
| `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux |
|
||||
| `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux |
|
||||
| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary and may serve guest I/O. |
|
||||
| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary, its local durable backend admits I/O, and it may serve guest I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). |
|
||||
| `NotReadyReason` | string | NotReadyReason says why FrontendPrimaryReady is false, first match: a workspace primary holds no granted lease now (NotReadyLeaseNotHeld); the local durable backend admits no I/O (its evidence: attach pending, fenced, detached) or has no status for the volume; the frontend target is not listening yet; this replica is not the healthy primary. Empty when ready. (omitted when empty) |
|
||||
| `AuthorityRole` | string | AuthorityRole is primary, superseded or unknown. |
|
||||
| `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. |
|
||||
| `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) |
|
||||
|
||||
Reference in new issue
Block a user