mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Merge pull request #327 from seaweedfs/train/20261121-6
Train 6: #318 + #320
This commit is contained in:
commit
9da65c9802
49 files changed
+4891
-158
No files matched your search
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// Automatic GC stays default-off until restart-safe unknown-CAS settlement and
|
||||
// the 50/200-volume root-scan measurement both pass. Retention remains enabled.
|
||||
// The CLI fixes the maximum cut/copy lifetime at five minutes and the HEAD
|
||||
// hydration reader at thirty seconds. A one-minute mark fits strictly inside
|
||||
// the one-hour grace. No elapsed TTL alone authorizes capture-intent expiry.
|
||||
func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string) (func(context.Context, string) error, func() error, error) {
|
||||
closeFn := func() error { return nil }
|
||||
cfg := chunkstore.GCConfig{Grace: defaultChunkGCGrace, IntentTTL: defaultChunkIntentTTL}
|
||||
if collect {
|
||||
if master == "" {
|
||||
return nil, closeFn, errors.New("automatic chunk GC requires blockmaster authority")
|
||||
}
|
||||
if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout {
|
||||
return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds")
|
||||
}
|
||||
conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
return nil, closeFn, err
|
||||
}
|
||||
closeFn = conn.Close
|
||||
evidence := control.NewEvidenceServiceClient(conn)
|
||||
cfg.IssuedEpoch = func(ctx context.Context, vol string) (uint64, error) {
|
||||
reply, err := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 {
|
||||
return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol)
|
||||
}
|
||||
return reply.Epoch, nil
|
||||
}
|
||||
}
|
||||
return func(ctx context.Context, vol string) error {
|
||||
retained, err := cat.Retain(ctx, vol, false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("retain deleted=%d not_attempted=%d: %w", len(retained.Deleted), len(retained.NotAttempted), err)
|
||||
}
|
||||
if !collect {
|
||||
return nil
|
||||
}
|
||||
out, err := cat.ExecuteVolumeGC(ctx, vol, blobs, cfg, true)
|
||||
log.Printf("blockvolume: maintenance volume=%s mark=%s reclaimed=%d settled=%d unknown=%v", vol, out.MarkOutcome, out.Reclaimed, out.SettledCopies, out.UnknownOutcomes)
|
||||
return err
|
||||
}, closeFn, nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"path"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type maintenanceGCFiler struct {
|
||||
chunkstore.Filer
|
||||
gcCalls, marked, freed int
|
||||
failSecond bool
|
||||
}
|
||||
|
||||
func (f *maintenanceGCFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if name == "_GC_MARK" {
|
||||
f.gcCalls++
|
||||
return nil, errors.New("witness: GC reached")
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
func (f *maintenanceGCFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if string(e.Extended["swb.snap.state"]) == chunkstore.SnapDeleting {
|
||||
if f.failSecond && f.marked == 1 {
|
||||
return errors.New("second retention mark refused")
|
||||
}
|
||||
f.marked++
|
||||
}
|
||||
return f.Filer.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
func (f *maintenanceGCFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
|
||||
if err == nil && path.Base(dir) == "snapnames" {
|
||||
f.freed++
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type maintenanceBlobs struct{}
|
||||
|
||||
func (maintenanceBlobs) DeleteBlob(context.Context, string) error { return nil }
|
||||
func (maintenanceBlobs) Put(context.Context, []byte) (string, error) { return "unused", nil }
|
||||
func (maintenanceBlobs) Get(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("unexpected blob read")
|
||||
}
|
||||
func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) {
|
||||
for _, partial := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "missing", true: "partial"}[partial], func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := &maintenanceGCFiler{Filer: chunkstore.NewMemFiler(), failSecond: partial}
|
||||
cat, err := chunkstore.NewCatalog(f, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vol := "missing-volume"
|
||||
if partial {
|
||||
vol = "v1"
|
||||
if _, err = cat.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = cat.SetRetentionPolicy(ctx, vol, chunkstore.RetentionPolicy{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().Add(-48 * time.Hour)
|
||||
cat.SetClock(func() time.Time { return now })
|
||||
for _, name := range []string{"a", "b"} {
|
||||
if _, err = cat.CreateSnapshot(ctx, vol, chunkstore.SnapshotRequest{Name: name, RequestID: "req"}, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(time.Second)
|
||||
}
|
||||
now = time.Now()
|
||||
}
|
||||
pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closeFn()
|
||||
if err = pass(ctx, vol); err == nil {
|
||||
t.Fatal("retention failure accepted")
|
||||
}
|
||||
if f.gcCalls != 0 {
|
||||
t.Fatalf("retention failure entered GC %d times", f.gcCalls)
|
||||
}
|
||||
if partial && (f.marked != 1 || f.freed != 1) {
|
||||
t.Fatalf("partial retention effects not retained: marked=%d freed=%d err=%v", f.marked, f.freed, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceDefaultRetainNeedsNoEpochClient(t *testing.T) {
|
||||
f := chunkstore.NewMemFiler()
|
||||
cat, err := chunkstore.NewCatalog(f, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = cat.EnsureVolume(context.Background(), "v", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pass, closeFn, err := newChunkMaintenance(cat, nil, false, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closeFn()
|
||||
if err = pass(context.Background(), "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,15 @@ import (
|
||||
|
||||
const (
|
||||
defaultChunkPath = "/swblock/chunks"
|
||||
// The remote holds snapshots, not live data: cuts are published at
|
||||
// snapshots, at detach/stop and on explicit request. The timer is off
|
||||
// by default (an operator may set one, e.g. 15m, as a host-loss safety
|
||||
// net); the dirty threshold only bounds how large one cut can grow.
|
||||
defaultChunkCaptureInterval = 0
|
||||
defaultChunkDirtyThreshold = 512 // chunks, 2 GiB at 4 MiB chunks
|
||||
// Periodic HEAD publication bounds the host-loss recovery point. Automatic
|
||||
// named snapshots remain explicit catalog operations.
|
||||
defaultChunkCaptureInterval = 15 * time.Minute
|
||||
defaultChunkMaintenanceInterval = time.Hour
|
||||
defaultChunkCutTimeout = 5 * time.Minute
|
||||
defaultChunkMaintenanceTimeout = time.Minute
|
||||
defaultChunkGCGrace = time.Hour
|
||||
defaultChunkIntentTTL = time.Hour
|
||||
defaultChunkDirtyThreshold = 512 // chunks, 2 GiB at 4 MiB chunks
|
||||
)
|
||||
|
||||
type chunkFlags struct {
|
||||
@@ -37,6 +40,8 @@ type chunkFlags struct {
|
||||
collection string
|
||||
replication string
|
||||
captureInterval time.Duration
|
||||
maintenanceInterval time.Duration
|
||||
automaticGC bool
|
||||
dirtyThreshold int
|
||||
uploadConcurrency int
|
||||
hydrationWorkers int
|
||||
@@ -56,7 +61,7 @@ func validateChunkFlags(f flags) error {
|
||||
}
|
||||
if f.durableImpl != "walstore-chunk" {
|
||||
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
|
||||
c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold ||
|
||||
c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || c.dirtyThreshold != defaultChunkDirtyThreshold ||
|
||||
c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" {
|
||||
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
|
||||
}
|
||||
@@ -77,6 +82,12 @@ func validateChunkFlags(f flags) error {
|
||||
if !path.IsAbs(c.path) || path.Clean(c.path) != c.path || c.path == "/" {
|
||||
return fmt.Errorf("--chunk-path=%q must be a clean absolute filer directory other than /", c.path)
|
||||
}
|
||||
if c.maintenanceInterval < 0 {
|
||||
return errors.New("--chunk-maintenance-interval must not be negative")
|
||||
}
|
||||
if c.captureInterval > 0 && c.captureInterval < 5*time.Minute {
|
||||
return errors.New("--chunk-capture-interval must be 0 or at least 5m")
|
||||
}
|
||||
if c.captureInterval < 0 {
|
||||
return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval)
|
||||
}
|
||||
@@ -106,14 +117,15 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi
|
||||
// provider's per-volume remotes, the catalog under the same base (VOLUME
|
||||
// entries, snapshots) and the client's closer.
|
||||
type chunkWiring struct {
|
||||
remoteFor func(volumeID string) (storage.ChunkRemote, error)
|
||||
catalog *chunkstore.Catalog
|
||||
close func() error
|
||||
remoteFor func(volumeID string) (storage.ChunkRemote, error)
|
||||
catalog *chunkstore.Catalog
|
||||
maintenance func(context.Context, string) error
|
||||
close func() error
|
||||
}
|
||||
|
||||
// newChunkWiring dials the filer and refuses unless it is the only filer of
|
||||
// its group (chunkstore.CheckSingleFiler).
|
||||
func newChunkWiring(c chunkFlags) (chunkWiring, error) {
|
||||
func newChunkWiring(c chunkFlags, master ...string) (chunkWiring, error) {
|
||||
client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{
|
||||
FilerGRPC: c.filer,
|
||||
Collection: c.collection,
|
||||
@@ -133,7 +145,17 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) {
|
||||
_ = client.Close()
|
||||
return chunkWiring{}, err
|
||||
}
|
||||
var masterAddr string
|
||||
if len(master) > 0 {
|
||||
masterAddr = master[0]
|
||||
}
|
||||
maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr)
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return chunkWiring{}, err
|
||||
}
|
||||
return chunkWiring{
|
||||
maintenance: maintenance,
|
||||
remoteFor: func(volumeID string) (storage.ChunkRemote, error) {
|
||||
root, err := chunkVolumeRoot(c.path, volumeID)
|
||||
if err != nil {
|
||||
@@ -142,7 +164,7 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) {
|
||||
return chunkstore.NewSWFSChunkRemote(client, root)
|
||||
},
|
||||
catalog: cat,
|
||||
close: client.Close,
|
||||
close: func() error { return errors.Join(closeMaintenance(), client.Close()) },
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,11 @@ func TestWALStoreChunkFlags(t *testing.T) {
|
||||
return append(phase150RequiredBlockvolumeArgs(), extra...)
|
||||
}
|
||||
f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
|
||||
"--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=30s"))
|
||||
"--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=5m"))
|
||||
if err != nil {
|
||||
t.Fatalf("walstore-chunk with a filer: %v", err)
|
||||
}
|
||||
if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 30*time.Second || f.chunk.controlEndpoint {
|
||||
if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 5*time.Minute || f.chunk.controlEndpoint {
|
||||
t.Fatalf("parsed chunk flags = %+v", f.chunk)
|
||||
}
|
||||
f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
|
||||
@@ -31,8 +31,8 @@ func TestWALStoreChunkFlags(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.chunk.captureInterval != 0 || d.chunk.dirtyThreshold != 512 {
|
||||
t.Fatalf("scheduler defaults interval %s threshold %d, want timer off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold)
|
||||
if d.chunk.captureInterval != 15*time.Minute || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC || d.chunk.dirtyThreshold != 512 {
|
||||
t.Fatalf("scheduler defaults interval %s threshold %d, want capture 15m, maintenance 1h, GC off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold)
|
||||
}
|
||||
off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
|
||||
"--chunk-capture-interval=0", "--chunk-dirty-threshold=0"))
|
||||
@@ -43,13 +43,15 @@ func TestWALStoreChunkFlags(t *testing.T) {
|
||||
t.Fatalf("walstore with the chunk defaults untouched: %v", err)
|
||||
}
|
||||
refused := map[string][]string{
|
||||
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"),
|
||||
"no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"),
|
||||
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"),
|
||||
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"),
|
||||
"negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"),
|
||||
"chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"),
|
||||
"chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"),
|
||||
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"),
|
||||
"no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"),
|
||||
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"),
|
||||
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"),
|
||||
"below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"),
|
||||
"negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"),
|
||||
"negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"),
|
||||
"chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"),
|
||||
"chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"),
|
||||
"control endpoint on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--status-addr=127.0.0.1:0",
|
||||
"--chunk-control-endpoint"),
|
||||
"control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
|
||||
|
||||
@@ -203,7 +203,9 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
|
||||
fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)")
|
||||
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit")
|
||||
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net")
|
||||
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 15m, minimum 5m); 0 disables")
|
||||
fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables")
|
||||
fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification")
|
||||
fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)")
|
||||
fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)")
|
||||
fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)")
|
||||
@@ -658,8 +660,12 @@ func run(f flags) int {
|
||||
var chunkErr error
|
||||
var chunk chunkWiring
|
||||
if cfg.Impl == durable.ImplWALStoreChunk {
|
||||
chunk, chunkErr = newChunkWiring(f.chunk)
|
||||
chunk, chunkErr = newChunkWiring(f.chunk, f.masterAddr)
|
||||
cfg.ChunkCaptureInterval = f.chunk.captureInterval
|
||||
cfg.ChunkCutTimeout = defaultChunkCutTimeout
|
||||
cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval
|
||||
cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout
|
||||
cfg.ChunkMaintenance = chunk.maintenance
|
||||
cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy
|
||||
cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold
|
||||
cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency
|
||||
|
||||
@@ -83,7 +83,7 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
if len(args) < 2 {
|
||||
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld")
|
||||
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld|workspace")
|
||||
usage(stderr)
|
||||
return ops.VolumeStatusExitInvalid
|
||||
}
|
||||
@@ -128,6 +128,8 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
return runOpsChunk(args[2:], stdout, stderr)
|
||||
case "volume-unheld":
|
||||
return runOpsVolumeUnheld(args[2:], stdout, stderr)
|
||||
case "workspace":
|
||||
return runOpsWorkspace(args[2:], stdout, stderr)
|
||||
default:
|
||||
fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1])
|
||||
usage(stderr)
|
||||
@@ -2296,6 +2298,8 @@ func usage(w io.Writer) {
|
||||
fmt.Fprintln(w, " sw-block ops chunk show --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer <host:port> --master <blockmaster-grpc> [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]")
|
||||
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
|
||||
fmt.Fprintln(w, " sw-block ops workspace force-move --master <addr> --volume <id> --target-host <server-id> --target-data <addr> --target-ctrl <addr> --request-id <id> --confirm-forced <volume>@<epoch> [--dry-run]")
|
||||
fmt.Fprintln(w, " sw-block ops workspace lost-range --master <addr> --volume <id> [--request-id <id>] (authority only; no bypass: see `sw-block ops workspace help`)")
|
||||
}
|
||||
|
||||
func emptyCLI(value string) string {
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
|
||||
)
|
||||
|
||||
// Exit codes of `sw-block ops workspace`.
|
||||
const (
|
||||
wsExitOK = 0
|
||||
wsExitRefused = 1 // the master refused; nothing moved
|
||||
wsExitRefusedLocally = 2 // bad usage or confirmation; no RPC was sent
|
||||
wsExitUnknown = 3 // outcome unknown: rerun with the SAME --request-id
|
||||
wsExitReadoutUnproven = 4 // move issued (or ranges exist) but the lost range is not proven
|
||||
wsDefaultTimeout = 30 * time.Second
|
||||
workspaceForceMoveName = "sw-block ops workspace force-move"
|
||||
workspaceLostRangeName = "sw-block ops workspace lost-range"
|
||||
)
|
||||
|
||||
const workspaceUsage = `usage:
|
||||
sw-block ops workspace force-move --master ADDR --volume V --target-host H --target-data A --target-ctrl A
|
||||
--request-id ID --confirm-forced V@EPOCH [--dry-run] [--timeout 30s]
|
||||
sw-block ops workspace lost-range --master ADDR --volume V [--request-id ID] [--timeout 30s]
|
||||
|
||||
force-move FORCES an RF1 workspace volume's authority off a holder that is gone,
|
||||
abandoning what it wrote after the last published HEAD. It moves AUTHORITY only:
|
||||
starting the volume on the target host is the next step, done separately. The
|
||||
blockmaster admits it only once the holder's lease horizon and its granted or
|
||||
restart deadline, each plus the clock-skew bound, have passed; before that it is
|
||||
refused and this command says when it becomes admissible. There is NO bypass
|
||||
flag. Clean (detached) moves are not offered here.
|
||||
|
||||
--confirm-forced must be exactly <volume>@<expected epoch>, retyped: the epoch
|
||||
is the holder's epoch the move is sent against, and the master refuses it when
|
||||
that is no longer current. --dry-run asks the master for an advisory preview
|
||||
(nothing is written; admission is re-checked at the move); it is never a
|
||||
confirmation. The lost range is stored before the move is issued and printed
|
||||
from that record; the authority store and its lost-range files stay off the
|
||||
volume hosts (layout rule).
|
||||
|
||||
lost-range prints the stored lost ranges of the volume's issued forced moves, in
|
||||
issue order (all of them, or the one of --request-id). It never prints "no loss"
|
||||
for a forced move whose record is missing or fails its checks.
|
||||
|
||||
exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage
|
||||
or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME
|
||||
--request-id; 4 the move is issued but its lost range is not proven (or a
|
||||
stored range is unreadable).
|
||||
`
|
||||
|
||||
// workspaceDial is swapped by tests.
|
||||
var workspaceDial = wsclient.Dial
|
||||
|
||||
// runOpsWorkspace is `sw-block ops workspace`.
|
||||
func runOpsWorkspace(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(stderr, workspaceUsage)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
switch args[0] {
|
||||
case "force-move":
|
||||
return runWorkspaceForceMove(args[1:], stdout, stderr)
|
||||
case "lost-range":
|
||||
return runWorkspaceLostRange(args[1:], stdout, stderr)
|
||||
case "-h", "--help", "help":
|
||||
fmt.Fprint(stdout, workspaceUsage)
|
||||
return wsExitOK
|
||||
default:
|
||||
fmt.Fprintf(stderr, "sw-block ops workspace: unknown subcommand %q\n", args[0])
|
||||
fmt.Fprint(stderr, workspaceUsage)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
}
|
||||
|
||||
func workspaceExit(o wsclient.Outcome) int {
|
||||
switch o {
|
||||
case wsclient.OutcomeOK:
|
||||
return wsExitOK
|
||||
case wsclient.OutcomeRefusedLocally:
|
||||
return wsExitRefusedLocally
|
||||
case wsclient.OutcomeRefused:
|
||||
return wsExitRefused
|
||||
case wsclient.OutcomeReadoutUnproven:
|
||||
return wsExitReadoutUnproven
|
||||
}
|
||||
return wsExitUnknown
|
||||
}
|
||||
|
||||
func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
|
||||
fs := flag.NewFlagSet(workspaceForceMoveName, flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) }
|
||||
var m wsclient.ForcedMove
|
||||
var master string
|
||||
var dryRun bool
|
||||
var timeout time.Duration
|
||||
fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port")
|
||||
fs.StringVar(&m.VolumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&m.TargetHost, "target-host", "", "target node server id")
|
||||
fs.StringVar(&m.TargetDataAddr, "target-data", "", "target data address host:port")
|
||||
fs.StringVar(&m.TargetCtrlAddr, "target-ctrl", "", "target control address host:port")
|
||||
fs.StringVar(&m.RequestID, "request-id", "", "this move's id; a rerun with the same id returns the stored grant")
|
||||
fs.StringVar(&m.Confirm, "confirm-forced", "", "exactly <volume>@<expected epoch>")
|
||||
fs.BoolVar(&dryRun, "dry-run", false, "advisory preview only; writes nothing")
|
||||
fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPCs")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
if fs.NArg() != 0 || master == "" || m.VolumeID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" || m.RequestID == "" || timeout <= 0 {
|
||||
fmt.Fprintf(stderr, "%s: --master, --volume, --target-host, --target-data, --target-ctrl, --request-id and --confirm-forced are required (refused locally; nothing sent)\n", workspaceForceMoveName)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
// Row Parse -> Refused: checked before any connection or RPC.
|
||||
if _, err := wsclient.ParseConfirmation(m.Confirm, m.VolumeID); err != nil {
|
||||
fmt.Fprintf(stderr, "%s: refused locally, nothing sent: %v\n", workspaceForceMoveName, err)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s: refused locally, nothing sent: master address: %v\n", workspaceForceMoveName, err)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
if dryRun {
|
||||
return workspacePreview(ctx, c, m, stdout, stderr)
|
||||
}
|
||||
g, err := c.ForceMove(ctx, m)
|
||||
switch o := wsclient.OutcomeOf(err); o {
|
||||
case wsclient.OutcomeOK:
|
||||
printForcedGrant(stdout, g)
|
||||
fmt.Fprintln(stdout, wsclient.Readout(m.VolumeID, g.GetLostRange()))
|
||||
fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", m.VolumeID, g.GetNewHost())
|
||||
return wsExitOK
|
||||
case wsclient.OutcomeReadoutUnproven:
|
||||
if g != nil {
|
||||
printForcedGrant(stdout, g)
|
||||
}
|
||||
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
|
||||
fmt.Fprintf(stderr, "%s: the move IS issued; do not assume no loss. Check the master's load errors, and read the range with:\n", workspaceForceMoveName)
|
||||
fmt.Fprintf(stderr, "%s%s\n", workspaceRecoveryPrefix, shellCommand("sw-block", "ops", "workspace", "lost-range", "--master", master, "--volume", m.VolumeID, "--request-id", m.RequestID))
|
||||
return wsExitReadoutUnproven
|
||||
case wsclient.OutcomeRefused:
|
||||
fmt.Fprintf(stderr, "%s: refused by the master (nothing moved): %v\n", workspaceForceMoveName, err)
|
||||
if at, ok := c.AdmissibleAt(ctx, m); ok {
|
||||
fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano()))
|
||||
}
|
||||
return wsExitRefused
|
||||
case wsclient.OutcomeUnknown:
|
||||
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
|
||||
fmt.Fprintf(stderr, "%s: outcome unknown: rerun with the SAME --request-id %s\n", workspaceForceMoveName, m.RequestID)
|
||||
return wsExitUnknown
|
||||
default:
|
||||
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
|
||||
return workspaceExit(o)
|
||||
}
|
||||
}
|
||||
|
||||
// workspaceRecoveryPrefix starts the line that carries a recovery command.
|
||||
const workspaceRecoveryPrefix = " "
|
||||
|
||||
// shellCommand joins args for a POSIX shell, single-quoting any argument
|
||||
// that is not plainly safe, so a printed command can be pasted as is.
|
||||
func shellCommand(args ...string) string {
|
||||
out := make([]string, len(args))
|
||||
for i, a := range args {
|
||||
out[i] = shellQuote(a)
|
||||
}
|
||||
return strings.Join(out, " ")
|
||||
}
|
||||
|
||||
func shellQuote(a string) string {
|
||||
if a != "" && strings.Trim(a, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" {
|
||||
return a
|
||||
}
|
||||
return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'"
|
||||
}
|
||||
|
||||
func printForcedGrant(w io.Writer, g *control.WorkspaceGrant) {
|
||||
fmt.Fprintf(w, "forced move issued: volume %s request %s: %s@%d on %s -> %s@%d on %s (kept HEAD gen %d, remote LSN %d)\n",
|
||||
g.GetVolumeId(), g.GetRequestId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetOldHost(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost(), g.GetHeadGen(), g.GetRemoteLsn())
|
||||
}
|
||||
|
||||
// workspacePreview is the --dry-run row: advisory, writes nothing, exit 0
|
||||
// whatever the answer (a failed preview call is reported by its outcome).
|
||||
func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.ForcedMove, stdout, stderr io.Writer) int {
|
||||
p, err := c.PreviewForcedMove(ctx, m)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s --dry-run: %v\n", workspaceForceMoveName, err)
|
||||
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
|
||||
fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName)
|
||||
}
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
}
|
||||
verdict := "not admitted"
|
||||
if p.GetAdmitted() {
|
||||
verdict = "admitted"
|
||||
}
|
||||
fmt.Fprintf(stdout, "preview (advisory): at master time %s, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation.\n", wsclient.FormatTime(p.GetMasterTimeNs()))
|
||||
if p.GetReason() != "" {
|
||||
fmt.Fprintf(stdout, "forced move %s: %s\n", verdict, p.GetReason())
|
||||
} else {
|
||||
fmt.Fprintf(stdout, "forced move %s\n", verdict)
|
||||
}
|
||||
if !p.GetAdmitted() && p.GetLostUntilNs() > p.GetMasterTimeNs() {
|
||||
fmt.Fprintf(stdout, "admissible at %s, master clock\n", wsclient.FormatTime(p.GetLostUntilNs()))
|
||||
}
|
||||
if p.GetHeadRead() {
|
||||
at := "unknown"
|
||||
if p.GetHeadTimeKnown() {
|
||||
at = wsclient.FormatTime(p.GetHeadTimeNs()) + " " + wsclient.HeadTimeClock
|
||||
}
|
||||
fmt.Fprintf(stdout, "HEAD now: gen %d, epoch %d, holder %s, remote LSN %d, published at %s\n", p.GetHeadGen(), p.GetHeadEpoch(), p.GetHeadHolder(), p.GetHeadRemoteLsn(), at)
|
||||
if p.GetAdmitted() {
|
||||
fmt.Fprintf(stdout, "if moved now: writes with LSN <= %d are kept; writes acknowledged after that and before %s, master clock, may be lost\n", p.GetHeadRemoteLsn(), wsclient.FormatTime(p.GetLostUntilNs()))
|
||||
}
|
||||
} else if p.GetHeadError() != "" {
|
||||
fmt.Fprintf(stdout, "HEAD read failed: %s\n", p.GetHeadError())
|
||||
}
|
||||
return wsExitOK
|
||||
}
|
||||
|
||||
func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
|
||||
fs := flag.NewFlagSet(workspaceLostRangeName, flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) }
|
||||
var master, volume, requestID string
|
||||
var timeout time.Duration
|
||||
fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port")
|
||||
fs.StringVar(&volume, "volume", "", "volume id")
|
||||
fs.StringVar(&requestID, "request-id", "", "only this forced move's range (default: all, in issue order)")
|
||||
fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
if fs.NArg() != 0 || master == "" || volume == "" || timeout <= 0 {
|
||||
fmt.Fprintf(stderr, "%s: --master and --volume are required\n", workspaceLostRangeName)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
c, err := workspaceDial(master)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s: master address: %v\n", workspaceLostRangeName, err)
|
||||
return wsExitRefusedLocally
|
||||
}
|
||||
defer c.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
ranges, err := c.LostRanges(ctx, volume, requestID)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%s: %v\n", workspaceLostRangeName, err)
|
||||
if wsclient.OutcomeOf(err) == wsclient.OutcomeReadoutUnproven {
|
||||
fmt.Fprintf(stderr, "%s: a forced move's lost range is missing or unreadable: the readout is NOT proven; do not assume no loss\n", workspaceLostRangeName)
|
||||
}
|
||||
return workspaceExit(wsclient.OutcomeOf(err))
|
||||
}
|
||||
if len(ranges) == 0 {
|
||||
fmt.Fprintf(stdout, "volume %s has no issued forced move\n", volume)
|
||||
return wsExitOK
|
||||
}
|
||||
for i, r := range ranges {
|
||||
fmt.Fprintf(stdout, "range %d of %d: request %s, %s@%d -> epoch %d, lost after LSN %d, until %s (master clock)\n",
|
||||
i+1, len(ranges), r.GetRequestId(), r.GetOldReplicaId(), r.GetOldEpoch(), r.GetNewEpoch(), r.GetLostAfterLsn(), wsclient.FormatTime(r.GetLostUntilNs()))
|
||||
fmt.Fprintf(stdout, " %s\n", wsclient.Readout(volume, r))
|
||||
}
|
||||
return wsExitOK
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"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"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// seedForcedVolume makes r1 on node-a the holder of vol-f at epoch 1 (lease
|
||||
// renewed once) with a prepared target binding on node-b.
|
||||
func seedForcedVolume(t *testing.T, h *master.Host) {
|
||||
t.Helper()
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
ws := control.NewWorkspaceServiceClient(conn)
|
||||
for _, server := range []string{"node-a", "node-b"} {
|
||||
if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-f", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range []*control.WorkspaceBinding{
|
||||
{VolumeId: "vol-f", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"},
|
||||
{VolumeId: "vol-f", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"},
|
||||
} {
|
||||
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-f", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for deadline := time.Now().Add(3 * time.Second); ; time.Sleep(10 * time.Millisecond) {
|
||||
if line, ok := h.Publisher().VolumeAuthorityLine("vol-f"); ok && line.Epoch == 1 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("no authority line for vol-f")
|
||||
}
|
||||
}
|
||||
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The CLI against a real master: before the horizon the move is refused
|
||||
// (exit 1) with when it becomes admissible, and the dry run writes nothing;
|
||||
// after it the move is issued with the readout of the stored range; a rerun
|
||||
// with the same request id prints the same; lost-range prints that range;
|
||||
// after a restart with the range file damaged a rerun exits 4 (issued,
|
||||
// readout unproven) and lost-range exits 4. A confirmation at another epoch
|
||||
// is refused by the master's state (exit 1); a malformed one never leaves
|
||||
// the CLI (exit 2).
|
||||
func TestWorkspaceForceMoveAgainstRealMaster(t *testing.T) {
|
||||
headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC)
|
||||
authDir := t.TempDir()
|
||||
cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil
|
||||
}}
|
||||
h, stop := startDeleteMaster(t, cfg)
|
||||
stopped := false
|
||||
defer func() {
|
||||
if !stopped {
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
seedForcedVolume(t, h)
|
||||
args := func(extra ...string) []string {
|
||||
return append([]string{"ops", "workspace", "force-move", "--master", h.Addr(), "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200",
|
||||
"--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1"}, extra...)
|
||||
}
|
||||
|
||||
if code, _, errOut := runCLI(args("--confirm-forced", "vol-f@1x")); code != wsExitRefusedLocally {
|
||||
t.Fatalf("malformed confirmation: exit %d %s", code, errOut)
|
||||
}
|
||||
if code, _, errOut := runCLI(args("--confirm-forced", "vol-f@2")); code != wsExitRefused || !strings.Contains(errOut, "no holder of volume") {
|
||||
t.Fatalf("confirmation at another epoch: exit %d %s", code, errOut)
|
||||
}
|
||||
code, _, errOut := runCLI(args("--confirm-forced", "vol-f@1"))
|
||||
if code != wsExitRefused || !strings.Contains(errOut, "has not elapsed") || !strings.Contains(errOut, "admissible at ") {
|
||||
t.Fatalf("before the horizon: exit %d %s", code, errOut)
|
||||
}
|
||||
code, out, _ := runCLI(args("--confirm-forced", "vol-f@1", "--dry-run"))
|
||||
if code != wsExitOK || !strings.Contains(out, "forced move not admitted") || !strings.Contains(out, "admissible at ") {
|
||||
t.Fatalf("dry run before the horizon: exit %d\n%s", code, out)
|
||||
}
|
||||
if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 {
|
||||
t.Fatalf("refusal or dry run wrote a journal record: %+v", st.Moves)
|
||||
}
|
||||
|
||||
st := h.Publisher().WorkspaceState("vol-f")
|
||||
skew := time.Duration(st.Lease.MaxClockSkewNS)
|
||||
if skew < cfg.WorkspaceMaxClockSkew {
|
||||
skew = cfg.WorkspaceMaxClockSkew
|
||||
}
|
||||
time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond)
|
||||
|
||||
code, out, errOut = runCLI(args("--confirm-forced", "vol-f@1"))
|
||||
if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b (kept HEAD gen 9, remote LSN 42)\n") ||
|
||||
!strings.Contains(out, "volume vol-f restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; writes acknowledged by r1@1 after that and before ") {
|
||||
t.Fatalf("forced move: exit %d stderr %s\n%s", code, errOut, out)
|
||||
}
|
||||
code2, out2, _ := runCLI(args("--confirm-forced", "vol-f@1"))
|
||||
if code2 != wsExitOK || out2 != out {
|
||||
t.Fatalf("rerun with the same request id: exit %d\n%s\nwant\n%s", code2, out2, out)
|
||||
}
|
||||
readout := strings.Split(out, "\n")[1]
|
||||
code, lr, _ := runCLI([]string{"ops", "workspace", "lost-range", "--master", h.Addr(), "--volume", "vol-f"})
|
||||
if code != wsExitOK || !strings.HasPrefix(lr, "range 1 of 1: request force-1, r1@1 -> epoch 2, lost after LSN 42") || !strings.Contains(lr, " "+readout+"\n") {
|
||||
t.Fatalf("lost-range: exit %d\n%s\nwant readout %s", code, lr, readout)
|
||||
}
|
||||
|
||||
stop()
|
||||
stopped = true
|
||||
var files []string
|
||||
_ = filepath.WalkDir(authDir, func(p string, d fs.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() && strings.HasSuffix(p, ".lostrange.json") {
|
||||
files = append(files, p)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if len(files) != 1 {
|
||||
t.Fatalf("lost range files %v", files)
|
||||
}
|
||||
raw, err := os.ReadFile(files[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(files[0], []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":41`, 1)), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h2, stop2 := startDeleteMaster(t, cfg)
|
||||
defer stop2()
|
||||
args2 := func(extra ...string) []string {
|
||||
a := args(extra...)
|
||||
a[4] = h2.Addr()
|
||||
return a
|
||||
}
|
||||
code, out, errOut = runCLI(args2("--confirm-forced", "vol-f@1"))
|
||||
if code != wsExitReadoutUnproven || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1") || strings.Contains(out, "restored to") || !strings.Contains(errOut, "not proven") {
|
||||
t.Fatalf("rerun with a damaged range: exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
if code, _, errOut = runCLI([]string{"ops", "workspace", "lost-range", "--master", h2.Addr(), "--volume", "vol-f"}); code != wsExitReadoutUnproven {
|
||||
t.Fatalf("lost-range with a damaged range: exit %d %s", code, errOut)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
)
|
||||
|
||||
type lockedLog struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (l *lockedLog) Write(p []byte) (int, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.b.Write(p)
|
||||
}
|
||||
|
||||
func (l *lockedLog) String() string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.b.String()
|
||||
}
|
||||
|
||||
// A failure AFTER the forced move is issued (here the binding
|
||||
// reconciliation, made to fail by moving the binding store's directory away)
|
||||
// is reported through the RPC, the client and the CLI as an unknown outcome
|
||||
// with the same-request-id recovery, never as a refusal ("nothing moved")
|
||||
// and never with a fresh request id; the master's audit log records the
|
||||
// issue; a rerun with the same id then returns the stored grant.
|
||||
func TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome(t *testing.T) {
|
||||
logs := &lockedLog{}
|
||||
lifecycleDir := t.TempDir()
|
||||
cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true,
|
||||
Logger: log.New(logs, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}, nil
|
||||
}}
|
||||
h, stop := startDeleteMaster(t, cfg)
|
||||
defer stop()
|
||||
seedForcedVolume(t, h)
|
||||
st := h.Publisher().WorkspaceState("vol-f")
|
||||
skew := time.Duration(st.Lease.MaxClockSkewNS)
|
||||
if skew < cfg.WorkspaceMaxClockSkew {
|
||||
skew = cfg.WorkspaceMaxClockSkew
|
||||
}
|
||||
time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond)
|
||||
|
||||
bindings := filepath.Join(lifecycleDir, "workspace-bindings")
|
||||
if err := os.Rename(bindings, bindings+".aside"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"ops", "workspace", "force-move", "--master", h.Addr(), "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200",
|
||||
"--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1", "--confirm-forced", "vol-f@1"}
|
||||
code, out, errOut := runCLI(args)
|
||||
if line, ok := h.Publisher().VolumeAuthorityLine("vol-f"); !ok || line.Epoch != 2 {
|
||||
t.Fatalf("fixture: the forced move was not issued before the failure: %+v", line)
|
||||
}
|
||||
if code != wsExitUnknown || strings.Contains(errOut, "nothing moved") || strings.Contains(out, "nothing moved") ||
|
||||
!strings.Contains(errOut, "rerun with the SAME --request-id force-1") || strings.Contains(strings.ToLower(errOut), "new request id") {
|
||||
t.Fatalf("post-issue failure: exit %d stdout %q stderr %s; want exit 3 with the same-id recovery and no refusal", code, out, errOut)
|
||||
}
|
||||
if !strings.Contains(logs.String(), `forced move issued volume="vol-f" request="force-1"`) {
|
||||
t.Fatalf("issued forced move missing from the audit log:\n%s", logs.String())
|
||||
}
|
||||
if err := os.Rename(bindings+".aside", bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, out, errOut = runCLI(args)
|
||||
if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b") {
|
||||
t.Fatalf("rerun with the same id: exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// fakeWorkspace is a workspace service with canned answers that records
|
||||
// every call.
|
||||
type fakeWorkspace struct {
|
||||
control.UnimplementedWorkspaceServiceServer
|
||||
mu sync.Mutex
|
||||
calls map[string]int
|
||||
moves []*control.WorkspaceMove
|
||||
status *control.WorkspaceStatus
|
||||
move func(*control.WorkspaceMove) (*control.WorkspaceGrant, error)
|
||||
preview *control.WorkspaceMovePreview
|
||||
ranges []*control.WorkspaceLostRange
|
||||
rangeErr error
|
||||
lastLR *control.WorkspaceLostRangeQuery
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) count(m string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.calls == nil {
|
||||
f.calls = map[string]int{}
|
||||
}
|
||||
f.calls[m]++
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) n(m string) int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.calls[m]
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) total() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
n := 0
|
||||
for _, c := range f.calls {
|
||||
n += c
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) QueryWorkspace(context.Context, *control.WorkspaceVolume) (*control.WorkspaceStatus, error) {
|
||||
f.count("QueryWorkspace")
|
||||
return f.status, nil
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) MoveWorkspace(_ context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
f.count("MoveWorkspace")
|
||||
f.mu.Lock()
|
||||
f.moves = append(f.moves, q)
|
||||
f.mu.Unlock()
|
||||
return f.move(q)
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) PreviewWorkspaceMove(context.Context, *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) {
|
||||
f.count("PreviewWorkspaceMove")
|
||||
if f.preview == nil {
|
||||
return nil, status.Error(codes.Unavailable, "no preview")
|
||||
}
|
||||
return f.preview, nil
|
||||
}
|
||||
|
||||
func (f *fakeWorkspace) QueryWorkspaceLostRange(_ context.Context, q *control.WorkspaceLostRangeQuery) (*control.WorkspaceLostRanges, error) {
|
||||
f.count("QueryWorkspaceLostRange")
|
||||
f.mu.Lock()
|
||||
f.lastLR = q
|
||||
f.mu.Unlock()
|
||||
if f.rangeErr != nil {
|
||||
return nil, f.rangeErr
|
||||
}
|
||||
return &control.WorkspaceLostRanges{Ranges: f.ranges}, nil
|
||||
}
|
||||
|
||||
// startFakeWorkspace serves f; dials counts the CLI's connections.
|
||||
func startFakeWorkspace(t *testing.T, f *fakeWorkspace) (addr string, dials *int) {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
control.RegisterWorkspaceServiceServer(srv, f)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
n := 0
|
||||
prev := workspaceDial
|
||||
workspaceDial = func(a string) (*wsclient.Client, error) { n++; return wsclient.Dial(a) }
|
||||
t.Cleanup(func() { workspaceDial = prev })
|
||||
return lis.Addr().String(), &n
|
||||
}
|
||||
|
||||
var (
|
||||
wsHeadTime = time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC)
|
||||
wsLostUntil = time.Date(2026, 11, 21, 1, 5, 0, 0, time.UTC)
|
||||
)
|
||||
|
||||
func wsHolder() *control.WorkspaceStatus {
|
||||
return &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}
|
||||
}
|
||||
|
||||
func wsGrant(q *control.WorkspaceMove) *control.WorkspaceGrant {
|
||||
return &control.WorkspaceGrant{RequestId: q.RequestId, VolumeId: q.VolumeId, OldReplicaId: q.ExpectedReplicaId, NewReplicaId: q.TargetReplicaId, Kind: "forced",
|
||||
OldEpoch: q.ExpectedEpoch, NewEpoch: q.ExpectedEpoch + 1, HeadGen: 9, RemoteLsn: 42, Issued: true, OldHost: "node-a", NewHost: q.TargetServerId,
|
||||
LostRange: &control.WorkspaceLostRange{RequestId: q.RequestId, VolumeId: q.VolumeId, NewEpoch: q.ExpectedEpoch + 1, OldReplicaId: q.ExpectedReplicaId, OldEpoch: q.ExpectedEpoch,
|
||||
LostAfterLsn: 42, LostUntilNs: wsLostUntil.UnixNano(), HeadGen: 9, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true}}
|
||||
}
|
||||
|
||||
const wsReadout = "volume vol restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " +
|
||||
"writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00Z, master clock, may be lost; the upper bound is a time, not an LSN."
|
||||
|
||||
func forceMoveArgs(addr string, extra ...string) []string {
|
||||
return append([]string{"ops", "workspace", "force-move", "--master", addr, "--volume", "vol", "--target-host", "node-b", "--target-data", "10.0.0.2:3260",
|
||||
"--target-ctrl", "10.0.0.2:9100", "--request-id", "req-1"}, extra...)
|
||||
}
|
||||
|
||||
func runCLI(args []string) (int, string, string) {
|
||||
var out, errOut bytes.Buffer
|
||||
code := run(args, &out, &errOut)
|
||||
return code, out.String(), errOut.String()
|
||||
}
|
||||
|
||||
// Row Parse -> Refused (INV-WS-FORCED-CONFIRM-001): a confirmation that is
|
||||
// absent or not exactly <volume>@<expected epoch> exits 2 with no
|
||||
// connection and no RPC.
|
||||
func TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { return wsGrant(q), nil }}
|
||||
addr, dials := startFakeWorkspace(t, f)
|
||||
for _, extra := range [][]string{nil, {"--confirm-forced", "other@3"}, {"--confirm-forced", "vol"}, {"--confirm-forced", "vol@x"}, {"--confirm-forced", "vol@0"},
|
||||
{"--confirm-forced", "vol@3", "--force"}, {"--dry-run"}} {
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, extra...))
|
||||
if code != wsExitRefusedLocally || out != "" {
|
||||
t.Fatalf("%v: exit %d stdout %q; want 2 and nothing", extra, code, out)
|
||||
}
|
||||
if len(extra) > 0 && extra[len(extra)-1] != "--force" && !strings.Contains(errOut, "refused locally") {
|
||||
t.Fatalf("%v: stderr %q", extra, errOut)
|
||||
}
|
||||
}
|
||||
if *dials != 0 || f.total() != 0 {
|
||||
t.Fatalf("refused locally after %d dials and %d RPCs", *dials, f.total())
|
||||
}
|
||||
}
|
||||
|
||||
// Row Parse -> Preview: --dry-run calls only the preview, writes nothing,
|
||||
// labels the answer advisory, says when a refused move becomes admissible,
|
||||
// and exits 0 whatever the answer.
|
||||
func TestWorkspaceForceMove_Row2_DryRunPreview(t *testing.T) {
|
||||
master := time.Date(2026, 11, 21, 1, 4, 0, 0, time.UTC)
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { panic("dry run moved") },
|
||||
preview: &control.WorkspaceMovePreview{Reason: "workspace forced move lease expiry plus clock-skew margin has not elapsed", LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: master.UnixNano()}}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run"))
|
||||
if code != wsExitOK || f.n("MoveWorkspace") != 0 || f.n("PreviewWorkspaceMove") != 1 {
|
||||
t.Fatalf("exit %d, %v; stderr %s", code, f.calls, errOut)
|
||||
}
|
||||
for _, s := range []string{"preview (advisory): at master time 2026-11-21T01:04:00Z, may change; admission is re-checked at the move", "this is not a confirmation",
|
||||
"forced move not admitted: workspace forced move lease expiry", "admissible at 2026-11-21T01:05:00Z, master clock"} {
|
||||
if !strings.Contains(out, s) {
|
||||
t.Fatalf("stdout lacks %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
f.preview = &control.WorkspaceMovePreview{Admitted: true, LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(time.Minute).UnixNano(),
|
||||
HeadRead: true, HeadGen: 9, HeadEpoch: 3, HeadHolder: "node-a/r1", HeadRemoteLsn: 42, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true}
|
||||
code, out, _ = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run"))
|
||||
if code != wsExitOK || f.n("MoveWorkspace") != 0 || strings.Contains(out, "admissible at") ||
|
||||
!strings.Contains(out, "forced move admitted") || !strings.Contains(out, "HEAD now: gen 9, epoch 3, holder node-a/r1, remote LSN 42, published at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution)") {
|
||||
t.Fatalf("admitted preview: exit %d\n%s", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
// Rows Parse -> Sent and Sent -> Granted: the move is sent as kind forced,
|
||||
// force true, at the confirmed epoch with the request id; the grant and the
|
||||
// readout from its stored range are printed, with the next step.
|
||||
func TestWorkspaceForceMove_Row3and4_SentAndGranted(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { return wsGrant(q), nil }}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3"))
|
||||
if code != wsExitOK || errOut != "" {
|
||||
t.Fatalf("exit %d stderr %s", code, errOut)
|
||||
}
|
||||
q := f.moves[0]
|
||||
if len(f.moves) != 1 || q.Kind != "forced" || !q.Force || q.ExpectedEpoch != 3 || q.ExpectedReplicaId != "r1" || q.TargetReplicaId != "r1" || q.RequestId != "req-1" ||
|
||||
q.VolumeId != "vol" || q.TargetServerId != "node-b" || q.TargetDataAddr != "10.0.0.2:3260" || q.TargetCtrlAddr != "10.0.0.2:9100" {
|
||||
t.Fatalf("sent %+v", f.moves)
|
||||
}
|
||||
want := "forced move issued: volume vol request req-1: r1@3 on node-a -> r1@4 on node-b (kept HEAD gen 9, remote LSN 42)\n" + wsReadout + "\n" +
|
||||
"next: start volume vol on node-b (this command moved authority only)\n"
|
||||
if out != want {
|
||||
t.Fatalf("stdout\n got %q\nwant %q", out, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Row Sent -> Refused: a FailedPrecondition prints the master's reason and,
|
||||
// before the horizon, when the move becomes admissible; exit 1.
|
||||
func TestWorkspaceForceMove_Row5_MasterRefusal(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
return nil, status.Error(codes.FailedPrecondition, "workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}, preview: &control.WorkspaceMovePreview{LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(-time.Minute).UnixNano()}}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3"))
|
||||
if code != wsExitRefused || out != "" || !strings.Contains(errOut, "refused by the master (nothing moved)") || !strings.Contains(errOut, "has not elapsed") ||
|
||||
!strings.Contains(errOut, "admissible at 2026-11-21T01:05:00Z, master clock") || !strings.Contains(errOut, "there is no bypass") {
|
||||
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
// Past the horizon (refused for another reason) no time is promised.
|
||||
f.preview = &control.WorkspaceMovePreview{Admitted: true, LostUntilNs: wsLostUntil.UnixNano(), MasterTimeNs: wsLostUntil.Add(time.Minute).UnixNano()}
|
||||
if code, _, errOut = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")); code != wsExitRefused || strings.Contains(errOut, "admissible at") {
|
||||
t.Fatalf("exit %d stderr %s", code, errOut)
|
||||
}
|
||||
// A confirmation at an epoch the master never had is refused before the move.
|
||||
moves := f.n("MoveWorkspace")
|
||||
if code, _, errOut = runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@7")); code != wsExitRefused || f.n("MoveWorkspace") != moves || !strings.Contains(errOut, "no holder of volume") {
|
||||
t.Fatalf("stale epoch: exit %d stderr %s", code, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
// Row Sent -> Unknown: a transport error or the deadline leaves the outcome
|
||||
// unknown; exit 3 with "rerun with the SAME --request-id".
|
||||
func TestWorkspaceForceMove_Row6_OutcomeUnknown(t *testing.T) {
|
||||
for name, move := range map[string]func(*control.WorkspaceMove) (*control.WorkspaceGrant, error){
|
||||
"unavailable": func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
return nil, status.Error(codes.Unavailable, "connection reset")
|
||||
},
|
||||
"deadline": func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
time.Sleep(2 * time.Second)
|
||||
return nil, status.Error(codes.Unavailable, "late")
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: move}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--timeout", "500ms"))
|
||||
if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "outcome unknown: rerun with the SAME --request-id req-1") {
|
||||
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Row Granted -> LostMissing: an issued forced grant without its stored
|
||||
// range (or with another move's) exits 4: the move is issued, the readout is
|
||||
// not proven, and "no loss" is never printed. lost-range with a missing or
|
||||
// corrupt record (DataLoss) exits 4 too.
|
||||
func TestWorkspaceForceMove_Row7_ReadoutUnproven(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
g := wsGrant(q)
|
||||
g.LostRange, g.LostRangeError = nil, "workspace lost range missing or unreadable: forced move \"req-1\" has no loaded lost range record"
|
||||
return g, nil
|
||||
}, rangeErr: status.Error(codes.DataLoss, "workspace lost range missing or unreadable")}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3"))
|
||||
if code != wsExitReadoutUnproven || !strings.HasPrefix(out, "forced move issued: volume vol request req-1") || strings.Contains(out, "restored to") ||
|
||||
!strings.Contains(errOut, "lost range is not proven") || !strings.Contains(errOut, "the move IS issued; do not assume no loss") {
|
||||
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
code, out, errOut = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"})
|
||||
if code != wsExitReadoutUnproven || out != "" || !strings.Contains(errOut, "NOT proven") {
|
||||
t.Fatalf("lost-range: exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
// splitShellWords splits a POSIX shell line of plain words and
|
||||
// single-quoted parts and backslash escapes (the forms shellCommand prints).
|
||||
func splitShellWords(t *testing.T, line string) []string {
|
||||
t.Helper()
|
||||
var words []string
|
||||
var cur strings.Builder
|
||||
in, quoted, inQuote, escaped := false, false, false, false
|
||||
for _, r := range line {
|
||||
switch {
|
||||
case escaped:
|
||||
cur.WriteRune(r)
|
||||
escaped, in = false, true
|
||||
case inQuote && r == '\'':
|
||||
inQuote = false
|
||||
case inQuote:
|
||||
cur.WriteRune(r)
|
||||
case r == '\'':
|
||||
inQuote, in, quoted = true, true, true
|
||||
case r == '\\':
|
||||
escaped = true
|
||||
case r == ' ':
|
||||
if in {
|
||||
words = append(words, cur.String())
|
||||
cur.Reset()
|
||||
in, quoted = false, false
|
||||
}
|
||||
default:
|
||||
cur.WriteRune(r)
|
||||
in = true
|
||||
}
|
||||
}
|
||||
if inQuote {
|
||||
t.Fatalf("unterminated quote in %q", line)
|
||||
}
|
||||
if in || quoted {
|
||||
words = append(words, cur.String())
|
||||
}
|
||||
return words
|
||||
}
|
||||
|
||||
// The exit-4 recovery command carries the master address and survives
|
||||
// arguments that need quoting: the printed words parse back to the same
|
||||
// values and run as a lost-range command against the same master.
|
||||
func TestWorkspaceForceMoveRecoveryCommandRuns(t *testing.T) {
|
||||
const reqID = "req 1'$x"
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
g := wsGrant(q)
|
||||
g.LostRange, g.LostRangeError = nil, "missing"
|
||||
return g, nil
|
||||
}, ranges: nil}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
args := forceMoveArgs(addr, "--confirm-forced", "vol@3")
|
||||
args[len(args)-3] = reqID // --request-id value
|
||||
code, _, errOut := runCLI(args)
|
||||
if code != wsExitReadoutUnproven {
|
||||
t.Fatalf("exit %d %s", code, errOut)
|
||||
}
|
||||
var line string
|
||||
for _, l := range strings.Split(errOut, "\n") {
|
||||
if strings.HasPrefix(l, workspaceRecoveryPrefix+"sw-block ") {
|
||||
line = strings.TrimPrefix(l, workspaceRecoveryPrefix)
|
||||
}
|
||||
}
|
||||
words := splitShellWords(t, line)
|
||||
want := []string{"sw-block", "ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", reqID}
|
||||
if strings.Join(words, "\x00") != strings.Join(want, "\x00") {
|
||||
t.Fatalf("recovery command %q parses to %q; want %q", line, words, want)
|
||||
}
|
||||
f.ranges = []*control.WorkspaceLostRange{{RequestId: reqID, VolumeId: "vol", NewEpoch: 4, OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: wsLostUntil.UnixNano(), HeadGen: 9}}
|
||||
if code, out, errOut := runCLI(words[1:]); code != wsExitOK || f.lastLR.RequestId != reqID || f.lastLR.VolumeId != "vol" || !strings.Contains(out, "range 1 of 1") {
|
||||
t.Fatalf("recovery command run: exit %d %+v stdout %q stderr %s", code, f.lastLR, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
// A successful answer that does not match the request (here the target)
|
||||
// is an unknown outcome, and one whose range disagrees with the kept HEAD
|
||||
// is unproven: neither prints the preservation readout.
|
||||
func TestWorkspaceForceMoveRejectsAMismatchedAnswer(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
fault func(*control.WorkspaceGrant)
|
||||
exit int
|
||||
}{
|
||||
"grant target": {func(g *control.WorkspaceGrant) { g.NewHost = "node-c" }, wsExitUnknown},
|
||||
"grant epoch": {func(g *control.WorkspaceGrant) { g.OldEpoch = 2 }, wsExitUnknown},
|
||||
"range volume": {func(g *control.WorkspaceGrant) { g.LostRange.VolumeId = "vol2" }, wsExitReadoutUnproven},
|
||||
"range frontier": {func(g *control.WorkspaceGrant) { g.LostRange.LostAfterLsn = 41 }, wsExitReadoutUnproven},
|
||||
"range head gen": {func(g *control.WorkspaceGrant) { g.LostRange.HeadGen = 8 }, wsExitReadoutUnproven},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
g := wsGrant(q)
|
||||
tc.fault(g)
|
||||
return g, nil
|
||||
}}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3"))
|
||||
if code != tc.exit || strings.Contains(out, "restored to") || strings.Contains(out, "next: start") {
|
||||
t.Fatalf("exit %d (want %d) stdout %q stderr %s", code, tc.exit, out, errOut)
|
||||
}
|
||||
if tc.exit == wsExitUnknown && !strings.Contains(errOut, "rerun with the SAME --request-id req-1") {
|
||||
t.Fatalf("no same-id recovery: %s", errOut)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Row Rerun same id -> Granted: the master replays the stored grant, and
|
||||
// the output is the same, from the stored range.
|
||||
func TestWorkspaceForceMove_Row8_RerunSameRequestID(t *testing.T) {
|
||||
stored := map[string]*control.WorkspaceGrant{}
|
||||
f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
if g, ok := stored[q.RequestId]; ok {
|
||||
return g, nil
|
||||
}
|
||||
stored[q.RequestId] = wsGrant(q)
|
||||
return nil, status.Error(codes.Unavailable, "reply lost")
|
||||
}}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
if code, _, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3")); code != wsExitUnknown {
|
||||
t.Fatalf("first run: exit %d; want unknown", code)
|
||||
}
|
||||
code, out, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3"))
|
||||
code2, out2, _ := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3"))
|
||||
if code != wsExitOK || code2 != wsExitOK || out != out2 || !strings.Contains(out, wsReadout) {
|
||||
t.Fatalf("reruns: exit %d/%d\n%s\n%s", code, code2, out, out2)
|
||||
}
|
||||
if len(f.moves) != 3 || f.moves[0].RequestId != f.moves[2].RequestId {
|
||||
t.Fatalf("moves %+v", f.moves)
|
||||
}
|
||||
}
|
||||
|
||||
// lost-range lists every stored range in issue order (or the one of
|
||||
// --request-id), each with its readout; a volume without forced moves says
|
||||
// so.
|
||||
func TestWorkspaceLostRangeListsAllInOrder(t *testing.T) {
|
||||
q := &control.WorkspaceMove{RequestId: "req-1", VolumeId: "vol", ExpectedReplicaId: "r1", TargetReplicaId: "r1", ExpectedEpoch: 3}
|
||||
first := wsGrant(q).LostRange
|
||||
second := &control.WorkspaceLostRange{RequestId: "req-2", VolumeId: "vol", NewEpoch: 5, OldReplicaId: "r1", OldEpoch: 4, LostAfterLsn: 42,
|
||||
LostUntilNs: wsLostUntil.Add(time.Minute).UnixNano(), HeadGen: 9, HeadTimeNs: wsHeadTime.UnixNano(), HeadTimeKnown: true}
|
||||
f := &fakeWorkspace{ranges: []*control.WorkspaceLostRange{first, second}}
|
||||
addr, _ := startFakeWorkspace(t, f)
|
||||
code, out, _ := runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"})
|
||||
i1, i2 := strings.Index(out, "range 1 of 2: request req-1, r1@3 -> epoch 4"), strings.Index(out, "range 2 of 2: request req-2, r1@4 -> epoch 5")
|
||||
if code != wsExitOK || i1 < 0 || i2 < i1 || !strings.Contains(out, " "+wsReadout+"\n") || !strings.Contains(out, "acknowledged by r1@4 after that and before 2026-11-21T01:06:00Z") {
|
||||
t.Fatalf("exit %d\n%s", code, out)
|
||||
}
|
||||
if f.lastLR.RequestId != "" {
|
||||
t.Fatalf("listed with request id %q", f.lastLR.RequestId)
|
||||
}
|
||||
f.ranges = []*control.WorkspaceLostRange{second}
|
||||
if code, out, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", "req-2"}); code != wsExitOK || f.lastLR.RequestId != "req-2" || !strings.Contains(out, "range 1 of 1: request req-2") {
|
||||
t.Fatalf("by request id: exit %d %+v\n%s", code, f.lastLR, out)
|
||||
}
|
||||
f.ranges = nil
|
||||
if code, out, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol"}); code != wsExitOK || out != "volume vol has no issued forced move\n" {
|
||||
t.Fatalf("none: exit %d %q", code, out)
|
||||
}
|
||||
f.rangeErr = status.Error(codes.NotFound, "no issued forced move with that request id")
|
||||
if code, _, _ = runCLI([]string{"ops", "workspace", "lost-range", "--master", addr, "--volume", "vol", "--request-id", "x"}); code != wsExitRefused {
|
||||
t.Fatalf("unknown request id: exit %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
// The help says authority only, the next step, and that no bypass exists.
|
||||
func TestWorkspaceHelpText(t *testing.T) {
|
||||
code, out, _ := runCLI([]string{"ops", "workspace", "help"})
|
||||
out = strings.Join(strings.Fields(out), " ")
|
||||
for _, s := range []string{"AUTHORITY only", "starting the volume on the target host is the next step", "There is NO bypass", "never a confirmation", "<volume>@<expected epoch>"} {
|
||||
if code != wsExitOK || !strings.Contains(out, s) {
|
||||
t.Fatalf("help lacks %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
)
|
||||
|
||||
// The issuing write of a forced move reaches the authority store (renamed
|
||||
// into place) but the store reports an error (directory sync): the master
|
||||
// cannot know whether the move is issued, and memory stays unissued. The
|
||||
// CLI must report an unknown outcome with the same-request-id recovery,
|
||||
// never "nothing moved", also on a rerun before the master restarts; after a
|
||||
// restart the master reloads the issued record and a rerun with the same id
|
||||
// gets the grant.
|
||||
func TestWorkspaceForceMoveUncertainIssueWriteIsUnknown(t *testing.T) {
|
||||
logs := &lockedLog{}
|
||||
cfg := master.Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
|
||||
Logger: log.New(logs, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}, nil
|
||||
}}
|
||||
h, stop := startDeleteMaster(t, cfg)
|
||||
stopped := false
|
||||
defer func() {
|
||||
if !stopped {
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
seedForcedVolume(t, h)
|
||||
st := h.Publisher().WorkspaceState("vol-f")
|
||||
skew := time.Duration(st.Lease.MaxClockSkewNS)
|
||||
if skew < cfg.WorkspaceMaxClockSkew {
|
||||
skew = cfg.WorkspaceMaxClockSkew
|
||||
}
|
||||
time.Sleep(time.Until(time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)) + 100*time.Millisecond)
|
||||
|
||||
var faults atomic.Int32
|
||||
authority.SetPutAfterRenameFaultForTest(func(r authority.DurableRecord) error {
|
||||
if r.Workspace == nil {
|
||||
return nil
|
||||
}
|
||||
for _, m := range r.Workspace.Moves {
|
||||
if m.RequestID == "force-1" && m.Issued && faults.Add(1) == 1 {
|
||||
return errors.New("injected directory fsync failure after the rename")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(func() { authority.SetPutAfterRenameFaultForTest(nil) })
|
||||
|
||||
args := func(addr string) []string {
|
||||
return []string{"ops", "workspace", "force-move", "--master", addr, "--volume", "vol-f", "--target-host", "node-b", "--target-data", "127.0.0.1:29200",
|
||||
"--target-ctrl", "127.0.0.1:29100", "--request-id", "force-1", "--confirm-forced", "vol-f@1"}
|
||||
}
|
||||
for _, attempt := range []string{"first", "rerun before restart"} {
|
||||
code, out, errOut := runCLI(args(h.Addr()))
|
||||
if code != wsExitUnknown || strings.Contains(errOut+out, "nothing moved") || !strings.Contains(errOut, "rerun with the SAME --request-id force-1") {
|
||||
t.Fatalf("%s: exit %d stdout %q stderr %s; want exit 3 with the same-id recovery and no refusal", attempt, code, out, errOut)
|
||||
}
|
||||
}
|
||||
if faults.Load() != 1 {
|
||||
t.Fatalf("fixture: the issuing write failed %d times; want once", faults.Load())
|
||||
}
|
||||
if line, _ := h.Publisher().VolumeAuthorityLine("vol-f"); line.Epoch != 1 {
|
||||
t.Fatalf("fixture: memory published the issue (epoch %d); this control needs it unpublished", line.Epoch)
|
||||
}
|
||||
if !strings.Contains(logs.String(), `MoveWorkspace outcome unknown volume="vol-f" request="force-1"`) || strings.Contains(logs.String(), "forced move issued") {
|
||||
t.Fatalf("master log must record an unknown outcome, not an issue:\n%s", logs.String())
|
||||
}
|
||||
|
||||
stop()
|
||||
stopped = true
|
||||
h2, stop2 := startDeleteMaster(t, cfg)
|
||||
defer stop2()
|
||||
if line, _ := h2.Publisher().VolumeAuthorityLine("vol-f"); line.Epoch != 2 {
|
||||
t.Fatalf("fixture: the reloaded store does not hold the issued move (epoch %d)", line.Epoch)
|
||||
}
|
||||
code, out, errOut := runCLI(args(h2.Addr()))
|
||||
if code != wsExitOK || !strings.HasPrefix(out, "forced move issued: volume vol-f request force-1: r1@1 on node-a -> r1@2 on node-b") || !strings.Contains(out, "restored to the last published image") {
|
||||
t.Fatalf("rerun after restart: exit %d stdout %q stderr %s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
@@ -469,6 +469,11 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
p.mu.Lock()
|
||||
if p.workspaceUncertain[ask.VolumeID] {
|
||||
p.mu.Unlock()
|
||||
if grant != nil {
|
||||
// An earlier workspace write may have landed (an issue among
|
||||
// them): a move cannot be answered definitely until a reload.
|
||||
return fmt.Errorf("authority: workspace persistence uncertain; restart required: %w", ErrWorkspaceOutcomeUncertain)
|
||||
}
|
||||
return fmt.Errorf("authority: workspace persistence uncertain; restart required")
|
||||
}
|
||||
if p.workspace[ask.VolumeID] != nil && ask.Intent != IntentRefreshEndpoint && grant == nil {
|
||||
@@ -607,6 +612,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
p.refreshLeaseViewLocked(ask.VolumeID)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if issuedWorkspace != nil {
|
||||
// The store may have written the issuing record before
|
||||
// failing (e.g. a directory sync after the rename): the
|
||||
// move's outcome is unknown, not refused.
|
||||
return fmt.Errorf("authority: durable Put of a workspace move issue failed: %w: %w", err, ErrWorkspaceOutcomeUncertain)
|
||||
}
|
||||
return fmt.Errorf("authority: durable Put failed, rolling back mint: %w", err)
|
||||
}
|
||||
p.writeSeqByVolume[ask.VolumeID] = nextSeq
|
||||
|
||||
@@ -6,8 +6,26 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// putAfterRenameFault, when set, runs in every FileAuthorityStore.Put after
|
||||
// the record's rename (its bytes are in the final file) and before the
|
||||
// directory sync; an error fails that Put as a failed sync would.
|
||||
var putAfterRenameFault atomic.Pointer[func(DurableRecord) error]
|
||||
|
||||
// SetPutAfterRenameFaultForTest installs (nil clears) that hook for every
|
||||
// FileAuthorityStore in the process. Tests only: it models a durable write
|
||||
// whose caller sees an error (directory sync or close failing after the
|
||||
// rename).
|
||||
func SetPutAfterRenameFaultForTest(hook func(DurableRecord) error) {
|
||||
if hook == nil {
|
||||
putAfterRenameFault.Store(nil)
|
||||
return
|
||||
}
|
||||
putAfterRenameFault.Store(&hook)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// P14 S5 — File-Per-Volume Authority Store
|
||||
//
|
||||
@@ -188,6 +206,11 @@ func (s *FileAuthorityStore) Put(record DurableRecord) error {
|
||||
_ = os.Remove(tempPath)
|
||||
return fmt.Errorf("authority_store: rename temp->final: %w", err)
|
||||
}
|
||||
if h := putAfterRenameFault.Load(); h != nil {
|
||||
if err := (*h)(record); err != nil {
|
||||
return fmt.Errorf("authority_store: after rename: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort fsync the directory so the rename is durable.
|
||||
// On Windows, opening directories as files for fsync is not
|
||||
|
||||
@@ -2,18 +2,29 @@ package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WorkspaceHead is read from the configured HEAD source, never supplied as
|
||||
// operator evidence. Detached means the old holder's final cut is committed.
|
||||
// FilerMtimeNS is the HEAD entry's modification time as the filer reports it
|
||||
// with that same read (1 s resolution; the entry's mtime is set by the cut
|
||||
// that wrote it); 0 means the source gave none (unknown, never invented).
|
||||
type WorkspaceHead struct {
|
||||
Gen, Epoch, RemoteLSN uint64
|
||||
Holder string
|
||||
Detached bool
|
||||
FilerMtimeNS int64
|
||||
}
|
||||
|
||||
// ErrWorkspaceOutcomeUncertain marks a move whose outcome is unknown: its
|
||||
// issuing write failed after it may have reached the store, or the volume's
|
||||
// workspace persistence is already uncertain. Memory shows it unissued, but
|
||||
// a reload may find it issued; a definite refusal must not be reported.
|
||||
var ErrWorkspaceOutcomeUncertain = errors.New("workspace move outcome unknown: an authority write may have landed")
|
||||
|
||||
type WorkspaceLease struct {
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
@@ -350,19 +361,32 @@ func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, req
|
||||
// forcedMoveAdmissionLocked returns the audit bound of the lost range when a
|
||||
// forced move is admitted. Caller holds p.mu.
|
||||
func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLease) (int64, error) {
|
||||
now := p.workspaceNow()
|
||||
lostUntil, _, err := p.forcedMoveBarrierLocked(volume, lease)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return lostUntil, nil
|
||||
}
|
||||
|
||||
// forcedMoveBarrierLocked evaluates forced admission at master time now. It
|
||||
// returns the barrier (the audit bound of the lost range, wall time: the
|
||||
// later of lease expiry and the granted or restart deadline, each plus
|
||||
// skew) whether or not it has passed, and an error while it has not.
|
||||
// Caller holds p.mu.
|
||||
func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease) (lostUntil int64, now time.Time, err error) {
|
||||
now = p.workspaceNow()
|
||||
skew := p.workspaceSkew(lease)
|
||||
deadline := p.leaseDeadlineLocked(volume)
|
||||
if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) {
|
||||
return 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
// The audit bound only, in wall time: the admission above keeps both
|
||||
// The audit bound only, in wall time: the admission below keeps both
|
||||
// predicates (the deadline's monotonic reading included).
|
||||
lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano()
|
||||
lostUntil = time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano()
|
||||
if d := deadline.Add(skew).UnixNano(); d > lostUntil {
|
||||
lostUntil = d
|
||||
}
|
||||
return lostUntil, nil
|
||||
if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) {
|
||||
return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
return lostUntil, now, nil
|
||||
}
|
||||
|
||||
// issueWorkspaceMove marks the move issued and starts the new holder's lease
|
||||
@@ -414,16 +438,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
return s, r.NewEpoch, now, nil
|
||||
}
|
||||
}
|
||||
owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID
|
||||
if !owned && q.Kind == "forced" {
|
||||
// Admitted (the expected holder's lease has expired) and HEAD read
|
||||
// after that: a HEAD at an older epoch means the expected holder
|
||||
// never claimed it, or an earlier holder's late claim landed. The
|
||||
// lost range starts at this HEAD's RemoteLSN. A HEAD at the expected
|
||||
// or a higher epoch that is not the expected holder's stays refused.
|
||||
owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch
|
||||
}
|
||||
if !owned {
|
||||
if !workspaceHeadAdmits(q, h) {
|
||||
return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder")
|
||||
}
|
||||
if q.Kind == "clean" {
|
||||
@@ -443,7 +458,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind,
|
||||
OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr}
|
||||
if q.Kind == "forced" {
|
||||
lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil}
|
||||
lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil, HeadTimeNS: h.FilerMtimeNS}
|
||||
if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil {
|
||||
return nil, 0, time.Time{}, err
|
||||
}
|
||||
@@ -456,3 +471,81 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
p.issueWorkspaceMove(s, len(s.Moves)-1, now)
|
||||
return s, r.NewEpoch, now, nil
|
||||
}
|
||||
|
||||
// workspaceHeadAdmits is the HEAD rule of a move: HEAD is the expected
|
||||
// holder's at the expected epoch, or, for a forced move only, any published
|
||||
// HEAD at an older epoch. Admitted (the expected holder's lease has expired)
|
||||
// and HEAD read after that: a HEAD at an older epoch means the expected
|
||||
// holder never claimed it, or an earlier holder's late claim landed. The
|
||||
// lost range starts at this HEAD's RemoteLSN. A HEAD at the expected or a
|
||||
// higher epoch that is not the expected holder's stays refused.
|
||||
func workspaceHeadAdmits(q WorkspaceMoveRequest, h WorkspaceHead) bool {
|
||||
owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID
|
||||
if !owned && q.Kind == "forced" {
|
||||
owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch
|
||||
}
|
||||
return owned
|
||||
}
|
||||
|
||||
// WorkspaceForcedMovePreview is a forced move's admission as the publisher
|
||||
// would judge it now. It is advisory: MoveWorkspace checks again.
|
||||
type WorkspaceForcedMovePreview struct {
|
||||
Admitted bool
|
||||
Reason string // why not admitted, or a note on an admitted replay
|
||||
// LostUntilNS is the forced barrier (master wall time): the move is
|
||||
// admissible from then on, and it bounds the lost range. 0 when there
|
||||
// is no lease of the expected holder to judge.
|
||||
LostUntilNS int64
|
||||
NowNS int64 // the master time of this judgement
|
||||
Replay bool // the request id is an issued move: a move replays it
|
||||
}
|
||||
|
||||
// PreviewWorkspaceForcedMove runs the forced admission of req (request
|
||||
// validation, journal replay, the expected line and lease, the barrier)
|
||||
// without reserving, writing or minting anything. The HEAD rule is
|
||||
// WorkspaceMoveHeadAdmits, applied by the caller to a HEAD read after an
|
||||
// admitted preview, as for the move itself.
|
||||
func (p *Publisher) PreviewWorkspaceForcedMove(req WorkspaceMoveRequest) WorkspaceForcedMovePreview {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
out := WorkspaceForcedMovePreview{NowNS: p.workspaceNow().UnixNano()}
|
||||
if req.Kind != "forced" {
|
||||
out.Reason = "workspace move preview: forced moves only"
|
||||
return out
|
||||
}
|
||||
if err := validateWorkspaceMoveRequest(req); err != nil {
|
||||
out.Reason = err.Error()
|
||||
return out
|
||||
}
|
||||
if _, replay, err := p.issuedWorkspaceReplayLocked(req); err != nil {
|
||||
out.Reason = err.Error()
|
||||
return out
|
||||
} else if replay {
|
||||
out.Admitted, out.Replay = true, true
|
||||
out.Reason = "request id already issued: a move with it returns the stored grant"
|
||||
if lr, ok := p.lostRangeForRequestLocked(req.VolumeID, req.RequestID); ok {
|
||||
out.LostUntilNS = lr.LostUntilNS
|
||||
}
|
||||
return out
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(req.VolumeID)
|
||||
s := p.workspace[req.VolumeID]
|
||||
if !ok || line.info.Epoch != req.ExpectedEpoch || line.info.ReplicaID != req.ExpectedReplicaID || s == nil || s.Lease == nil {
|
||||
out.Reason = "workspace move: missing or changed authority/lease"
|
||||
return out
|
||||
}
|
||||
lostUntil, now, err := p.forcedMoveBarrierLocked(req.VolumeID, s.Lease)
|
||||
out.LostUntilNS, out.NowNS = lostUntil, now.UnixNano()
|
||||
if err != nil {
|
||||
out.Reason = err.Error()
|
||||
return out
|
||||
}
|
||||
out.Admitted = true
|
||||
return out
|
||||
}
|
||||
|
||||
// WorkspaceMoveHeadAdmits reports whether head passes the HEAD rule of req
|
||||
// (the same predicate a move applies).
|
||||
func WorkspaceMoveHeadAdmits(req WorkspaceMoveRequest, head WorkspaceHead) bool {
|
||||
return workspaceHeadAdmits(req, head)
|
||||
}
|
||||
@@ -16,6 +16,11 @@ import (
|
||||
// none of them was acknowledged later than LostUntilNS (master time: the
|
||||
// forced barrier, the lease horizon or restart deadline plus skew). The
|
||||
// lease carries no write frontier, so the upper bound is a time.
|
||||
//
|
||||
// HeadTimeNS is the kept HEAD entry's filer mtime, read with that HEAD at the
|
||||
// move; 0 means unknown (the filer gave none, or the record predates the
|
||||
// field). It is stored apart from the checksummed v1 range body (see
|
||||
// lostRangeEnvelope) so the encoding of the ranges themselves is unchanged.
|
||||
type WorkspaceLostRange struct {
|
||||
RequestID string
|
||||
NewEpoch uint64
|
||||
@@ -23,17 +28,82 @@ type WorkspaceLostRange struct {
|
||||
OldEpoch uint64
|
||||
LostAfterLSN uint64
|
||||
LostUntilNS int64
|
||||
HeadTimeNS int64 `json:"-"`
|
||||
}
|
||||
|
||||
// lostRangeFileExtension does not end in storeFileExtension: authority
|
||||
// loaders, old and new, never read these files.
|
||||
const lostRangeFileExtension = ".lostrange.json"
|
||||
|
||||
// lostRangeEnvelope: Checksum covers VolumeID and Ranges exactly as before
|
||||
// HEAD times existed, so a binary that predates them still verifies and
|
||||
// loads the file (it ignores the two fields after it). HeadTimes carries the
|
||||
// non-zero HEAD times; HeadTimesChecksum covers VolumeID, Ranges and
|
||||
// HeadTimes together, and a file with HeadTimes but without a matching
|
||||
// HeadTimesChecksum fails its checks.
|
||||
type lostRangeEnvelope struct {
|
||||
Version int `json:"v"`
|
||||
VolumeID string `json:"volume"`
|
||||
Ranges []WorkspaceLostRange `json:"ranges"`
|
||||
Checksum string `json:"checksum"`
|
||||
Version int `json:"v"`
|
||||
VolumeID string `json:"volume"`
|
||||
Ranges []WorkspaceLostRange `json:"ranges"`
|
||||
Checksum string `json:"checksum"`
|
||||
HeadTimes []lostRangeHeadTime `json:"head_times,omitempty"`
|
||||
HeadTimesChecksum string `json:"head_times_checksum,omitempty"`
|
||||
}
|
||||
|
||||
type lostRangeHeadTime struct {
|
||||
RequestID string
|
||||
NewEpoch uint64
|
||||
HeadTimeNS int64
|
||||
}
|
||||
|
||||
func lostRangeHeadTimesChecksum(volumeID string, ranges []WorkspaceLostRange, times []lostRangeHeadTime) string {
|
||||
body, err := json.Marshal(struct {
|
||||
VolumeID string
|
||||
Ranges []WorkspaceLostRange
|
||||
HeadTimes []lostRangeHeadTime
|
||||
}{volumeID, ranges, times})
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func encodeLostRangeEnvelope(volumeID string, ranges []WorkspaceLostRange) lostRangeEnvelope {
|
||||
env := lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)}
|
||||
for _, r := range ranges {
|
||||
if r.HeadTimeNS != 0 {
|
||||
env.HeadTimes = append(env.HeadTimes, lostRangeHeadTime{RequestID: r.RequestID, NewEpoch: r.NewEpoch, HeadTimeNS: r.HeadTimeNS})
|
||||
}
|
||||
}
|
||||
if len(env.HeadTimes) > 0 {
|
||||
env.HeadTimesChecksum = lostRangeHeadTimesChecksum(volumeID, ranges, env.HeadTimes)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// decodeLostRangeHeadTimes checks env's HEAD times and copies them onto its
|
||||
// ranges.
|
||||
func decodeLostRangeHeadTimes(env *lostRangeEnvelope) error {
|
||||
if len(env.HeadTimes) == 0 && env.HeadTimesChecksum == "" {
|
||||
return nil
|
||||
}
|
||||
if env.HeadTimesChecksum != lostRangeHeadTimesChecksum(env.VolumeID, env.Ranges, env.HeadTimes) {
|
||||
return errors.New("head times checksum mismatch")
|
||||
}
|
||||
for _, t := range env.HeadTimes {
|
||||
found := false
|
||||
for i := range env.Ranges {
|
||||
if env.Ranges[i].RequestID == t.RequestID && env.Ranges[i].NewEpoch == t.NewEpoch {
|
||||
env.Ranges[i].HeadTimeNS = t.HeadTimeNS
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("head time for unknown range %s/%d", t.RequestID, t.NewEpoch)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lostRangeChecksum(volumeID string, ranges []WorkspaceLostRange) string {
|
||||
@@ -54,7 +124,7 @@ func (s *FileAuthorityStore) PutWorkspaceLostRanges(volumeID string, ranges []Wo
|
||||
if volumeID == "" {
|
||||
return fmt.Errorf("authority_store: lost range with empty VolumeID")
|
||||
}
|
||||
payload, err := json.Marshal(lostRangeEnvelope{Version: 1, VolumeID: volumeID, Ranges: ranges, Checksum: lostRangeChecksum(volumeID, ranges)})
|
||||
payload, err := json.Marshal(encodeLostRangeEnvelope(volumeID, ranges))
|
||||
if err != nil {
|
||||
return fmt.Errorf("authority_store: encode lost range: %w", err)
|
||||
}
|
||||
@@ -136,6 +206,8 @@ func (s *FileAuthorityStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLo
|
||||
err = errors.New("checksum mismatch")
|
||||
case encodeVolumeIDForFilename(env.VolumeID)+lostRangeFileExtension != name:
|
||||
err = fmt.Errorf("filename does not match VolumeID %q", env.VolumeID)
|
||||
default:
|
||||
err = decodeLostRangeHeadTimes(&env)
|
||||
}
|
||||
if err != nil {
|
||||
skips = append(skips, fmt.Errorf("%s: %w: lost range %v", name, ErrCorruptRecord, err))
|
||||
@@ -189,6 +261,51 @@ func (p *Publisher) recordLostRangeLocked(volume string, r WorkspaceLostRange) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// ErrWorkspaceLostRangeMissing: an issued forced move has no readable lost
|
||||
// range (never written, or its file failed its checks at load and was
|
||||
// skipped). The readout is unproven; it must never be reported as no loss.
|
||||
var ErrWorkspaceLostRangeMissing = errors.New("workspace lost range missing or unreadable")
|
||||
|
||||
// ErrWorkspaceNoForcedMove: the request id names no issued forced move.
|
||||
var ErrWorkspaceNoForcedMove = errors.New("workspace: no issued forced move with that request id")
|
||||
|
||||
// WorkspaceLostRangeReadout is one stored lost range with the stored move
|
||||
// record it belongs to (the HEAD generation the move kept, and the hosts).
|
||||
type WorkspaceLostRangeReadout struct {
|
||||
WorkspaceLostRange
|
||||
VolumeID string
|
||||
HeadGen uint64
|
||||
OldHost, NewHost string
|
||||
}
|
||||
|
||||
// WorkspaceLostRangeReadouts returns the stored lost range of every issued
|
||||
// forced move of volume, in journal (issue) order, or only requestID's when
|
||||
// it is not empty. Nothing is recomputed. Any issued forced move in scope
|
||||
// whose range is not loaded fails the whole read with
|
||||
// ErrWorkspaceLostRangeMissing; an empty result means the volume has no
|
||||
// issued forced move.
|
||||
func (p *Publisher) WorkspaceLostRangeReadouts(volume, requestID string) ([]WorkspaceLostRangeReadout, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
var out []WorkspaceLostRangeReadout
|
||||
if s := p.workspace[volume]; s != nil {
|
||||
for _, m := range s.Moves {
|
||||
if !m.Issued || m.Kind != "forced" || (requestID != "" && m.RequestID != requestID) {
|
||||
continue
|
||||
}
|
||||
r, ok := p.lostRangeLocked(volume, m.RequestID, m.NewEpoch)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: forced move %q (epoch %d -> %d) of volume %q has no loaded lost range record", ErrWorkspaceLostRangeMissing, m.RequestID, m.OldEpoch, m.NewEpoch, volume)
|
||||
}
|
||||
out = append(out, WorkspaceLostRangeReadout{WorkspaceLostRange: r, VolumeID: volume, HeadGen: m.HeadGen, OldHost: m.OldHost, NewHost: m.NewHost})
|
||||
}
|
||||
}
|
||||
if requestID != "" && len(out) == 0 {
|
||||
return nil, fmt.Errorf("%w: %q on volume %q", ErrWorkspaceNoForcedMove, requestID, volume)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WorkspaceLostRanges returns the lost ranges of volume's issued forced
|
||||
// moves (an entry with no matching issued move is ignored).
|
||||
func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange {
|
||||
@@ -209,3 +326,16 @@ func (p *Publisher) WorkspaceLostRanges(volume string) []WorkspaceLostRange {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// lostRangeForRequestLocked returns the recorded range of requestID's
|
||||
// journal record, if any. Called under p.mu.
|
||||
func (p *Publisher) lostRangeForRequestLocked(volume, requestID string) (WorkspaceLostRange, bool) {
|
||||
if s := p.workspace[volume]; s != nil {
|
||||
for _, m := range s.Moves {
|
||||
if m.RequestID == requestID {
|
||||
return p.lostRangeLocked(volume, requestID, m.NewEpoch)
|
||||
}
|
||||
}
|
||||
}
|
||||
return WorkspaceLostRange{}, false
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The HEAD time a forced move kept, as the filer reported it with HEAD.
|
||||
var headFilerTime = time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC)
|
||||
|
||||
// pastBarrier moves now past the forced barrier of v's current lease.
|
||||
func pastBarrier(t *testing.T, p *Publisher, now *time.Time) {
|
||||
t.Helper()
|
||||
st := p.WorkspaceState("v")
|
||||
if st == nil || st.Lease == nil {
|
||||
t.Fatal("no lease")
|
||||
}
|
||||
barrier := time.Unix(0, st.Lease.ExpiresAtNS)
|
||||
if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) {
|
||||
barrier = d
|
||||
}
|
||||
*now = barrier.Add(p.workspaceSkew(st.Lease)).Add(time.Second)
|
||||
}
|
||||
|
||||
// INV-WS-LOST-RANGE-READOUT-001: a forced move stores the kept HEAD's filer
|
||||
// time with its range; the readout returns it, with the move record's HEAD
|
||||
// generation, also after a reload. A range with a HEAD time keeps the v1
|
||||
// checksum over the ranges, so a binary that predates HEAD times still
|
||||
// verifies the file; a range without one is written exactly as before.
|
||||
func TestWorkspaceForcedMoveStoresHeadFilerTime(t *testing.T) {
|
||||
for _, known := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "filer time known", false: "filer time unknown"}[known], func(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
head := forcedLostRangeHead
|
||||
if known {
|
||||
head.FilerMtimeNS = headFilerTime.UnixNano()
|
||||
}
|
||||
r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := WorkspaceLostRangeReadout{WorkspaceLostRange: WorkspaceLostRange{RequestID: "f", NewEpoch: r.NewEpoch, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano(), HeadTimeNS: head.FilerMtimeNS},
|
||||
VolumeID: "v", HeadGen: 7, OldHost: "old-node", NewHost: "new-node"}
|
||||
for name, q := range map[string]*Publisher{"running": p, "reloaded": NewPublisher(nil, WithStore(disk))} {
|
||||
got, err := q.WorkspaceLostRangeReadouts("v", "")
|
||||
if err != nil || len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("%s: readout %+v %v; want [%+v]", name, got, err, want)
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "v"+lostRangeFileExtension))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(raw), "head_times") != known {
|
||||
t.Fatalf("head times present=%v in %s", !known, raw)
|
||||
}
|
||||
// What a binary that predates HEAD times reads and checks.
|
||||
type oldRange struct {
|
||||
RequestID string
|
||||
NewEpoch uint64
|
||||
OldReplicaID string
|
||||
OldEpoch uint64
|
||||
LostAfterLSN uint64
|
||||
LostUntilNS int64
|
||||
}
|
||||
var old struct {
|
||||
Version int `json:"v"`
|
||||
VolumeID string `json:"volume"`
|
||||
Ranges []oldRange `json:"ranges"`
|
||||
Checksum string `json:"checksum"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := json.Marshal(struct {
|
||||
VolumeID string
|
||||
Ranges []oldRange
|
||||
}{old.VolumeID, old.Ranges})
|
||||
sum := sha256.Sum256(body)
|
||||
if old.Version != 1 || old.Checksum != hex.EncodeToString(sum[:]) || len(old.Ranges) != 1 || old.Ranges[0].LostAfterLSN != 42 {
|
||||
t.Fatalf("an older binary would not verify the file: %s", raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A HEAD time changed on disk without its checksum fails the file's checks:
|
||||
// the readout then fails, never "no loss" and never a wrong time.
|
||||
func TestWorkspaceLostRangeHeadTimeTamperFailsClosed(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
head := forcedLostRangeHead
|
||||
head.FilerMtimeNS = headFilerTime.UnixNano()
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "v"+lostRangeFileExtension)
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var env map[string]any
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env["head_times"].([]any)[0].(map[string]any)["HeadTimeNS"] = float64(headFilerTime.Add(time.Hour).UnixNano())
|
||||
tampered, _ := json.Marshal(env)
|
||||
if err := os.WriteFile(path, tampered, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reloaded := NewPublisher(nil, WithStore(disk))
|
||||
if _, err := reloaded.WorkspaceLostRangeReadouts("v", ""); !errors.Is(err, ErrWorkspaceLostRangeMissing) {
|
||||
t.Fatalf("tampered head time: %v; want ErrWorkspaceLostRangeMissing", err)
|
||||
}
|
||||
if !loadErrorsMention(reloaded, "head times checksum mismatch") {
|
||||
t.Fatalf("load errors %v do not name the failed check", reloaded.LoadErrors())
|
||||
}
|
||||
}
|
||||
|
||||
func loadErrorsMention(p *Publisher, s string) bool {
|
||||
for _, e := range p.LoadErrors() {
|
||||
if strings.Contains(e.Error(), s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Accumulation: a second forced move with no cut between (HEAD unchanged,
|
||||
// still at the first holder's epoch) keeps the same LostAfterLSN with a
|
||||
// later LostUntil; a forced move after a new cut starts at the new HEAD. The
|
||||
// readout lists every range in issue order, or one by request id; replays
|
||||
// return the stored ranges, never recomputed ones.
|
||||
func TestWorkspaceLostRangeAccumulatesInIssueOrder(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
disk, _ := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
h1 := forcedLostRangeHead
|
||||
h1.FilerMtimeNS = headFilerTime.UnixNano()
|
||||
f1, err := p.MoveWorkspace(ctx, forcedLostRangeReq, h1) // old-node -> new-node, epoch 1 -> 2
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pastBarrier(t, p, now)
|
||||
f2req := WorkspaceMoveRequest{RequestID: "f2", VolumeID: "v", ExpectedReplicaID: "old", TargetReplicaID: "old", ExpectedHost: "new-node", TargetHost: "third-node",
|
||||
ExpectedEpoch: f1.NewEpoch, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true}
|
||||
f2, err := p.MoveWorkspace(ctx, f2req, h1) // the grantee never cut: HEAD unchanged
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pastBarrier(t, p, now)
|
||||
h3 := WorkspaceHead{Gen: 8, Epoch: f2.NewEpoch, Holder: "third-node/old", RemoteLSN: 50, FilerMtimeNS: headFilerTime.Add(time.Minute).UnixNano()}
|
||||
f3req := WorkspaceMoveRequest{RequestID: "f3", VolumeID: "v", ExpectedReplicaID: "old", TargetReplicaID: "old", ExpectedHost: "third-node", TargetHost: "old-node",
|
||||
ExpectedEpoch: f2.NewEpoch, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
if _, err := p.MoveWorkspace(ctx, f3req, h3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := p.WorkspaceLostRangeReadouts("v", "")
|
||||
if err != nil || len(got) != 3 {
|
||||
t.Fatalf("readout %+v %v; want three ranges", got, err)
|
||||
}
|
||||
if got[0].RequestID != "f" || got[1].RequestID != "f2" || got[2].RequestID != "f3" {
|
||||
t.Fatalf("not in issue order: %+v", got)
|
||||
}
|
||||
if got[1].LostAfterLSN != got[0].LostAfterLSN || got[1].LostUntilNS <= got[0].LostUntilNS || got[1].HeadGen != 7 || got[1].HeadTimeNS != h1.FilerMtimeNS {
|
||||
t.Fatalf("no cut between: want the same LostAfterLSN, a later LostUntil and the same HEAD: %+v then %+v", got[0], got[1])
|
||||
}
|
||||
if got[2].LostAfterLSN != 50 || got[2].HeadGen != 8 || got[2].HeadTimeNS != h3.FilerMtimeNS || got[2].LostUntilNS <= got[1].LostUntilNS {
|
||||
t.Fatalf("after a cut: want a range from the new HEAD: %+v", got[2])
|
||||
}
|
||||
one, err := p.WorkspaceLostRangeReadouts("v", "f2")
|
||||
if err != nil || len(one) != 1 || one[0] != got[1] {
|
||||
t.Fatalf("by request id: %+v %v; want [%+v]", one, err, got[1])
|
||||
}
|
||||
if _, err := p.WorkspaceLostRangeReadouts("v", "nope"); !errors.Is(err, ErrWorkspaceNoForcedMove) {
|
||||
t.Fatalf("unknown request id: %v", err)
|
||||
}
|
||||
// A replay much later, after a reload, returns the stored grant and the
|
||||
// stored range: nothing is recomputed from the replay's clock or HEAD.
|
||||
*now = now.Add(time.Hour)
|
||||
q := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return *now }))
|
||||
r2, err := q.MoveWorkspace(ctx, f2req, WorkspaceHead{Gen: 99, Epoch: 9, Holder: "x/y", RemoteLSN: 999, FilerMtimeNS: 1})
|
||||
if err != nil || r2 != f2 {
|
||||
t.Fatalf("replay %+v %v; want the stored grant %+v", r2, err, f2)
|
||||
}
|
||||
again, err := q.WorkspaceLostRangeReadouts("v", "")
|
||||
if err != nil || len(again) != 3 || again[0] != got[0] || again[1] != got[1] || again[2] != got[2] {
|
||||
t.Fatalf("after reload and replay: %+v %v; want %+v", again, err, got)
|
||||
}
|
||||
}
|
||||
|
||||
// Fail closed: an issued forced move whose range file is missing, or fails
|
||||
// its checksum, makes the readout fail (all ranges, or its own); it never
|
||||
// returns an empty "no loss".
|
||||
func TestWorkspaceLostRangeReadoutFailsClosed(t *testing.T) {
|
||||
for _, damage := range []string{"missing", "checksum"} {
|
||||
t.Run(damage, func(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
if _, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "v"+lostRangeFileExtension)
|
||||
if damage == "missing" {
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":43`, 1)), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
reloaded := NewPublisher(nil, WithStore(disk))
|
||||
for _, id := range []string{"", "f"} {
|
||||
got, err := reloaded.WorkspaceLostRangeReadouts("v", id)
|
||||
if !errors.Is(err, ErrWorkspaceLostRangeMissing) || got != nil {
|
||||
t.Fatalf("request %q: %+v %v; want ErrWorkspaceLostRangeMissing", id, got, err)
|
||||
}
|
||||
}
|
||||
if damage == "checksum" && !loadErrorsMention(reloaded, "checksum mismatch") {
|
||||
t.Fatalf("load errors %v", reloaded.LoadErrors())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// skipRangeStore drops the lost range write but reports success: the
|
||||
// mutant "grant issued, range write skipped".
|
||||
type skipRangeStore struct{ *FileAuthorityStore }
|
||||
|
||||
func (skipRangeStore) PutWorkspaceLostRanges(string, []WorkspaceLostRange) error { return nil }
|
||||
|
||||
// The mutant "grant issued, range write skipped" is detected: the move
|
||||
// issues (the store claimed the range durable), but the readout of a master
|
||||
// that reloads from disk fails closed instead of reporting no loss. (The
|
||||
// order itself, range before issue, is TestWorkspaceForcedMoveLostRangeOrdering.)
|
||||
func TestWorkspaceLostRangeSkippedWriteIsDetected(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, skipRangeStore{disk}, false)
|
||||
*now = barrier.Add(time.Second)
|
||||
if r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead); err != nil || !r.Issued {
|
||||
t.Fatalf("fixture: %+v %v", r, err)
|
||||
}
|
||||
if _, err := NewPublisher(nil, WithStore(disk)).WorkspaceLostRangeReadouts("v", "f"); !errors.Is(err, ErrWorkspaceLostRangeMissing) {
|
||||
t.Fatalf("skipped range write not detected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// countWritesStore counts every durable write, authority and lost range.
|
||||
type countWritesStore struct {
|
||||
*FileAuthorityStore
|
||||
writes atomic.Int64
|
||||
}
|
||||
|
||||
func (s *countWritesStore) Put(r DurableRecord) error {
|
||||
s.writes.Add(1)
|
||||
return s.FileAuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
func (s *countWritesStore) PutWorkspaceLostRanges(v string, rs []WorkspaceLostRange) error {
|
||||
s.writes.Add(1)
|
||||
return s.FileAuthorityStore.PutWorkspaceLostRanges(v, rs)
|
||||
}
|
||||
|
||||
// The preview runs the forced admission and writes nothing: before the
|
||||
// barrier it is refused and names the barrier (when it becomes admissible);
|
||||
// after it, it is admitted, and the move then records exactly that barrier
|
||||
// as LostUntil. A replay previews as admitted with the stored bound.
|
||||
func TestWorkspaceForcedMovePreviewWritesNothing(t *testing.T) {
|
||||
disk, dir := newTempStore(t)
|
||||
store := &countWritesStore{FileAuthorityStore: disk}
|
||||
p, now, barrier := forcedLostRangeFixture(t, store, false)
|
||||
before, state := store.writes.Load(), p.WorkspaceState("v")
|
||||
*now = barrier.Add(-time.Nanosecond)
|
||||
pv := p.PreviewWorkspaceForcedMove(forcedLostRangeReq)
|
||||
if pv.Admitted || pv.LostUntilNS != barrier.UnixNano() || pv.NowNS != now.UnixNano() || !strings.Contains(pv.Reason, "has not elapsed") {
|
||||
t.Fatalf("preview before the barrier: %+v", pv)
|
||||
}
|
||||
*now = barrier.Add(time.Second)
|
||||
pv = p.PreviewWorkspaceForcedMove(forcedLostRangeReq)
|
||||
if !pv.Admitted || pv.LostUntilNS != barrier.UnixNano() || pv.Replay {
|
||||
t.Fatalf("preview after the barrier: %+v", pv)
|
||||
}
|
||||
bad := forcedLostRangeReq
|
||||
bad.ExpectedEpoch = 5
|
||||
if pv := p.PreviewWorkspaceForcedMove(bad); pv.Admitted || !strings.Contains(pv.Reason, "missing or changed authority/lease") {
|
||||
t.Fatalf("preview at a stale epoch: %+v", pv)
|
||||
}
|
||||
clean := forcedLostRangeReq
|
||||
clean.Kind, clean.Force = "clean", false
|
||||
if pv := p.PreviewWorkspaceForcedMove(clean); pv.Admitted {
|
||||
t.Fatalf("preview of a clean move: %+v", pv)
|
||||
}
|
||||
if !WorkspaceMoveHeadAdmits(forcedLostRangeReq, forcedLostRangeHead) || WorkspaceMoveHeadAdmits(forcedLostRangeReq, WorkspaceHead{Gen: 9, Epoch: 1, Holder: "other/old"}) {
|
||||
t.Fatal("the preview's HEAD rule differs from the move's")
|
||||
}
|
||||
if got := store.writes.Load(); got != before {
|
||||
t.Fatalf("preview wrote %d times", got-before)
|
||||
}
|
||||
if after := p.WorkspaceState("v"); len(after.Moves) != len(state.Moves) || *after.Lease != *state.Lease {
|
||||
t.Fatalf("preview changed state: %+v -> %+v", state, after)
|
||||
}
|
||||
if m, _ := filepath.Glob(filepath.Join(dir, "*"+lostRangeFileExtension)); len(m) != 0 {
|
||||
t.Fatalf("preview wrote a lost range file: %v", m)
|
||||
}
|
||||
r, err := p.MoveWorkspace(context.Background(), forcedLostRangeReq, forcedLostRangeHead)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := p.WorkspaceLostRanges("v"); len(got) != 1 || got[0].LostUntilNS != pv.LostUntilNS {
|
||||
t.Fatalf("move recorded %+v; the preview named %d", got, pv.LostUntilNS)
|
||||
}
|
||||
writes := store.writes.Load()
|
||||
*now = now.Add(time.Hour)
|
||||
if pv := p.PreviewWorkspaceForcedMove(forcedLostRangeReq); !pv.Admitted || !pv.Replay || pv.LostUntilNS != barrier.UnixNano() {
|
||||
t.Fatalf("preview of the issued request %+v (grant %+v)", pv, r)
|
||||
}
|
||||
if store.writes.Load() != writes {
|
||||
t.Fatal("replay preview wrote")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// An issuing write that lands in the store but reports an error (the
|
||||
// directory sync after the rename) leaves the move's outcome unknown:
|
||||
// MoveWorkspace fails with ErrWorkspaceOutcomeUncertain while memory shows
|
||||
// it unissued, a retry before a reload fails the same way, and a reload finds
|
||||
// it issued and replays it. Ordinary refusals (admission before the barrier,
|
||||
// a failed lost-range write before the issue) are not marked uncertain.
|
||||
func TestWorkspaceUncertainIssueWriteIsTyped(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
disk, _ := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, false)
|
||||
req := forcedLostRangeReq
|
||||
req.RequestID = "uncertain-1"
|
||||
|
||||
*now = barrier.Add(-time.Nanosecond)
|
||||
if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) {
|
||||
t.Fatalf("admission refusal before the barrier: %v; want a plain refusal", err)
|
||||
}
|
||||
*now = barrier.Add(time.Second)
|
||||
testLostRangeFaultHook = func(string) error { return errInjected }
|
||||
t.Cleanup(func() { testLostRangeFaultHook = nil })
|
||||
if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, errInjected) || errors.Is(err, ErrWorkspaceOutcomeUncertain) {
|
||||
t.Fatalf("lost-range write failure before the issue: %v; want a plain refusal", err)
|
||||
}
|
||||
testLostRangeFaultHook = nil
|
||||
|
||||
faults := 0
|
||||
SetPutAfterRenameFaultForTest(func(r DurableRecord) error {
|
||||
if r.Workspace != nil {
|
||||
for _, m := range r.Workspace.Moves {
|
||||
if m.RequestID == req.RequestID && m.Issued {
|
||||
faults++
|
||||
return errInjected
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(func() { SetPutAfterRenameFaultForTest(nil) })
|
||||
if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) {
|
||||
t.Fatalf("issuing write landed then failed: %v; want ErrWorkspaceOutcomeUncertain", err)
|
||||
}
|
||||
SetPutAfterRenameFaultForTest(nil)
|
||||
if faults != 1 || p.IssuedWorkspaceMove(req) {
|
||||
t.Fatalf("fixture: faults=%d issued in memory=%v; want one fault and memory unissued", faults, p.IssuedWorkspaceMove(req))
|
||||
}
|
||||
if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) {
|
||||
t.Fatalf("retry before a reload: %v; want ErrWorkspaceOutcomeUncertain", err)
|
||||
}
|
||||
reloaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, func() time.Time { return *now }))
|
||||
if !reloaded.IssuedWorkspaceMove(req) {
|
||||
t.Fatal("the reloaded store does not hold the issued move")
|
||||
}
|
||||
r, err := reloaded.MoveWorkspace(ctx, req, WorkspaceHead{})
|
||||
if err != nil || !r.Issued || r.RequestID != req.RequestID {
|
||||
t.Fatalf("replay after reload: %+v %v", r, err)
|
||||
}
|
||||
if got, err := reloaded.WorkspaceLostRangeReadouts("v", req.RequestID); err != nil || len(got) != 1 || got[0].LostAfterLSN != 42 {
|
||||
t.Fatalf("readout after reload: %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,7 @@ type gcIntent struct {
|
||||
// Different collectors may duplicate idempotent blob deletes but cannot
|
||||
// shorten either collector's independent two-mark grace requirement.
|
||||
type Collector struct {
|
||||
scope string // empty traces and reclaims the entire namespace
|
||||
cat *Catalog
|
||||
blobs BlobDeleter
|
||||
cfg GCConfig
|
||||
@@ -218,7 +219,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
|
||||
// and the actual CAS domain must have
|
||||
// advanced. Mere lease loss, or issuance without takeover,
|
||||
// cannot authorize expiry of a paused publisher's intent.
|
||||
expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued
|
||||
expire = (g.scope == "" || g.scope == vol) && authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued
|
||||
}
|
||||
if expire {
|
||||
expired = append(expired, gcIntent{r, in})
|
||||
@@ -256,6 +257,10 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
|
||||
}
|
||||
}
|
||||
}
|
||||
// INV-MAINT-SCOPE: roots above remain catalog-wide; candidates are local.
|
||||
if g.scope != "" && g.scope != vol {
|
||||
continue
|
||||
}
|
||||
pageAfter := ""
|
||||
for {
|
||||
page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage)
|
||||
|
||||
@@ -31,6 +31,9 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) {
|
||||
}
|
||||
var pending []copyAttempt
|
||||
for _, vol := range vols {
|
||||
if g.scope != "" && g.scope != vol {
|
||||
continue
|
||||
}
|
||||
r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol))
|
||||
if e != nil {
|
||||
return 0, e
|
||||
|
||||
@@ -25,6 +25,7 @@ type savedGCCandidate struct {
|
||||
Digest string `json:"digest"`
|
||||
}
|
||||
type savedGCMark struct {
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Format int `json:"format"`
|
||||
Base string `json:"base"`
|
||||
GraceNs int64 `json:"grace_ns"`
|
||||
@@ -53,6 +54,19 @@ type GCExecution struct {
|
||||
// and identify uncertain stages, rather than asserting remote absence.
|
||||
// The catalog namespace is the scope; permanent tombstones are untouched.
|
||||
func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool) (out GCExecution, err error) {
|
||||
return c.executeGC(ctx, blobs, cfg, apply, "")
|
||||
}
|
||||
|
||||
// ExecuteVolumeGC reclaims only volumeID's objects while tracing every volume's
|
||||
// roots. Its persisted two-mark coverage never aliases namespace-wide coverage.
|
||||
func (c *Catalog) ExecuteVolumeGC(ctx context.Context, volumeID string, blobs BlobDeleter, cfg GCConfig, apply bool) (GCExecution, error) {
|
||||
if err := CheckVolumeID(volumeID); err != nil {
|
||||
return GCExecution{GCResult: GCResult{UnknownUnbound: true}}, err
|
||||
}
|
||||
return c.executeGC(ctx, blobs, cfg, apply, volumeID)
|
||||
}
|
||||
|
||||
func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool, scope string) (out GCExecution, err error) {
|
||||
// Pre-binding needles remain unenumerable even if admission/readback fails.
|
||||
out.UnknownUnbound = true
|
||||
out.DryRun = !apply
|
||||
@@ -62,6 +76,7 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
g.scope = scope
|
||||
mark, previous, err := g.readMark(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
@@ -109,7 +124,7 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig
|
||||
}
|
||||
|
||||
func (g *Collector) mark(ready bool) savedGCMark {
|
||||
m := savedGCMark{Format: 1, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
|
||||
m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
|
||||
if ready {
|
||||
m.LastNs = g.last.UnixNano()
|
||||
for p, c := range g.candidates {
|
||||
@@ -119,8 +134,15 @@ func (g *Collector) mark(ready bool) savedGCMark {
|
||||
return m
|
||||
}
|
||||
|
||||
func (g *Collector) markDir() string {
|
||||
if g.scope != "" {
|
||||
return path.Join(g.cat.base, g.scope)
|
||||
}
|
||||
return g.cat.base
|
||||
}
|
||||
|
||||
func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) {
|
||||
e, err := g.cat.f.LookupEntry(ctx, g.cat.base, gcMarkName)
|
||||
e, err := g.cat.f.LookupEntry(ctx, g.markDir(), gcMarkName)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, "", nil
|
||||
}
|
||||
@@ -141,7 +163,7 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error)
|
||||
if err = d.Decode(&trailing); err != io.EOF {
|
||||
return nil, "", errors.New("chunkstore: trailing GC mark content")
|
||||
}
|
||||
if m.Format != 1 || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 {
|
||||
if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 {
|
||||
return nil, "", errors.New("chunkstore: incompatible GC mark")
|
||||
}
|
||||
if m.Ready {
|
||||
@@ -151,7 +173,7 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error)
|
||||
}
|
||||
for p, c := range m.Candidates {
|
||||
digest, err := hex.DecodeString(c.Digest)
|
||||
if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.cat.base+"/") || !strings.Contains(p, "/"+keysDir+"/") {
|
||||
if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.markDir()+"/") || !strings.Contains(p, "/"+keysDir+"/") {
|
||||
return nil, "", errors.New("chunkstore: invalid GC candidate state")
|
||||
}
|
||||
}
|
||||
@@ -176,9 +198,9 @@ func (g *Collector) writeMark(ctx context.Context, m savedGCMark, expected strin
|
||||
now := g.cfg.Now().Unix()
|
||||
e := &filerpb.Entry{Name: gcMarkName, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Crtime: now, Mtime: now, FileMode: 0600}, Content: body, Extended: map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(token)}}
|
||||
if expected == "" {
|
||||
err = g.cat.f.CreateEntry(ctx, g.cat.base, e, true)
|
||||
err = g.cat.f.CreateEntry(ctx, g.markDir(), e, true)
|
||||
} else {
|
||||
err = g.cat.f.UpdateEntry(ctx, g.cat.base, e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)})
|
||||
err = g.cat.f.UpdateEntry(ctx, g.markDir(), e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)})
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("chunkstore: GC watermark changed or unavailable: %w", err)
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
v2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2"))
|
||||
for _, key := range []string{"rooted-only-from-v2", "local-orphan"} {
|
||||
if err := v1.Put(ctx, key, []byte(key)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := v2.Put(ctx, "foreign-orphan", []byte("foreign")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := v2.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "snapshot:v2/s1/req", Keys: []string{"@v1/rooted-only-from-v2"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
}
|
||||
if _, err := v1.Get(ctx, "local-orphan"); err == nil {
|
||||
t.Error("local orphan not reclaimed")
|
||||
}
|
||||
if _, err := v1.Get(ctx, "rooted-only-from-v2"); err != nil {
|
||||
t.Errorf("foreign root lost: %v", err)
|
||||
}
|
||||
if _, err := v2.Get(ctx, "foreign-orphan"); err != nil {
|
||||
t.Errorf("scoped pass reclaimed foreign candidate: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGC_GraceConstructorRejectsCopyDeadline(t *testing.T) {
|
||||
_, b, c, g, _ := gcFixture(t)
|
||||
for _, grace := range []time.Duration{0, c.deadline() - time.Nanosecond, c.deadline()} {
|
||||
cfg := g.cfg
|
||||
cfg.Grace = grace
|
||||
if _, err := NewCollector(c, b, cfg); err == nil {
|
||||
t.Errorf("accepted grace %s <= copy deadline", grace)
|
||||
}
|
||||
}
|
||||
cfg := g.cfg
|
||||
cfg.Grace = c.deadline() + time.Nanosecond
|
||||
if _, err := NewCollector(c, b, cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.ExecuteGC(ctx, b, g.cfg, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
// A separate scope must take its own first mark, even with mature global coverage.
|
||||
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
|
||||
if err != nil || result.Reclaimed != 0 {
|
||||
t.Fatalf("scope imported namespace coverage: %+v %v", result, err)
|
||||
}
|
||||
if _, err = f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName); errors.Is(err, ErrNotFound) {
|
||||
t.Fatal("scoped watermark absent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeGC_IncompletePassAndConfigChangeDiscardCoverage(t *testing.T) {
|
||||
for _, mode := range []string{"incomplete", "config"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
if mode == "incomplete" {
|
||||
g.scope = "v1"
|
||||
_, token, err := g.readMark(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = g.writeMark(ctx, g.mark(false), token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
g.cfg.IntentTTL += time.Second
|
||||
}
|
||||
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
|
||||
if err != nil || result.Reclaimed != 0 {
|
||||
t.Fatalf("stale coverage used: %+v %v", result, err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
result, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
|
||||
if err != nil || result.Reclaimed != 1 {
|
||||
t.Fatalf("fresh coverage did not progress: %+v %v", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeGC_ForeignForkHeadIsSoleRoot(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x22)})
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil || out.Reclaimed != 0 {
|
||||
t.Fatalf("foreign-only fork root reclaimed: %+v %v", out, err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
}
|
||||
for _, ref := range h.Chunks {
|
||||
if _, err := r.Get(ctx, ref.Key); err != nil {
|
||||
t.Fatal("fork bytes reclaimed", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remotes := map[string]*ChunkRemote{}
|
||||
for _, vol := range []string{"v1", "v2"} {
|
||||
remote, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
|
||||
remotes[vol] = remote
|
||||
if err := remote.Put(ctx, "capture", []byte("protected")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := remote.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old", Keys: []string{"capture"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil }
|
||||
*now = time.Now().Add(3 * time.Hour)
|
||||
foreign, _ := remotes["v2"].ListIntents(ctx)
|
||||
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
|
||||
local, _ := remotes["v1"].ListIntents(ctx)
|
||||
after, _ := remotes["v2"].ListIntents(ctx)
|
||||
if err != nil || result.ExpiredIntents != 1 || len(local) != 0 || !reflect.DeepEqual(foreign, after) {
|
||||
t.Fatalf("capture scope mutated foreign intent: %+v %v before=%+v after=%+v", result, err, foreign, after)
|
||||
}
|
||||
if _, err := remotes["v2"].Get(ctx, "capture"); err != nil {
|
||||
t.Fatal("foreign protection lost", err)
|
||||
}
|
||||
result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true)
|
||||
if err != nil || result.ExpiredIntents != 1 {
|
||||
t.Fatalf("foreign positive eligibility not witnessed: %+v %v", result, err)
|
||||
}
|
||||
}
|
||||
func TestVolumeGC_ForeignEligibleCopyIsNotSettled(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
c.SetClock(func() time.Time { return *now })
|
||||
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, vol := range []string{"v1", "v2"} {
|
||||
h := publishSource(t, f, b.fakeBlobs, vol, map[uint64][]byte{0: chunkBytes(0x55)})
|
||||
snapshotDir(t, f, vol, "held")
|
||||
holdFirst(f, path.Join(catBase, vol, snapsDir, "held")+"/")
|
||||
if _, err := c.CreateSnapshot(ctx, vol, SnapshotRequest{Name: "held", RequestID: "dead"}, h); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("copy not held: %v", err)
|
||||
}
|
||||
}
|
||||
before := intentsOf(t, f, "v2")
|
||||
foreignPath := snapPath(t, f, "v2", "held")
|
||||
*now = now.Add(DefaultOpDeadline + time.Second)
|
||||
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
|
||||
after := intentsOf(t, f, "v2")
|
||||
if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v1")) != 0 || !reflect.DeepEqual(before, after) {
|
||||
t.Fatalf("copy scope changed foreign attempt: %+v %v", result, err)
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, path.Dir(foreignPath), path.Base(foreignPath)); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("foreign pending copy claimed: %v", err)
|
||||
}
|
||||
result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true)
|
||||
if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v2")) != 0 {
|
||||
t.Fatalf("foreign positive settlement not witnessed: %+v %v", result, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type maintenanceStubLayer struct{ storage.ChunkLayer }
|
||||
|
||||
func (maintenanceStubLayer) Fenced() bool { return false }
|
||||
func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) {
|
||||
for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} {
|
||||
t.Run(field, func(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
|
||||
lin := chunkLineage{"v1", "r1", 3, 1}
|
||||
layer := &maintenanceStubLayer{}
|
||||
h := &volHandle{chunk: layer}
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}}
|
||||
if !p.maintenanceCurrent("v1", h, layer, lin) {
|
||||
t.Fatal("healthy same attachment refused")
|
||||
}
|
||||
switch field {
|
||||
case "epoch":
|
||||
id.Epoch++
|
||||
case "replica":
|
||||
id.ReplicaID = "r2"
|
||||
case "endpoint":
|
||||
id.EndpointVersion++
|
||||
case "handle":
|
||||
p.volumes["v1"] = &volHandle{chunk: layer}
|
||||
case "layer":
|
||||
h.chunk = &maintenanceStubLayer{}
|
||||
}
|
||||
p.view = precopyQueueView{id}
|
||||
p.cfg.ChunkMaintenanceInterval = time.Nanosecond
|
||||
calls := 0
|
||||
p.cfg.ChunkMaintenance = func(context.Context, string) error { calls++; return nil }
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) })
|
||||
if calls != 0 {
|
||||
t.Fatalf("foreign attachment admitted %d passes", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) {
|
||||
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
|
||||
layer := &maintenanceStubLayer{}
|
||||
h := &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}}
|
||||
entered := make(chan struct{}, 2)
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, cfg: ProviderConfig{ChunkMaintenanceInterval: time.Nanosecond, ChunkMaintenance: func(ctx context.Context, _ string) error { entered <- struct{}{}; <-ctx.Done(); return ctx.Err() }}}
|
||||
var stopperDone chan struct{}
|
||||
t.Cleanup(func() {
|
||||
p.mu.Lock()
|
||||
stop, ownerDone := h.chunkStop, h.chunkDone
|
||||
p.mu.Unlock()
|
||||
if stop != nil {
|
||||
stop()
|
||||
}
|
||||
for _, done := range []<-chan struct{}{stopperDone, ownerDone} {
|
||||
if done != nil {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("cleanup did not join outstanding maintenance stopper/owner")
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
for i := 0; i < 2; i++ {
|
||||
p.mu.Lock()
|
||||
p.startChunkLoop("v1", h, layer)
|
||||
p.mu.Unlock()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("same handle did not arm")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
stopperDone = done
|
||||
go func() { p.stopChunkLoop(h); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("stopped owner did not join")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) {
|
||||
interval := 15 * time.Minute
|
||||
seen := map[time.Duration]bool{}
|
||||
for i := 0; i < 200; i++ {
|
||||
s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true)
|
||||
offset := s.firstDue.Sub(t0)
|
||||
if offset <= 0 || offset >= interval {
|
||||
t.Fatalf("phase outside interval: %s", offset)
|
||||
}
|
||||
seen[offset] = true
|
||||
if _, due := testPolicy().due(s, s.firstDue.Add(-time.Nanosecond), false); due {
|
||||
t.Fatal("published before own phase")
|
||||
}
|
||||
}
|
||||
if len(seen) < 190 {
|
||||
t.Fatalf("200 volumes collapsed into %d phases", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
// Virtual quiescence observes the join boundary directly, so a slow storage
|
||||
// Close cannot accidentally make an omitted scheduler join look correct.
|
||||
func TestMaintenanceStopJoinsBeforeRelease(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done, release, cancelled := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
finish := func() { once.Do(func() { close(release) }) }
|
||||
defer finish()
|
||||
p := &DurableProvider{}
|
||||
h := &volHandle{chunkStop: cancel, chunkDone: done}
|
||||
go func() { <-ctx.Done(); close(cancelled); <-release; close(done) }()
|
||||
returned1, returned2 := make(chan struct{}), make(chan struct{})
|
||||
go func() { p.stopChunkLoop(h); close(returned1) }()
|
||||
<-cancelled
|
||||
go func() { p.stopChunkLoop(h); close(returned2) }()
|
||||
synctest.Wait()
|
||||
for _, returned := range []chan struct{}{returned1, returned2} {
|
||||
select {
|
||||
case <-returned:
|
||||
t.Error("stop released before worker join")
|
||||
default:
|
||||
}
|
||||
}
|
||||
finish()
|
||||
<-returned1
|
||||
<-returned2
|
||||
})
|
||||
}
|
||||
@@ -172,6 +172,13 @@ type ProviderConfig struct {
|
||||
// passed since the volume's last successful cut (of any kind). Zero
|
||||
// disables the timer.
|
||||
ChunkCaptureInterval time.Duration
|
||||
// ChunkCutTimeout bounds a cut as a whole; zero uses five minutes.
|
||||
ChunkCutTimeout time.Duration
|
||||
// Maintenance runs serially for an attached healthy volume. Zero interval disables
|
||||
// it. Callback ownership ends only after cancellation and worker settlement.
|
||||
ChunkMaintenanceInterval time.Duration
|
||||
ChunkMaintenanceTimeout time.Duration
|
||||
ChunkMaintenance func(context.Context, string) error
|
||||
// DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest
|
||||
// I/O stopped before it resumes or settles: the drain and final cut get
|
||||
// three quarters of it, the settlement of a failed cut the rest (the
|
||||
@@ -266,9 +273,10 @@ 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
|
||||
recoverGen uint64
|
||||
waitGen uint64
|
||||
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
|
||||
@@ -336,6 +344,12 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura
|
||||
if cfg.Impl == ImplWALStoreChunk && cfg.ChunkRemoteFor == nil {
|
||||
return nil, fmt.Errorf("durable: impl %q requires ProviderConfig.ChunkRemoteFor", ImplWALStoreChunk)
|
||||
}
|
||||
if cfg.ChunkCaptureInterval < 0 || cfg.ChunkCutTimeout < 0 || cfg.ChunkMaintenanceInterval < 0 || cfg.ChunkMaintenanceTimeout < 0 {
|
||||
return nil, fmt.Errorf("durable: chunk schedule durations must not be negative")
|
||||
}
|
||||
if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil {
|
||||
return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback")
|
||||
}
|
||||
if cfg.ChunkBlocks == 0 {
|
||||
cfg.ChunkBlocks = defaultChunkBlocks
|
||||
}
|
||||
|
||||
@@ -320,12 +320,14 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
|
||||
// startChunkLoop starts the periodic cuts of an attached layer, if configured
|
||||
// and not already running. The caller holds h.attachMu and p.mu.
|
||||
func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) {
|
||||
if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil {
|
||||
if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil {
|
||||
return
|
||||
}
|
||||
loopCtx, cancel := context.WithCancel(context.Background())
|
||||
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
|
||||
go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone)
|
||||
lin := h.chunkLineage
|
||||
current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) }
|
||||
go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current)
|
||||
}
|
||||
|
||||
func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) {
|
||||
@@ -466,7 +468,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
|
||||
}
|
||||
|
||||
return storage.AttachChunkLayer(ws, remote, cfg)
|
||||
layer, attachErr := storage.AttachChunkLayer(ws, remote, cfg)
|
||||
if attachErr == nil {
|
||||
h.chunkLineage = lin
|
||||
}
|
||||
return layer, attachErr
|
||||
}
|
||||
|
||||
// closeBoundRemote ends every remote call when the provider closes, so a
|
||||
@@ -635,7 +641,7 @@ const (
|
||||
|
||||
// cutPolicy decides when an automatic cut is due. The remote holds
|
||||
// snapshots, not live data: cuts are published at Snapshot, Detach/stop
|
||||
// and explicit Cut, and automatically only by the operator's timer:
|
||||
// and explicit Cut, and automatically by the configured timer:
|
||||
// - the timer fires once interval has passed since the last successful
|
||||
// cut of any kind (explicit Cut, Snapshot and Detach included); zero
|
||||
// disables it, and with it every automatic cut;
|
||||
@@ -760,6 +766,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
cutCtx, cancel := p.chunkCutContext(ctx)
|
||||
trace := p.testChunkLoopTrace
|
||||
if trace != nil {
|
||||
trace("due", ls.LastCutNs, false)
|
||||
@@ -769,19 +776,21 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
// A cut that completed after this decision (an explicit one
|
||||
// running meanwhile) restarted the timer: no cut now.
|
||||
var skipped bool
|
||||
_, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs)
|
||||
_, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.LastCutNs)
|
||||
if trace != nil {
|
||||
trace("cut", ls.LastCutNs, skipped)
|
||||
}
|
||||
if skipped {
|
||||
cancel()
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
_, err = layer.Cut(ctx)
|
||||
_, err = layer.Cut(cutCtx)
|
||||
if trace != nil {
|
||||
trace("cut", ls.LastCutNs, false)
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
s = pol.after(s, start, time.Now(), err)
|
||||
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
|
||||
log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff)
|
||||
@@ -789,15 +798,122 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
}
|
||||
}
|
||||
|
||||
// chunkBackground owns both workers and their cancellation. A fence is observed
|
||||
// even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN:
|
||||
// done closes only after every admitted worker has returned.
|
||||
func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool) {
|
||||
defer close(done)
|
||||
defer cancel()
|
||||
var workers sync.WaitGroup
|
||||
if p.cfg.ChunkCaptureInterval > 0 {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
cutDone := make(chan struct{})
|
||||
p.chunkLoop(ctx, volumeID, layer, cutDone)
|
||||
}()
|
||||
}
|
||||
if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil {
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }()
|
||||
}
|
||||
timer := time.NewTicker(chunkSchedulePoll)
|
||||
defer timer.Stop()
|
||||
for ctx.Err() == nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
if layer.Fenced() {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
workers.Wait()
|
||||
}
|
||||
|
||||
// maintenanceCurrent binds the pass to the attached handle AND its lineage.
|
||||
// The projection can remain healthy while a different owner replaces it.
|
||||
func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, layer storage.ChunkLayer, lin chunkLineage) bool {
|
||||
p.mu.Lock()
|
||||
active := !p.closed && p.volumes[volumeID] == h && h.chunk == layer
|
||||
p.mu.Unlock()
|
||||
cur := p.view.Projection()
|
||||
return active && chunkAuthority(cur, volumeID) && cur.VolumeID == lin.volumeID && cur.ReplicaID == lin.replicaID && cur.Epoch == lin.epoch && cur.EndpointVersion == lin.endpoint
|
||||
}
|
||||
|
||||
func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool) {
|
||||
interval := p.cfg.ChunkMaintenanceInterval
|
||||
due := time.Now().Add(interval)
|
||||
if p.cfg.ChunkStagger {
|
||||
due = time.Now().Add(hostlimit.Phase(volumeID+":maintenance", interval))
|
||||
}
|
||||
timer := time.NewTimer(time.Until(due))
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if ctx.Err() != nil || layer.Fenced() {
|
||||
return
|
||||
}
|
||||
if !current() {
|
||||
return
|
||||
}
|
||||
timeout := p.cfg.ChunkMaintenanceTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = time.Minute
|
||||
}
|
||||
passCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
// The projection has no change channel. One bounded watcher belongs to
|
||||
// this pass, never to an individual tick; cancellation is joined below.
|
||||
watchDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(watchDone)
|
||||
tick := time.NewTicker(chunkSchedulePoll)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-passCtx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if layer.Fenced() || !current() {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
err := p.cfg.ChunkMaintenance(passCtx, volumeID)
|
||||
cancel()
|
||||
<-watchDone
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Printf("durable: maintenance volume=%s: %v", volumeID, err)
|
||||
}
|
||||
// Completion-relative reset coalesces all elapsed ticks; no catch-up queue.
|
||||
timer.Reset(interval)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *DurableProvider) stopChunkLoop(h *volHandle) {
|
||||
p.mu.Lock()
|
||||
stop, done := h.chunkStop, h.chunkDone
|
||||
h.chunkStop = nil
|
||||
p.mu.Unlock()
|
||||
if stop != nil {
|
||||
stop()
|
||||
}
|
||||
// Every concurrent stopper joins the same lifetime; none can clear ownership
|
||||
// while an earlier stopper is still waiting for an admitted remote call.
|
||||
if done != nil {
|
||||
<-done
|
||||
}
|
||||
p.mu.Lock()
|
||||
if h.chunkDone == done {
|
||||
h.chunkStop = nil
|
||||
h.chunkDone = nil
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
func (p *DurableProvider) chunkLayer(volumeID string) (storage.ChunkLayer, error) {
|
||||
@@ -831,6 +947,8 @@ func (p *DurableProvider) chunkHandle(volumeID string) (*volHandle, storage.Chun
|
||||
// CaptureVolume takes one quiesced cut of volumeID and publishes it to the
|
||||
// remote. It returns the cut's LSN.
|
||||
func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (uint64, error) {
|
||||
ctx, cancel := p.chunkCutContext(ctx)
|
||||
defer cancel()
|
||||
layer, err := p.chunkLayer(volumeID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -841,6 +959,8 @@ func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (u
|
||||
// MakeVolumeRemoteDurable returns nil only once volumeID's writes up to lsn
|
||||
// are published in the remote HEAD (snapshot, detach, migrate).
|
||||
func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID string, lsn uint64) error {
|
||||
ctx, cancel := p.chunkCutContext(ctx)
|
||||
defer cancel()
|
||||
layer, err := p.chunkLayer(volumeID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -863,7 +983,17 @@ func chunkFenced(volumeID string, h *volHandle) error {
|
||||
// and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is
|
||||
// MakeRemoteDurable(minLSN) returning the cut: an LSN never written is
|
||||
// refused before anything is published, and the cut must reach minLSN.
|
||||
func (p *DurableProvider) chunkCutContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
timeout := p.cfg.ChunkCutTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 5 * time.Minute
|
||||
}
|
||||
return context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
|
||||
func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) {
|
||||
ctx, cancel := p.chunkCutContext(ctx)
|
||||
defer cancel()
|
||||
h, layer, err := p.chunkHandle(volumeID)
|
||||
if err != nil {
|
||||
return storage.ChunkCutResult{}, err
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) {
|
||||
entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
finish := func() { once.Do(func() { close(release) }) }
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
ChunkMaintenanceInterval: time.Millisecond,
|
||||
ChunkMaintenance: func(ctx context.Context, vol string) error {
|
||||
close(entered)
|
||||
<-ctx.Done()
|
||||
close(cancelled)
|
||||
<-release
|
||||
return ctx.Err()
|
||||
},
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { finish(); _ = p.Close() })
|
||||
s := openRecovered(t, p)
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("maintenance did not start with cut timer off")
|
||||
}
|
||||
writeDone := make(chan error, 1)
|
||||
writerSettled := make(chan struct{})
|
||||
go func() { defer close(writerSettled); _, err := s.Write(1, block(0x51)); writeDone <- err }()
|
||||
t.Cleanup(func() {
|
||||
finish()
|
||||
_ = p.Close()
|
||||
select {
|
||||
case <-writerSettled:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("writer cleanup did not settle")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case err := <-writeDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("maintenance held a guest lock")
|
||||
}
|
||||
closed := make(chan error, 1)
|
||||
closeSettled := make(chan struct{})
|
||||
go func() { defer close(closeSettled); closed <- p.Close() }()
|
||||
t.Cleanup(func() {
|
||||
finish()
|
||||
select {
|
||||
case <-closeSettled:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("Close cleanup did not settle")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-cancelled:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Close did not cancel maintenance")
|
||||
}
|
||||
select {
|
||||
case err := <-closed:
|
||||
t.Fatalf("Close released resources before worker join: %v", err)
|
||||
default:
|
||||
}
|
||||
finish()
|
||||
select {
|
||||
case err := <-closed:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Close did not join")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) {
|
||||
view := v1View()
|
||||
entered, cancelled := make(chan struct{}), make(chan struct{})
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
|
||||
ChunkMaintenanceInterval: time.Millisecond,
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error {
|
||||
close(entered)
|
||||
<-ctx.Done()
|
||||
close(cancelled)
|
||||
return ctx.Err()
|
||||
},
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
openRecovered(t, p)
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no pass")
|
||||
}
|
||||
view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})
|
||||
select {
|
||||
case <-cancelled:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("lost authority did not cancel held pass")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenancePassHasOneDeadline(t *testing.T) {
|
||||
entered := make(chan error, 1)
|
||||
three := make(chan struct{})
|
||||
var completed atomic.Int32
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
|
||||
ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenanceTimeout: 10 * time.Millisecond,
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error {
|
||||
<-ctx.Done()
|
||||
select {
|
||||
case entered <- ctx.Err():
|
||||
default:
|
||||
}
|
||||
if completed.Add(1) == 3 {
|
||||
close(three)
|
||||
}
|
||||
return ctx.Err()
|
||||
},
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
done := make(chan struct{})
|
||||
go func() { _ = p.Close(); close(done) }()
|
||||
timer := time.NewTimer(5 * time.Second)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-entered:
|
||||
case <-timer.C:
|
||||
t.Error("deadline callback cleanup failed to join")
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
openRecovered(t, p)
|
||||
// Deliberately leave the one-slot observation full across recurring passes.
|
||||
select {
|
||||
case <-three:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("recurring callback blocked with delayed receiver")
|
||||
}
|
||||
select {
|
||||
case err := <-entered:
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
default:
|
||||
t.Fatal("no deadline observation")
|
||||
}
|
||||
}
|
||||
|
||||
type pendingMaintenancePut struct{ *storage.MemChunkRemote }
|
||||
|
||||
func (r pendingMaintenancePut) Put(ctx context.Context, _ string, _ []byte) error {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) {
|
||||
remote := pendingMaintenancePut{storage.NewMemChunkRemote()}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkCutTimeout: 10 * time.Millisecond,
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
s := openRecovered(t, p)
|
||||
if _, err = s.Write(1, block(0x48)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = p.CaptureVolume(context.Background(), "v1")
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("whole cut did not expire: %v", err)
|
||||
}
|
||||
h, err := remote.GetHead(context.Background())
|
||||
if err != nil || h.Gen != 0 {
|
||||
t.Fatalf("expired upload published: %+v %v", h, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) {
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
finish := func() { once.Do(func() { close(release) }) }
|
||||
var calls atomic.Int32
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
|
||||
ChunkMaintenanceInterval: time.Millisecond,
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error {
|
||||
if calls.Add(1) == 1 {
|
||||
close(entered)
|
||||
}
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return ctx.Err()
|
||||
},
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { finish(); _ = p.Close() })
|
||||
openRecovered(t, p)
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no pass")
|
||||
}
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
if got := calls.Load(); got != 1 {
|
||||
t.Fatalf("held pass started %d workers", got)
|
||||
}
|
||||
// Close cancels the held pass before release; there is no queued retry to drain.
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := calls.Load(); got != 1 {
|
||||
t.Fatalf("Close dispatched %d elapsed ticks", got)
|
||||
}
|
||||
finish()
|
||||
}
|
||||
|
||||
func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) {
|
||||
remote := storage.NewMemChunkRemote()
|
||||
p := schedProvider(t, remote, time.Millisecond, 0)
|
||||
s := openRecovered(t, p)
|
||||
lsn, err := s.Write(1, block(0x91))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
var first storage.ChunkHead
|
||||
for {
|
||||
first, err = remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.RemoteLSN >= lsn {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
var before int64
|
||||
for before == 0 {
|
||||
before = p.DurableStatuses()[0].Chunk.Stats.LastCutNs
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("first cut did not settle", ctx.Err())
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
for {
|
||||
status := p.DurableStatuses()[0]
|
||||
if status.Chunk.Stats.LastCutNs > before {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("no periodic noop", ctx.Err())
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
after, err := remote.GetHead(ctx)
|
||||
if err != nil || after.Gen != first.Gen {
|
||||
t.Fatalf("noop churned HEAD: before=%d after=%d err=%v", first.Gen, after.Gen, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceHealthyLineageChangeCancelsHeldPass(t *testing.T) {
|
||||
for _, field := range []string{"epoch", "replica", "endpoint"} {
|
||||
t.Run(field, func(t *testing.T) {
|
||||
view := v1View()
|
||||
entered, cancelled := make(chan struct{}), make(chan struct{})
|
||||
var enterOnce, cancelOnce sync.Once
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
|
||||
ChunkMaintenanceInterval: time.Millisecond,
|
||||
ChunkMaintenance: func(ctx context.Context, _ string) error {
|
||||
enterOnce.Do(func() { close(entered) })
|
||||
<-ctx.Done()
|
||||
cancelOnce.Do(func() { close(cancelled) })
|
||||
return ctx.Err()
|
||||
},
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
done := make(chan struct{})
|
||||
go func() { _ = p.Close(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("lineage cleanup did not join")
|
||||
}
|
||||
})
|
||||
openRecovered(t, p)
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no held pass")
|
||||
}
|
||||
cur := view.Projection()
|
||||
switch field {
|
||||
case "epoch":
|
||||
cur.Epoch++
|
||||
case "replica":
|
||||
cur.ReplicaID = "r2"
|
||||
case "endpoint":
|
||||
cur.EndpointVersion++
|
||||
}
|
||||
view.set(cur)
|
||||
select {
|
||||
case <-cancelled:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("healthy foreign lineage did not cancel pass")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,25 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
)
|
||||
|
||||
// headFilerMtimeNS is the HEAD entry's mtime from the filer's Last-Modified
|
||||
// header of the same response as the content (1 s resolution), or 0
|
||||
// (unknown) when the header is absent, unparseable or not after the epoch.
|
||||
func headFilerMtimeNS(h http.Header) int64 {
|
||||
v := h.Get("Last-Modified")
|
||||
if v == "" {
|
||||
return 0
|
||||
}
|
||||
t, err := http.ParseTime(v)
|
||||
if err != nil || t.UnixNano() <= 0 {
|
||||
return 0
|
||||
}
|
||||
return t.UnixNano()
|
||||
}
|
||||
|
||||
// NewWorkspaceHEADReader reads inline HEAD content from the configured filer
|
||||
// HTTP directory. It never follows redirects or accepts operator-supplied HEAD
|
||||
// evidence. W2's detached state is part of the committed HEAD document.
|
||||
// evidence. W2's detached state is part of the committed HEAD document. The
|
||||
// HEAD's filer mtime comes from the same response (headFilerMtimeNS).
|
||||
func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authority.WorkspaceHead, error), error) {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
@@ -79,6 +95,6 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori
|
||||
} else if doc.DetachedBy != nil {
|
||||
return authority.WorkspaceHead{}, fmt.Errorf("active HEAD retains detachedBy proof")
|
||||
}
|
||||
return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached"}, nil
|
||||
return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached", FilerMtimeNS: headFilerMtimeNS(res.Header)}, nil
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// lostRangeFiles lists the lost range side files under dir.
|
||||
func lostRangeFiles(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() && strings.HasSuffix(p, ".lostrange.json") {
|
||||
out = append(out, p)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// startStoppableMaster starts a master and registers its close as cleanup
|
||||
// immediately; the returned stop closes it at most once (an explicit stop
|
||||
// before a restart, then the cleanup, never closes twice).
|
||||
func startStoppableMaster(t *testing.T, cfg Config) (*Host, func()) {
|
||||
t.Helper()
|
||||
h, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
var once sync.Once
|
||||
stop := func() { once.Do(func() { closeTestMaster(t, h) }) }
|
||||
t.Cleanup(stop)
|
||||
return h, stop
|
||||
}
|
||||
|
||||
// forcedMoveHost starts a master whose volume vol-f is held by r1 on node-a
|
||||
// (epoch 1, lease renewed once) with a prepared target binding on node-b.
|
||||
// The returned stop closes it once; it is also registered as cleanup as soon
|
||||
// as the master starts, so a failing setup step never leaks it.
|
||||
func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceServiceClient, *control.WorkspaceMove) {
|
||||
t.Helper()
|
||||
h, stop := startStoppableMaster(t, cfg)
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { conn.Close() })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
client := control.NewWorkspaceServiceClient(conn)
|
||||
for _, server := range []string{"node-a", "node-b"} {
|
||||
if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-f", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := &control.WorkspaceBinding{VolumeId: "vol-f", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}
|
||||
target := &control.WorkspaceBinding{VolumeId: "vol-f", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"}
|
||||
for _, b := range []*control.WorkspaceBinding{src, target} {
|
||||
if _, err := client.RegisterWorkspaceBinding(ctx, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-f", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, h.Publisher(), "vol-f")
|
||||
if _, err := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h, stop, client, &control.WorkspaceMove{RequestId: "force-1", VolumeId: "vol-f", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "forced", Force: true}
|
||||
}
|
||||
|
||||
// INV-WS-LOST-RANGE-READOUT-001 over the real master: the preview writes
|
||||
// nothing and says when the move becomes admissible; the issued forced
|
||||
// grant carries the stored range (with the HEAD's filer time read with HEAD)
|
||||
// and is logged; a replay returns the same grant; the lost range RPC returns
|
||||
// the same stored range; after a restart with the range file damaged, a
|
||||
// replay still returns the issued grant but without a range and with the
|
||||
// reason, and the lost range RPC fails with DataLoss, never "no loss".
|
||||
func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) {
|
||||
logs := &syncBuffer{}
|
||||
headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC)
|
||||
authDir := t.TempDir()
|
||||
cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
|
||||
Logger: log.New(logs, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil
|
||||
}}
|
||||
h, stop, client, move := forcedMoveHost(t, cfg)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pv, err := client.PreviewWorkspaceMove(ctx, move)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pv.Admitted || pv.LostUntilNs <= pv.MasterTimeNs || pv.HeadRead || !strings.Contains(pv.Reason, "has not elapsed") {
|
||||
t.Fatalf("preview before the horizon: %+v", pv)
|
||||
}
|
||||
if _, err := client.MoveWorkspace(ctx, move); status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("move before the horizon: %v; want FailedPrecondition", err)
|
||||
}
|
||||
select {
|
||||
case <-time.After(time.Until(time.Unix(0, pv.LostUntilNs)) + 50*time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
pv2, err := client.PreviewWorkspaceMove(ctx, move)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pv2.Admitted || !pv2.HeadRead || pv2.HeadGen != 9 || pv2.HeadRemoteLsn != 42 || !pv2.HeadTimeKnown || pv2.HeadTimeNs != headTime.UnixNano() || pv2.LostUntilNs != pv.LostUntilNs {
|
||||
t.Fatalf("preview after the horizon: %+v", pv2)
|
||||
}
|
||||
if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 {
|
||||
t.Fatalf("preview wrote a journal record: %+v", st.Moves)
|
||||
}
|
||||
if files := lostRangeFiles(t, authDir); len(files) != 0 {
|
||||
t.Fatalf("preview wrote a lost range: %v", files)
|
||||
}
|
||||
|
||||
g, err := client.MoveWorkspace(ctx, move)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := &control.WorkspaceLostRange{RequestId: "force-1", VolumeId: "vol-f", NewEpoch: g.NewEpoch, OldReplicaId: "r1", OldEpoch: move.ExpectedEpoch,
|
||||
LostAfterLsn: 42, LostUntilNs: pv.LostUntilNs, HeadGen: 9, HeadTimeNs: headTime.UnixNano(), HeadTimeKnown: true}
|
||||
if !g.Issued || g.LostRangeError != "" || !proto.Equal(g.LostRange, want) {
|
||||
t.Fatalf("forced grant %+v; want lost range %+v", g, want)
|
||||
}
|
||||
for _, s := range []string{`forced move issued volume="vol-f" request="force-1"`, "old=node-a/r1@1", "new=node-b/r1@2", "replay=false", "lost_after_lsn=42", "head_gen=9", "head_filer_time=2026-11-21T01:02:03Z"} {
|
||||
if !strings.Contains(logs.String(), s) {
|
||||
t.Fatalf("master log lacks %q:\n%s", s, logs.String())
|
||||
}
|
||||
}
|
||||
g2, err := client.MoveWorkspace(ctx, move)
|
||||
if err != nil || !proto.Equal(g, g2) {
|
||||
t.Fatalf("replay %+v %v; want the stored grant %+v", g2, err, g)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "replay=true") {
|
||||
t.Fatalf("replayed forced grant not logged:\n%s", logs.String())
|
||||
}
|
||||
for _, id := range []string{"", "force-1"} {
|
||||
lr, err := client.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f", RequestId: id})
|
||||
if err != nil || len(lr.Ranges) != 1 || !proto.Equal(lr.Ranges[0], want) {
|
||||
t.Fatalf("lost range query %q: %+v %v", id, lr, err)
|
||||
}
|
||||
}
|
||||
if _, err := client.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f", RequestId: "nope"}); status.Code(err) != codes.NotFound {
|
||||
t.Fatalf("unknown request id: %v; want NotFound", err)
|
||||
}
|
||||
if st, err := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-f"}); err != nil || len(st.Moves) != 1 || !proto.Equal(st.Moves[0].LostRange, want) {
|
||||
t.Fatalf("QueryWorkspace moves %+v %v", st.GetMoves(), err)
|
||||
}
|
||||
if pv3, err := client.PreviewWorkspaceMove(ctx, move); err != nil || !pv3.Admitted || pv3.HeadRead || pv3.LostUntilNs != pv.LostUntilNs {
|
||||
t.Fatalf("preview of the issued request: %+v %v", pv3, err)
|
||||
}
|
||||
|
||||
stop()
|
||||
files := lostRangeFiles(t, authDir)
|
||||
if len(files) != 1 {
|
||||
t.Fatalf("lost range files %v", files)
|
||||
}
|
||||
raw, err := os.ReadFile(files[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(files[0], []byte(strings.Replace(string(raw), `"LostAfterLSN":42`, `"LostAfterLSN":41`, 1)), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h2, _ := startStoppableMaster(t, cfg)
|
||||
conn, err := grpc.NewClient(h2.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
c2 := control.NewWorkspaceServiceClient(conn)
|
||||
g3, err := c2.MoveWorkspace(ctx, move)
|
||||
if err != nil || !g3.Issued || g3.NewEpoch != g.NewEpoch || g3.LostRange != nil || !strings.Contains(g3.LostRangeError, "missing or unreadable") {
|
||||
t.Fatalf("replay with a damaged range: %+v %v; want the issued grant without a range, with the reason", g3, err)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "lost_range=UNPROVEN") {
|
||||
t.Fatalf("unproven range not logged:\n%s", logs.String())
|
||||
}
|
||||
if _, err := c2.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-f"}); status.Code(err) != codes.DataLoss {
|
||||
t.Fatalf("lost range query with a damaged record: %v; want DataLoss", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The HEAD reader takes the HEAD entry's mtime from the filer's
|
||||
// Last-Modified header of the same response; without a usable header the
|
||||
// time is unknown (0), never invented.
|
||||
func TestWorkspaceHEADReadsFilerMtime(t *testing.T) {
|
||||
mtime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC)
|
||||
for _, tc := range []struct {
|
||||
name, header string
|
||||
want int64
|
||||
}{
|
||||
{"last-modified", mtime.Format(http.TimeFormat), mtime.UnixNano()},
|
||||
{"absent", "", 0},
|
||||
{"unparseable", "yesterday", 0},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if tc.header != "" {
|
||||
w.Header().Set("Last-Modified", tc.header)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"format":1,"gen":9,"epoch":3,"holder":"old","remote_lsn":42}`))
|
||||
}))
|
||||
defer s.Close()
|
||||
read, err := NewWorkspaceHEADReader(s.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := read(context.Background(), "v")
|
||||
if err != nil || h.FilerMtimeNS != tc.want || h.Gen != 9 || h.RemoteLSN != 42 {
|
||||
t.Fatalf("HEAD %+v %v; want filer mtime %d", h, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -132,6 +133,53 @@ func grantFact(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant {
|
||||
OldEpoch: r.OldEpoch, NewEpoch: r.NewEpoch, HeadGen: r.HeadGen, RemoteLsn: r.RemoteLSN, Issued: r.Issued, OldHost: r.OldHost, NewHost: r.NewHost}
|
||||
}
|
||||
|
||||
// lostRangeFact is the wire form of a stored lost range.
|
||||
func lostRangeFact(r authority.WorkspaceLostRangeReadout) *control.WorkspaceLostRange {
|
||||
return &control.WorkspaceLostRange{RequestId: r.RequestID, VolumeId: r.VolumeID, NewEpoch: r.NewEpoch, OldReplicaId: r.OldReplicaID, OldEpoch: r.OldEpoch,
|
||||
LostAfterLsn: r.LostAfterLSN, LostUntilNs: r.LostUntilNS, HeadGen: r.HeadGen, HeadTimeNs: r.HeadTimeNS, HeadTimeKnown: r.HeadTimeNS != 0}
|
||||
}
|
||||
|
||||
// grantWithLostRange is grantFact plus, for an issued forced grant, its
|
||||
// stored lost range; a range that cannot be read leaves lost_range unset and
|
||||
// says why in lost_range_error (the readout is then unproven, not empty).
|
||||
func (s *services) grantWithLostRange(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant {
|
||||
g := grantFact(r)
|
||||
if !r.Issued || r.Kind != "forced" {
|
||||
return g
|
||||
}
|
||||
ranges, err := s.host.Publisher().WorkspaceLostRangeReadouts(r.VolumeID, r.RequestID)
|
||||
switch {
|
||||
case err != nil:
|
||||
g.LostRangeError = err.Error()
|
||||
case len(ranges) != 1:
|
||||
g.LostRangeError = fmt.Sprintf("%v: %d ranges for request %q", authority.ErrWorkspaceLostRangeMissing, len(ranges), r.RequestID)
|
||||
default:
|
||||
g.LostRange = lostRangeFact(ranges[0])
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// logForcedGrant records an issued forced move (also a replay of one).
|
||||
func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIssue error) {
|
||||
if g == nil || !g.GetIssued() || g.GetKind() != "forced" {
|
||||
return
|
||||
}
|
||||
lost := "lost_range=UNPROVEN (" + g.GetLostRangeError() + ")"
|
||||
if l := g.GetLostRange(); l != nil {
|
||||
head := "unknown"
|
||||
if l.GetHeadTimeKnown() {
|
||||
head = time.Unix(0, l.GetHeadTimeNs()).UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
lost = fmt.Sprintf("lost_after_lsn=%d lost_until_ns=%d lost_until=%s head_gen=%d head_filer_time=%s",
|
||||
l.GetLostAfterLsn(), l.GetLostUntilNs(), time.Unix(0, l.GetLostUntilNs()).UTC().Format(time.RFC3339Nano), l.GetHeadGen(), head)
|
||||
}
|
||||
if postIssue != nil {
|
||||
lost += fmt.Sprintf(" answer_failed_after_issue=%q", postIssue.Error())
|
||||
}
|
||||
s.host.log.Printf("blockmaster: MoveWorkspace forced move issued volume=%q request=%q old=%s/%s@%d new=%s/%s@%d replay=%t %s",
|
||||
g.GetVolumeId(), g.GetRequestId(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), replay, lost)
|
||||
}
|
||||
|
||||
func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
|
||||
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
|
||||
return nil, err
|
||||
@@ -157,11 +205,19 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
// local precondition below; Publisher checks the expected epoch atomically.
|
||||
// A refusal is logged after the lock is released (deferred first, so it
|
||||
// runs last): a slow log writer never holds workspaceMu.
|
||||
// An issued forced grant is logged the same way, also after the unlock.
|
||||
var refusal string
|
||||
var issued *control.WorkspaceGrant
|
||||
var replay bool
|
||||
var postIssue, unknown error
|
||||
defer func() {
|
||||
if refusal != "" {
|
||||
s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal)
|
||||
}
|
||||
s.logForcedGrant(issued, replay, postIssue)
|
||||
if unknown != nil {
|
||||
s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown)
|
||||
}
|
||||
}()
|
||||
s.host.workspaceMu.Lock()
|
||||
defer s.host.workspaceMu.Unlock()
|
||||
@@ -171,11 +227,72 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, target, replay, why, err := s.workspaceMoveCheckLocked(q)
|
||||
if err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
if refusal = why; refusal != "" {
|
||||
return nil, status.Error(codes.FailedPrecondition, refusal)
|
||||
}
|
||||
if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
r, err := s.host.Publisher().MoveWorkspace(ctx, req, head)
|
||||
if err != nil {
|
||||
// A move that is issued in spite of the error (it failed after the
|
||||
// issue) is never a refusal: the caller recovers its grant with the
|
||||
// same request id.
|
||||
if s.host.Publisher().IssuedWorkspaceMove(req) {
|
||||
issued, postIssue = s.issuedRecord(req), err
|
||||
return nil, postIssueError(q, err)
|
||||
}
|
||||
if errors.Is(err, authority.ErrWorkspaceOutcomeUncertain) {
|
||||
unknown = err
|
||||
return nil, status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id",
|
||||
q.GetRequestId(), q.GetVolumeId(), err)
|
||||
}
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
// The move is issued from here on: record it for the audit log before
|
||||
// anything else can fail.
|
||||
issued = s.grantWithLostRange(r)
|
||||
if err = s.host.reconcileWorkspaceBindings(); err != nil {
|
||||
postIssue = err
|
||||
return nil, postIssueError(q, err)
|
||||
}
|
||||
return issued, nil
|
||||
}
|
||||
|
||||
// postIssueError reports a failure after q's move was issued: never
|
||||
// FailedPrecondition (a definite refusal); Internal, which clients treat as
|
||||
// an unknown outcome, with the same-request-id recovery.
|
||||
func postIssueError(q *control.WorkspaceMove, err error) error {
|
||||
return status.Errorf(codes.Internal, "workspace move %q of volume %q is ISSUED, but a step after the issue failed: %v; rerun with the same request id to get its grant",
|
||||
q.GetRequestId(), q.GetVolumeId(), err)
|
||||
}
|
||||
|
||||
// issuedRecord is the answer for req's issued journal record, if any.
|
||||
func (s *services) issuedRecord(req authority.WorkspaceMoveRequest) *control.WorkspaceGrant {
|
||||
if st := s.host.Publisher().WorkspaceState(req.VolumeID); st != nil {
|
||||
for _, m := range st.Moves {
|
||||
if m.RequestID == req.RequestID && m.Issued {
|
||||
return s.grantWithLostRange(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// workspaceMoveCheckLocked builds the authority request of q and the
|
||||
// blockmaster's own refusal of it ("" when none): endpoints, source host,
|
||||
// target node and binding. It reads and writes nothing else; MoveWorkspace
|
||||
// and PreviewWorkspaceMove share it. Caller holds workspaceMu.
|
||||
func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req authority.WorkspaceMoveRequest, target lifecycle.NodeRegistration, replay bool, refusal string, err error) {
|
||||
oldHost := s.host.workspaceSourceHost(q.GetVolumeId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch())
|
||||
target, ok := s.host.lifecycle.Nodes.GetNode(q.GetTargetServerId())
|
||||
bindings, explicit, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId())
|
||||
if err != nil {
|
||||
return nil, workspaceError(err)
|
||||
return authority.WorkspaceMoveRequest{}, lifecycle.NodeRegistration{}, false, "", err
|
||||
}
|
||||
// A volume without per-volume bindings may move to any port on the
|
||||
// target node's registered hosts (a host runs several slots): the host
|
||||
@@ -189,12 +306,12 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
req := authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID,
|
||||
req = authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID,
|
||||
ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()}
|
||||
// Strict journal isolation refuses new work only: an exact replay of an
|
||||
// issued move (its reply lost, the target found co-located since) gets
|
||||
// its durable grant back from MoveWorkspace, never a definite refusal.
|
||||
replay := ok && s.host.Publisher().IssuedWorkspaceMove(req)
|
||||
replay = ok && s.host.Publisher().IssuedWorkspaceMove(req)
|
||||
switch {
|
||||
case endpointErr != nil:
|
||||
refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr)
|
||||
@@ -209,20 +326,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
case !matched:
|
||||
refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
|
||||
}
|
||||
if refusal != "" {
|
||||
return nil, status.Error(codes.FailedPrecondition, refusal)
|
||||
}
|
||||
if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
r, err := s.host.Publisher().MoveWorkspace(ctx, req, head)
|
||||
if err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
if err = s.host.reconcileWorkspaceBindings(); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
return grantFact(r), nil
|
||||
return req, target, replay, refusal, nil
|
||||
}
|
||||
|
||||
// sameHost reports whether two host:port addresses name the same host:
|
||||
@@ -276,7 +380,103 @@ func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolum
|
||||
out.RevocationAck = &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: q.GetVolumeId(), ReplicaId: state.Ack.ReplicaID, Epoch: state.Ack.Epoch}, HeadGen: state.Ack.HeadGen}
|
||||
}
|
||||
for _, r := range state.Moves {
|
||||
out.Moves = append(out.Moves, grantFact(r))
|
||||
out.Moves = append(out.Moves, s.grantWithLostRange(r))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// QueryWorkspaceLostRange returns the stored lost ranges of the volume's
|
||||
// issued forced moves in issue order, or the one of request_id. A forced
|
||||
// move whose range is missing or failed its checks fails the call with
|
||||
// DataLoss: the readout is unproven, never "no loss".
|
||||
func (s *services) QueryWorkspaceLostRange(ctx context.Context, q *control.WorkspaceLostRangeQuery) (*control.WorkspaceLostRanges, error) {
|
||||
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ranges, err := s.host.Publisher().WorkspaceLostRangeReadouts(q.GetVolumeId(), q.GetRequestId())
|
||||
switch {
|
||||
case errors.Is(err, authority.ErrWorkspaceLostRangeMissing):
|
||||
return nil, status.Error(codes.DataLoss, err.Error())
|
||||
case errors.Is(err, authority.ErrWorkspaceNoForcedMove):
|
||||
return nil, status.Error(codes.NotFound, err.Error())
|
||||
case err != nil:
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
out := &control.WorkspaceLostRanges{}
|
||||
for _, r := range ranges {
|
||||
out.Ranges = append(out.Ranges, lostRangeFact(r))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PreviewWorkspaceMove answers what MoveWorkspace would do with a forced
|
||||
// move now, writing nothing: the blockmaster's own checks, the publisher's
|
||||
// forced admission (with the barrier, i.e. when it becomes admissible) and,
|
||||
// only once admitted, the HEAD read and HEAD rule, as the move does. A
|
||||
// refusal is an answer (admitted false, reason), not an RPC error.
|
||||
func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) {
|
||||
out := &control.WorkspaceMovePreview{}
|
||||
if !s.host.cfg.WorkspaceRPC {
|
||||
return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled")
|
||||
}
|
||||
if q.GetKind() != "forced" || !q.GetForce() {
|
||||
out.Reason = "workspace move preview: forced moves only (kind forced, force true)"
|
||||
out.MasterTimeNs = time.Now().UnixNano()
|
||||
return out, nil
|
||||
}
|
||||
var req authority.WorkspaceMoveRequest
|
||||
var replay bool
|
||||
if err := func() error {
|
||||
s.host.workspaceMu.Lock()
|
||||
defer s.host.workspaceMu.Unlock()
|
||||
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
|
||||
out.Reason = status.Convert(err).Message()
|
||||
return nil
|
||||
}
|
||||
r, target, _, why, err := s.workspaceMoveCheckLocked(q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req = r
|
||||
pv := s.host.Publisher().PreviewWorkspaceForcedMove(req)
|
||||
out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS
|
||||
switch {
|
||||
case why != "":
|
||||
out.Admitted, out.Reason = false, why
|
||||
case !pv.Admitted:
|
||||
out.Reason = pv.Reason
|
||||
case pv.Replay:
|
||||
replay, out.Reason = true, pv.Reason
|
||||
default:
|
||||
if err := s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
|
||||
out.Admitted, out.Reason = false, err.Error()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
if out.MasterTimeNs == 0 {
|
||||
out.MasterTimeNs = time.Now().UnixNano()
|
||||
}
|
||||
if !out.Admitted || replay { // a replay never reads a new HEAD
|
||||
return out, nil
|
||||
}
|
||||
// As for the move: HEAD is read only after admission, outside the lock,
|
||||
// bounded even when the caller set no deadline.
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
head, err := s.host.cfg.WorkspaceHeadReader(readCtx, q.GetVolumeId())
|
||||
if err != nil {
|
||||
out.Admitted, out.HeadError = false, err.Error()
|
||||
out.Reason = "workspace move: HEAD read failed: " + err.Error()
|
||||
return out, nil
|
||||
}
|
||||
out.HeadRead = true
|
||||
out.HeadGen, out.HeadEpoch, out.HeadHolder, out.HeadRemoteLsn = head.Gen, head.Epoch, head.Holder, head.RemoteLSN
|
||||
out.HeadTimeNs, out.HeadTimeKnown = head.FilerMtimeNS, head.FilerMtimeNS != 0
|
||||
if !authority.WorkspaceMoveHeadAdmits(req, head) {
|
||||
out.Admitted, out.Reason = false, "workspace move: HEAD not owned by expected holder"
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -414,21 +414,26 @@ func (x *WorkspaceMove) GetTargetServerId() string {
|
||||
}
|
||||
|
||||
type WorkspaceGrant struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
|
||||
VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
OldReplicaId string `protobuf:"bytes,3,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"`
|
||||
NewReplicaId string `protobuf:"bytes,4,opt,name=new_replica_id,json=newReplicaId,proto3" json:"new_replica_id,omitempty"`
|
||||
Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"`
|
||||
OldEpoch uint64 `protobuf:"varint,6,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"`
|
||||
NewEpoch uint64 `protobuf:"varint,7,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"`
|
||||
HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"`
|
||||
RemoteLsn uint64 `protobuf:"varint,9,opt,name=remote_lsn,json=remoteLsn,proto3" json:"remote_lsn,omitempty"`
|
||||
Issued bool `protobuf:"varint,10,opt,name=issued,proto3" json:"issued,omitempty"`
|
||||
OldHost string `protobuf:"bytes,11,opt,name=old_host,json=oldHost,proto3" json:"old_host,omitempty"`
|
||||
NewHost string `protobuf:"bytes,12,opt,name=new_host,json=newHost,proto3" json:"new_host,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
|
||||
VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
OldReplicaId string `protobuf:"bytes,3,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"`
|
||||
NewReplicaId string `protobuf:"bytes,4,opt,name=new_replica_id,json=newReplicaId,proto3" json:"new_replica_id,omitempty"`
|
||||
Kind string `protobuf:"bytes,5,opt,name=kind,proto3" json:"kind,omitempty"`
|
||||
OldEpoch uint64 `protobuf:"varint,6,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"`
|
||||
NewEpoch uint64 `protobuf:"varint,7,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"`
|
||||
HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"`
|
||||
RemoteLsn uint64 `protobuf:"varint,9,opt,name=remote_lsn,json=remoteLsn,proto3" json:"remote_lsn,omitempty"`
|
||||
Issued bool `protobuf:"varint,10,opt,name=issued,proto3" json:"issued,omitempty"`
|
||||
OldHost string `protobuf:"bytes,11,opt,name=old_host,json=oldHost,proto3" json:"old_host,omitempty"`
|
||||
NewHost string `protobuf:"bytes,12,opt,name=new_host,json=newHost,proto3" json:"new_host,omitempty"`
|
||||
// Forced grants only: the lost range stored before the issue (also on a
|
||||
// replay). Absent on a forced grant means the readout is not proven, and
|
||||
// lost_range_error says why; it never means "no loss".
|
||||
LostRange *WorkspaceLostRange `protobuf:"bytes,13,opt,name=lost_range,json=lostRange,proto3" json:"lost_range,omitempty"`
|
||||
LostRangeError string `protobuf:"bytes,14,opt,name=lost_range_error,json=lostRangeError,proto3" json:"lost_range_error,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WorkspaceGrant) Reset() {
|
||||
@@ -545,6 +550,370 @@ func (x *WorkspaceGrant) GetNewHost() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceGrant) GetLostRange() *WorkspaceLostRange {
|
||||
if x != nil {
|
||||
return x.LostRange
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *WorkspaceGrant) GetLostRangeError() string {
|
||||
if x != nil {
|
||||
return x.LostRangeError
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// What a forced move abandoned. head_gen 0: no published HEAD (everything the
|
||||
// old holder wrote is lost). head_time_ns is the HEAD entry's filer mtime read
|
||||
// with HEAD at the move (1 s resolution), valid only when head_time_known.
|
||||
// lost_until_ns is master time; the upper bound is a time, not an LSN.
|
||||
type WorkspaceLostRange struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
|
||||
VolumeId string `protobuf:"bytes,2,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
NewEpoch uint64 `protobuf:"varint,3,opt,name=new_epoch,json=newEpoch,proto3" json:"new_epoch,omitempty"`
|
||||
OldReplicaId string `protobuf:"bytes,4,opt,name=old_replica_id,json=oldReplicaId,proto3" json:"old_replica_id,omitempty"`
|
||||
OldEpoch uint64 `protobuf:"varint,5,opt,name=old_epoch,json=oldEpoch,proto3" json:"old_epoch,omitempty"`
|
||||
LostAfterLsn uint64 `protobuf:"varint,6,opt,name=lost_after_lsn,json=lostAfterLsn,proto3" json:"lost_after_lsn,omitempty"`
|
||||
LostUntilNs int64 `protobuf:"varint,7,opt,name=lost_until_ns,json=lostUntilNs,proto3" json:"lost_until_ns,omitempty"`
|
||||
HeadGen uint64 `protobuf:"varint,8,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"`
|
||||
HeadTimeNs int64 `protobuf:"varint,9,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"`
|
||||
HeadTimeKnown bool `protobuf:"varint,10,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) Reset() {
|
||||
*x = WorkspaceLostRange{}
|
||||
mi := &file_workspace_proto_msgTypes[7]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WorkspaceLostRange) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceLostRange) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[7]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WorkspaceLostRange.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspaceLostRange) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{7}
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetRequestId() string {
|
||||
if x != nil {
|
||||
return x.RequestId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetVolumeId() string {
|
||||
if x != nil {
|
||||
return x.VolumeId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetNewEpoch() uint64 {
|
||||
if x != nil {
|
||||
return x.NewEpoch
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetOldReplicaId() string {
|
||||
if x != nil {
|
||||
return x.OldReplicaId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetOldEpoch() uint64 {
|
||||
if x != nil {
|
||||
return x.OldEpoch
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetLostAfterLsn() uint64 {
|
||||
if x != nil {
|
||||
return x.LostAfterLsn
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetLostUntilNs() int64 {
|
||||
if x != nil {
|
||||
return x.LostUntilNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetHeadGen() uint64 {
|
||||
if x != nil {
|
||||
return x.HeadGen
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetHeadTimeNs() int64 {
|
||||
if x != nil {
|
||||
return x.HeadTimeNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRange) GetHeadTimeKnown() bool {
|
||||
if x != nil {
|
||||
return x.HeadTimeKnown
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type WorkspaceLostRangeQuery struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
RequestId string `protobuf:"bytes,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRangeQuery) Reset() {
|
||||
*x = WorkspaceLostRangeQuery{}
|
||||
mi := &file_workspace_proto_msgTypes[8]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRangeQuery) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WorkspaceLostRangeQuery) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceLostRangeQuery) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[8]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WorkspaceLostRangeQuery.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspaceLostRangeQuery) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{8}
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRangeQuery) GetVolumeId() string {
|
||||
if x != nil {
|
||||
return x.VolumeId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRangeQuery) GetRequestId() string {
|
||||
if x != nil {
|
||||
return x.RequestId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type WorkspaceLostRanges struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Ranges []*WorkspaceLostRange `protobuf:"bytes,1,rep,name=ranges,proto3" json:"ranges,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRanges) Reset() {
|
||||
*x = WorkspaceLostRanges{}
|
||||
mi := &file_workspace_proto_msgTypes[9]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRanges) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WorkspaceLostRanges) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceLostRanges) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[9]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WorkspaceLostRanges.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspaceLostRanges) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{9}
|
||||
}
|
||||
|
||||
func (x *WorkspaceLostRanges) GetRanges() []*WorkspaceLostRange {
|
||||
if x != nil {
|
||||
return x.Ranges
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lost_until_ns is when a forced move becomes admissible (0 if the master has
|
||||
// no lease to judge). HEAD is read only when admitted, as for the move.
|
||||
type WorkspaceMovePreview struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Admitted bool `protobuf:"varint,1,opt,name=admitted,proto3" json:"admitted,omitempty"`
|
||||
Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"`
|
||||
LostUntilNs int64 `protobuf:"varint,3,opt,name=lost_until_ns,json=lostUntilNs,proto3" json:"lost_until_ns,omitempty"`
|
||||
MasterTimeNs int64 `protobuf:"varint,4,opt,name=master_time_ns,json=masterTimeNs,proto3" json:"master_time_ns,omitempty"`
|
||||
HeadRead bool `protobuf:"varint,5,opt,name=head_read,json=headRead,proto3" json:"head_read,omitempty"`
|
||||
HeadError string `protobuf:"bytes,6,opt,name=head_error,json=headError,proto3" json:"head_error,omitempty"`
|
||||
HeadGen uint64 `protobuf:"varint,7,opt,name=head_gen,json=headGen,proto3" json:"head_gen,omitempty"`
|
||||
HeadEpoch uint64 `protobuf:"varint,8,opt,name=head_epoch,json=headEpoch,proto3" json:"head_epoch,omitempty"`
|
||||
HeadHolder string `protobuf:"bytes,9,opt,name=head_holder,json=headHolder,proto3" json:"head_holder,omitempty"`
|
||||
HeadRemoteLsn uint64 `protobuf:"varint,10,opt,name=head_remote_lsn,json=headRemoteLsn,proto3" json:"head_remote_lsn,omitempty"`
|
||||
HeadTimeNs int64 `protobuf:"varint,11,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"`
|
||||
HeadTimeKnown bool `protobuf:"varint,12,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) Reset() {
|
||||
*x = WorkspaceMovePreview{}
|
||||
mi := &file_workspace_proto_msgTypes[10]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WorkspaceMovePreview) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceMovePreview) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[10]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WorkspaceMovePreview.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspaceMovePreview) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{10}
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetAdmitted() bool {
|
||||
if x != nil {
|
||||
return x.Admitted
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetReason() string {
|
||||
if x != nil {
|
||||
return x.Reason
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetLostUntilNs() int64 {
|
||||
if x != nil {
|
||||
return x.LostUntilNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetMasterTimeNs() int64 {
|
||||
if x != nil {
|
||||
return x.MasterTimeNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadRead() bool {
|
||||
if x != nil {
|
||||
return x.HeadRead
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadError() string {
|
||||
if x != nil {
|
||||
return x.HeadError
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadGen() uint64 {
|
||||
if x != nil {
|
||||
return x.HeadGen
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadEpoch() uint64 {
|
||||
if x != nil {
|
||||
return x.HeadEpoch
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadHolder() string {
|
||||
if x != nil {
|
||||
return x.HeadHolder
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadRemoteLsn() uint64 {
|
||||
if x != nil {
|
||||
return x.HeadRemoteLsn
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadTimeNs() int64 {
|
||||
if x != nil {
|
||||
return x.HeadTimeNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WorkspaceMovePreview) GetHeadTimeKnown() bool {
|
||||
if x != nil {
|
||||
return x.HeadTimeKnown
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type WorkspaceStatus struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"`
|
||||
@@ -557,7 +926,7 @@ type WorkspaceStatus struct {
|
||||
|
||||
func (x *WorkspaceStatus) Reset() {
|
||||
*x = WorkspaceStatus{}
|
||||
mi := &file_workspace_proto_msgTypes[7]
|
||||
mi := &file_workspace_proto_msgTypes[11]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -569,7 +938,7 @@ func (x *WorkspaceStatus) String() string {
|
||||
func (*WorkspaceStatus) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[7]
|
||||
mi := &file_workspace_proto_msgTypes[11]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -582,7 +951,7 @@ func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkspaceStatus.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspaceStatus) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{7}
|
||||
return file_workspace_proto_rawDescGZIP(), []int{11}
|
||||
}
|
||||
|
||||
func (x *WorkspaceStatus) GetLease() *WorkspaceLeaseFact {
|
||||
@@ -626,7 +995,7 @@ type WorkspaceBinding struct {
|
||||
|
||||
func (x *WorkspaceBinding) Reset() {
|
||||
*x = WorkspaceBinding{}
|
||||
mi := &file_workspace_proto_msgTypes[8]
|
||||
mi := &file_workspace_proto_msgTypes[12]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -638,7 +1007,7 @@ func (x *WorkspaceBinding) String() string {
|
||||
func (*WorkspaceBinding) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[8]
|
||||
mi := &file_workspace_proto_msgTypes[12]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -651,7 +1020,7 @@ func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkspaceBinding.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspaceBinding) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{8}
|
||||
return file_workspace_proto_rawDescGZIP(), []int{12}
|
||||
}
|
||||
|
||||
func (x *WorkspaceBinding) GetVolumeId() string {
|
||||
@@ -700,7 +1069,7 @@ type WorkspacePlacement struct {
|
||||
|
||||
func (x *WorkspacePlacement) Reset() {
|
||||
*x = WorkspacePlacement{}
|
||||
mi := &file_workspace_proto_msgTypes[9]
|
||||
mi := &file_workspace_proto_msgTypes[13]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -712,7 +1081,7 @@ func (x *WorkspacePlacement) String() string {
|
||||
func (*WorkspacePlacement) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_workspace_proto_msgTypes[9]
|
||||
mi := &file_workspace_proto_msgTypes[13]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -725,7 +1094,7 @@ func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkspacePlacement.ProtoReflect.Descriptor instead.
|
||||
func (*WorkspacePlacement) Descriptor() ([]byte, []int) {
|
||||
return file_workspace_proto_rawDescGZIP(), []int{9}
|
||||
return file_workspace_proto_rawDescGZIP(), []int{13}
|
||||
}
|
||||
|
||||
func (x *WorkspacePlacement) GetVolumeId() string {
|
||||
@@ -786,7 +1155,7 @@ const file_workspace_proto_rawDesc = "" +
|
||||
"\x04kind\x18\b \x01(\tR\x04kind\x12\x14\n" +
|
||||
"\x05force\x18\t \x01(\bR\x05force\x12(\n" +
|
||||
"\x10target_server_id\x18\n" +
|
||||
" \x01(\tR\x0etargetServerId\"\xee\x02\n" +
|
||||
" \x01(\tR\x0etargetServerId\"\xe4\x03\n" +
|
||||
"\x0eWorkspaceGrant\x12\x1d\n" +
|
||||
"\n" +
|
||||
"request_id\x18\x01 \x01(\tR\trequestId\x12\x1b\n" +
|
||||
@@ -802,7 +1171,48 @@ const file_workspace_proto_rawDesc = "" +
|
||||
"\x06issued\x18\n" +
|
||||
" \x01(\bR\x06issued\x12\x19\n" +
|
||||
"\bold_host\x18\v \x01(\tR\aoldHost\x12\x19\n" +
|
||||
"\bnew_host\x18\f \x01(\tR\anewHost\"\xb2\x02\n" +
|
||||
"\bnew_host\x18\f \x01(\tR\anewHost\x12J\n" +
|
||||
"\n" +
|
||||
"lost_range\x18\r \x01(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\tlostRange\x12(\n" +
|
||||
"\x10lost_range_error\x18\x0e \x01(\tR\x0elostRangeError\"\xdf\x02\n" +
|
||||
"\x12WorkspaceLostRange\x12\x1d\n" +
|
||||
"\n" +
|
||||
"request_id\x18\x01 \x01(\tR\trequestId\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x02 \x01(\tR\bvolumeId\x12\x1b\n" +
|
||||
"\tnew_epoch\x18\x03 \x01(\x04R\bnewEpoch\x12$\n" +
|
||||
"\x0eold_replica_id\x18\x04 \x01(\tR\foldReplicaId\x12\x1b\n" +
|
||||
"\told_epoch\x18\x05 \x01(\x04R\boldEpoch\x12$\n" +
|
||||
"\x0elost_after_lsn\x18\x06 \x01(\x04R\flostAfterLsn\x12\"\n" +
|
||||
"\rlost_until_ns\x18\a \x01(\x03R\vlostUntilNs\x12\x19\n" +
|
||||
"\bhead_gen\x18\b \x01(\x04R\aheadGen\x12 \n" +
|
||||
"\fhead_time_ns\x18\t \x01(\x03R\n" +
|
||||
"headTimeNs\x12&\n" +
|
||||
"\x0fhead_time_known\x18\n" +
|
||||
" \x01(\bR\rheadTimeKnown\"U\n" +
|
||||
"\x17WorkspaceLostRangeQuery\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1d\n" +
|
||||
"\n" +
|
||||
"request_id\x18\x02 \x01(\tR\trequestId\"Z\n" +
|
||||
"\x13WorkspaceLostRanges\x12C\n" +
|
||||
"\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\x9d\x03\n" +
|
||||
"\x14WorkspaceMovePreview\x12\x1a\n" +
|
||||
"\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" +
|
||||
"\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" +
|
||||
"\rlost_until_ns\x18\x03 \x01(\x03R\vlostUntilNs\x12$\n" +
|
||||
"\x0emaster_time_ns\x18\x04 \x01(\x03R\fmasterTimeNs\x12\x1b\n" +
|
||||
"\thead_read\x18\x05 \x01(\bR\bheadRead\x12\x1d\n" +
|
||||
"\n" +
|
||||
"head_error\x18\x06 \x01(\tR\theadError\x12\x19\n" +
|
||||
"\bhead_gen\x18\a \x01(\x04R\aheadGen\x12\x1d\n" +
|
||||
"\n" +
|
||||
"head_epoch\x18\b \x01(\x04R\theadEpoch\x12\x1f\n" +
|
||||
"\vhead_holder\x18\t \x01(\tR\n" +
|
||||
"headHolder\x12&\n" +
|
||||
"\x0fhead_remote_lsn\x18\n" +
|
||||
" \x01(\x04R\rheadRemoteLsn\x12 \n" +
|
||||
"\fhead_time_ns\x18\v \x01(\x03R\n" +
|
||||
"headTimeNs\x12&\n" +
|
||||
"\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\"\xb2\x02\n" +
|
||||
"\x0fWorkspaceStatus\x12A\n" +
|
||||
"\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" +
|
||||
"\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" +
|
||||
@@ -818,7 +1228,7 @@ const file_workspace_proto_rawDesc = "" +
|
||||
"\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1b\n" +
|
||||
"\tserver_id\x18\x02 \x01(\tR\bserverId\x12\x1d\n" +
|
||||
"\n" +
|
||||
"replica_id\x18\x03 \x01(\tR\treplicaId2\x81\x06\n" +
|
||||
"replica_id\x18\x03 \x01(\tR\treplicaId2\xeb\a\n" +
|
||||
"\x10WorkspaceService\x12p\n" +
|
||||
"\x18RegisterWorkspaceBinding\x12).seaweedfs.block.control.WorkspaceBinding\x1a).seaweedfs.block.control.WorkspaceBinding\x12f\n" +
|
||||
"\x0ePlaceWorkspace\x12+.seaweedfs.block.control.WorkspacePlacement\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12n\n" +
|
||||
@@ -826,7 +1236,9 @@ const file_workspace_proto_rawDesc = "" +
|
||||
"\x0fRevokeWorkspace\x12*.seaweedfs.block.control.WorkspaceIdentity\x1a+.seaweedfs.block.control.WorkspaceLeaseFact\x12o\n" +
|
||||
"\x13AckWorkspaceRevoked\x12/.seaweedfs.block.control.WorkspaceRevocationAck\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12`\n" +
|
||||
"\rMoveWorkspace\x12&.seaweedfs.block.control.WorkspaceMove\x1a'.seaweedfs.block.control.WorkspaceGrant\x12d\n" +
|
||||
"\x0eQueryWorkspace\x12(.seaweedfs.block.control.WorkspaceVolume\x1a(.seaweedfs.block.control.WorkspaceStatusB=Z;github.com/seaweedfs/seaweed-block/core/rpc/control;controlb\x06proto3"
|
||||
"\x0eQueryWorkspace\x12(.seaweedfs.block.control.WorkspaceVolume\x1a(.seaweedfs.block.control.WorkspaceStatus\x12y\n" +
|
||||
"\x17QueryWorkspaceLostRange\x120.seaweedfs.block.control.WorkspaceLostRangeQuery\x1a,.seaweedfs.block.control.WorkspaceLostRanges\x12m\n" +
|
||||
"\x14PreviewWorkspaceMove\x12&.seaweedfs.block.control.WorkspaceMove\x1a-.seaweedfs.block.control.WorkspaceMovePreviewB=Z;github.com/seaweedfs/seaweed-block/core/rpc/control;controlb\x06proto3"
|
||||
|
||||
var (
|
||||
file_workspace_proto_rawDescOnce sync.Once
|
||||
@@ -840,44 +1252,54 @@ func file_workspace_proto_rawDescGZIP() []byte {
|
||||
return file_workspace_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 10)
|
||||
var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 14)
|
||||
var file_workspace_proto_goTypes = []any{
|
||||
(*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity
|
||||
(*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume
|
||||
(*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty
|
||||
(*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact
|
||||
(*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck
|
||||
(*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove
|
||||
(*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant
|
||||
(*WorkspaceStatus)(nil), // 7: seaweedfs.block.control.WorkspaceStatus
|
||||
(*WorkspaceBinding)(nil), // 8: seaweedfs.block.control.WorkspaceBinding
|
||||
(*WorkspacePlacement)(nil), // 9: seaweedfs.block.control.WorkspacePlacement
|
||||
(*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity
|
||||
(*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume
|
||||
(*WorkspaceEmpty)(nil), // 2: seaweedfs.block.control.WorkspaceEmpty
|
||||
(*WorkspaceLeaseFact)(nil), // 3: seaweedfs.block.control.WorkspaceLeaseFact
|
||||
(*WorkspaceRevocationAck)(nil), // 4: seaweedfs.block.control.WorkspaceRevocationAck
|
||||
(*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove
|
||||
(*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant
|
||||
(*WorkspaceLostRange)(nil), // 7: seaweedfs.block.control.WorkspaceLostRange
|
||||
(*WorkspaceLostRangeQuery)(nil), // 8: seaweedfs.block.control.WorkspaceLostRangeQuery
|
||||
(*WorkspaceLostRanges)(nil), // 9: seaweedfs.block.control.WorkspaceLostRanges
|
||||
(*WorkspaceMovePreview)(nil), // 10: seaweedfs.block.control.WorkspaceMovePreview
|
||||
(*WorkspaceStatus)(nil), // 11: seaweedfs.block.control.WorkspaceStatus
|
||||
(*WorkspaceBinding)(nil), // 12: seaweedfs.block.control.WorkspaceBinding
|
||||
(*WorkspacePlacement)(nil), // 13: seaweedfs.block.control.WorkspacePlacement
|
||||
}
|
||||
var file_workspace_proto_depIdxs = []int32{
|
||||
0, // 0: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity
|
||||
3, // 1: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact
|
||||
4, // 2: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck
|
||||
6, // 3: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant
|
||||
8, // 4: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding
|
||||
8, // 5: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding
|
||||
9, // 6: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement
|
||||
0, // 7: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity
|
||||
0, // 8: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity
|
||||
4, // 9: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck
|
||||
5, // 10: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove
|
||||
1, // 11: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume
|
||||
8, // 12: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding
|
||||
2, // 13: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty
|
||||
3, // 14: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact
|
||||
3, // 15: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact
|
||||
2, // 16: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty
|
||||
6, // 17: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant
|
||||
7, // 18: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus
|
||||
12, // [12:19] is the sub-list for method output_type
|
||||
5, // [5:12] is the sub-list for method input_type
|
||||
5, // [5:5] is the sub-list for extension type_name
|
||||
5, // [5:5] is the sub-list for extension extendee
|
||||
0, // [0:5] is the sub-list for field type_name
|
||||
7, // 1: seaweedfs.block.control.WorkspaceGrant.lost_range:type_name -> seaweedfs.block.control.WorkspaceLostRange
|
||||
7, // 2: seaweedfs.block.control.WorkspaceLostRanges.ranges:type_name -> seaweedfs.block.control.WorkspaceLostRange
|
||||
3, // 3: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact
|
||||
4, // 4: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck
|
||||
6, // 5: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant
|
||||
12, // 6: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding
|
||||
12, // 7: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding
|
||||
13, // 8: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement
|
||||
0, // 9: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity
|
||||
0, // 10: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity
|
||||
4, // 11: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck
|
||||
5, // 12: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove
|
||||
1, // 13: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume
|
||||
8, // 14: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:input_type -> seaweedfs.block.control.WorkspaceLostRangeQuery
|
||||
5, // 15: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:input_type -> seaweedfs.block.control.WorkspaceMove
|
||||
12, // 16: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding
|
||||
2, // 17: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty
|
||||
3, // 18: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact
|
||||
3, // 19: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact
|
||||
2, // 20: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty
|
||||
6, // 21: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant
|
||||
11, // 22: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus
|
||||
9, // 23: seaweedfs.block.control.WorkspaceService.QueryWorkspaceLostRange:output_type -> seaweedfs.block.control.WorkspaceLostRanges
|
||||
10, // 24: seaweedfs.block.control.WorkspaceService.PreviewWorkspaceMove:output_type -> seaweedfs.block.control.WorkspaceMovePreview
|
||||
16, // [16:25] is the sub-list for method output_type
|
||||
7, // [7:16] is the sub-list for method input_type
|
||||
7, // [7:7] is the sub-list for extension type_name
|
||||
7, // [7:7] is the sub-list for extension extendee
|
||||
0, // [0:7] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_workspace_proto_init() }
|
||||
@@ -891,7 +1313,7 @@ func file_workspace_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_workspace_proto_rawDesc), len(file_workspace_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 10,
|
||||
NumMessages: 14,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -26,6 +26,8 @@ const (
|
||||
WorkspaceService_AckWorkspaceRevoked_FullMethodName = "/seaweedfs.block.control.WorkspaceService/AckWorkspaceRevoked"
|
||||
WorkspaceService_MoveWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/MoveWorkspace"
|
||||
WorkspaceService_QueryWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspace"
|
||||
WorkspaceService_QueryWorkspaceLostRange_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspaceLostRange"
|
||||
WorkspaceService_PreviewWorkspaceMove_FullMethodName = "/seaweedfs.block.control.WorkspaceService/PreviewWorkspaceMove"
|
||||
)
|
||||
|
||||
// WorkspaceServiceClient is the client API for WorkspaceService service.
|
||||
@@ -43,6 +45,13 @@ type WorkspaceServiceClient interface {
|
||||
AckWorkspaceRevoked(ctx context.Context, in *WorkspaceRevocationAck, opts ...grpc.CallOption) (*WorkspaceEmpty, error)
|
||||
MoveWorkspace(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceGrant, error)
|
||||
QueryWorkspace(ctx context.Context, in *WorkspaceVolume, opts ...grpc.CallOption) (*WorkspaceStatus, error)
|
||||
// The stored lost ranges of the volume's issued forced moves, in issue
|
||||
// order (or the one of request_id); never recomputed. A forced move whose
|
||||
// range is missing or unreadable fails with DATA_LOSS, never "no loss".
|
||||
QueryWorkspaceLostRange(ctx context.Context, in *WorkspaceLostRangeQuery, opts ...grpc.CallOption) (*WorkspaceLostRanges, error)
|
||||
// Read-only forced-move admission check (no reservation, no journal
|
||||
// write): advisory, re-checked by MoveWorkspace.
|
||||
PreviewWorkspaceMove(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceMovePreview, error)
|
||||
}
|
||||
|
||||
type workspaceServiceClient struct {
|
||||
@@ -123,6 +132,26 @@ func (c *workspaceServiceClient) QueryWorkspace(ctx context.Context, in *Workspa
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *workspaceServiceClient) QueryWorkspaceLostRange(ctx context.Context, in *WorkspaceLostRangeQuery, opts ...grpc.CallOption) (*WorkspaceLostRanges, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(WorkspaceLostRanges)
|
||||
err := c.cc.Invoke(ctx, WorkspaceService_QueryWorkspaceLostRange_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *workspaceServiceClient) PreviewWorkspaceMove(ctx context.Context, in *WorkspaceMove, opts ...grpc.CallOption) (*WorkspaceMovePreview, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(WorkspaceMovePreview)
|
||||
err := c.cc.Invoke(ctx, WorkspaceService_PreviewWorkspaceMove_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WorkspaceServiceServer is the server API for WorkspaceService service.
|
||||
// All implementations must embed UnimplementedWorkspaceServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -138,6 +167,13 @@ type WorkspaceServiceServer interface {
|
||||
AckWorkspaceRevoked(context.Context, *WorkspaceRevocationAck) (*WorkspaceEmpty, error)
|
||||
MoveWorkspace(context.Context, *WorkspaceMove) (*WorkspaceGrant, error)
|
||||
QueryWorkspace(context.Context, *WorkspaceVolume) (*WorkspaceStatus, error)
|
||||
// The stored lost ranges of the volume's issued forced moves, in issue
|
||||
// order (or the one of request_id); never recomputed. A forced move whose
|
||||
// range is missing or unreadable fails with DATA_LOSS, never "no loss".
|
||||
QueryWorkspaceLostRange(context.Context, *WorkspaceLostRangeQuery) (*WorkspaceLostRanges, error)
|
||||
// Read-only forced-move admission check (no reservation, no journal
|
||||
// write): advisory, re-checked by MoveWorkspace.
|
||||
PreviewWorkspaceMove(context.Context, *WorkspaceMove) (*WorkspaceMovePreview, error)
|
||||
mustEmbedUnimplementedWorkspaceServiceServer()
|
||||
}
|
||||
|
||||
@@ -169,6 +205,12 @@ func (UnimplementedWorkspaceServiceServer) MoveWorkspace(context.Context, *Works
|
||||
func (UnimplementedWorkspaceServiceServer) QueryWorkspace(context.Context, *WorkspaceVolume) (*WorkspaceStatus, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method QueryWorkspace not implemented")
|
||||
}
|
||||
func (UnimplementedWorkspaceServiceServer) QueryWorkspaceLostRange(context.Context, *WorkspaceLostRangeQuery) (*WorkspaceLostRanges, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method QueryWorkspaceLostRange not implemented")
|
||||
}
|
||||
func (UnimplementedWorkspaceServiceServer) PreviewWorkspaceMove(context.Context, *WorkspaceMove) (*WorkspaceMovePreview, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method PreviewWorkspaceMove not implemented")
|
||||
}
|
||||
func (UnimplementedWorkspaceServiceServer) mustEmbedUnimplementedWorkspaceServiceServer() {}
|
||||
func (UnimplementedWorkspaceServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -316,6 +358,42 @@ func _WorkspaceService_QueryWorkspace_Handler(srv interface{}, ctx context.Conte
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _WorkspaceService_QueryWorkspaceLostRange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(WorkspaceLostRangeQuery)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(WorkspaceServiceServer).QueryWorkspaceLostRange(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: WorkspaceService_QueryWorkspaceLostRange_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(WorkspaceServiceServer).QueryWorkspaceLostRange(ctx, req.(*WorkspaceLostRangeQuery))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _WorkspaceService_PreviewWorkspaceMove_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(WorkspaceMove)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(WorkspaceServiceServer).PreviewWorkspaceMove(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: WorkspaceService_PreviewWorkspaceMove_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(WorkspaceServiceServer).PreviewWorkspaceMove(ctx, req.(*WorkspaceMove))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// WorkspaceService_ServiceDesc is the grpc.ServiceDesc for WorkspaceService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -351,6 +429,14 @@ var WorkspaceService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "QueryWorkspace",
|
||||
Handler: _WorkspaceService_QueryWorkspace_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "QueryWorkspaceLostRange",
|
||||
Handler: _WorkspaceService_QueryWorkspaceLostRange_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "PreviewWorkspaceMove",
|
||||
Handler: _WorkspaceService_PreviewWorkspaceMove_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "workspace.proto",
|
||||
|
||||
@@ -13,6 +13,13 @@ service WorkspaceService {
|
||||
rpc AckWorkspaceRevoked(WorkspaceRevocationAck) returns (WorkspaceEmpty);
|
||||
rpc MoveWorkspace(WorkspaceMove) returns (WorkspaceGrant);
|
||||
rpc QueryWorkspace(WorkspaceVolume) returns (WorkspaceStatus);
|
||||
// The stored lost ranges of the volume's issued forced moves, in issue
|
||||
// order (or the one of request_id); never recomputed. A forced move whose
|
||||
// range is missing or unreadable fails with DATA_LOSS, never "no loss".
|
||||
rpc QueryWorkspaceLostRange(WorkspaceLostRangeQuery) returns (WorkspaceLostRanges);
|
||||
// Read-only forced-move admission check (no reservation, no journal
|
||||
// write): advisory, re-checked by MoveWorkspace.
|
||||
rpc PreviewWorkspaceMove(WorkspaceMove) returns (WorkspaceMovePreview);
|
||||
}
|
||||
message WorkspaceIdentity { string volume_id = 1; string replica_id = 2; uint64 epoch = 3; }
|
||||
message WorkspaceVolume { string volume_id = 1; }
|
||||
@@ -34,6 +41,32 @@ message WorkspaceGrant {
|
||||
string kind = 5; uint64 old_epoch = 6; uint64 new_epoch = 7;
|
||||
uint64 head_gen = 8; uint64 remote_lsn = 9; bool issued = 10;
|
||||
string old_host = 11; string new_host = 12;
|
||||
// Forced grants only: the lost range stored before the issue (also on a
|
||||
// replay). Absent on a forced grant means the readout is not proven, and
|
||||
// lost_range_error says why; it never means "no loss".
|
||||
WorkspaceLostRange lost_range = 13;
|
||||
string lost_range_error = 14;
|
||||
}
|
||||
// What a forced move abandoned. head_gen 0: no published HEAD (everything the
|
||||
// old holder wrote is lost). head_time_ns is the HEAD entry's filer mtime read
|
||||
// with HEAD at the move (1 s resolution), valid only when head_time_known.
|
||||
// lost_until_ns is master time; the upper bound is a time, not an LSN.
|
||||
message WorkspaceLostRange {
|
||||
string request_id = 1; string volume_id = 2; uint64 new_epoch = 3;
|
||||
string old_replica_id = 4; uint64 old_epoch = 5;
|
||||
uint64 lost_after_lsn = 6; int64 lost_until_ns = 7;
|
||||
uint64 head_gen = 8; int64 head_time_ns = 9; bool head_time_known = 10;
|
||||
}
|
||||
message WorkspaceLostRangeQuery { string volume_id = 1; string request_id = 2; }
|
||||
message WorkspaceLostRanges { repeated WorkspaceLostRange ranges = 1; }
|
||||
// lost_until_ns is when a forced move becomes admissible (0 if the master has
|
||||
// no lease to judge). HEAD is read only when admitted, as for the move.
|
||||
message WorkspaceMovePreview {
|
||||
bool admitted = 1; string reason = 2;
|
||||
int64 lost_until_ns = 3; int64 master_time_ns = 4;
|
||||
bool head_read = 5; string head_error = 6;
|
||||
uint64 head_gen = 7; uint64 head_epoch = 8; string head_holder = 9; uint64 head_remote_lsn = 10;
|
||||
int64 head_time_ns = 11; bool head_time_known = 12;
|
||||
}
|
||||
message WorkspaceStatus {
|
||||
WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2;
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
// Package wsclient is the operator client of the blockmaster workspace
|
||||
// service for FORCED moves: the move itself, its read-only preview, and the
|
||||
// lost-range readout. The sw-block CLI and other operator tools share it so
|
||||
// the confirmation rule and the readout wording are the same everywhere.
|
||||
//
|
||||
// A forced move transfers AUTHORITY only. Starting the volume on the target
|
||||
// is the next step, and nothing here bypasses the master's admission (lease
|
||||
// horizon plus clock skew): there is no bypass.
|
||||
package wsclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// Outcome classifies a call's failure for the operator.
|
||||
type Outcome int
|
||||
|
||||
const (
|
||||
// OutcomeOK: the call succeeded.
|
||||
OutcomeOK Outcome = iota
|
||||
// OutcomeRefusedLocally: refused before any RPC (bad confirmation).
|
||||
OutcomeRefusedLocally
|
||||
// OutcomeRefused: the master answered with a definite refusal; nothing
|
||||
// was moved by this call.
|
||||
OutcomeRefused
|
||||
// OutcomeUnknown: transport error or deadline; the move may or may not
|
||||
// have been issued. Rerun with the SAME request id: the master replays
|
||||
// an issued move's stored grant and never mints a second one.
|
||||
OutcomeUnknown
|
||||
// OutcomeReadoutUnproven: the lost range cannot be read (missing record
|
||||
// or failed checks); it must never be reported as "no loss".
|
||||
OutcomeReadoutUnproven
|
||||
)
|
||||
|
||||
// ErrConfirmation refuses a forced move locally: the confirmation must be
|
||||
// exactly "<volume>@<expected epoch>".
|
||||
var ErrConfirmation = errors.New("forced move confirmation")
|
||||
|
||||
// Error carries a classified failure.
|
||||
type Error struct {
|
||||
Outcome Outcome
|
||||
Op string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Op + ": " + e.Err.Error() }
|
||||
func (e *Error) Unwrap() error { return e.Err }
|
||||
|
||||
// OutcomeOf returns err's outcome (OutcomeOK for nil).
|
||||
func OutcomeOf(err error) Outcome {
|
||||
if err == nil {
|
||||
return OutcomeOK
|
||||
}
|
||||
var e *Error
|
||||
if errors.As(err, &e) {
|
||||
return e.Outcome
|
||||
}
|
||||
return OutcomeUnknown
|
||||
}
|
||||
|
||||
// classify maps a gRPC error: the master's definite answers are refusals,
|
||||
// DataLoss is an unproven readout, anything else leaves the outcome unknown.
|
||||
func classify(op string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.PermissionDenied, codes.Unimplemented:
|
||||
return &Error{Outcome: OutcomeRefused, Op: op, Err: errors.New(status.Convert(err).Message())}
|
||||
case codes.DataLoss:
|
||||
return &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: errors.New(status.Convert(err).Message())}
|
||||
}
|
||||
return &Error{Outcome: OutcomeUnknown, Op: op, Err: err}
|
||||
}
|
||||
|
||||
// ParseConfirmation checks that confirm is exactly "<volume>@<epoch>" for
|
||||
// volume, with a positive decimal epoch, and returns that epoch: it is the
|
||||
// expected epoch the move is sent with (the master refuses it unless it is
|
||||
// the current one).
|
||||
func ParseConfirmation(confirm, volume string) (uint64, error) {
|
||||
if confirm == "" {
|
||||
return 0, fmt.Errorf("%w: --confirm-forced %s@<expected epoch> is required", ErrConfirmation, volume)
|
||||
}
|
||||
at := strings.LastIndexByte(confirm, '@')
|
||||
if at < 0 || confirm[:at] != volume {
|
||||
return 0, fmt.Errorf("%w: %q does not name volume %q as %s@<expected epoch>", ErrConfirmation, confirm, volume, volume)
|
||||
}
|
||||
digits := confirm[at+1:]
|
||||
epoch, err := strconv.ParseUint(digits, 10, 64)
|
||||
if err != nil || epoch == 0 || strconv.FormatUint(epoch, 10) != digits {
|
||||
return 0, fmt.Errorf("%w: %q: the epoch must be a positive decimal number", ErrConfirmation, confirm)
|
||||
}
|
||||
return epoch, nil
|
||||
}
|
||||
|
||||
// ForcedMove names a forced move. TargetHost is the target node's server id.
|
||||
type ForcedMove struct {
|
||||
RequestID, VolumeID string
|
||||
TargetHost, TargetDataAddr, TargetCtrlAddr string
|
||||
// Confirm must be exactly "<VolumeID>@<expected epoch>".
|
||||
Confirm string
|
||||
}
|
||||
|
||||
// Client calls the workspace service.
|
||||
type Client struct {
|
||||
rpc control.WorkspaceServiceClient
|
||||
conn *grpc.ClientConn
|
||||
}
|
||||
|
||||
// New wraps an existing service client.
|
||||
func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc} }
|
||||
|
||||
// Dial connects to the blockmaster gRPC address (plaintext, as the other
|
||||
// operator commands).
|
||||
func Dial(addr string) (*Client, error) {
|
||||
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{rpc: control.NewWorkspaceServiceClient(conn), conn: conn}, nil
|
||||
}
|
||||
|
||||
// Close closes a Dial connection.
|
||||
func (c *Client) Close() error {
|
||||
if c.conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// request checks the confirmation (no RPC on failure), resolves the
|
||||
// holder's logical replica id at the confirmed epoch from QueryWorkspace
|
||||
// (v1 keeps the replica id across moves) and builds the forced request.
|
||||
func (c *Client) request(ctx context.Context, op string, m ForcedMove) (*control.WorkspaceMove, error) {
|
||||
epoch, err := ParseConfirmation(m.Confirm, m.VolumeID)
|
||||
if err != nil {
|
||||
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: err}
|
||||
}
|
||||
if m.RequestID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" {
|
||||
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("a request id, target host and target data/ctrl addresses are required")}
|
||||
}
|
||||
st, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: m.VolumeID})
|
||||
if err != nil {
|
||||
e := classify(op+": read the volume's holder", err)
|
||||
var ce *Error
|
||||
if errors.As(e, &ce) && ce.Outcome == OutcomeUnknown {
|
||||
ce.Err = fmt.Errorf("no move was sent: %w", ce.Err)
|
||||
}
|
||||
return nil, e
|
||||
}
|
||||
replica := holderAt(st, epoch)
|
||||
if replica == "" {
|
||||
cur := "none"
|
||||
if l := st.GetLease(); l != nil {
|
||||
cur = fmt.Sprintf("%s@%d", l.GetReplicaId(), l.GetEpoch())
|
||||
}
|
||||
return nil, &Error{Outcome: OutcomeRefused, Op: op, Err: fmt.Errorf("the master knows no holder of volume %q at epoch %d (current lease: %s); nothing was sent", m.VolumeID, epoch, cur)}
|
||||
}
|
||||
return &control.WorkspaceMove{RequestId: m.RequestID, VolumeId: m.VolumeID, ExpectedReplicaId: replica, ExpectedEpoch: epoch, TargetReplicaId: replica,
|
||||
TargetServerId: m.TargetHost, TargetDataAddr: m.TargetDataAddr, TargetCtrlAddr: m.TargetCtrlAddr, Kind: "forced", Force: true}, nil
|
||||
}
|
||||
|
||||
// holderAt returns the logical replica id that held the volume at epoch:
|
||||
// the current lease, or the journal (an issued move from or to that epoch,
|
||||
// e.g. on a rerun after the move issued).
|
||||
func holderAt(st *control.WorkspaceStatus, epoch uint64) string {
|
||||
if l := st.GetLease(); l != nil && l.GetEpoch() == epoch && l.GetReplicaId() != "" {
|
||||
return l.GetReplicaId()
|
||||
}
|
||||
for _, g := range st.GetMoves() {
|
||||
if g.GetOldEpoch() == epoch && g.GetOldReplicaId() != "" {
|
||||
return g.GetOldReplicaId()
|
||||
}
|
||||
if g.GetIssued() && g.GetNewEpoch() == epoch && g.GetNewReplicaId() != "" {
|
||||
return g.GetNewReplicaId()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ForceMove sends the forced move (kind forced, force true) only when the
|
||||
// confirmation matches. On success the grant is issued; its stored lost
|
||||
// range is grant.LostRange, and when that is absent the error is
|
||||
// OutcomeReadoutUnproven with the grant still returned.
|
||||
func (c *Client) ForceMove(ctx context.Context, m ForcedMove) (*control.WorkspaceGrant, error) {
|
||||
const op = "forced move"
|
||||
q, err := c.request(ctx, op, m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g, err := c.rpc.MoveWorkspace(ctx, q)
|
||||
if err != nil {
|
||||
return nil, classify(op, err)
|
||||
}
|
||||
if err := checkGrant(g, q); err != nil {
|
||||
return g, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)}
|
||||
}
|
||||
if err := checkRange(g.GetLostRange(), g); err != nil {
|
||||
return g, &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: err}
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// checkGrant binds a successful answer to the request that was sent: an
|
||||
// issued forced grant for this request id and volume, from the expected
|
||||
// holder at the expected epoch to the requested target, at a higher epoch.
|
||||
// Anything else leaves the outcome unknown.
|
||||
func checkGrant(g *control.WorkspaceGrant, q *control.WorkspaceMove) error {
|
||||
if !g.GetIssued() || g.GetKind() != "forced" || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() ||
|
||||
g.GetOldReplicaId() != q.GetExpectedReplicaId() || g.GetOldEpoch() != q.GetExpectedEpoch() ||
|
||||
g.GetNewReplicaId() != q.GetTargetReplicaId() || g.GetNewHost() != q.GetTargetServerId() || g.GetNewEpoch() <= g.GetOldEpoch() {
|
||||
return fmt.Errorf("the answer does not match the request (issued=%t kind=%q request=%q volume=%q old=%s@%d new=%s@%d on %q)",
|
||||
g.GetIssued(), g.GetKind(), g.GetRequestId(), g.GetVolumeId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkRange: a forced grant must carry its own stored range, naming the
|
||||
// same move and the same kept HEAD (generation and frontier).
|
||||
func checkRange(r *control.WorkspaceLostRange, g *control.WorkspaceGrant) error {
|
||||
if r == nil {
|
||||
why := g.GetLostRangeError()
|
||||
if why == "" {
|
||||
why = "the master returned no lost range"
|
||||
}
|
||||
return fmt.Errorf("move issued (volume %s epoch %d -> %d) but the lost range is not proven: %s", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), why)
|
||||
}
|
||||
if r.GetRequestId() != g.GetRequestId() || r.GetVolumeId() != g.GetVolumeId() || r.GetNewEpoch() != g.GetNewEpoch() || r.GetOldEpoch() != g.GetOldEpoch() || r.GetOldReplicaId() != g.GetOldReplicaId() {
|
||||
return fmt.Errorf("move issued (volume %s epoch %d -> %d) but its lost range names another move (volume %q request %q epoch %d)", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), r.GetVolumeId(), r.GetRequestId(), r.GetNewEpoch())
|
||||
}
|
||||
if r.GetHeadGen() != g.GetHeadGen() || r.GetLostAfterLsn() != g.GetRemoteLsn() {
|
||||
return fmt.Errorf("move issued (volume %s epoch %d -> %d) but its lost range disagrees with the kept HEAD (range gen %d LSN %d, grant gen %d LSN %d)", g.GetVolumeId(), g.GetOldEpoch(), g.GetNewEpoch(), r.GetHeadGen(), r.GetLostAfterLsn(), g.GetHeadGen(), g.GetRemoteLsn())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PreviewForcedMove asks the master whether the forced move is admitted
|
||||
// now, writing nothing. The confirmation is checked as for the move (the
|
||||
// preview is evaluated at its epoch), but a preview never stands in for it.
|
||||
func (c *Client) PreviewForcedMove(ctx context.Context, m ForcedMove) (*control.WorkspaceMovePreview, error) {
|
||||
const op = "forced move preview"
|
||||
q, err := c.request(ctx, op, m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p, err := c.rpc.PreviewWorkspaceMove(ctx, q)
|
||||
return p, classify(op, err)
|
||||
}
|
||||
|
||||
// previewMove is PreviewForcedMove for an already built request.
|
||||
func (c *Client) previewMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) {
|
||||
p, err := c.rpc.PreviewWorkspaceMove(ctx, q)
|
||||
return p, classify("forced move preview", err)
|
||||
}
|
||||
|
||||
// AdmissibleAt asks the preview for when a refused forced move becomes
|
||||
// admissible; ok is false when the preview cannot tell (admitted already,
|
||||
// no lease, or the preview failed).
|
||||
func (c *Client) AdmissibleAt(ctx context.Context, m ForcedMove) (at time.Time, ok bool) {
|
||||
q, err := c.request(ctx, "forced move preview", m)
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
p, err := c.previewMove(ctx, q)
|
||||
if err != nil || p.GetLostUntilNs() == 0 || p.GetLostUntilNs() <= p.GetMasterTimeNs() {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.Unix(0, p.GetLostUntilNs()), true
|
||||
}
|
||||
|
||||
// LostRanges returns the stored lost ranges of the volume's issued forced
|
||||
// moves in issue order, or requestID's only. A missing or unreadable record
|
||||
// is OutcomeReadoutUnproven.
|
||||
func (c *Client) LostRanges(ctx context.Context, volume, requestID string) ([]*control.WorkspaceLostRange, error) {
|
||||
r, err := c.rpc.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: volume, RequestId: requestID})
|
||||
if err != nil {
|
||||
return nil, classify("lost range", err)
|
||||
}
|
||||
for _, x := range r.GetRanges() {
|
||||
if x.GetVolumeId() != volume || (requestID != "" && x.GetRequestId() != requestID) {
|
||||
return nil, &Error{Outcome: OutcomeReadoutUnproven, Op: "lost range", Err: fmt.Errorf("the answer names another range (volume %q request %q)", x.GetVolumeId(), x.GetRequestId())}
|
||||
}
|
||||
}
|
||||
return r.GetRanges(), nil
|
||||
}
|
||||
|
||||
// HeadTimeClock labels a HEAD time: the filer entry's mtime, which the
|
||||
// host that published the HEAD sets from its own clock.
|
||||
const HeadTimeClock = "(publishing host clock as recorded in the filer, 1 s resolution)"
|
||||
|
||||
// FormatTime prints a master or filer time.
|
||||
func FormatTime(ns int64) string { return time.Unix(0, ns).UTC().Format(time.RFC3339Nano) }
|
||||
|
||||
// Readout is the operator sentence for a stored lost range of volume.
|
||||
func Readout(volume string, r *control.WorkspaceLostRange) string {
|
||||
old := fmt.Sprintf("%s@%d", r.GetOldReplicaId(), r.GetOldEpoch())
|
||||
if r.GetHeadGen() == 0 {
|
||||
return fmt.Sprintf("no remote image exists: everything written by %s is lost.", old)
|
||||
}
|
||||
at := "an unknown time (no filer time was recorded)"
|
||||
if r.GetHeadTimeKnown() {
|
||||
at = FormatTime(r.GetHeadTimeNs()) + " " + HeadTimeClock
|
||||
}
|
||||
return fmt.Sprintf("volume %s restored to the last published image at %s (gen %d, LSN %d): writes with LSN <= %d are preserved; "+
|
||||
"writes acknowledged by %s after that and before %s, master clock, may be lost; the upper bound is a time, not an LSN.",
|
||||
volume, at, r.GetHeadGen(), r.GetLostAfterLsn(), r.GetLostAfterLsn(), old, FormatTime(r.GetLostUntilNs()))
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package wsclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// fakeRPC answers QueryWorkspace and MoveWorkspace and counts every call.
|
||||
type fakeRPC struct {
|
||||
control.WorkspaceServiceClient // nil: other methods panic
|
||||
calls int
|
||||
status *control.WorkspaceStatus
|
||||
moves []*control.WorkspaceMove
|
||||
grant *control.WorkspaceGrant
|
||||
moveErr error
|
||||
}
|
||||
|
||||
func (f *fakeRPC) QueryWorkspace(context.Context, *control.WorkspaceVolume, ...grpc.CallOption) (*control.WorkspaceStatus, error) {
|
||||
f.calls++
|
||||
return f.status, nil
|
||||
}
|
||||
|
||||
func (f *fakeRPC) MoveWorkspace(_ context.Context, q *control.WorkspaceMove, _ ...grpc.CallOption) (*control.WorkspaceGrant, error) {
|
||||
f.calls++
|
||||
f.moves = append(f.moves, q)
|
||||
return f.grant, f.moveErr
|
||||
}
|
||||
|
||||
// INV-WS-FORCED-CONFIRM-001: the confirmation is exactly <volume>@<epoch>.
|
||||
func TestParseConfirmation(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
confirm, volume string
|
||||
epoch uint64
|
||||
}{
|
||||
{"vol@3", "vol", 3},
|
||||
{"a@b@7", "a@b", 7},
|
||||
{"", "vol", 0},
|
||||
{"vol", "vol", 0},
|
||||
{"vol@", "vol", 0},
|
||||
{"other@3", "vol", 0},
|
||||
{"vol@0", "vol", 0},
|
||||
{"vol@03", "vol", 0},
|
||||
{"vol@+3", "vol", 0},
|
||||
{"vol@-3", "vol", 0},
|
||||
{"vol@3 ", "vol", 0},
|
||||
{" vol@3", "vol", 0},
|
||||
{"VOL@3", "vol", 0},
|
||||
} {
|
||||
got, err := ParseConfirmation(tc.confirm, tc.volume)
|
||||
if got != tc.epoch || (err == nil) != (tc.epoch != 0) || (err != nil && !errors.Is(err, ErrConfirmation)) {
|
||||
t.Errorf("ParseConfirmation(%q, %q) = %d, %v; want %d", tc.confirm, tc.volume, got, err, tc.epoch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var testMove = ForcedMove{RequestID: "req-1", VolumeID: "vol", TargetHost: "node-b", TargetDataAddr: "10.0.0.2:1", TargetCtrlAddr: "10.0.0.2:2", Confirm: "vol@3"}
|
||||
|
||||
// INV-WS-FORCED-CONFIRM-001: force:true is sent only with a matching
|
||||
// confirmation, and then always with kind forced and the confirmed epoch.
|
||||
func TestForceMoveSendsForceOnlyWithTheConfirmation(t *testing.T) {
|
||||
for _, bad := range []string{"", "vol@x", "other@3", "vol@0"} {
|
||||
f := &fakeRPC{}
|
||||
m := testMove
|
||||
m.Confirm = bad
|
||||
if _, err := New(f).ForceMove(context.Background(), m); OutcomeOf(err) != OutcomeRefusedLocally || f.calls != 0 {
|
||||
t.Fatalf("confirmation %q: %v after %d RPCs; want a local refusal and none", bad, err, f.calls)
|
||||
}
|
||||
}
|
||||
f := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}, moveErr: status.Error(codes.FailedPrecondition, "not yet")}
|
||||
if _, err := New(f).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeRefused {
|
||||
t.Fatalf("master refusal: %v", err)
|
||||
}
|
||||
q := f.moves[0]
|
||||
if len(f.moves) != 1 || q.Kind != "forced" || !q.Force || q.ExpectedEpoch != 3 || q.ExpectedReplicaId != "r1" || q.TargetReplicaId != "r1" || q.RequestId != "req-1" || q.TargetServerId != "node-b" {
|
||||
t.Fatalf("sent %+v", f.moves)
|
||||
}
|
||||
}
|
||||
|
||||
// The holder's replica id at the confirmed epoch comes from the lease, or
|
||||
// on a rerun after the issue from the journal; an epoch the master never
|
||||
// had is refused without sending a move.
|
||||
func TestForceMoveResolvesTheHolder(t *testing.T) {
|
||||
rerun := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 4},
|
||||
Moves: []*control.WorkspaceGrant{{RequestId: "req-1", OldReplicaId: "r1", OldEpoch: 3, NewReplicaId: "r1", NewEpoch: 4, Issued: true, Kind: "forced"}}}, moveErr: status.Error(codes.Unavailable, "down")}
|
||||
if _, err := New(rerun).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeUnknown || len(rerun.moves) != 1 || rerun.moves[0].ExpectedReplicaId != "r1" {
|
||||
t.Fatalf("rerun: %v %+v", err, rerun.moves)
|
||||
}
|
||||
stale := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 9}}}
|
||||
if _, err := New(stale).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeRefused || len(stale.moves) != 0 {
|
||||
t.Fatalf("stale epoch: %v, %d moves sent", err, len(stale.moves))
|
||||
}
|
||||
}
|
||||
|
||||
// goodGrant is the issued forced grant for testMove with its own range.
|
||||
func goodGrant() *control.WorkspaceGrant {
|
||||
return &control.WorkspaceGrant{RequestId: "req-1", VolumeId: "vol", Kind: "forced", Issued: true, OldReplicaId: "r1", OldEpoch: 3, NewReplicaId: "r1", NewEpoch: 4,
|
||||
OldHost: "node-a", NewHost: "node-b", HeadGen: 9, RemoteLsn: 42,
|
||||
LostRange: &control.WorkspaceLostRange{RequestId: "req-1", VolumeId: "vol", NewEpoch: 4, OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: 1, HeadGen: 9}}
|
||||
}
|
||||
|
||||
func holderAt3() *control.WorkspaceStatus {
|
||||
return &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 3}}
|
||||
}
|
||||
|
||||
// A forced grant without its own stored range is issued but unproven.
|
||||
func TestForceMoveGrantWithoutRangeIsUnproven(t *testing.T) {
|
||||
g := goodGrant()
|
||||
if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); err != nil {
|
||||
t.Fatalf("own range: %v", err)
|
||||
}
|
||||
g.LostRange = nil
|
||||
got, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove)
|
||||
if OutcomeOf(err) != OutcomeReadoutUnproven || got != g {
|
||||
t.Fatalf("no range: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The answer is bound to the request: each identity field of the grant
|
||||
// corrupted on its own leaves the outcome unknown; each identity or
|
||||
// frontier field of the range corrupted on its own leaves the readout
|
||||
// unproven. Neither ever yields a successful readout.
|
||||
func TestForceMoveBindsGrantAndRange(t *testing.T) {
|
||||
grantFaults := map[string]func(*control.WorkspaceGrant){
|
||||
"not issued": func(g *control.WorkspaceGrant) { g.Issued = false },
|
||||
"kind": func(g *control.WorkspaceGrant) { g.Kind = "clean" },
|
||||
"request": func(g *control.WorkspaceGrant) { g.RequestId = "req-2" },
|
||||
"volume": func(g *control.WorkspaceGrant) { g.VolumeId = "vol2" },
|
||||
"old replica": func(g *control.WorkspaceGrant) { g.OldReplicaId = "r2" },
|
||||
"old epoch": func(g *control.WorkspaceGrant) { g.OldEpoch = 2 },
|
||||
"new replica": func(g *control.WorkspaceGrant) { g.NewReplicaId = "r2" },
|
||||
"target host": func(g *control.WorkspaceGrant) { g.NewHost = "node-c" },
|
||||
"epoch not up": func(g *control.WorkspaceGrant) { g.NewEpoch = 3 },
|
||||
}
|
||||
for name, fault := range grantFaults {
|
||||
g := goodGrant()
|
||||
fault(g)
|
||||
if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeUnknown {
|
||||
t.Errorf("grant %s corrupted: %v; want unknown", name, err)
|
||||
}
|
||||
}
|
||||
rangeFaults := map[string]func(*control.WorkspaceLostRange){
|
||||
"request": func(r *control.WorkspaceLostRange) { r.RequestId = "req-2" },
|
||||
"volume": func(r *control.WorkspaceLostRange) { r.VolumeId = "vol2" },
|
||||
"new epoch": func(r *control.WorkspaceLostRange) { r.NewEpoch = 5 },
|
||||
"old epoch": func(r *control.WorkspaceLostRange) { r.OldEpoch = 2 },
|
||||
"old replica": func(r *control.WorkspaceLostRange) { r.OldReplicaId = "r2" },
|
||||
"head gen": func(r *control.WorkspaceLostRange) { r.HeadGen = 8 },
|
||||
"lost after": func(r *control.WorkspaceLostRange) { r.LostAfterLsn = 41 },
|
||||
}
|
||||
for name, fault := range rangeFaults {
|
||||
g := goodGrant()
|
||||
fault(g.LostRange)
|
||||
if _, err := New(&fakeRPC{status: holderAt3(), grant: g}).ForceMove(context.Background(), testMove); OutcomeOf(err) != OutcomeReadoutUnproven {
|
||||
t.Errorf("range %s corrupted: %v; want unproven", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lostRangeRPC answers QueryWorkspaceLostRange with fixed ranges.
|
||||
type lostRangeRPC struct {
|
||||
control.WorkspaceServiceClient
|
||||
ranges []*control.WorkspaceLostRange
|
||||
}
|
||||
|
||||
func (f *lostRangeRPC) QueryWorkspaceLostRange(context.Context, *control.WorkspaceLostRangeQuery, ...grpc.CallOption) (*control.WorkspaceLostRanges, error) {
|
||||
return &control.WorkspaceLostRanges{Ranges: f.ranges}, nil
|
||||
}
|
||||
|
||||
// A lost-range answer that names another volume or request is unproven.
|
||||
func TestLostRangesBindsTheAnswer(t *testing.T) {
|
||||
r := goodGrant().LostRange
|
||||
if got, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "vol", "req-1"); err != nil || len(got) != 1 {
|
||||
t.Fatalf("matching answer: %v", err)
|
||||
}
|
||||
if _, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "other", ""); OutcomeOf(err) != OutcomeReadoutUnproven {
|
||||
t.Fatalf("another volume: %v", err)
|
||||
}
|
||||
if _, err := New(&lostRangeRPC{ranges: []*control.WorkspaceLostRange{r}}).LostRanges(context.Background(), "vol", "req-9"); OutcomeOf(err) != OutcomeReadoutUnproven {
|
||||
t.Fatalf("another request: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassify(t *testing.T) {
|
||||
for code, want := range map[codes.Code]Outcome{
|
||||
codes.FailedPrecondition: OutcomeRefused, codes.NotFound: OutcomeRefused, codes.DataLoss: OutcomeReadoutUnproven,
|
||||
codes.Unavailable: OutcomeUnknown, codes.DeadlineExceeded: OutcomeUnknown, codes.Canceled: OutcomeUnknown, codes.Internal: OutcomeUnknown,
|
||||
} {
|
||||
if got := OutcomeOf(classify("op", status.Error(code, "x"))); got != want {
|
||||
t.Errorf("%v: %v; want %v", code, got, want)
|
||||
}
|
||||
}
|
||||
if OutcomeOf(classify("op", context.DeadlineExceeded)) != OutcomeUnknown {
|
||||
t.Error("a bare deadline is not unknown")
|
||||
}
|
||||
}
|
||||
|
||||
// INV-WS-LOST-RANGE-READOUT-001: the readout wording (ruling A: HEAD time is
|
||||
// the filer time; the upper bound is master time).
|
||||
func TestReadoutWording(t *testing.T) {
|
||||
r := &control.WorkspaceLostRange{OldReplicaId: "r1", OldEpoch: 3, LostAfterLsn: 42, LostUntilNs: time.Date(2026, 11, 21, 1, 5, 0, 5, time.UTC).UnixNano(),
|
||||
HeadGen: 9, HeadTimeNs: time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC).UnixNano(), HeadTimeKnown: true}
|
||||
want := "volume vol restored to the last published image at 2026-11-21T01:02:03Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " +
|
||||
"writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00.000000005Z, master clock, may be lost; the upper bound is a time, not an LSN."
|
||||
if got := Readout("vol", r); got != want {
|
||||
t.Fatalf("readout\n got %s\nwant %s", got, want)
|
||||
}
|
||||
r.HeadTimeKnown = false
|
||||
want = "volume vol restored to the last published image at an unknown time (no filer time was recorded) (gen 9, LSN 42): writes with LSN <= 42 are preserved; " +
|
||||
"writes acknowledged by r1@3 after that and before 2026-11-21T01:05:00.000000005Z, master clock, may be lost; the upper bound is a time, not an LSN."
|
||||
if got := Readout("vol", r); got != want {
|
||||
t.Fatalf("readout, time unknown\n got %s\nwant %s", got, want)
|
||||
}
|
||||
r.HeadGen = 0
|
||||
if got := Readout("vol", r); got != "no remote image exists: everything written by r1@3 is lost." {
|
||||
t.Fatalf("no-HEAD readout: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -121,3 +121,90 @@ func TestChunkStageV3_FourTimesCapConvergesUnderSteadyWrites(t *testing.T) {
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
assertNoIntentsLeft(t, f)
|
||||
}
|
||||
|
||||
// Each of two deadlines interrupts the third upload, after two immutable chunks
|
||||
// completed. The next pass must reuse those chunks rather than restart the set.
|
||||
type deadlineProgressRemote struct {
|
||||
successful map[string][]byte
|
||||
*fakeChunkRemote
|
||||
completed int
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) error {
|
||||
r.calls++
|
||||
if r.completed == 2 {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
err := r.fakeChunkRemote.Put(ctx, key, b)
|
||||
if err == nil {
|
||||
r.completed++
|
||||
if _, exists := r.successful[key]; exists {
|
||||
return errors.New("test: retransmitted unchanged successful key")
|
||||
}
|
||||
if r.successful == nil {
|
||||
r.successful = map[string][]byte{}
|
||||
}
|
||||
r.successful[key] = append([]byte(nil), b...)
|
||||
}
|
||||
return err
|
||||
}
|
||||
func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) {
|
||||
s, f, l, w := precopyLayer(t, 1, 5)
|
||||
l.cfg.COWSpillLimit = ctChunkBytes
|
||||
l.cfg.UploadConcurrency = 1
|
||||
r := &deadlineProgressRemote{fakeChunkRemote: f}
|
||||
l.remote = r
|
||||
base := f.stats().head.Gen
|
||||
previous := 0
|
||||
lastSubmitted := s.NextLSN() - 1
|
||||
expectedImage := w.imageAt(lastSubmitted)
|
||||
var finalHead chunkHead
|
||||
for pass := 0; pass < 3; pass++ {
|
||||
r.completed = 0
|
||||
r.calls = 0
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
result, err := l.Cut(ctx)
|
||||
cancel()
|
||||
if pass < 2 {
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("pass %d did not reach injected deadline: %v", pass, err)
|
||||
}
|
||||
if f.stats().head.Gen != base {
|
||||
t.Fatal("deadline moved HEAD")
|
||||
}
|
||||
l.stMu.Lock()
|
||||
cached := len(l.reusable)
|
||||
l.stMu.Unlock()
|
||||
if cached <= previous {
|
||||
t.Fatalf("pass %d restarted dirty set: cached=%d previous=%d", pass, cached, previous)
|
||||
}
|
||||
previous = cached
|
||||
} else if err != nil || result.Head.Gen != base+1 {
|
||||
t.Fatalf("third pass failed to publish: %+v %v", result, err)
|
||||
} else {
|
||||
finalHead = result.Head
|
||||
}
|
||||
}
|
||||
// Five changed chunks, five successful puts, no retransmission after expiry.
|
||||
if len(r.successful) != 5 {
|
||||
t.Fatalf("successful upload keys=%d want5", len(r.successful))
|
||||
}
|
||||
totalBytes := 0
|
||||
for _, payload := range r.successful {
|
||||
totalBytes += len(payload)
|
||||
}
|
||||
if totalBytes != 5*ctChunkBytes {
|
||||
t.Fatalf("uploaded bytes=%d want%d", totalBytes, 5*ctChunkBytes)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
if finalHead.RemoteLSN != lastSubmitted {
|
||||
t.Fatalf("final frontier=%d want last submitted=%d", finalHead.RemoteLSN, lastSubmitted)
|
||||
}
|
||||
assertImage(t, "final complete submitted image", f.imageOf(t, finalHead), expectedImage)
|
||||
if previous != 4 {
|
||||
t.Fatalf("reusable chunks=%d", previous)
|
||||
}
|
||||
assertNoIntentsLeft(t, f)
|
||||
}
|
||||
@@ -72,8 +72,8 @@ A workspace runs one replica (RF=1). It does not use the replication engine of t
|
||||
| Permanent host loss | the image at the last successful cut (HEAD `RemoteLSN`); writes after it are lost |
|
||||
| Clean move (Detach) | everything written before Detach: guest I/O is stopped, then Detach publishes a final cut before the host releases the volume |
|
||||
|
||||
- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) bounds pre-copy staging work; native COW copies the remainder outside its barrier. It never triggers a cut.
|
||||
- **So the default RPO is unbounded** until the integrator cuts. This is a design choice for workspaces, where a cut at a semantic point is more useful than a timer.
|
||||
- **When cuts happen.** At semantic points chosen by the integrator, on explicit request, and by the periodic timer (default 15m, minimum 5m in the OSS CLI; 0 disables). Periodic cuts update HEAD without creating named snapshots. `--chunk-dirty-threshold` bounds staging work and never triggers a cut.
|
||||
- **Recoverable frontier.** The confirmed remote HEAD is the recovery point after host loss. The default capture interval is 15m; failed or expired attempts retry with bounded backoff and reusable uploads, and do not claim a newly durable recovery point.
|
||||
- Multi-replica workspaces combined with chunk snapshots are not supported.
|
||||
|
||||
## 3. Remote layout
|
||||
@@ -235,6 +235,33 @@ stateDiagram-v2
|
||||
|
||||
The attempt path is never removed, so a late create can never land after a delete.
|
||||
|
||||
### Attached-volume scheduling
|
||||
|
||||
Blockvolume defaults to periodic HEAD capture every 15 minutes (minimum 5
|
||||
minutes, 0 disables) and retention every hour. Named snapshots remain explicit.
|
||||
A five-minute context covers the whole cut; completed immutable uploads survive
|
||||
an expired attempt only under matching version/HEAD generation. Automatic GC is
|
||||
opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog
|
||||
scan cost. Scoped GC changes candidates, not the catalog root domain; each volume
|
||||
has independent persisted mark coverage. CLI catalog mutations also check the
|
||||
single-filer deployment constraint before mutation.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> PendingAttach
|
||||
PendingAttach --> Armed: attached and healthy
|
||||
Armed --> Running: staggered due event
|
||||
Running --> Armed: retention and optional scoped GC settle
|
||||
Running --> Draining: detach, fence, close
|
||||
Armed --> Draining: detach, fence, close
|
||||
Draining --> Closed: cancel and join every worker
|
||||
Draining --> Armed: safe detach abort, same current handle
|
||||
```
|
||||
|
||||
No catch-up queue is accumulated. Retention failure skips GC; incomplete marks
|
||||
and configuration changes do not authorize reclamation. Unknown same-epoch CAS
|
||||
intents remain rooted after restart; elapsed TTL is not a settlement proof.
|
||||
|
||||
## 7. Lease, takeover and host moves
|
||||
|
||||
**Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`).
|
||||
|
||||
@@ -93,10 +93,10 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a
|
||||
| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` |
|
||||
| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` |
|
||||
| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` |
|
||||
| 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 other than the source, 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; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` |
|
||||
| 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 other than the source, 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; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-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 | 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 | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` |
|
||||
| Moved | epoch issued | the move journal record is durable first; 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 | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-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 move journal record is durable first; 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/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` |
|
||||
|
||||
### M3 Replica role and peer state
|
||||
|
||||
@@ -258,6 +258,11 @@ stateDiagram-v2
|
||||
| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
|
||||
| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` |
|
||||
|
||||
Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes;
|
||||
0 explicitly disables); they do not create named snapshots. One five-minute
|
||||
context covers a cut, including uploads. Deadline-aborted uploads remain rooted
|
||||
and reusable only while their chunk version and HEAD generation match.
|
||||
|
||||
### M6 Chunk lifecycle
|
||||
|
||||
HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete).
|
||||
@@ -345,9 +350,19 @@ snapshot lifetime; local persistence does not bypass it.
|
||||
|
||||
`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots.
|
||||
|
||||
### M8. Attached-volume maintenance
|
||||
|
||||
`PendingAttach -> Armed -> Due -> Running -> Armed`; elapsed ticks coalesce.
|
||||
A stable volume phase staggers the one-hour retention schedule. GC is opt-in
|
||||
pending density qualification. Detach/fence/Close cancels and joins before
|
||||
catalog/storage release; only a still-current handle may re-arm after safe abort.
|
||||
A pass has one minute for retention and optional GC; retention failure skips GC.
|
||||
A scoped GC pass traces the whole catalog but mutates only its target volume,
|
||||
with a separate scope/config-bound mark. Incomplete marks carry no coverage.
|
||||
|
||||
## Part B. Invariant ledger
|
||||
|
||||
118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new.
|
||||
126 rows: 107 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 111 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.
|
||||
|
||||
@@ -471,13 +486,17 @@ Notes:
|
||||
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns carries its lost range as stored before the issue (the kept HEAD's remote LSN, LostUntil in master time, the kept HEAD's generation and the HEAD entry's filer mtime read with that HEAD, or "unknown"), also on a replay and after a restart; `QueryWorkspaceLostRange` returns the same stored ranges, all of them in issue order or one by request id, never recomputed. A forced move whose range record is missing or fails its checks (the range checksum or the HEAD-time checksum) makes the readout fail (a grant without a range and with the reason; `DataLoss` from the query; CLI exit 4) and is never reported as no loss. A failure after the issue (e.g. the binding reconciliation) is answered as `Internal` naming the move ISSUED, never as a refusal; the client reports it as an unknown outcome with the same-request-id recovery (never a new request id), and the master's audit log records the issued forced move. An issuing write that may have reached the store but reported an error (memory unissued), and any move on a volume whose workspace persistence is already uncertain, fail with `ErrWorkspaceOutcomeUncertain` and are answered as an unknown outcome (`Internal`, restart then rerun with the same request id), logged as unknown, never as a refusal; admission refusals and failures before the issue stay `FailedPrecondition`. The client accepts a grant only when it matches the request (request id, volume, expected holder and epoch, target replica and host, a higher epoch; else unknown) and its range only when it names the same move and kept HEAD (volume, request id, epochs, old replica, HEAD generation, frontier = remote LSN; else unproven). `PreviewWorkspaceMove` runs the forced admission and writes nothing. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`, `decodeLostRangeHeadTimes`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `PreviewWorkspaceForcedMove`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/authority/authority.go` `applyWithWorkspaceMove`; `core/host/master/workspace_service.go` `MoveWorkspace`, `grantWithLostRange`, `postIssueError`, `issuedRecord`, `logForcedGrant`, `QueryWorkspaceLostRange`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove`, `checkGrant`, `checkRange`, `LostRanges`, `Readout`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange`, `shellCommand` | `TestWorkspaceForcedMoveStoresHeadFilerTime`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeAccumulatesInIssueOrder`, `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected`, `TestWorkspaceForcedMovePreviewWritesNothing` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`); `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven`, `TestForceMoveBindsGrantAndRange`, `TestLostRangesBindsTheAnswer`, `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row7_ReadoutUnproven`, `TestWorkspaceForceMove_Row8_RerunSameRequestID`, `TestWorkspaceForceMoveRecoveryCommandRuns`, `TestWorkspaceForceMoveRejectsAMismatchedAnswer`, `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`); `TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome` (`cmd/sw-block/workspace_postissue_test.go`); `TestWorkspaceForceMoveUncertainIssueWriteIsUnknown` (`cmd/sw-block/workspace_uncertain_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-CONFIRM-001` | The OSS operator client (`sw-block ops workspace force-move`, `wsclient.ForceMove`) sends a move with `force: true` only when `--confirm-forced` is exactly `<volume>@<expected epoch>` (that volume, a positive decimal epoch), and then always as kind forced at that epoch with the operator's request id; anything else is refused before any connection or RPC (exit 2). A confirmation at an epoch the master has no holder for is refused without sending a move. There is no bypass flag, and `--dry-run` is never a confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `ForceMove`, `holderAt`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove` | `TestParseConfirmation`, `TestForceMoveSendsForceOnlyWithTheConfirmation`, `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally`, `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceForceMove_Row3and4_SentAndGranted`, `TestWorkspaceForceMove_Row5_MasterRefusal`, `TestWorkspaceForceMove_Row6_OutcomeUnknown`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE |
|
||||
|
||||
Notes:
|
||||
|
||||
- `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary.
|
||||
- `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits).
|
||||
- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here.
|
||||
- `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models.
|
||||
- `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun).
|
||||
- `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged.
|
||||
|
||||
### B.5 Workspace: the cut pipeline
|
||||
@@ -519,10 +538,13 @@ Notes:
|
||||
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE |
|
||||
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
|
||||
| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE |
|
||||
| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE |
|
||||
| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
|
||||
| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE |
|
||||
| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE |
|
||||
| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB |
|
||||
| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRejectsCopyDeadline` | `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
|
||||
| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE |
|
||||
| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE |
|
||||
| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE |
|
||||
@@ -530,7 +552,6 @@ Notes:
|
||||
|
||||
Notes:
|
||||
|
||||
- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace.
|
||||
|
||||
### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
------------------------- MODULE MaintenanceOwner -------------------------
|
||||
EXTENDS Naturals, TLC
|
||||
CONSTANT AllowOverlap, ReleaseBeforeJoin, AllowStaleRearm
|
||||
VARIABLES state, due, workers, released, owner, current, arms, closing
|
||||
vars == <<state,due,workers,released,owner,current,arms,closing>>
|
||||
Init == /\ state = "pending" /\ due = FALSE /\ workers = 0 /\ released = FALSE
|
||||
/\ owner = 1 /\ current = 1 /\ arms = 0 /\ closing = FALSE
|
||||
Attach == /\ state = "pending" /\ state' = "armed" /\ arms' = arms+1
|
||||
/\ UNCHANGED <<due,workers,released,owner,current,closing>>
|
||||
Tick == /\ state = "armed" /\ due' = TRUE
|
||||
/\ UNCHANGED <<state,workers,released,owner,current,arms,closing>>
|
||||
Start == /\ state = "armed" /\ due /\ (workers = 0 \/ AllowOverlap)
|
||||
/\ workers < 2 /\ workers' = workers+1 /\ due' = FALSE
|
||||
/\ UNCHANGED <<state,released,owner,current,arms,closing>>
|
||||
Finish == /\ workers > 0 /\ workers' = workers-1
|
||||
/\ UNCHANGED <<state,due,released,owner,current,arms,closing>>
|
||||
Stop == /\ state = "armed" /\ state' = "draining" /\ due' = FALSE
|
||||
/\ closing' \in BOOLEAN /\ UNCHANGED <<workers,released,owner,current,arms>>
|
||||
Join == /\ state = "draining" /\ (workers = 0 \/ ReleaseBeforeJoin)
|
||||
/\ state' = IF closing THEN "closed" ELSE "idle"
|
||||
/\ released' = TRUE /\ UNCHANGED <<due,workers,owner,current,arms,closing>>
|
||||
Rearm == /\ state = "idle" /\ arms < 3 /\ (owner = current \/ AllowStaleRearm)
|
||||
/\ state' = "armed" /\ released' = FALSE /\ arms' = arms+1
|
||||
/\ UNCHANGED <<due,workers,owner,current,closing>>
|
||||
ReplaceHandle == /\ state = "idle" /\ workers = 0 /\ current = 1
|
||||
/\ current' = 2
|
||||
/\ UNCHANGED <<state,due,workers,released,owner,arms,closing>>
|
||||
AttachCurrent == /\ state = "idle" /\ workers = 0 /\ owner # current /\ arms < 3
|
||||
/\ owner' = current /\ state' = "armed" /\ released' = FALSE
|
||||
/\ arms' = arms+1 /\ UNCHANGED <<due,workers,current,closing>>
|
||||
Next == Attach \/ Tick \/ Start \/ Finish \/ Stop \/ Join \/ Rearm \/ ReplaceHandle \/ AttachCurrent
|
||||
Spec == Init /\ [][Next]_vars
|
||||
OneOwner == workers <= 1
|
||||
JoinedBeforeRelease == released => workers = 0
|
||||
NoCatchupQueue == due \in BOOLEAN
|
||||
CurrentHandleAtAdmission == workers > 0 => owner = current
|
||||
=============================================================================
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS AllowOverlap = FALSE
|
||||
ReleaseBeforeJoin = TRUE
|
||||
AllowStaleRearm = FALSE
|
||||
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS AllowOverlap = TRUE
|
||||
ReleaseBeforeJoin = FALSE
|
||||
AllowStaleRearm = FALSE
|
||||
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS AllowOverlap = FALSE
|
||||
ReleaseBeforeJoin = FALSE
|
||||
AllowStaleRearm = FALSE
|
||||
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS AllowOverlap = FALSE
|
||||
ReleaseBeforeJoin = FALSE
|
||||
AllowStaleRearm = TRUE
|
||||
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -335,6 +335,53 @@ four negative controls separately remove retirement, the frame join, the
|
||||
readiness guard or ACK progress restoration. This abstracts successful admitted
|
||||
frames and does not prove physical-I/O, authority rollback or timing behavior.
|
||||
|
||||
## Attached-volume maintenance
|
||||
|
||||
`MaintenanceOwner.tla` now includes joined-stop re-arm on the same current
|
||||
handle, and replacement followed by a new attachment. At most three arms and
|
||||
two handles make the graph finite. Local review-fold run 2026-11-21 03:47 UTC,
|
||||
TLC2.19 / Java21 /512MiB, jar SHA256
|
||||
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`:
|
||||
|
||||
```sh
|
||||
java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config MaintenanceOwner_safe.cfg MaintenanceOwner
|
||||
```
|
||||
|
||||
Positive exited0,105generated/54distinct, queue empty, depth12. Negative configs
|
||||
`overlap` exited12 at OneOwner (20/14 depth6), `early_release` at
|
||||
JoinedBeforeRelease (25/14 depth6), and `stale_rearm` at
|
||||
CurrentHandleAtAdmission (50/33 depth8). Unique `-metadir` paths were used.
|
||||
Native tests separately bind replica/epoch/endpoint and current handle/layer,
|
||||
witness cancellation while held, and same-handle stop/join/re-arm. This finite
|
||||
model does not establish physical-I/O cancellation or a fleet scheduling bound.
|
||||
|
||||
`ScopedMaintenanceGC.tla` extends S9's scope correspondence: three keys across
|
||||
two volumes, one foreign-only root, independent local coverage and crash/config
|
||||
invalidation. `ScopedMaintenanceGC_safe.cfg` checks foreign-root preservation,
|
||||
local candidate scope and coverage ownership: 20 generated / 10 distinct states,
|
||||
depth 9, with the same TLC/jar. Its three negative configs narrow
|
||||
the root domain, widen reclamation or import namespace coverage. Native tests
|
||||
exercise the persisted mark records and real catalog root traversal; the finite
|
||||
model abstracts the complete mark and grace, whose timing remains in S9.
|
||||
No 50/200-volume density or metadata-RPC qualification is claimed; automatic GC
|
||||
remains opt-in, while periodic HEAD capture and retention are enabled by the CLI.
|
||||
|
||||
The unchanged S9 timing models were replayed with the same TLC/jar:
|
||||
`cfg/S9_rule_G4.cfg` (`RetentionGCTiming`, D=2/G=4/MD=1/MaxT=10)
|
||||
passed with 26,341 generated / 10,798 distinct states, depth 23;
|
||||
`cfg/S9b_G3_MD1.cfg` (`RetentionGCMulti`, G=3/MD=1/MaxT=12)
|
||||
passed with 11,303 / 5,743, depth 23.
|
||||
|
||||
`cfg/Maintenance_lifecycle.cfg` replays unchanged `ChunkLifecycleFixed` with
|
||||
one snapshot caller/deleter, MaxHostOps=1 and MaxRuns=1, fork/delete/create,
|
||||
lost replies/pending/sweep enabled. Safety invariants and HeadMonotone passed:
|
||||
42,133,769 generated / 7,224,016 distinct states, depth 47 (TLC 2.19, same jar).
|
||||
This config permits terminal stuttering (`CHECK_DEADLOCK FALSE`); it does not
|
||||
prove deadlock freedom. The original `Fix_mix_small` replay stopped with a
|
||||
terminal deadlock at depth 23 after 28,242,446 / 5,592,191 states (callers Done,
|
||||
gc_loop); it is not reported as a completed green run. No protocol guards in
|
||||
ChunkLifecycleFixed were changed.
|
||||
|
||||
`PrecopyFixedAdmission.tla` checks cost admission over five physical rounds.
|
||||
A known estimate fits the 1.2-second allowance, or uses the five-second declared
|
||||
freeze limit when it is at least 90% of the previous comparable known estimate or on the final
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
------------------------ MODULE ScopedMaintenanceGC ------------------------
|
||||
EXTENDS Naturals, FiniteSets, TLC
|
||||
CONSTANTS TraceForeign, LocalSweep, ImportGlobal
|
||||
VARIABLES marks, localPasses, deleted, complete, early
|
||||
vars == <<marks, localPasses, deleted, complete, early>>
|
||||
Keys == {"rooted", "local", "foreign"}
|
||||
Init == /\ marks = 0 /\ localPasses = 0 /\ deleted = {} /\ complete = FALSE /\ early = FALSE
|
||||
\* A foreign-volume intent is the only root of the target's local key.
|
||||
Roots == IF TraceForeign THEN {"rooted"} ELSE {}
|
||||
Start == /\ ~complete /\ complete' = TRUE /\ UNCHANGED <<marks, localPasses, deleted, early>>
|
||||
Finish == /\ complete /\ localPasses < 2
|
||||
/\ LET coverage == IF ImportGlobal THEN 1 ELSE marks
|
||||
scope == IF LocalSweep THEN {"rooted", "local"} ELSE Keys
|
||||
IN /\ deleted' = deleted \cup (IF coverage = 1 THEN scope \ Roots ELSE {})
|
||||
/\ early' = (early \/ (coverage = 1 /\ localPasses = 0))
|
||||
/\ marks' = 1
|
||||
/\ localPasses' = localPasses + 1 /\ complete' = FALSE
|
||||
CrashOrConfigChange == /\ marks' = 0 /\ localPasses' = 0 /\ complete' = FALSE
|
||||
/\ UNCHANGED <<deleted, early>>
|
||||
Next == Start \/ Finish \/ CrashOrConfigChange
|
||||
Spec == Init /\ [][Next]_vars
|
||||
ForeignRootSurvives == "rooted" \notin deleted
|
||||
OwnCoverageOnly == ~early
|
||||
ForeignCandidatesUntouched == "foreign" \notin deleted
|
||||
=============================================================================
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS TraceForeign = TRUE
|
||||
LocalSweep = TRUE
|
||||
ImportGlobal = TRUE
|
||||
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS TraceForeign = FALSE
|
||||
LocalSweep = TRUE
|
||||
ImportGlobal = FALSE
|
||||
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS TraceForeign = TRUE
|
||||
LocalSweep = TRUE
|
||||
ImportGlobal = FALSE
|
||||
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,6 @@
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS TraceForeign = TRUE
|
||||
LocalSweep = FALSE
|
||||
ImportGlobal = FALSE
|
||||
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,20 @@
|
||||
\* Maintenance safety replay: one snapshot caller/deleter, one host operation/run.
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
SnapCallers = {s1}
|
||||
Deleters = {d1}
|
||||
ForkOn = TRUE
|
||||
DelSnapOn = TRUE
|
||||
CreateOn = TRUE
|
||||
MaxHostOps = 1
|
||||
MaxRuns = 1
|
||||
LostReply = TRUE
|
||||
PendingOn = TRUE
|
||||
SweepOn = TRUE
|
||||
defaultInitValue = defaultInitValue
|
||||
SYMMETRY Symm
|
||||
INVARIANT TypeOK GCSafe SnapOnlyExplicitDelete AckedChunksSurvive CommitClean NoPublishAfterCommit NoIdReuse GiveBackReleases
|
||||
PROPERTY HeadMonotone
|
||||
|
||||
\* Bounded terminal states may stutter; safety, not deadlock freedom.
|
||||
CHECK_DEADLOCK FALSE
|
||||
Reference in new issue
Block a user