Merge pull request #135 from seaweedfs/feat/blockvolume-workspace-lease

feat: self-fence workspace blockvolume on lease loss
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-15 14:03:17 -08:00
commit 95e32afc8a
14 files changed
+1127 -33

No files matched your search

+61 -15
View File
@@ -6,6 +6,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"net"
@@ -35,13 +36,14 @@ import (
)
type flags struct {
masterAddr string
serverID string
volumeID string
replicaID string
dataAddr string
ctrlAddr string
hbInterval time.Duration
masterAddr string
serverID string
volumeID string
replicaID string
dataAddr string
ctrlAddr string
hbInterval time.Duration
workspaceLease bool
// printReadyLine: test-only flag — emits one structured JSON
// line to stdout on the FIRST received assignment with
// Epoch > 0. L2 subprocess smoke uses this to assert route
@@ -148,6 +150,7 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)")
fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)")
fs.DurationVar(&f.hbInterval, "heartbeat-interval", 2*time.Second, "heartbeat send interval")
fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "walstore-chunk workspace: require host-owned master lease; fail closed when unavailable")
fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout on first assignment")
fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy")
fs.StringVar(&f.statusAddr, "status-addr", "", "address for the status HTTP endpoint (e.g. 127.0.0.1:0); empty disables")
@@ -230,6 +233,9 @@ func parseFlags(args []string) (flags, error) {
default:
return flags{}, fmt.Errorf("--durable-impl=%q invalid; want smartwal, walstore, parallel-walstore, or walstore-chunk", f.durableImpl)
}
if f.workspaceLease && (f.durableRoot == "" || f.durableImpl != "walstore-chunk") {
return flags{}, fmt.Errorf("--workspace-lease requires --durable-root and --durable-impl=walstore-chunk")
}
if err := validateChunkFlags(f); err != nil {
return flags{}, err
}
@@ -490,6 +496,7 @@ func run(f flags) int {
HeartbeatInterval: f.hbInterval,
ReadyMarker: readyCh,
EnableT1Readiness: f.enableT1Readiness,
WorkspaceLease: f.workspaceLease,
})
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume:", err)
@@ -538,6 +545,7 @@ func run(f flags) int {
// accept connections.
var provider frontend.Provider
var durableProv *durable.DurableProvider
var workspaceRemoteFor func(string) (storage.ChunkRemote, error)
if f.durableRoot != "" {
cfg := durable.ProviderConfig{
Impl: durable.ImplName(f.durableImpl),
@@ -557,6 +565,7 @@ func run(f flags) int {
cfg.ChunkHolder = chunkHolder(f)
if chunkErr == nil {
cfg.ChunkRemoteFor = chunk.remoteFor
workspaceRemoteFor = chunk.remoteFor
cfg.ChunkAttachCheck = chunkAttachCheck(chunk.catalog)
defer chunk.close()
}
@@ -1110,15 +1119,35 @@ func run(f flags) int {
}
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
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:
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
// exact drain; it cannot ACK a merely requested or failed close.
h.FenceWorkspaceLease()
var drainErr error
if leaseStop != nil && durableProv != nil {
drainErr = durableProv.Backend(f.volumeID).StopIO(leaseStop.ctx, "workspace lease fenced")
}
h.SetFrontendTargets(nil)
if nvmeTarget != nil {
_ = nvmeTarget.Close()
drainErr = errors.Join(drainErr, nvmeTarget.Close())
}
if iscsiTarget != nil {
_ = iscsiTarget.Close()
drainErr = errors.Join(drainErr, iscsiTarget.Close())
}
// Tear down replication BEFORE durable storage close (LIFO
// listener lifecycle). Listener closes its accept loop +
@@ -1130,19 +1159,36 @@ func run(f flags) int {
replListen.Stop()
}
if replVolume != nil {
_ = replVolume.Close()
drainErr = errors.Join(drainErr, replVolume.Close())
}
// T3b: close DurableProvider in correct order — Provider.Close
// closes backends first (flags them closed) then storage files
// (releases fd + final fsync).
if durableProv != nil {
_ = durableProv.Close()
drainErr = errors.Join(drainErr, durableProv.Close())
}
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
if leaseStop != nil {
gen := uint64(0)
if drainErr == nil {
gen, drainErr = workspaceDetachedGeneration(leaseStop.ctx, workspaceRemoteFor, leaseStop.id, chunkHolder(f))
}
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")
}
}
if err := h.Close(); err != nil {
fmt.Fprintln(os.Stderr, "blockvolume: close:", err)
return 1
@@ -0,0 +1,23 @@
package main
import "testing"
func TestWorkspaceLeaseFlagIsExplicitAndChunkOnly(t *testing.T) {
base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"}
legacy, err := parseFlags(base)
if err != nil || legacy.workspaceLease {
t.Fatal("legacy mode changed", legacy, err)
}
if _, err := parseFlags(append(append([]string{}, base...), "--workspace-lease")); err == nil {
t.Fatal("workspace lease accepted without walstore-chunk")
}
chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888")
disabled, err := parseFlags(chunk)
if err != nil || disabled.workspaceLease {
t.Fatal("ordinary chunk volume opted in", err)
}
enabled, err := parseFlags(append(chunk, "--workspace-lease"))
if err != nil || !enabled.workspaceLease {
t.Fatal("explicit workspace flag not installed", err)
}
}
@@ -0,0 +1,72 @@
package main
import (
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/host/volume"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type workspaceStopResult struct {
gen uint64
err error
}
type workspaceStopRequest struct {
ctx context.Context
id *control.WorkspaceIdentity
reply chan workspaceStopResult
}
// The lease worker requests closure; only run's owner closes the actual
// frontends, replication and provider. Signal cancellation suppresses ACK even
// when it races an already-requested revocation drain.
func startWorkspaceLease(ctx context.Context, h *volume.Host) (<-chan workspaceStopRequest, <-chan error) {
requests := make(chan workspaceStopRequest)
done := make(chan error, 1)
go func() {
done <- h.RunWorkspaceLease(ctx, func(stopCtx context.Context, id *control.WorkspaceIdentity) (uint64, error) {
req := workspaceStopRequest{ctx: stopCtx, id: id, reply: make(chan workspaceStopResult, 1)}
select {
case requests <- req:
case <-ctx.Done():
return 0, ctx.Err()
case <-stopCtx.Done():
return 0, stopCtx.Err()
}
select {
case result := <-req.reply:
return result.gen, result.err
case <-ctx.Done():
return 0, ctx.Err()
case <-stopCtx.Done():
return 0, stopCtx.Err()
}
})
}()
return requests, done
}
// CLEAN requires a prior Detach while the lease was valid. This is read-only:
// revocation, expiry and cancellation never manufacture a final cut/proof.
func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (storage.ChunkRemote, error), id *control.WorkspaceIdentity, holder string) (uint64, error) {
if err := ctx.Err(); err != nil {
return 0, err
}
if remoteFor == nil || id == nil {
return 0, fmt.Errorf("workspace remote/identity missing")
}
remote, err := remoteFor(id.VolumeId)
if err != nil {
return 0, err
}
head, err := remote.GetHead(ctx)
if err != nil {
return 0, err
}
proof := head.DetachedBy
if head.Gen == 0 || head.Epoch != id.Epoch || head.Holder != holder || head.State != storage.ChunkHeadDetached || proof == nil || proof.Gen != head.Gen || proof.Epoch != head.Epoch || proof.Holder != head.Holder {
return 0, fmt.Errorf("workspace shutdown has no matching stored detached HEAD")
}
return head.Gen, nil
}
@@ -0,0 +1,215 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend"
master "github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"
"time"
)
func leaseBinaryAddress(t *testing.T) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
ln.Close()
return addr
}
func leaseBinaryPoll(t *testing.T, what string, fn func() bool) {
t.Helper()
end := time.Now().Add(30 * time.Second)
for !fn() {
if time.Now().After(end) {
t.Fatal(what)
}
time.Sleep(20 * time.Millisecond)
}
}
func leaseBinaryPost(addr, op string) (int, []byte, error) {
c := &http.Client{Timeout: 5 * time.Second}
resp, err := c.Post("http://"+addr+"/chunk/"+op, "application/json", bytes.NewBufferString(`{"volumeID":"vol-a","timeoutMs":3000}`))
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 65536))
return resp.StatusCode, b, err
}
func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
if os.Getenv("CHUNKSTORE_WEED") == "" {
t.Skip("CHUNKSTORE_WEED not set")
}
exe := filepath.Join(t.TempDir(), "blockvolume")
build := exec.Command("go", "build", "-race", "-p", "4", "-o", exe, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build: %v %s", err, out)
}
cluster := startWorkspaceWeed(t)
for _, enabled := range []bool{false, true} {
t.Run(fmt.Sprintf("workspace-rpc-%v", enabled), func(t *testing.T) {
base := fmt.Sprintf("/workspace-lease-%d", time.Now().UnixNano())
reader, err := master.NewWorkspaceHEADReader("http://" + cluster.filerHTTP + base)
if err != nil {
t.Fatal(err)
}
h, err := master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: enabled, WorkspaceHeadReader: reader})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() {
ctx, c := context.WithTimeout(context.Background(), 5*time.Second)
defer c()
_ = h.Close(ctx)
})
dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t)
if _, err = h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: dataAddr, CtrlAddr: ctrlAddr}); err != nil {
t.Fatal(err)
}
if _, err = h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "vol-a", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
if err = h.ObservationHost().Ingest(authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(), Slots: []authority.SlotFact{{VolumeID: "vol-a", ReplicaID: "r1", DataAddr: dataAddr, CtrlAddr: ctrlAddr}}}); err != nil {
t.Fatal(err)
}
if _, err = h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
leaseBinaryPoll(t, "no initial authority", func() bool { line, ok := h.Publisher().VolumeAuthorityLine("vol-a"); return ok && line.Epoch > 0 })
line, _ := h.Publisher().VolumeAuthorityLine("vol-a")
logPath := filepath.Join(t.TempDir(), "volume.log")
log, err := os.Create(logPath)
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease")
cmd.Stdout, cmd.Stderr = log, log
if err = cmd.Start(); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
exited := false
t.Cleanup(func() {
if !exited {
_ = cmd.Process.Kill()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("binary did not exit after kill")
}
}
log.Close()
if t.Failed() {
b, _ := os.ReadFile(logPath)
if len(b) > 14000 {
b = b[len(b)-14000:]
}
t.Logf("volume log: %s", b)
}
})
client := &http.Client{Timeout: time.Second}
projection := func() (frontend.Projection, bool) {
resp, e := client.Get("http://" + statusAddr + "/status?volume=vol-a")
if e != nil {
return frontend.Projection{}, false
}
defer resp.Body.Close()
var p frontend.Projection
e = json.NewDecoder(resp.Body).Decode(&p)
return p, e == nil
}
remote := cluster.remote(t, base+"/vol-a")
if !enabled {
leaseBinaryPoll(t, "unleased host did not adopt assignment", func() bool { p, ok := projection(); return ok && p.Epoch == line.Epoch })
// Exercise an actual cut request, not just the status presentation.
code, b, e := leaseBinaryPost(statusAddr, "cut")
if e != nil || code >= 200 && code < 300 {
t.Fatalf("unleased cut: %d %s %v", code, b, e)
}
if p, ok := projection(); !ok || p.Healthy {
t.Fatal("disabled WorkspaceRPC served", p, ok)
}
if state := h.Publisher().WorkspaceState("vol-a"); state != nil {
t.Fatal("disabled RPC enrolled a lease", state)
}
_ = cmd.Process.Signal(syscall.SIGTERM)
} else {
leaseBinaryPoll(t, "valid lease did not admit binary", func() bool { p, ok := projection(); return ok && p.Healthy })
// Actual provider/filer cut and canonical Detach happen before Revoke.
leaseBinaryPoll(t, "provider was not operational", func() bool { code, _, e := leaseBinaryPost(statusAddr, "cut"); return e == nil && code == 200 })
code, b, e := leaseBinaryPost(statusAddr, "detach")
if e != nil || code != 200 {
t.Fatalf("detach: %d %s %v", code, b, e)
}
detached, e := remote.GetHead(context.Background())
if e != nil || detached.State != "detached" || detached.DetachedBy == nil {
t.Fatal(detached, e)
}
conn, e := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if e != nil {
t.Fatal(e)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_, e = control.NewWorkspaceServiceClient(conn).RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: line.Epoch})
cancel()
if e != nil {
t.Fatal(e)
}
leaseBinaryPoll(t, "binary did not ACK its own drained shutdown", func() bool { s := h.Publisher().WorkspaceState("vol-a"); return s != nil && s.Ack != nil })
state := h.Publisher().WorkspaceState("vol-a")
if state.Ack.HeadGen != detached.Gen {
t.Fatal("ACK differs from stored detached HEAD", state, detached)
}
current, e := remote.GetHead(context.Background())
if e != nil || current.Gen != detached.Gen {
t.Fatal("revoke performed a forbidden extra cut", current, e)
}
}
select {
case err := <-done:
exited = true
if err != nil {
t.Fatal("binary exit", err)
}
case <-time.After(8 * time.Second):
t.Fatal("binary did not finish shutdown")
}
if c, e := net.DialTimeout("tcp", nvmeAddr, 200*time.Millisecond); e == nil {
c.Close()
t.Fatal("NVMe frontend still accepts after shutdown")
}
if !enabled {
head, e := remote.GetHead(context.Background())
if e != nil || head.Gen != 0 {
t.Fatal("unleased binary changed HEAD", head, e)
}
}
})
}
}
@@ -0,0 +1,156 @@
//go:build subprocess && chunkstore_integration
package main_test
// The process helper follows the existing chunkstore integration harness.
// Only real loopback SeaweedFS processes and per-test temporary state are used.
import (
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"math/rand"
"net"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
type w4WeedCluster struct {
master, filerHTTP, filerGRPC string
dir string
weed string
}
func w4FreePortPair(t *testing.T, used map[int]bool) int {
t.Helper()
for i := 0; i < 200; i++ {
p := 20000 + rand.Intn(20000)
if used[p] || used[p+10000] {
continue
}
ok := true
for _, q := range []int{p, p + 10000} {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", q))
if err != nil {
ok = false
break
}
l.Close()
}
if ok {
used[p], used[p+10000] = true, true
return p
}
}
t.Fatal("no free port pair")
return 0
}
func w4WaitTCP(t *testing.T, addr string, d time.Duration) {
t.Helper()
deadline := time.Now().Add(d)
for time.Now().Before(deadline) {
if c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil {
c.Close()
return
}
time.Sleep(100 * time.Millisecond)
}
t.Fatalf("%s not listening after %v", addr, d)
}
func startWorkspaceWeed(t *testing.T) *w4WeedCluster {
t.Helper()
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
t.Skip("CHUNKSTORE_WEED not set")
}
dir := t.TempDir()
used := map[int]bool{}
mp, vp, fp := w4FreePortPair(t, used), w4FreePortPair(t, used), w4FreePortPair(t, used)
c := &w4WeedCluster{
master: fmt.Sprintf("127.0.0.1:%d", mp),
filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp),
filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000),
dir: dir,
weed: weed,
}
run := func(name string, args ...string) {
logf, err := os.Create(filepath.Join(dir, name+".log"))
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(weed, args...)
cmd.Stdout, cmd.Stderr = logf, logf
cmd.Dir = dir
if err := cmd.Start(); err != nil {
t.Fatalf("start %s: %v", name, err)
}
t.Cleanup(func() {
_ = cmd.Process.Kill()
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Errorf("weed %s did not exit after kill", name)
}
logf.Close()
if t.Failed() {
b, _ := os.ReadFile(logf.Name())
if len(b) > 4000 {
b = b[len(b)-4000:]
}
t.Logf("---- %s log tail ----\n%s", name, b)
}
})
}
for _, d := range []string{"m", "v", "f"} {
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
t.Fatal(err)
}
}
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000")
w4WaitTCP(t, c.master, 20*time.Second)
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32")
run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f"))
w4WaitTCP(t, c.filerGRPC, 30*time.Second)
// Wait until an assign succeeds (volume registered, volumes growable).
cl := c.client(t, "/swblock/vols/probe")
deadline := time.Now().Add(60 * time.Second)
for {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, err := cl.Put(ctx, []byte("probe"))
cancel()
if err == nil {
break
}
if time.Now().After(deadline) {
t.Fatalf("cluster never accepted a write: %v", err)
}
time.Sleep(500 * time.Millisecond)
}
return c
}
func (c *w4WeedCluster) client(t *testing.T, assignPath string) *chunkstore.SWFS {
t.Helper()
cl, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", AssignPath: assignPath})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = cl.Close() })
return cl
}
func (c *w4WeedCluster) remote(t *testing.T, root string) *chunkstore.ChunkRemote {
t.Helper()
r, err := chunkstore.NewSWFSChunkRemote(c.client(t, root), root)
if err != nil {
t.Fatal(err)
}
return r
}
@@ -187,6 +187,10 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.HeadGen == 0 || s == nil || s.Lease == nil || !s.Lease.Revoking {
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
}
now := p.workspaceNow()
if now.UnixNano() >= s.Lease.ExpiresAtNS || !now.Before(p.workspaceLeaseDeadline[volume]) {
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
}
if s.Ack != nil && *s.Ack != ack {
return fmt.Errorf("workspace revoke ACK changed")
}
@@ -0,0 +1,30 @@
package authority
import (
"context"
"testing"
"time"
)
func TestWorkspaceExpiredLeaseCannotAcknowledgeCLEAN(t *testing.T) {
disk, _ := newTempStore(t)
now := time.Unix(1000, 0)
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return now }))
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
ctx := context.Background()
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
now = now.Add(2 * time.Second)
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err == nil {
t.Fatal("expired lease recorded a CLEAN revocation ACK")
}
if p.WorkspaceState("v").Ack != nil {
t.Fatal("refused ACK persisted")
}
}
+8
View File
@@ -59,6 +59,7 @@ type Config struct {
// sketch §11.L2 requires. Off by default (so T0 tests keep
// their documented non-healthy projection).
EnableT1Readiness bool
WorkspaceLease bool // Opt-in: require a workspace lease before I/O or capture.
// ReplicationVolume, when non-nil, receives peer-set updates on
// every self-replica AssignmentFact. The Host calls
@@ -142,6 +143,11 @@ type Host struct {
wg sync.WaitGroup
started atomic.Bool
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
readyOnce atomic.Bool
readyMarkerMu sync.Mutex
supportingReadyMarks map[string]struct{}
@@ -255,6 +261,7 @@ func New(cfg Config) (*Host, error) {
// View wires host as the SupersedeProbe so fail-closed kicks
// in when master names another replica at a newer lineage.
h.view = NewAdapterProjectionView(adpt, cfg.VolumeID, cfg.ReplicaID, h)
h.view.workspaceRequired = cfg.WorkspaceLease
return h, nil
}
@@ -535,6 +542,7 @@ func (h *Host) Start() context.Context {
// Close stops loops, closes the gRPC connection. Idempotent.
func (h *Host) Close() error {
h.FenceWorkspaceLease()
if h.cancel != nil {
h.cancel()
}
@@ -4,6 +4,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"sync/atomic"
)
// adapterProjector is the narrow seam this bridge needs. Keeps
@@ -69,10 +70,12 @@ type SupersedeProbe interface {
// I/O. Status surfaces that as replication_role=replica_ready; the
// frontend projection fails closed by reporting Healthy=false.
type AdapterProjectionView struct {
projector adapterProjector
volumeID string
replicaID string
probe SupersedeProbe
projector adapterProjector
volumeID string
replicaID string
probe SupersedeProbe
workspaceRequired bool // immutable after Host.New
workspaceGuard atomic.Pointer[WorkspaceLeaseGuard]
}
// NewAdapterProjectionView wires the bridge. probe may be nil
@@ -105,13 +108,18 @@ func (v *AdapterProjectionView) projectionWithSupersede() (frontend.Projection,
if superseded || (healthy && v.supportingReplicaReady(p.Epoch, p.EndpointVersion)) || v.roleAdmissionFailed() {
healthy = false
}
return frontend.Projection{
result := frontend.Projection{
VolumeID: v.volumeID,
ReplicaID: v.replicaID,
Epoch: p.Epoch,
EndpointVersion: p.EndpointVersion,
Healthy: healthy,
}, superseded
}
if v.workspaceRequired {
guard := v.workspaceGuard.Load()
result.Healthy = result.Healthy && guard != nil && guard.permits(result)
}
return result, superseded
}
func (v *AdapterProjectionView) supportingReplicaReady(selfEpoch, selfEV uint64) bool {
@@ -48,14 +48,19 @@ func NewWorkspaceLeaseGuard(base frontend.ProjectionView, client WorkspaceLeaseC
func (g *WorkspaceLeaseGuard) Projection() frontend.Projection {
p := g.base.Projection()
p.Healthy = p.Healthy && g.permits(p)
return p
}
// permits does not call the base view, so the host's shared projection can
// apply this lease gate without recursion. Never hold mu across RPC/drain.
func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool {
g.mu.Lock()
defer g.mu.Unlock()
if !g.until.IsZero() && !g.now().Before(g.until) {
g.fenced = true
}
allowed := !g.fenced && !g.until.IsZero()
g.mu.Unlock()
p.Healthy = p.Healthy && allowed && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch
return p
return !g.fenced && !g.until.IsZero() && p.VolumeID == g.id.VolumeId && p.ReplicaID == g.id.ReplicaId && p.Epoch == g.id.Epoch
}
// Refresh anchors validity to the request START. Reply latency can only shorten
@@ -71,7 +76,7 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
fenced, until := g.fenced, g.until
g.mu.Unlock()
if fenced {
return g.drain(g.revoked)
return g.drain(ctx, g.revoked)
}
rpcCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
if !until.IsZero() {
@@ -89,7 +94,7 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
}
g.mu.Unlock()
if expired {
_ = g.drain(false)
_ = g.drain(ctx, false)
}
return err
}
@@ -97,13 +102,13 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
g.mu.Lock()
g.fenced = true
g.mu.Unlock()
_ = g.drain(false)
_ = g.drain(ctx, false)
return fmt.Errorf("invalid workspace lease reply")
}
g.mu.Lock()
// Check the OLD deadline before accepting a newer grant. In particular a
// reply received after expiry cannot undo a fence latched by a frontend.
if (!g.until.IsZero() && !g.now().Before(g.until)) || !g.now().Before(start.Add(time.Duration(reply.ValidForNs))) {
if ctx.Err() != nil || rpcCtx.Err() != nil || (!g.until.IsZero() && !g.now().Before(g.until)) || !g.now().Before(start.Add(time.Duration(reply.ValidForNs))) {
g.fenced = true
}
if !g.fenced {
@@ -116,12 +121,12 @@ func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error {
closed := g.fenced
g.mu.Unlock()
if closed {
return g.drain(reply.Revoking)
return g.drain(ctx, reply.Revoking)
}
return nil
}
func (g *WorkspaceLeaseGuard) drain(ack bool) error {
func (g *WorkspaceLeaseGuard) drain(parent context.Context, ack bool) error {
if !g.stopped {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
gen, err := g.stop(ctx)
@@ -132,10 +137,22 @@ func (g *WorkspaceLeaseGuard) drain(ack bool) error {
g.headGen, g.stopped = gen, true
}
if ack {
if err := parent.Err(); err != nil {
return err
}
g.mu.Lock()
until := g.until
valid := !until.IsZero() && g.now().Before(until)
g.mu.Unlock()
if !valid {
return fmt.Errorf("workspace lease expired before clean ACK")
}
if g.headGen == 0 {
return fmt.Errorf("revocation drained without a committed HEAD gen")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
leaseCtx, leaseCancel := context.WithDeadline(parent, until)
defer leaseCancel()
ctx, cancel := context.WithTimeout(leaseCtx, 2*time.Second)
defer cancel()
_, err := g.client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &g.id, HeadGen: g.headGen})
return err
@@ -156,6 +173,9 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error {
}
g.mu.Lock()
delay := g.until.Sub(g.now()) / 3
if g.until.IsZero() {
delay = time.Second
}
g.mu.Unlock()
if delay < 50*time.Millisecond {
delay = 50 * time.Millisecond
@@ -169,7 +189,7 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error {
g.mu.Lock()
g.fenced = true
g.mu.Unlock()
err := g.drain(false)
err := g.drain(ctx, false)
g.operation.Unlock()
return err
case <-time.After(delay):
@@ -0,0 +1,70 @@
package volume
import (
"context"
"fmt"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"time"
)
// RunWorkspaceLease is the one-shot workspace lease lifecycle for this process.
// The view is gated from Host.New, including the interval before assignment or
// the first lease. A new assignment after fencing requires a new process.
// Stop must drain/close frontend, capture and replication, then observe the
// stored detached HEAD. It must not take a final cut on revocation or expiry.
func (h *Host) RunWorkspaceLease(ctx context.Context, stop func(context.Context, *control.WorkspaceIdentity) (uint64, error)) error {
return h.runWorkspaceLease(ctx, stop, nil)
}
// beforeInstall is a deterministic test seam before guard publication.
func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context, *control.WorkspaceIdentity) (uint64, error), beforeInstall func()) error {
if !h.cfg.WorkspaceLease || stop == nil {
return fmt.Errorf("workspace lease runtime is not configured")
}
if !h.workspaceLeaseStarted.CompareAndSwap(false, true) {
return fmt.Errorf("workspace lease runtime already started")
}
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
for {
if err := ctx.Err(); err != nil {
return err
}
p := h.view.Projection()
if p.Epoch > 0 {
id := &control.WorkspaceIdentity{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, Epoch: p.Epoch}
guard, err := NewWorkspaceLeaseGuard(h.view, control.NewWorkspaceServiceClient(h.conn), id, func(c context.Context) (uint64, error) { return stop(c, id) }, nil)
if err != nil {
return err
}
if beforeInstall != nil {
beforeInstall()
}
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
h.view.workspaceGuard.Store(guard)
h.workspaceLeaseMu.Unlock()
return guard.Run(ctx)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-tick.C:
}
}
}
// FenceWorkspaceLease closes admission synchronously before process shutdown.
// Physical drain remains owned by run's stop callback; this never ACKs/cuts.
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()
}
}
@@ -0,0 +1,334 @@
package volume
import (
"bytes"
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net"
"sync"
"sync/atomic"
"testing"
"time"
)
func workspaceRuntimeHost(t *testing.T, addr string, required bool) *Host {
t.Helper()
h, err := New(Config{MasterAddr: addr, ServerID: "node-a", VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9100", CtrlAddr: "127.0.0.1:9101", EnableT1Readiness: true, WorkspaceLease: required})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
h.applyFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:9100", CtrlAddr: "127.0.0.1:9101"})
end := time.Now().Add(time.Second)
for h.realAdpt.Projection().Mode != engine.ModeHealthy && time.Now().Before(end) {
time.Sleep(time.Millisecond)
}
if h.realAdpt.Projection().Mode != engine.ModeHealthy {
t.Fatal("fixture did not reach ordinary assignment health")
}
return h
}
func TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut(t *testing.T) {
h := workspaceRuntimeHost(t, "127.0.0.1:1", true)
if h.ProjectionView().Projection().Healthy {
t.Fatal("workspace host reports healthy without ever acquiring a lease")
}
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, h.ProjectionView())
if err != nil {
t.Fatal(err)
}
defer p.Close()
if _, err = p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
be := p.Backend("v1")
if _, err = be.Write(context.Background(), 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) {
t.Fatal("unleased write", err)
}
if _, err = p.CaptureVolume(context.Background(), "v1"); err == nil {
t.Fatal("unleased cut succeeded")
}
if head, err := remote.GetHead(context.Background()); err != nil || head.Gen != 0 {
t.Fatal("unleased HEAD mutation", head, err)
}
legacy := workspaceRuntimeHost(t, "127.0.0.1:1", false)
if !legacy.ProjectionView().Projection().Healthy {
t.Fatal("ordinary non-workspace host was gated")
}
}
// Wire peer exposes only the public lease RPCs. Storage, provider, projection,
// real host identity and lease runtime below are the production implementations.
type runtimeLeaseServer struct {
control.UnimplementedWorkspaceServiceServer
mu sync.Mutex
ttl time.Duration
disabled, blocked, revoking bool
acks int
ackGen uint64
first chan struct{}
once sync.Once
stopped *atomic.Bool
}
func (s *runtimeLeaseServer) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
s.once.Do(func() { close(s.first) })
s.mu.Lock()
ttl, disabled, blocked, revoking := s.ttl, s.disabled, s.blocked, s.revoking
s.mu.Unlock()
if disabled {
return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled")
}
if blocked {
<-ctx.Done()
return nil, ctx.Err()
}
return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(ttl), ExpiresAtNs: time.Now().Add(ttl).UnixNano(), Revoking: revoking}, nil
}
func (s *runtimeLeaseServer) AckWorkspaceRevoked(_ context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.stopped != nil && !s.stopped.Load() {
return nil, status.Error(codes.FailedPrecondition, "ACK preceded physical drain")
}
s.acks++
s.ackGen = q.HeadGen
return &control.WorkspaceEmpty{}, nil
}
func runtimeWire(t *testing.T, s *runtimeLeaseServer) string {
t.Helper()
s.first = make(chan struct{})
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
control.RegisterWorkspaceServiceServer(srv, s)
go srv.Serve(ln)
t.Cleanup(srv.Stop)
return ln.Addr().String()
}
func runtimeAwait(t *testing.T, what string, fn func() bool) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for !fn() {
select {
case <-ctx.Done():
t.Fatal(what, ctx.Err())
case <-time.After(time.Millisecond):
}
}
}
func runtimeStore(t *testing.T, h *Host) (*durable.DurableProvider, *storage.MemChunkRemote) {
t.Helper()
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, h.ProjectionView())
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)
}
return p, remote
}
func runtimeDone(t *testing.T, ch <-chan error) error {
t.Helper()
select {
case err := <-ch:
return err
case <-time.After(5 * time.Second):
t.Fatal("lease runtime did not finish")
return nil
}
}
func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) {
for _, kind := range []string{"expiry-stalled-renewal", "detach-then-revoke", "cancel"} {
t.Run(kind, func(t *testing.T) {
var stopped atomic.Bool
wire := &runtimeLeaseServer{ttl: 300 * time.Millisecond, stopped: &stopped}
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
p, remote := runtimeStore(t, h)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() {
done <- h.RunWorkspaceLease(ctx, func(c context.Context, id *control.WorkspaceIdentity) (uint64, error) {
if err := p.Backend("v1").StopIO(c, "workspace self-fence"); err != nil {
return 0, err
}
if err := p.Close(); err != nil {
return 0, err
}
stopped.Store(true)
head, err := remote.GetHead(c)
return head.Gen, err
})
}()
runtimeAwait(t, "leased operational provider", func() bool {
st := p.DurableStatuses()
return h.ProjectionView().Projection().Healthy && len(st) == 1 && st[0].Operational
})
want := bytes.Repeat([]byte{0x73}, 4096)
be := p.Backend("v1")
if n, err := be.Write(ctx, 4096, want); err != nil || n != 4096 {
t.Fatal(n, err)
}
if err := be.Sync(ctx); err != nil {
t.Fatal(err)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
before, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if kind == "detach-then-revoke" {
cut, _, err := p.DetachVolume(ctx, "v1")
if err != nil {
t.Fatal(err)
}
before = cut.Head
wire.mu.Lock()
wire.revoking = true
wire.mu.Unlock()
}
if kind == "expiry-stalled-renewal" {
wire.mu.Lock()
wire.blocked = true
wire.mu.Unlock()
}
if kind == "cancel" {
cancel()
h.FenceWorkspaceLease()
if h.ProjectionView().Projection().Healthy {
t.Fatal("cancel fence was delayed")
}
}
runtimeDone(t, done)
if !stopped.Load() || h.ProjectionView().Projection().Healthy {
t.Fatal("host/provider remained live")
}
if _, err := be.Write(context.Background(), 0, want); err == nil {
t.Fatal("fenced write succeeded")
}
if _, err := p.CaptureVolume(context.Background(), "v1"); err == nil {
t.Fatal("fenced cut succeeded")
}
after, err := remote.GetHead(context.Background())
if err != nil || after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN {
t.Fatal("shutdown published an extra cut", before, after, err)
}
ref := after.Chunks[0]
data, err := remote.Get(context.Background(), ref.Key)
if err != nil || !bytes.Equal(data[4096:8192], want) {
t.Fatal("leased data changed", err)
}
wire.mu.Lock()
acks, gen := wire.acks, wire.ackGen
wire.mu.Unlock()
if kind == "detach-then-revoke" {
if acks != 1 || gen != before.Gen || before.State != storage.ChunkHeadDetached {
t.Fatal("ACK not joined to real detach", acks, gen, before)
}
} else if acks != 0 {
t.Fatal("expiry/cancel ACKed clean", acks)
}
})
}
}
func TestWorkspaceHostDisabledRPCNeverFallsBack(t *testing.T) {
wire := &runtimeLeaseServer{ttl: time.Second, disabled: true}
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 0, nil })
}()
select {
case <-wire.first:
case <-time.After(time.Second):
t.Fatal("no lease request")
}
if h.ProjectionView().Projection().Healthy {
t.Fatal("disabled workspace RPC fell back to assignment-only serving")
}
cancel()
runtimeDone(t, done)
wire.mu.Lock()
defer wire.mu.Unlock()
if wire.acks != 0 {
t.Fatal("disabled RPC cancellation ACKed clean")
}
}
func TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs(t *testing.T) {
for _, kind := range []string{"cancel", "expiry", "drain-error"} {
t.Run(kind, func(t *testing.T) {
wire := &runtimeLeaseServer{ttl: 150 * time.Millisecond}
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
entered := make(chan struct{})
release := make(chan struct{})
done := make(chan error, 1)
go func() {
done <- h.RunWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) {
close(entered)
<-release
if kind == "drain-error" {
return 0, errors.New("drain failed")
}
return 7, nil
})
}()
runtimeAwait(t, "first lease", func() bool { return h.ProjectionView().Projection().Healthy })
wire.mu.Lock()
wire.revoking = true
wire.mu.Unlock()
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("revoke did not request drain")
}
if h.ProjectionView().Projection().Healthy {
t.Fatal("revoke drain left admission open")
}
if kind == "cancel" {
cancel()
}
if kind == "expiry" {
time.Sleep(200 * time.Millisecond)
}
close(release)
if err := runtimeDone(t, done); err == nil {
t.Fatal("terminal drain unexpectedly succeeded")
}
wire.mu.Lock()
defer wire.mu.Unlock()
if wire.acks != 0 {
t.Fatal("terminal drain sent clean ACK", wire.acks)
}
})
}
}
@@ -0,0 +1,78 @@
package volume
import (
"context"
"sync/atomic"
"testing"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
func TestWorkspaceFenceBeforeHeldInstallIsTerminal(t *testing.T) {
wire := &runtimeLeaseServer{ttl: time.Second}
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
arrived, release := make(chan struct{}), make(chan struct{})
var stops atomic.Int32
done := make(chan error, 1)
go func() {
done <- h.runWorkspaceLease(ctx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) {
stops.Add(1)
return 7, nil
}, func() { close(arrived); <-release })
}()
select {
case <-arrived:
case <-time.After(5 * time.Second):
t.Fatal("installer did not reach gate")
}
h.FenceWorkspaceLease()
close(release)
// A terminal fence must settle the real runtime without any RPC grant.
select {
case <-done:
case <-wire.first:
cancel()
_ = runtimeDone(t, done)
t.Fatal("installer renewed after synchronous host fence")
case <-time.After(5 * time.Second):
cancel()
_ = runtimeDone(t, done)
t.Fatal("fenced installer did not settle")
}
if stops.Load() != 1 || h.ProjectionView().Projection().Healthy {
t.Fatal("fence failed to stop installed guard", stops.Load())
}
}
func TestWorkspaceCanceledReplyCannotPublishGrant(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
arrived, reply := make(chan struct{}), make(chan struct{})
client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) {
close(arrived)
<-reply
return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(time.Second)}, nil
}}
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil)
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() { done <- g.Refresh(ctx) }()
select {
case <-arrived:
case <-time.After(5 * time.Second):
t.Fatal("renewal did not reach gate")
}
cancel()
close(reply)
if err := runtimeDone(t, done); err == nil {
t.Error("canceled renewal reported success")
}
if g.Projection().Healthy {
t.Error("canceled reply published a serving grant")
}
}
+30
View File
@@ -0,0 +1,30 @@
# Workspace host lease
Workspace launches must pass `--workspace-lease` together with
`--durable-root` and `--durable-impl=walstore-chunk`. The workspace launcher
must set this flag. Ordinary chunk volumes retain their existing behavior
when the flag is absent.
With the flag enabled, blockvolume owns renewal through WorkspaceRPC. Its
shared projection refuses frontend I/O and captures before the first grant,
when renewal expires, and after revocation or cancellation. A missing lease
or disabled WorkspaceRPC never selects an unguarded fallback. A fenced
process cannot become healthy again; start a new process for its assignment.
For a CLEAN move, stop guest I/O and call Detach while the lease is valid.
Detach installs the final cut and canonical detached HEAD proof. Then revoke
the assignment. Blockvolume closes frontend admission, drains and closes the
frontend, replication, and provider, reads the stored detached HEAD, and only
then ACKs its exact generation. The authority refuses an expired lease's ACK.
Revocation does not perform a final cut. Lease expiry or cancellation closes
the host without a CLEAN ACK or cut; recovery uses a FORCED move.
The shared projection loads the guard atomically. Guard operations serialize
renewal, drain, and ACK with the operation mutex; the state mutex is held only
for lease state, never across a base projection, RPC, or stop callback. The
projection never takes the operation mutex. The blockvolume main goroutine
alone closes physical resources; the lease worker requests closure and waits
for its result before ACK. Host shutdown fences admission synchronously.
The host installation mutex latches this terminal fence even before a guard
exists; a later-installed guard is born fenced. Its lock order is installation
mutex then guard state mutex. Canceled renewal replies cannot publish a grant.