From 5f4e92da5c850726f00d0a4657b234604ee29cf1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 5 Dec 2026 07:05:00 -0800 Subject: [PATCH] seaweed-block: preserve unchanged imports and batch durable publication --- .../cmd/blockmaster/import_unchanged_test.go | 91 +++++ seaweed-block/cmd/blockmaster/main.go | 16 +- .../blockmaster/node_registry_guard_test.go | 4 +- .../cmd/blockmaster/persist_exit_test.go | 112 ++++++ .../master_import_restart_integration_test.go | 111 ++++++ seaweed-block/core/host/master/host.go | 18 + .../core/host/master/lifecycle_failure.go | 25 ++ .../host/master/lifecycle_failure_test.go | 256 +++++++++++++ .../core/lifecycle/import_recovery_test.go | 239 ++++++++++++ .../core/lifecycle/import_step_sync_test.go | 181 +++++++++ .../core/lifecycle/import_syncfs_test.go | 360 ++++++++++++++++++ .../core/lifecycle/layout_identity_test.go | 7 + .../core/lifecycle/layout_redraw_test.go | 9 +- .../lifecycle/node_import_freshness_test.go | 60 +++ .../core/lifecycle/node_inventory.go | 123 +++++- .../core/lifecycle/placement_intent.go | 138 +++++-- .../core/lifecycle/placement_snapshot_test.go | 1 + .../lifecycle/placement_unchanged_test.go | 60 +++ seaweed-block/core/lifecycle/record_file.go | 207 +++++++++- .../core/lifecycle/record_syncfs_linux.go | 39 ++ .../core/lifecycle/record_syncfs_other.go | 12 + .../core/lifecycle/remove_retry_test.go | 85 +++++ seaweed-block/core/lifecycle/store.go | 49 ++- .../core/lifecycle/store_parent_sync_test.go | 4 +- .../core/lifecycle/volume_recovery_test.go | 111 ++++++ seaweed-block/docs/design/invariants.md | 41 +- seaweed-block/docs/operations-manual.md | 8 + seaweed-block/docs/time-bounds.tsv | 1 + 28 files changed, 2293 insertions(+), 75 deletions(-) create mode 100644 seaweed-block/cmd/blockmaster/import_unchanged_test.go create mode 100644 seaweed-block/cmd/blockmaster/persist_exit_test.go create mode 100644 seaweed-block/cmd/blockvolume/master_import_restart_integration_test.go create mode 100644 seaweed-block/core/host/master/lifecycle_failure.go create mode 100644 seaweed-block/core/host/master/lifecycle_failure_test.go create mode 100644 seaweed-block/core/lifecycle/import_recovery_test.go create mode 100644 seaweed-block/core/lifecycle/import_step_sync_test.go create mode 100644 seaweed-block/core/lifecycle/import_syncfs_test.go create mode 100644 seaweed-block/core/lifecycle/node_import_freshness_test.go create mode 100644 seaweed-block/core/lifecycle/placement_unchanged_test.go create mode 100644 seaweed-block/core/lifecycle/record_syncfs_linux.go create mode 100644 seaweed-block/core/lifecycle/record_syncfs_other.go create mode 100644 seaweed-block/core/lifecycle/remove_retry_test.go create mode 100644 seaweed-block/core/lifecycle/volume_recovery_test.go diff --git a/seaweed-block/cmd/blockmaster/import_unchanged_test.go b/seaweed-block/cmd/blockmaster/import_unchanged_test.go new file mode 100644 index 0000000000..8a0f95bd8f --- /dev/null +++ b/seaweed-block/cmd/blockmaster/import_unchanged_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +// Re-importing the same declarative spec must preserve the durable records, +// including the registration observation time. This checks replacement, not +// just equal JSON: an identical rewrite still pays the durability barriers. +func TestUnchangedSpecRestartKeepsAll999ImportRecords(t *testing.T) { + const count = 999 + authorityDir, lifecycleDir := t.TempDir(), t.TempDir() + open := func() *master.Host { + t.Helper() + h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir}) + if err != nil { + t.Fatal(err) + } + return h + } + closeHost := func(h *master.Host) { + t.Helper() + h.Start() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := h.Close(ctx); err != nil { + t.Fatal(err) + } + } + nodes := make([]lifecycle.NodeRegistration, count) + intents := make([]lifecycle.PlacementIntent, count) + for i := range nodes { + id := fmt.Sprintf("n%04d", i) + nodes[i] = lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"} + intents[i] = lifecycle.PlacementIntent{VolumeID: fmt.Sprintf("v%04d", i), DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: id, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}} + } + importSpec := func(h *master.Host) { + t.Helper() + if err := importLifecycleNodeInventory(h, nodes); err != nil { + t.Fatal(err) + } + if err := importLifecyclePlacementIntents(h, intents); err != nil { + t.Fatal(err) + } + } + h := open() + importSpec(h) + closeHost(h) + before := make(map[string]os.FileInfo, 2*count) + for _, kind := range []string{"nodes", "placements"} { + entries, err := os.ReadDir(filepath.Join(lifecycleDir, kind)) + if err != nil { + t.Fatal(err) + } + if len(entries) != count { + t.Fatalf("%s records=%d, want %d", kind, len(entries), count) + } + for _, entry := range entries { + path := filepath.Join(lifecycleDir, kind, entry.Name()) + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + before[path] = info + } + } + h = open() + importSpec(h) + closeHost(h) + rewritten := map[string]int{} + for path, info := range before { + after, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(info, after) || !info.ModTime().Equal(after.ModTime()) { + rewritten[filepath.Base(filepath.Dir(path))]++ + } + } + if rewritten["nodes"] != 0 || rewritten["placements"] != 0 { + t.Fatalf("unchanged restart replaced records: nodes=%d placements=%d; want zero", rewritten["nodes"], rewritten["placements"]) + } +} diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index b73a2e6987..ca4476d024 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -274,6 +274,7 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents") } cfg := master.Config{ + FailStopLifecycleWrites: true, EphemeralLauncherState: (f.launcherManifestDir != "" || f.launcherKubernetesApply) && f.launcherStateHostPath == "", AuthorityStoreDir: f.authorityStore, LifecycleStoreDir: f.lifecycleStore, @@ -334,6 +335,7 @@ func run(f flags) int { cfg.WorkspaceRPC = true cfg.WorkspaceHeadReader = reader } + fmt.Fprintf(os.Stderr, "blockmaster: lifecycle import durability: %s\n", lifecycle.ImportDurabilityMode()) h, err = master.New(cfg) if err != nil { fmt.Fprintln(os.Stderr, "blockmaster:", err) @@ -478,10 +480,8 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra if stores == nil { return fmt.Errorf("lifecycle node import requires --lifecycle-store") } - for _, node := range nodes { - if _, err := stores.Nodes.RegisterNode(node); err != nil { - return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err) - } + if err := stores.Nodes.ImportNodes(nodes); err != nil { + return fmt.Errorf("import lifecycle nodes: %w", err) } return nil } @@ -510,6 +510,7 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme if stores == nil { return fmt.Errorf("lifecycle placement import requires --lifecycle-store") } + plans := make([]lifecycle.PlacementPlan, 0, len(intents)) for _, intent := range intents { if stores.Deletions.Reserved(intent.VolumeID) { continue // never placed again (see importLifecycleVolumes) @@ -528,9 +529,10 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme Source: slot.Source, }) } - if _, err := stores.Placements.ApplyPlan(plan); err != nil { - return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err) - } + plans = append(plans, plan) + } + if err := stores.Placements.ImportPlans(plans); err != nil { + return fmt.Errorf("import lifecycle placement seeds: %w", err) } return nil } diff --git a/seaweed-block/cmd/blockmaster/node_registry_guard_test.go b/seaweed-block/cmd/blockmaster/node_registry_guard_test.go index 77b785079e..b4f0c3bd05 100644 --- a/seaweed-block/cmd/blockmaster/node_registry_guard_test.go +++ b/seaweed-block/cmd/blockmaster/node_registry_guard_test.go @@ -56,7 +56,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) { if !ok { return true } - if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "ImportNodes" || sel.Sel.Name == "RemoveNode") { sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name) } return true @@ -68,7 +68,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) { t.Fatal(err) } sort.Strings(sites) - want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"} + want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.ImportNodes", "core/host/master/format_gate.go:RetireHost.RemoveNode"} if strings.Join(sites, ",") != strings.Join(want, ",") { t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want) } diff --git a/seaweed-block/cmd/blockmaster/persist_exit_test.go b/seaweed-block/cmd/blockmaster/persist_exit_test.go new file mode 100644 index 0000000000..fa719b63f9 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/persist_exit_test.go @@ -0,0 +1,112 @@ +//go:build linux + +package main + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) { + root := t.TempDir() + nodeDir := filepath.Join(root, "lifecycle", "nodes") + store, err := lifecycle.OpenNodeInventoryStore(nodeDir) + if err != nil { + t.Fatal(err) + } + old := lifecycle.NodeRegistration{ServerID: "kept", Addr: "127.0.0.1:19001"} + old, err = store.RegisterNode(old) + if err != nil { + t.Fatal(err) + } + // A real rename failure, even as root; the preceding committed record + // stays untouched. Directories are not parsed as JSON records on reload. + block := filepath.Join(nodeDir, "new.json") + if err := os.Mkdir(block, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil { + t.Fatal(err) + } + spec := filepath.Join(root, "spec.yaml") + if err := os.WriteFile(spec, []byte("nodes:\n - server_id: new\n addr: 127.0.0.1:19002\n"), 0600); err != nil { + t.Fatal(err) + } + args := []string{"--listen", "127.0.0.1:0", "--authority-store", filepath.Join(root, "authority"), "--lifecycle-store", filepath.Join(root, "lifecycle"), "--cluster-spec", spec} + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep)) + out, runErr := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != 1 { + t.Fatalf("master did not fail-stop with exit1: %v context=%v\n%s", runErr, ctx.Err(), out) + } + text := string(out) + if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) { + t.Fatalf("missing single persistence ERROR: %s", text) + } + oldRaw, err := json.Marshal(old) + if err != nil { + t.Fatal(err) + } + recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMasterImportPersistenceRecoveryChild$", "-test.timeout=8s") + recovery.Env = append(os.Environ(), "MASTER_RECOVERY_ROOT="+root, "MASTER_RECOVERY_OLD="+string(oldRaw)) + if out, err := recovery.CombinedOutput(); err != nil { + t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out) + } +} + +func TestMasterImportPersistenceRecoveryChild(t *testing.T) { + root := os.Getenv("MASTER_RECOVERY_ROOT") + if root == "" { + t.Skip("bounded recovery subprocess") + } + nodeDir := filepath.Join(root, "lifecycle", "nodes") + var old lifecycle.NodeRegistration + if err := json.Unmarshal([]byte(os.Getenv("MASTER_RECOVERY_OLD")), &old); err != nil { + t.Fatal(err) + } + // A new master must load the complete committed record, not a speculative + // new registration or partial JSON from the failed write. + h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle")}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { + closeCtx, stop := context.WithTimeout(context.Background(), 5*time.Second) + defer stop() + if err := h.Close(closeCtx); err != nil { + t.Error(err) + } + }) + if got, ok := h.Lifecycle().Nodes.GetNodeSnapshot("kept"); !ok || got.ServerID != old.ServerID || got.Addr != old.Addr || !got.SeenAt.Equal(old.SeenAt) { + t.Fatalf("committed record lost on restart: %+v %v", got, ok) + } + if _, ok := h.Lifecycle().Nodes.GetNodeSnapshot("new"); ok { + t.Fatal("failed record appeared on restart") + } + entries, err := os.ReadDir(nodeDir) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") { + raw, err := os.ReadFile(filepath.Join(nodeDir, entry.Name())) + if err != nil || !json.Valid(raw) { + t.Fatalf("partial record %s: %v", entry.Name(), err) + } + } + } +} diff --git a/seaweed-block/cmd/blockvolume/master_import_restart_integration_test.go b/seaweed-block/cmd/blockvolume/master_import_restart_integration_test.go new file mode 100644 index 0000000000..b1cf9c3fee --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_import_restart_integration_test.go @@ -0,0 +1,111 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// A master restart must not replace live holders while rebuilding its +// heartbeat view. Registration time is deliberately older than the window; +// only the new process's received heartbeats make its node evidence fresh. +func TestMasterImportRestartKeepsLiveHoldersAcrossFreshnessWindow(t *testing.T) { + const window = 6 * time.Second + env := startHandoffEnvVolumes(t, 1, []string{"v2"}, "--freshness-window", window.String(), "--lifecycle-product-loop-interval", "100ms") + env.volExtra = append(env.volExtra, "--heartbeat-interval", "250ms") + for id, volume := range map[string]string{"s1": "v1", "n-v2": "v2"} { + host := env.hosts[id] + host.volume, host.replica = volume, "r1" + env.hosts[id] = host + } + first, second := f1Up(t, env, "s1"), f1Up(t, env, "n-v2") + epochs := map[string]uint64{} + for volume, holder := range map[string]*daemon{"v1": first, "v2": second} { + epoch, err := adoptedEpochOf(volume, holder.line("blockvolume: volume "+volume+" adopted as PRIMARY at r1@")) + if err != nil { + t.Fatal(err) + } + epochs[volume] = epoch + } + // Both durable registrations now age beyond freshness while holders keep + // reporting; a restart must not renew these durable observation times. + time.Sleep(window + 100*time.Millisecond) + env.masterProcess.term(t, 10*time.Second) + started := time.Now() + env.masterProcess = env.h.start(t, "blockmaster-import-restarted", env.h.master, env.masterArgs...) + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + client := control.NewClusterEvidenceServiceClient(conn) + fresh := map[string]bool{} + verified := map[string]bool{} + observed := map[string]bool{} + samples := 0 + for time.Since(started) < window { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + status, err := client.GetClusterStatus(ctx, &control.GetClusterStatusRequest{}) + cancel() + if err == nil { + samples++ + for _, node := range status.Nodes { + if at := node.GetLastHeartbeatAt(); at != nil && at.AsTime().After(started) { + fresh[node.GetNodeName()] = true + } + } + for _, volume := range status.Volumes { + if epoch, ok := epochs[volume.VolumeId]; ok && volume.Epoch != 0 { + observed[volume.VolumeId] = true + if volume.Epoch != epoch { + t.Fatalf("%s changed epoch after restart: %d -> %d", volume.VolumeId, epoch, volume.Epoch) + } + } + } + for _, event := range status.Events { + if event.EventType == "placement_verified" { + verified[event.VolumeId] = true + } + } + } + for _, bad := range []string{"primary lost:", "decision=replace("} { + if env.masterProcess.has(bad) { + t.Fatalf("live-holder restart made a loss/replacement decision: %s", bad) + } + } + for id, d := range map[string]*daemon{"s1": first, "n-v2": second} { + select { + case <-d.done: + t.Fatalf("live holder %s exited during master restart: %v", id, d.err) + default: + } + } + time.Sleep(100 * time.Millisecond) + } + if samples == 0 { + t.Fatal("no successful status sample in the freshness window") + } + for _, id := range []string{"s1", "n-v2"} { + if !fresh[id] { + t.Fatalf("live node %s never became fresh after restart", id) + } + } + for id := range epochs { + if !observed[id] { + t.Fatalf("volume %s never showed its authoritative epoch again", id) + } + if !verified[id] { + t.Fatalf("placement %s did not verify again within one window", id) + } + } + for _, id := range []string{"s1", "n-v2"} { + block := pattern("restart-live-io!") + env.writeBlock(t, id, 0, block) + } + t.Logf("master restart: %d status samples, both nodes fresh, both placements verified, no loss/replacement or holder exit within %s", samples, window) +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 407908c61a..095578b3a4 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -121,6 +121,11 @@ type Config struct { // GET /status/workspace-lease on this loopback address. StatusListen string + // FailStopLifecycleWrites exits the process on uncertain lifecycle-store + // persistence. The supervised blockmaster executable enables it; embedders + // that leave it off must reopen a failed store before attempting mutations. + FailStopLifecycleWrites bool + // Logger is used for structured startup and error logging. If // nil, the default log package logger is used. Logger *log.Logger @@ -275,6 +280,10 @@ func New(cfg Config) (*Host, error) { if lg == nil { lg = log.Default() } + var persistenceFailure lifecycle.PersistenceFailureHandler + if cfg.FailStopLifecycleWrites { + persistenceFailure = lifecycleFailStop(lg) + } holder := &publisherHolder{} ctrlCfg := cfg.ControllerConfig @@ -323,9 +332,18 @@ func New(cfg Config) (*Host, error) { // the master's state it reads. lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir) if err != nil { + var failure *lifecycle.RecordPersistenceError + if persistenceFailure != nil && errors.As(err, &failure) { + persistenceFailure(failure) + } _ = boot.Close() return nil, fmt.Errorf("master.New: lifecycle stores: %w", err) } + if lifecycleStores != nil && persistenceFailure != nil { + lifecycleStores.Nodes.SetPersistenceFailureHandler(persistenceFailure) + lifecycleStores.Placements.SetPersistenceFailureHandler(persistenceFailure) + lifecycleStores.Volumes.SetPersistenceFailureHandler(persistenceFailure) + } // A new cluster starts at the current level: with no prior // state in any master store (no authority record reloaded or skipped, no // attestation file, no volume, node, placement or deletion in the diff --git a/seaweed-block/core/host/master/lifecycle_failure.go b/seaweed-block/core/host/master/lifecycle_failure.go new file mode 100644 index 0000000000..4da45848c5 --- /dev/null +++ b/seaweed-block/core/host/master/lifecycle_failure.go @@ -0,0 +1,25 @@ +package master + +import ( + "log" + "os" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func lifecycleFailStop(logger *log.Logger) lifecycle.PersistenceFailureHandler { + var once sync.Once + return func(failure *lifecycle.RecordPersistenceError) { + once.Do(func() { + // Arm termination before touching the logger: its writer or output + // mutex may be blocked. ERROR delivery is best effort in that case. + time.AfterFunc(time.Second, func() { os.Exit(1) }) + logger.Printf("ERROR lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err) + // A graceful close can wait on the writer that discovered the error. + // The supervisor restarts; Open establishes the recovery barriers. + os.Exit(1) + }) + } +} diff --git a/seaweed-block/core/host/master/lifecycle_failure_test.go b/seaweed-block/core/host/master/lifecycle_failure_test.go new file mode 100644 index 0000000000..8f4b23b8ed --- /dev/null +++ b/seaweed-block/core/host/master/lifecycle_failure_test.go @@ -0,0 +1,256 @@ +//go:build linux + +package master + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func TestLifecyclePersistenceFailureStopsTheProcess(t *testing.T) { + for _, kind := range []string{"nodes", "placements", "volumes", "concurrent"} { + t.Run(kind, func(t *testing.T) { + root := t.TempDir() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceExitChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "LIFECYCLE_EXIT_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 { + t.Fatalf("master failed to exit1: %v context=%v\n%s", err, ctx.Err(), out) + } + text := string(out) + record := "new.json" + if kind == "volumes" { + record = "kept.json" + } + if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) { + t.Fatalf("missing single record/store/error line: %s", text) + } + recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceRecoveryChild$", "-test.timeout=8s") + recovery.Env = append(os.Environ(), "LIFECYCLE_RECOVERY_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind) + if out, err := recovery.CombinedOutput(); err != nil { + t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } +} + +func TestLifecyclePersistenceRecoveryChild(t *testing.T) { + root := os.Getenv("LIFECYCLE_RECOVERY_ROOT") + if root == "" { + t.Skip("bounded recovery subprocess") + } + kind := os.Getenv("LIFECYCLE_EXIT_KIND") + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle"), FailStopLifecycleWrites: true}) + if err != nil { + t.Fatal("restart", err) + } + h.Start() + t.Cleanup(func() { + c, stop := context.WithTimeout(context.Background(), 5*time.Second) + defer stop() + if err := h.Close(c); err != nil { + t.Error(err) + } + }) + kinds := []string{kind} + if kind == "concurrent" { + kinds = []string{"nodes", "placements"} + } + for _, part := range kinds { + raw, err := os.ReadFile(filepath.Join(root, "lifecycle", part, "kept.json")) + if err != nil { + t.Fatal(err) + } + want, err := os.ReadFile(filepath.Join(root, part+"-sha256")) + if err != nil || fmt.Sprintf("%x", sha256.Sum256(raw)) != string(want) { + t.Fatalf("restart changed committed %s: %v", part, err) + } + var kept, failed bool + switch part { + case "nodes": + _, kept = h.Lifecycle().Nodes.GetNodeSnapshot("kept") + _, failed = h.Lifecycle().Nodes.GetNodeSnapshot("new") + case "placements": + _, kept = h.Lifecycle().Placements.GetPlacementSnapshot("kept") + _, failed = h.Lifecycle().Placements.GetPlacementSnapshot("new") + case "volumes": + _, kept = h.Lifecycle().Volumes.GetVolumeSnapshot("kept") + _, failed = h.Lifecycle().Volumes.GetVolumeSnapshot("new") + } + if !kept || failed { + t.Fatalf("restart published wrong %s records", part) + } + entries, err := os.ReadDir(filepath.Join(root, "lifecycle", part)) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") { + raw, err := os.ReadFile(filepath.Join(root, "lifecycle", part, entry.Name())) + if err != nil || !json.Valid(raw) { + t.Fatalf("partial record %s: %v", entry.Name(), err) + } + } + } + } +} + +type blockedLifecycleLog struct { + entered chan struct{} + once sync.Once +} + +func (w *blockedLifecycleLog) Write(p []byte) (int, error) { + w.once.Do(func() { close(w.entered) }) + select {} +} + +func TestLifecycleFailStopExitsWithBlockedLogger(t *testing.T) { + for _, mode := range []string{"writer", "held-lock"} { + t.Run(mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecycleBlockedLoggerChild$", "-test.timeout=4s") + cmd.Env = append(os.Environ(), "LIFECYCLE_BLOCKED_LOG="+mode) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 { + t.Fatalf("blocked logger prevented own exit1: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } +} + +func TestLifecycleBlockedLoggerChild(t *testing.T) { + mode := os.Getenv("LIFECYCLE_BLOCKED_LOG") + if mode == "" { + t.Skip("bounded blocked-sink child") + } + w := &blockedLifecycleLog{entered: make(chan struct{})} + logger := log.New(w, "", 0) + if mode == "held-lock" { + go logger.Print("earlier message") + <-w.entered + } + fail := lifecycleFailStop(logger) + go fail(&lifecycle.RecordPersistenceError{Store: "nodes", Record: "v.json", Err: errors.New("fixture")}) + fail(&lifecycle.RecordPersistenceError{Store: "placements", Record: "v.json", Err: errors.New("fixture")}) + os.Exit(91) +} + +func TestLifecyclePersistenceExitChild(t *testing.T) { + root := os.Getenv("LIFECYCLE_EXIT_ROOT") + if root == "" { + t.Skip("bounded fail-stop subprocess") + } + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle"), FailStopLifecycleWrites: true}) + if err != nil { + t.Fatal(err) + } + h.Start() + put := func(kind, id string) error { + switch kind { + case "nodes": + _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"}) + return err + case "placements": + _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}) + return err + default: + _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: id, SizeBytes: 1 << 20, ReplicationFactor: 1}) + return err + } + } + kinds := []string{os.Getenv("LIFECYCLE_EXIT_KIND")} + if kinds[0] == "concurrent" { + kinds = []string{"nodes", "placements"} + } + for _, kind := range kinds { + if err := put(kind, "kept"); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(root, "lifecycle", kind, "kept.json")) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, kind+"-sha256"), []byte(fmt.Sprintf("%x", sha256.Sum256(raw))), 0600); err != nil { + t.Fatal(err) + } + if kind == "volumes" { + continue + } + block := filepath.Join(root, "lifecycle", kind, "new.json") + if err := os.Mkdir(block, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil { + t.Fatal(err) + } + } + var descriptors []*os.File + if kinds[0] == "volumes" { + // Attach has no pre-write record lookup on disk. Exhaust only this child's + // descriptor budget so CreateTemp fails while its committed file stays intact. + var limit syscall.Rlimit + if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { + t.Fatal(err) + } + if limit.Cur > 128 { + limit.Cur = 128 + } + if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { + t.Fatal(err) + } + for { + file, err := os.Open(os.DevNull) + if errors.Is(err, syscall.EMFILE) { + break + } + if err != nil { + t.Fatal(err) + } + descriptors = append(descriptors, file) + } + } + start := make(chan struct{}) + done := make(chan error, len(kinds)) + for _, kind := range kinds { + go func(kind string) { + <-start + if kind == "volumes" { + _, err := h.Lifecycle().Volumes.AttachVolume("kept", "node") + done <- err + return + } + done <- put(kind, "new") + }(kind) + } + close(start) + for range kinds { + if err := <-done; err != nil { + fmt.Fprintln(os.Stderr, "persistence error returned instead of exiting:", err) + os.Exit(91) + } + } + runtime.KeepAlive(descriptors) + fmt.Fprintln(os.Stderr, "failed persistence did not stop master") + os.Exit(92) +} diff --git a/seaweed-block/core/lifecycle/import_recovery_test.go b/seaweed-block/core/lifecycle/import_recovery_test.go new file mode 100644 index 0000000000..d6ab9e29c4 --- /dev/null +++ b/seaweed-block/core/lifecycle/import_recovery_test.go @@ -0,0 +1,239 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +func TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk(t *testing.T) { + for _, kind := range []string{"nodes", "placements"} { + for _, mode := range []string{"reopen-barrier", "single-directory", "batch-directory", "batch-second-file"} { + t.Run(kind+"/"+mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordEqualityRecoveryChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "RECORD_RECOVERY_KIND="+kind, "RECORD_RECOVERY_MODE="+mode) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("recovery control: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } + } +} + +func TestRecordEqualityRecoveryChild(t *testing.T) { + kind := os.Getenv("RECORD_RECOVERY_KIND") + if kind == "" { + t.Skip("isolated recovery hooks") + } + mode := os.Getenv("RECORD_RECOVERY_MODE") + dir := t.TempDir() + fault := errors.New("injected recovery barrier failure") + var cause error = fault + if mode == "syncfs-second-rename" { + cause = os.ErrNotExist + } + useSyncfs := strings.HasPrefix(mode, "syncfs-") + var apply func(bool) error + var view func() any + var reopen func() error + var otherMutations func() []error + var setPolicy func(PersistenceFailureHandler) + var latched func() bool + if kind == "nodes" { + var store *NodeInventoryStore + reopen = func() error { var err error; store, err = OpenNodeInventoryStore(dir); return err } + apply = func(changed bool) error { + nodes := []NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001", SeenAt: time.Unix(1, 0).UTC()}, {ServerID: "b", Addr: "127.0.0.1:19001", SeenAt: time.Unix(1, 0).UTC()}} + if changed { + for i := range nodes { + nodes[i].Addr = "127.0.0.1:19002" + } + } + if mode == "single-directory" { + _, err := store.RegisterNode(nodes[0]) + return err + } + return store.ImportNodes(nodes) + } + view = func() any { return store.ListNodes() } + setPolicy = func(handler PersistenceFailureHandler) { store.SetPersistenceFailureHandler(handler) } + latched = func() bool { return store.writeErr != nil } + otherMutations = func() []error { + _, e := store.RegisterNode(NodeRegistration{ServerID: "c", Addr: "127.0.0.1:19001"}) + return []error{e, store.ImportNodes(nil), store.RemoveNode("a")} + } + } else { + var store *PlacementIntentStore + reopen = func() error { var err error; store, err = OpenPlacementIntentStore(dir); return err } + apply = func(changed bool) error { + plans := make([]PlacementPlan, 2) + for i, id := range []string{"a", "b"} { + plans[i] = PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}} + if changed { + plans[i].Candidates[0].ReplicaID = "r2" + } + } + if mode == "single-directory" { + _, err := store.ApplyPlan(plans[0]) + return err + } + return store.ImportPlans(plans) + } + view = func() any { return store.ListPlacements() } + setPolicy = func(handler PersistenceFailureHandler) { store.SetPersistenceFailureHandler(handler) } + latched = func() bool { return store.writeErr != nil } + otherMutations = func() []error { + _, e := store.ApplyPlan(PlacementPlan{VolumeID: "c", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}) + return []error{e, store.ImportPlans(nil), store.DeletePlacement("a")} + } + } + if err := reopen(); err != nil { + t.Fatal(err) + } + if err := apply(false); err != nil { + t.Fatal(err) + } + old := view() + callbacks := 0 + setPolicy(func(failure *RecordPersistenceError) { + callbacks++ + record := "" + if mode == "single-directory" { + record = "a.json" + } + if mode == "batch-second-file" || mode == "syncfs-second-rename" { + record = "b.json" + } + if !latched() || failure.Store != dir || failure.Record != record || !errors.Is(failure, cause) { + t.Fatalf("incorrect failure-policy context: %+v", failure) + } + }) + if mode == "reopen-barrier" { + called := 0 + durableRecordHooksForTest.Store(&durableRecordHooks{dirSync: func(path string) error { + called++ + if path != dir { + t.Fatal("recovery synced wrong directory") + } + return fault + }}) + defer durableRecordHooksForTest.Store(nil) + if err := reopen(); !errors.Is(err, fault) { + t.Fatalf("loaded records published without a successful recovery barrier: %v calls=%d", err, called) + } + if called != 1 { + t.Fatalf("recovery directory barriers=%d want1", called) + } + durableRecordHooksForTest.Store(nil) + if err := reopen(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(view(), old) { + t.Fatal("recovery barrier changed record contents") + } + return + } + files, filesystemSyncs, renames, directorySyncs, ioCalls := 0, 0, 0, 0, 0 + durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, + crash: func(point string) { + ioCalls++ + if point == "before-rename" { + renames++ + if mode == "syncfs-second-rename" && renames == 2 { + temps, err := filepath.Glob(filepath.Join(dir, "b.json.*.tmp")) + if err != nil || len(temps) != 1 { + t.Fatalf("second rename has no unique staged file: %v %v", temps, err) + } + if err := os.Remove(temps[0]); err != nil { + t.Fatal(err) + } + } + } + }, + fileSync: func(f *os.File) error { + ioCalls++ + files++ + if useSyncfs { + t.Fatal("batch syncfs control fell back to per-file fsync") + } + if mode == "batch-second-file" && files == 2 { + return fault + } + return f.Sync() + }, + fsSync: func(fd *os.File) error { + ioCalls++ + filesystemSyncs++ + if mode == "syncfs-failure" { + return fault + } + return syncRecordFilesystem(fd) + }, + dirSync: func(string) error { ioCalls++; directorySyncs++; return fault }, + }) + defer durableRecordHooksForTest.Store(nil) + if err := apply(true); !errors.Is(err, cause) { + t.Fatalf("fixture did not expose the failed persistence: %v", err) + } + if callbacks != 1 { + t.Fatalf("failure callbacks=%d want1", callbacks) + } + if !reflect.DeepEqual(view(), old) { + t.Fatal("failed write published its records") + } + if useSyncfs { + wantRenames, wantDirs := 0, 0 + if mode == "syncfs-second-rename" { + wantRenames = 2 + } + if mode == "syncfs-directory" { + wantRenames = 2 + wantDirs = 1 + } + if filesystemSyncs != 1 || renames != wantRenames || directorySyncs != wantDirs || files != 0 { + t.Fatalf("failure boundary: syncfs=%d renames=%d dir=%d files=%d", filesystemSyncs, renames, directorySyncs, files) + } + } + beforeRefusals := ioCalls + for _, err := range otherMutations() { + if !errors.Is(err, ErrLifecycleRecoveryRequired) { + t.Fatalf("mutation after uncertainty: %v", err) + } + } + if callbacks != 1 { + t.Fatalf("refused mutation called policy again: %d", callbacks) + } + retryErr := apply(false) + if !errors.Is(retryErr, ErrLifecycleRecoveryRequired) { + t.Fatalf("old-value retry must require recovery: %v", retryErr) + } + if callbacks != 1 || ioCalls != beforeRefusals { + t.Fatalf("poisoned mutation retried I/O/policy: io=%d/%d callbacks=%d", ioCalls, beforeRefusals, callbacks) + } + durableRecordHooksForTest.Store(nil) + if err := reopen(); err != nil { + t.Fatal(err) + } + if useSyncfs && !reflect.DeepEqual(view(), syncfsFailureReopenedView(old, mode)) { + t.Fatalf("reopen did not expose complete records at the injected boundary: got=%+v want=%+v", view(), syncfsFailureReopenedView(old, mode)) + } + if err := apply(false); err != nil { + t.Fatalf("recovered store cannot restore the old value: %v", err) + } + if err := reopen(); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(view(), old) { + t.Fatal("successful post-recovery write did not match disk") + } +} diff --git a/seaweed-block/core/lifecycle/import_step_sync_test.go b/seaweed-block/core/lifecycle/import_step_sync_test.go new file mode 100644 index 0000000000..f6ac096b17 --- /dev/null +++ b/seaweed-block/core/lifecycle/import_step_sync_test.go @@ -0,0 +1,181 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "reflect" + "testing" + "time" +) + +func TestImportStepSyncsChangedFilesThenOneDirectory(t *testing.T) { + for _, kind := range []string{"nodes", "placements"} { + for _, failure := range []string{"none", "file", "second-file", "directory"} { + t.Run(kind+"/"+failure, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportStepSyncChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "IMPORT_STEP_KIND="+kind, "IMPORT_STEP_FAILURE="+failure) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("import control: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } + } +} + +func TestImportStepSyncChild(t *testing.T) { + kind := os.Getenv("IMPORT_STEP_KIND") + if kind == "" { + t.Skip("isolated filesystem hooks") + } + failure := os.Getenv("IMPORT_STEP_FAILURE") + dir := t.TempDir() + var apply func(bool) error + var snapshot func() any + var reopen func() any + if kind == "nodes" { + store, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + nodes := []NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19001"}, {ServerID: "unchanged", Addr: "127.0.0.1:19001"}} + apply = func(change bool) error { + next := append([]NodeRegistration(nil), nodes...) + if change { + next[0].Addr = "127.0.0.1:19002" + next[1].Addr = "127.0.0.1:19002" + } + return store.ImportNodes(next) + } + snapshot = func() any { + var got []NodeRegistration + for _, node := range nodes { + r, _ := store.GetNodeSnapshot(node.ServerID) + got = append(got, r) + } + return got + } + reopen = func() any { + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + store = s + return s.ListNodes() + } + } else { + store, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + plans := make([]PlacementPlan, 3) + for i, id := range []string{"a", "b", "unchanged"} { + plans[i] = PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}} + } + apply = func(change bool) error { + next := make([]PlacementPlan, len(plans)) + copy(next, plans) + for i := range next { + next[i].Candidates = append([]PlacementCandidate(nil), plans[i].Candidates...) + } + if change { + next[0].Candidates[0].ReplicaID = "r2" + next[1].Candidates[0].ReplicaID = "r2" + } + return store.ImportPlans(next) + } + snapshot = func() any { + var got []PlacementIntent + for _, p := range plans { + r, _ := store.GetPlacementSnapshot(p.VolumeID) + got = append(got, r) + } + return got + } + reopen = func() any { + s, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + store = s + return s.ListPlacements() + } + } + if err := apply(false); err != nil { + t.Fatal(err) + } + old := snapshot() + var events []string + fault := errors.New("injected import sync failure") + // Qualify the portable per-file fallback independently of the syncfs path. + useSyncfs := false + durableRecordHooksForTest.Store(&durableRecordHooks{ + batchSyncfs: &useSyncfs, + fileSync: func(file *os.File) error { + events = append(events, "file") + if failure == "file" || failure == "second-file" && len(events) == 2 { + return fault + } + return file.Sync() + }, + dirSync: func(path string) error { + events = append(events, "directory") + if !reflect.DeepEqual(snapshot(), old) { + t.Fatal("step published before its directory barrier") + } + if path != dir { + t.Fatal("wrong import directory barrier") + } + if failure == "directory" { + return fault + } + return syncBindingParent(path) + }, + }) + defer durableRecordHooksForTest.Store(nil) + err := apply(true) + want := []string{"file", "file", "directory"} + if failure == "file" { + want = []string{"file"} + } else if failure == "second-file" { + want = []string{"file", "file"} + } + if !reflect.DeepEqual(events, want) { + t.Fatalf("events %v want %v", events, want) + } + if failure != "none" { + if !errors.Is(err, fault) { + t.Fatalf("sync failure hidden: %v", err) + } + if !reflect.DeepEqual(snapshot(), old) { + t.Fatal("failed step changed the published snapshot") + } + // A failed step requires recovery before any further mutations. + durableRecordHooksForTest.Store(nil) + if err := apply(true); !errors.Is(err, ErrLifecycleRecoveryRequired) { + t.Fatalf("mutation after failed persistence: %v", err) + } + reopen() + if err := apply(true); err != nil { + t.Fatal(err) + } + } else if err != nil { + t.Fatal(err) + } + completed := snapshot() + durableRecordHooksForTest.Store(nil) + if !reflect.DeepEqual(reopen(), completed) { + t.Fatal("completed import did not survive reopen") + } + events = nil + durableRecordHooksForTest.Store(&durableRecordHooks{fileSync: func(*os.File) error { return fmt.Errorf("unchanged file synced") }, dirSync: func(string) error { return fmt.Errorf("unchanged directory synced") }}) + if err := apply(true); err != nil { + t.Fatalf("unchanged step did I/O: %v", err) + } +} diff --git a/seaweed-block/core/lifecycle/import_syncfs_test.go b/seaweed-block/core/lifecycle/import_syncfs_test.go new file mode 100644 index 0000000000..138c214936 --- /dev/null +++ b/seaweed-block/core/lifecycle/import_syncfs_test.go @@ -0,0 +1,360 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "testing" + "time" +) + +func TestImportBatchStagesAllFilesBeforeAnyRename(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportBatchStageChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "IMPORT_BATCH_STAGE_CHILD=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("batch stage control: %v context=%v\n%s", err, ctx.Err(), out) + } +} + +func TestImportBatchStageChild(t *testing.T) { + if os.Getenv("IMPORT_BATCH_STAGE_CHILD") == "" { + t.Skip("isolated filesystem hooks") + } + dir := t.TempDir() + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + checked := false + useSyncfs := true + durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, crash: func(point string) { + if point != "before-rename" || checked { + return + } + checked = true + temps, err := filepath.Glob(filepath.Join(dir, "*.tmp")) + if err != nil { + t.Fatal(err) + } + if len(temps) != 2 { + t.Fatalf("first rename has %d staged files, want 2", len(temps)) + } + }}) + defer durableRecordHooksForTest.Store(nil) + if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil { + t.Fatal(err) + } + if !checked { + t.Fatal("rename boundary not observed") + } +} + +func TestImportSyncfsFailureAndOrdering(t *testing.T) { + for _, kind := range []string{"nodes", "placements"} { + for _, mode := range []string{"success", "failure", "old-kernel"} { + t.Run(kind+"/"+mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportSyncfsChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "IMPORT_SYNCFS_KIND="+kind, "IMPORT_SYNCFS_MODE="+mode) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("syncfs control: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } + } +} + +func TestImportSyncfsChild(t *testing.T) { + kind := os.Getenv("IMPORT_SYNCFS_KIND") + if kind == "" { + t.Skip("isolated filesystem hooks") + } + mode := os.Getenv("IMPORT_SYNCFS_MODE") + dir := t.TempDir() + var apply func() error + var reopen func() + var snapshot func() int + if kind == "nodes" { + var s *NodeInventoryStore + reopen = func() { + var err error + s, err = OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + } + apply = func() error { + return s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}) + } + snapshot = func() int { + n := 0 + for _, id := range []string{"a", "b"} { + if _, ok := s.GetNodeSnapshot(id); ok { + n++ + } + } + return n + } + } else { + var s *PlacementIntentStore + reopen = func() { + var err error + s, err = OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + } + apply = func() error { + return s.ImportPlans([]PlacementPlan{{VolumeID: "a", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}, {VolumeID: "b", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}}) + } + snapshot = func() int { + n := 0 + for _, id := range []string{"a", "b"} { + if _, ok := s.GetPlacementSnapshot(id); ok { + n++ + } + } + return n + } + } + reopen() + useSyncfs := mode != "old-kernel" + fault := errors.New("injected filesystem writeback failure") + var events []string + var failedTemps []string + install := func(fail bool) { + durableRecordHooksForTest.Store(&durableRecordHooks{ + batchSyncfs: &useSyncfs, + crash: func(point string) { + if point == "batch-open" { + temps, _ := filepath.Glob(filepath.Join(dir, "*.tmp")) + if len(temps) != 0 { + t.Fatal("syncfs fd opened after temp writes") + } + events = append(events, "open") + } + if point == "before-rename" { + if useSyncfs && !reflect.DeepEqual(events, []string{"open", "syncfs"}) && !reflect.DeepEqual(events, []string{"open", "syncfs", "rename"}) { + t.Fatalf("rename before syncfs completed: %v", events) + } + events = append(events, "rename") + } + }, + fileSync: func(f *os.File) error { + if useSyncfs { + t.Fatal("syncfs path used per-file fsync") + } + events = append(events, "file") + return f.Sync() + }, + fsSync: func(fd *os.File) error { + if fd.Name() != dir { + t.Fatal("wrong filesystem fd") + } + for _, name := range []string{"a.json", "b.json"} { + if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) { + t.Fatalf("final record visible before syncfs: %s %v", name, err) + } + } + temps, _ := filepath.Glob(filepath.Join(dir, "*.tmp")) + if len(temps) != 2 { + t.Fatalf("staged temps=%v", temps) + } + if snapshot() != 0 { + t.Fatal("published before syncfs") + } + if fail { + failedTemps = temps + events = append(events, "syncfs") + return fault + } + for _, temp := range temps { + for _, old := range failedTemps { + if temp == old { + t.Fatal("reused failed temp") + } + } + } + if err := syncRecordFilesystem(fd); err != nil { + return err + } + events = append(events, "syncfs") + return nil + }, + dirSync: func(path string) error { + if snapshot() != 0 { + t.Fatal("published before directory barrier") + } + events = append(events, "directory") + return syncBindingParent(path) + }, + }) + } + defer durableRecordHooksForTest.Store(nil) + install(mode == "failure") + err := apply() + if mode == "failure" { + if !errors.Is(err, fault) || !reflect.DeepEqual(events, []string{"open", "syncfs"}) { + t.Fatalf("failed syncfs retried/renamed: %v %v", events, err) + } + if snapshot() != 0 { + t.Fatal("failed import published") + } + if err := apply(); !errors.Is(err, ErrLifecycleRecoveryRequired) { + t.Fatalf("failed store admitted retry: %v", err) + } + if !reflect.DeepEqual(events, []string{"open", "syncfs"}) { + t.Fatal("poisoned retry performed I/O") + } + durableRecordHooksForTest.Store(nil) + reopen() + events = nil + install(false) + err = apply() + } + if err != nil { + t.Fatal(err) + } + want := []string{"open", "syncfs", "rename", "rename", "directory"} + if !useSyncfs { + want = []string{"file", "rename", "file", "rename", "directory"} + } + if !reflect.DeepEqual(events, want) { + t.Fatalf("events=%v want=%v", events, want) + } + if snapshot() != 2 { + t.Fatal("successful import not published") + } + durableRecordHooksForTest.Store(nil) + reopen() + if snapshot() != 2 { + t.Fatal("completed import lost on reopen") + } +} + +// Returned-error controls complement the process-crash ordering controls: +// the published view stays old while complete disk records may be old or new. +func TestImportSyncfsReturnedFailurePolicyAndReplay(t *testing.T) { + for _, kind := range []string{"nodes", "placements"} { + for _, mode := range []string{"syncfs-failure", "syncfs-second-rename", "syncfs-directory"} { + t.Run(kind+"/"+mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordEqualityRecoveryChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "RECORD_RECOVERY_KIND="+kind, "RECORD_RECOVERY_MODE="+mode) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("returned syncfs failure control: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } + } +} + +func syncfsFailureReopenedView(old any, mode string) any { + changed := func(id string) bool { + return mode == "syncfs-directory" || (mode == "syncfs-second-rename" && id == "a") + } + switch records := old.(type) { + case []NodeRegistration: + out := make([]NodeRegistration, len(records)) + for i, rec := range records { + out[i] = copyNodeRegistration(rec) + if changed(rec.ServerID) { + out[i].Addr = "127.0.0.1:19002" + } + } + return out + case []PlacementIntent: + out := make([]PlacementIntent, len(records)) + for i, rec := range records { + out[i] = copyPlacementIntent(rec) + if changed(rec.VolumeID) { + out[i].Slots[0].ReplicaID = "r2" + } + } + return out + default: + panic("unexpected fixture records") + } +} + +func TestSyncfsKernelGate(t *testing.T) { + for release, want := range map[string]bool{"5.7.19": false, "5.8.0": true, "6.8.0-azure": true, "4.19.0": false, "unknown": false, "5.x.0": false} { + if got := kernelHasSyncfsErrors(release); got != want { + t.Errorf("%s: got %v want %v", release, got, want) + } + } +} + +func TestImportSyncfsCrashBoundaries(t *testing.T) { + for _, point := range []string{"before-syncfs", "after-syncfs", "after-rename"} { + t.Run(point, func(t *testing.T) { + dir := t.TempDir() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportSyncfsCrashChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "IMPORT_CRASH_DIR="+dir, "IMPORT_CRASH_POINT="+point) + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 86 { + t.Fatalf("crash child: %v context=%v\n%s", err, ctx.Err(), out) + } + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + want := 0 + if point == "after-rename" { + want = 1 + } + if len(s.ListNodes()) != want { + t.Fatalf("reopen records=%v want=%d", s.ListNodes(), want) + } + for _, rec := range s.ListNodes() { + if rec.ServerID != "a" || rec.Addr != "127.0.0.1:19001" { + t.Fatalf("incomplete record: %+v", rec) + } + } + // A malformed final name is refused, never silently admitted; leftover + // unsynced temp names are ignored. This is a process-crash ordering + // control, not a claim to simulate a machine power loss. + if err := os.WriteFile(filepath.Join(dir, "broken.json"), []byte(`{"server_id":`), 0600); err != nil { + t.Fatal(err) + } + if _, err := OpenNodeInventoryStore(dir); err == nil { + t.Fatal("torn JSON accepted") + } + }) + } +} + +func TestImportSyncfsCrashChild(t *testing.T) { + dir := os.Getenv("IMPORT_CRASH_DIR") + if dir == "" { + t.Skip("bounded crash child") + } + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + useSyncfs := true + durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, crash: func(point string) { + if point == os.Getenv("IMPORT_CRASH_POINT") { + os.Exit(86) + } + }}) + if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(s.ListNodes()) + t.Fatalf("crash boundary not reached: %s", raw) +} diff --git a/seaweed-block/core/lifecycle/layout_identity_test.go b/seaweed-block/core/lifecycle/layout_identity_test.go index da9a6fb8e5..1318622b3d 100644 --- a/seaweed-block/core/lifecycle/layout_identity_test.go +++ b/seaweed-block/core/lifecycle/layout_identity_test.go @@ -126,6 +126,13 @@ func TestLifecycleLayoutIdentity(t *testing.T) { t.Fatal(err) } failed = false + if _, err := loaded.CreateVolume(failedSpec); !errors.Is(err, ErrLifecycleRecoveryRequired) { + t.Fatalf("retry before recovery: %v", err) + } + loaded, err = OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } b, err = loaded.CreateVolume(failedSpec) if err != nil || b.Spec.LayoutID != written.Spec.LayoutID { t.Fatalf("unknown put retry changed identity: %v %+v", err, b) diff --git a/seaweed-block/core/lifecycle/layout_redraw_test.go b/seaweed-block/core/lifecycle/layout_redraw_test.go index 96b67b022b..b2a96a3a5c 100644 --- a/seaweed-block/core/lifecycle/layout_redraw_test.go +++ b/seaweed-block/core/lifecycle/layout_redraw_test.go @@ -61,8 +61,15 @@ func TestRedrawPendingLayoutID(t *testing.T) { t.Fatal(e) } fail = false + if _, e := s.CreateVolume(spec); !errors.Is(e, ErrLifecycleRecoveryRequired) { + t.Fatalf("retry before recovery: %v", e) + } + s, e = OpenFileStore(s.dir) + if e != nil { + t.Fatal(e) + } // Exercise the public retry path, including metadata enrichment. It - // must settle disk B before a metadata put could overwrite it with A. + // must preserve recovered disk B before a metadata put could overwrite it with A. retry := spec retry.PVCName, retry.PVName = "claim", "pv" public, retryErr := s.CreateVolume(retry) diff --git a/seaweed-block/core/lifecycle/node_import_freshness_test.go b/seaweed-block/core/lifecycle/node_import_freshness_test.go new file mode 100644 index 0000000000..f4145fd685 --- /dev/null +++ b/seaweed-block/core/lifecycle/node_import_freshness_test.go @@ -0,0 +1,60 @@ +//go:build linux + +package lifecycle + +import ( + "testing" + "time" +) + +func TestUnchangedNodeRestartDoesNotRefreshAStaleObservation(t *testing.T) { + dir := t.TempDir() + now := time.Now().UTC() + oldSeen := now.Add(-2 * time.Hour) + reg := NodeRegistration{ServerID: "node", Addr: "127.0.0.1:19001", SeenAt: oldSeen} + store, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + if _, err := store.RegisterNode(reg); err != nil { + t.Fatal(err) + } + store, err = OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + reg.SeenAt = time.Time{} // cluster-spec registrations have no observation time + if _, err := store.RegisterNode(reg); err != nil { + t.Fatal(err) + } + got, ok := store.GetNodeSnapshot("node") + if !ok { + t.Fatal("node missing after re-import") + } + intent := PlacementIntent{VolumeID: "volume", DesiredRF: 1, Slots: []PlacementSlotIntent{{ServerID: "node", PoolID: "pool", Source: PlacementSourceBlankPool}}} + verified := VerifyPlacementIntent(intent, []NodeRegistration{got}, VerificationConfig{Now: now, FreshnessWindow: time.Hour}) + if verified.Verified || verified.Reason != VerifyReasonStaleObservation { + t.Fatalf("restart laundered a stale node fresh: seen=%s result=%+v", got.SeenAt, verified) + } + if !got.SeenAt.Equal(oldSeen) { + t.Fatalf("observation changed: got %s want %s", got.SeenAt, oldSeen) + } + // An explicit timestamp on otherwise identical declarative input cannot + // impersonate a heartbeat either. + reg.SeenAt = now + if _, err := store.RegisterNode(reg); err != nil { + t.Fatal(err) + } + got, _ = store.GetNodeSnapshot("node") + if !got.SeenAt.Equal(oldSeen) { + t.Fatal("timestamp-only registration refreshed the observation") + } + reopened, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + got, _ = reopened.GetNodeSnapshot("node") + if !got.SeenAt.Equal(oldSeen) { + t.Fatal("reloaded observation did not retain its original time") + } +} diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index 20027f6e09..f94224b340 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -7,6 +7,7 @@ import ( "log" "os" "path/filepath" + "reflect" "sort" "sync" "time" @@ -65,11 +66,13 @@ type NodeRegistration struct { // NodeInventoryStore persists one JSON registration record per server. type NodeInventoryStore struct { - mu sync.Mutex - dir string - records map[string]NodeRegistration - published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) - failWrite func() error // tests: a non-nil error fails the next record write or removal + mu sync.Mutex + dir string + writeErr error // failed persistence requires reopen before another mutation + onPersistenceFailure PersistenceFailureHandler + records map[string]NodeRegistration + published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + failWrite func() error // tests: a non-nil error fails the next record write or removal } // SetPersistHookForTest installs (nil clears) a callback that each later @@ -81,6 +84,14 @@ func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) { s.failWrite = hook } +// SetPersistenceFailureHandler installs the process host policy before serving. +// The callback runs under the writer mutex and must not reenter the store. +func (s *NodeInventoryStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) { + s.mu.Lock() + defer s.mu.Unlock() + s.onPersistenceFailure = handler +} + // OpenNodeInventoryStore opens or creates a node inventory store. func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { if dir == "" { @@ -111,6 +122,11 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) { if err := s.load(); err != nil { return nil, err } + // Loaded names may come from a failed rename/barrier attempt. Establish + // their durability before exposing them or taking an equality shortcut. + if err := syncRecordDirectory(dir); err != nil { + return nil, &RecordPersistenceError{Store: dir, Record: "", Err: err} + } for id, rec := range s.records { s.published.Store(id, copyNodeRegistration(rec)) } @@ -137,24 +153,29 @@ func (s *NodeInventoryStore) HoldWritesForTest() (release func()) { } // RegisterNode records the latest observed inventory for a server. -// Repeating registration replaces observation fields, but still does not -// publish authority or readiness. +// Changed registration replaces observation fields, but still does not +// publish authority or readiness. An unchanged declaration retains SeenAt +// (INV-NODE-REGISTRATION-FRESHNESS-001); only a heartbeat adds fresh evidence. func (s *NodeInventoryStore) RegisterNode(reg NodeRegistration) (NodeRegistration, error) { if err := validateNodeRegistration(reg); err != nil { return NodeRegistration{}, err } s.mu.Lock() defer s.mu.Unlock() - if reg.SeenAt.IsZero() { - reg.SeenAt = time.Now().UTC() + if err := recoveryRequired(s.writeErr); err != nil { + return NodeRegistration{}, err + } + reg, changed := s.registrationLocked(reg) + if !changed { + return copyNodeRegistration(reg), nil } - reg = normalizeNodeRegistration(reg) if err := s.putLocked(reg); err != nil { + latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure) return NodeRegistration{}, err } s.records[reg.ServerID] = reg s.published.Store(reg.ServerID, copyNodeRegistration(reg)) // committed: the file is in place - return reg, nil + return copyNodeRegistration(reg), nil } // RemoveNode deletes one registration record. Missing nodes are a @@ -165,15 +186,18 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error { } s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return err + } if s.failWrite != nil { if err := s.failWrite(); err != nil { return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err) } } - delete(s.records, serverID) if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err) } + delete(s.records, serverID) s.published.Delete(serverID) // committed: the file is gone return nil } @@ -327,3 +351,78 @@ func copyStringMap(in map[string]string) map[string]string { } return out } + +// ImportNodes replays one startup node step. All changed data is durable before +// rename; one directory barrier precedes publication of the changed snapshots. +func (s *NodeInventoryStore) ImportNodes(nodes []NodeRegistration) error { + s.mu.Lock() + defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return err + } + changed := make(map[string]NodeRegistration) + seen := make(map[string]bool) + order := make([]string, 0, len(nodes)) + for _, node := range nodes { + if err := validateNodeRegistration(node); err != nil { + return err + } + reg, differs := s.registrationLocked(node) + if !seen[reg.ServerID] { + order = append(order, reg.ServerID) + seen[reg.ServerID] = true + } + if !differs { + delete(changed, reg.ServerID) + continue + } + changed[reg.ServerID] = reg + } + writes := make([]recordWrite, 0, len(order)) + for _, id := range order { + if _, ok := changed[id]; !ok { + continue + } + if s.failWrite != nil { + if err := s.failWrite(); err != nil { + return err + } + } + raw, err := json.MarshalIndent(changed[id], "", " ") + if err != nil { + return fmt.Errorf("lifecycle: marshal node %s: %w", id, err) + } + writes = append(writes, recordWrite{name: id + ".json", raw: raw}) + } + if err := writeRecordBatchDurably(s.dir, writes); err != nil { + latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure) + return err + } + for _, id := range order { + if _, ok := changed[id]; !ok { + continue + } + reg := changed[id] + s.records[id] = reg + s.published.Store(id, copyNodeRegistration(reg)) + } + return nil +} + +func (s *NodeInventoryStore) registrationLocked(reg NodeRegistration) (NodeRegistration, bool) { + // Retain an independent value: a caller may reuse its pool slices. + reg = copyNodeRegistration(reg) + if old, ok := s.records[reg.ServerID]; ok { + unchanged := reg + unchanged.SeenAt = old.SeenAt + if reflect.DeepEqual(old, unchanged) { + // Declarative replay is not a new observation. Heartbeats supply + // freshness independently of this durable registration. + return copyNodeRegistration(old), false + } + } + if reg.SeenAt.IsZero() { + reg.SeenAt = time.Now().UTC() + } + return reg, true +} diff --git a/seaweed-block/core/lifecycle/placement_intent.go b/seaweed-block/core/lifecycle/placement_intent.go index 69216ae01c..2afe07e9d2 100644 --- a/seaweed-block/core/lifecycle/placement_intent.go +++ b/seaweed-block/core/lifecycle/placement_intent.go @@ -7,6 +7,7 @@ import ( "log" "os" "path/filepath" + "slices" "sort" "sync" ) @@ -36,10 +37,20 @@ type PlacementIntent struct { // PlacementIntentStore persists one placement intent per volume. type PlacementIntentStore struct { - mu sync.Mutex - dir string - records map[string]PlacementIntent - published sync.Map // committed immutable PlacementIntent values; renewal never takes mu + mu sync.Mutex + dir string + writeErr error // failed persistence requires reopen before another mutation + onPersistenceFailure PersistenceFailureHandler + records map[string]PlacementIntent + published sync.Map // committed immutable PlacementIntent values; renewal never takes mu +} + +// SetPersistenceFailureHandler installs the process host policy before serving. +// The callback runs under the writer mutex and must not reenter the store. +func (s *PlacementIntentStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) { + s.mu.Lock() + defer s.mu.Unlock() + s.onPersistenceFailure = handler } // OpenPlacementIntentStore opens or creates a placement intent store. @@ -72,6 +83,11 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { if err := s.load(); err != nil { return nil, err } + // Loaded names may come from a failed rename/barrier attempt. Establish + // their durability before exposing them or taking an equality shortcut. + if err := syncRecordDirectory(dir); err != nil { + return nil, &RecordPersistenceError{Store: dir, Record: "", Err: err} + } for volume, rec := range s.records { s.published.Store(volume, copyPlacementIntent(rec)) } @@ -81,32 +97,21 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) { // ApplyPlan records placement intent from a sufficient plan. Insufficient // plans are rejected rather than persisted as partial authority-shaped state. func (s *PlacementIntentStore) ApplyPlan(plan PlacementPlan) (PlacementIntent, error) { - if !plan.EnoughCandidates() { - return PlacementIntent{}, ErrInsufficientPlacementCandidates - } - intent := PlacementIntent{ - VolumeID: plan.VolumeID, - DesiredRF: plan.DesiredRF, - Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF), - } - for _, candidate := range plan.Candidates[:plan.DesiredRF] { - intent.Slots = append(intent.Slots, PlacementSlotIntent{ - ServerID: candidate.ServerID, - PoolID: candidate.PoolID, - ReplicaID: candidate.ReplicaID, - Source: candidate.Source, - DataAddr: candidate.DataAddr, - CtrlAddr: candidate.CtrlAddr, - ISCSIListenPort: candidate.ISCSIListenPort, - NVMeListenPort: candidate.NVMeListenPort, - }) - } - if err := validatePlacementIntent(intent); err != nil { + intent, err := placementIntentFromPlan(plan) + if err != nil { return PlacementIntent{}, err } s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return PlacementIntent{}, err + } + // Equal input already has a durable record; preserve it on restart. + if old, ok := s.records[intent.VolumeID]; ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) { + return copyPlacementIntent(old), nil + } if err := s.putLocked(intent); err != nil { + latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure) return PlacementIntent{}, err } s.records[intent.VolumeID] = intent @@ -122,6 +127,9 @@ func (s *PlacementIntentStore) DeletePlacement(volumeID string) error { } s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return err + } if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: remove placement intent %s: %w", volumeID, err) } @@ -262,3 +270,83 @@ func copyPlacementIntent(in PlacementIntent) PlacementIntent { out.Slots = append([]PlacementSlotIntent(nil), in.Slots...) return out } + +// ImportPlans replays one startup placement step and publishes only after +// the changed files and their shared directory barrier have completed. +func (s *PlacementIntentStore) ImportPlans(plans []PlacementPlan) error { + s.mu.Lock() + defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return err + } + changed := make(map[string]PlacementIntent) + seen := make(map[string]bool) + order := make([]string, 0, len(plans)) + for _, plan := range plans { + intent, err := placementIntentFromPlan(plan) + if err != nil { + return err + } + old, ok := s.records[intent.VolumeID] + if !seen[intent.VolumeID] { + order = append(order, intent.VolumeID) + seen[intent.VolumeID] = true + } + if ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) { + delete(changed, intent.VolumeID) + continue + } + changed[intent.VolumeID] = intent + } + writes := make([]recordWrite, 0, len(order)) + for _, id := range order { + if _, ok := changed[id]; !ok { + continue + } + raw, err := json.MarshalIndent(changed[id], "", " ") + if err != nil { + return fmt.Errorf("lifecycle: marshal placement intent %s: %w", id, err) + } + writes = append(writes, recordWrite{name: id + ".json", raw: raw}) + } + if err := writeRecordBatchDurably(s.dir, writes); err != nil { + latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure) + return err + } + for _, id := range order { + if _, ok := changed[id]; !ok { + continue + } + intent := changed[id] + s.records[id] = intent + s.published.Store(id, copyPlacementIntent(intent)) + } + return nil +} + +func placementIntentFromPlan(plan PlacementPlan) (PlacementIntent, error) { + if !plan.EnoughCandidates() { + return PlacementIntent{}, ErrInsufficientPlacementCandidates + } + intent := PlacementIntent{ + VolumeID: plan.VolumeID, + DesiredRF: plan.DesiredRF, + Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF), + } + for _, candidate := range plan.Candidates[:plan.DesiredRF] { + intent.Slots = append(intent.Slots, PlacementSlotIntent{ + ServerID: candidate.ServerID, + PoolID: candidate.PoolID, + ReplicaID: candidate.ReplicaID, + Source: candidate.Source, + DataAddr: candidate.DataAddr, + CtrlAddr: candidate.CtrlAddr, + ISCSIListenPort: candidate.ISCSIListenPort, + NVMeListenPort: candidate.NVMeListenPort, + }) + } + if err := validatePlacementIntent(intent); err != nil { + return PlacementIntent{}, err + } + return intent, nil +} diff --git a/seaweed-block/core/lifecycle/placement_snapshot_test.go b/seaweed-block/core/lifecycle/placement_snapshot_test.go index e74baa86aa..4f3dec9b5e 100644 --- a/seaweed-block/core/lifecycle/placement_snapshot_test.go +++ b/seaweed-block/core/lifecycle/placement_snapshot_test.go @@ -135,6 +135,7 @@ func TestPlacementSnapshotFailedCommitStaysCommitted(t *testing.T) { if ok != existed || !reflect.DeepEqual(got, before) { t.Fatal("reopen did not retain the committed placement") } + s = reopened // failed persistence requires reopening before further writes if _, err = s.ApplyPlan(plan); err != nil { t.Fatal("unblocked commit", err) } diff --git a/seaweed-block/core/lifecycle/placement_unchanged_test.go b/seaweed-block/core/lifecycle/placement_unchanged_test.go new file mode 100644 index 0000000000..1e44c407a9 --- /dev/null +++ b/seaweed-block/core/lifecycle/placement_unchanged_test.go @@ -0,0 +1,60 @@ +//go:build linux + +package lifecycle + +import ( + "os" + "path/filepath" + "testing" +) + +func TestPlacementRepeatKeepsRecordAndChangedPlanReplacesIt(t *testing.T) { + dir := t.TempDir() + store, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + plan := PlacementPlan{VolumeID: "volume", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}} + if _, err := store.ApplyPlan(plan); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "volume.json") + original, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + // Reloading must not cause an otherwise equal import to rewrite the file. + store, err = OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + if _, err := store.ApplyPlan(plan); err != nil { + t.Fatal(err) + } + repeated, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(original, repeated) || !original.ModTime().Equal(repeated.ModTime()) { + t.Fatal("equal placement plan rewrote its durable record") + } + plan.Candidates[0].ReplicaID = "r2" + if _, err := store.ApplyPlan(plan); err != nil { + t.Fatal(err) + } + changed, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if os.SameFile(repeated, changed) { + t.Fatal("changed placement did not replace its record") + } + reopened, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + got, ok := reopened.GetPlacementSnapshot("volume") + if !ok || len(got.Slots) != 1 || got.Slots[0].ReplicaID != "r2" { + t.Fatalf("changed plan did not survive reload: %+v", got) + } +} diff --git a/seaweed-block/core/lifecycle/record_file.go b/seaweed-block/core/lifecycle/record_file.go index 04e5b5e772..14718a29f7 100644 --- a/seaweed-block/core/lifecycle/record_file.go +++ b/seaweed-block/core/lifecycle/record_file.go @@ -1,18 +1,58 @@ package lifecycle import ( + "errors" "fmt" "os" "path/filepath" "sync/atomic" ) +// ErrLifecycleRecoveryRequired means a failed persistence operation may have +// changed disk. Reopen the store before making further mutations. +var ErrLifecycleRecoveryRequired = errors.New("lifecycle: store recovery required") + +// RecordPersistenceError identifies the operation whose durable outcome is +// uncertain. A process host can fail-stop rather than remain alive and poisoned. +type RecordPersistenceError struct { + Store string + Record string + Err error +} + +func (e *RecordPersistenceError) Error() string { + return fmt.Sprintf("lifecycle: persist store %q record %q: %v", e.Store, e.Record, e.Err) +} + +func (e *RecordPersistenceError) Unwrap() error { return e.Err } + +// PersistenceFailureHandler is called synchronously after a failed I/O has +// poisoned a store. It must not reenter a store; production exits the process. +type PersistenceFailureHandler func(*RecordPersistenceError) + +func latchPersistenceFailure(err error, prior *error, handler PersistenceFailureHandler) { + *prior = err + var failure *RecordPersistenceError + if handler != nil && errors.As(err, &failure) { + handler(failure) + } +} + +func recoveryRequired(writeErr error) error { + if writeErr == nil { + return nil + } + return fmt.Errorf("%w: %v", ErrLifecycleRecoveryRequired, writeErr) +} + // Hooks are installed only in isolated subprocess tests. Production uses // the real filesystem operations; one helper owns all publication seams. type durableRecordHooks struct { - crash func(string) - fileSync func(*os.File) error - dirSync func(string) error + crash func(string) + fileSync func(*os.File) error + dirSync func(string) error + batchSyncfs *bool + fsSync func(*os.File) error } var durableRecordHooksForTest atomic.Pointer[durableRecordHooks] @@ -20,42 +60,169 @@ var durableRecordHooksForTest atomic.Pointer[durableRecordHooks] // writeRecordDurably implements INV-LIFECYCLE-STORE-DURABLE-001 for puts and // replacements. A post-rename error may leave the new record on disk. func writeRecordDurably(dir, name string, raw []byte) error { + if err := writeRecordBeforeDirectorySync(dir, name, raw); err != nil { + return &RecordPersistenceError{Store: dir, Record: name, Err: err} + } + if err := syncRecordDirectory(dir); err != nil { + return &RecordPersistenceError{Store: dir, Record: name, Err: err} + } + return nil +} + +type recordWrite struct { + name string + raw []byte +} + +// A startup import makes all changed data durable before rename, then shares +// a directory barrier before publication. A failed step leaves complete old/new +// names. Linux >= 5.8 uses one syncfs for staged temps; other systems sync each. +func writeRecordBatchDurably(dir string, records []recordWrite) error { + if len(records) == 0 { + return nil + } + useSyncfs := recordBatchSyncfsSupported + hooks := durableRecordHooksForTest.Load() + if hooks != nil && hooks.batchSyncfs != nil { + useSyncfs = *hooks.batchSyncfs + } + if useSyncfs { + return writeRecordBatchWithSyncfs(dir, records) + } + for _, record := range records { + if err := writeRecordBeforeDirectorySync(dir, record.name, record.raw); err != nil { + return &RecordPersistenceError{Store: dir, Record: record.name, Err: err} + } + } + if err := syncRecordDirectory(dir); err != nil { + return &RecordPersistenceError{Store: dir, Record: "", Err: err} + } + return nil +} + +// ImportDurabilityMode reports the startup-selected batch persistence path. +// Single-record mutations always retain their file and directory fsyncs. +func ImportDurabilityMode() string { + if recordBatchSyncfsSupported { + return "syncfs (Linux >= 5.8)" + } + return "per-file fsync (syncfs writeback error reporting unavailable)" +} + +func writeRecordBatchWithSyncfs(dir string, records []recordWrite) error { + // Opening before any write samples the filesystem's writeback errseq. + fd, err := os.Open(dir) + if err != nil { + return &RecordPersistenceError{Store: dir, Record: "", Err: err} + } + defer fd.Close() + hooks := durableRecordHooksForTest.Load() + if hooks != nil && hooks.crash != nil { + hooks.crash("batch-open") + } + temps := make([]string, 0, len(records)) + defer func() { + for _, temp := range temps { + _ = os.Remove(temp) + } + }() + for _, record := range records { + temp, err := writeRecordTemp(dir, record.name, record.raw, false) + if err != nil { + return &RecordPersistenceError{Store: dir, Record: record.name, Err: err} + } + temps = append(temps, temp) + } + fsSync := syncRecordFilesystem + if hooks != nil && hooks.fsSync != nil { + fsSync = hooks.fsSync + } + // Never retry a failed syncfs: it consumes the writeback error. The caller + // poisons the store; recovery creates fresh temps for any subsequent import. + if hooks != nil && hooks.crash != nil { + hooks.crash("before-syncfs") + } + if err := fsSync(fd); err != nil { + return &RecordPersistenceError{Store: dir, Record: "", Err: fmt.Errorf("lifecycle: sync record filesystem: %w", err)} + } + if hooks != nil && hooks.crash != nil { + hooks.crash("after-syncfs") + } + for i, record := range records { + if hooks != nil && hooks.crash != nil { + hooks.crash("before-rename") + } + if err := os.Rename(temps[i], filepath.Join(dir, record.name)); err != nil { + return &RecordPersistenceError{Store: dir, Record: record.name, Err: err} + } + if hooks != nil && hooks.crash != nil { + hooks.crash("after-rename") + } + } + if err := syncRecordDirectory(dir); err != nil { + return &RecordPersistenceError{Store: dir, Record: "", Err: err} + } + return nil +} + +func writeRecordBeforeDirectorySync(dir, name string, raw []byte) error { + temp, err := writeRecordTemp(dir, name, raw, true) + if err != nil { + return err + } + defer os.Remove(temp) + hooks := durableRecordHooksForTest.Load() + if hooks != nil && hooks.crash != nil { + hooks.crash("before-rename") + } + if err := os.Rename(temp, filepath.Join(dir, name)); err != nil { + return fmt.Errorf("lifecycle: rename record %s: %w", name, err) + } + if hooks != nil && hooks.crash != nil { + hooks.crash("after-rename") + } + return nil +} + +func writeRecordTemp(dir, name string, raw []byte, syncFile bool) (temp string, resultErr error) { f, err := os.CreateTemp(dir, name+".*.tmp") if err != nil { - return fmt.Errorf("lifecycle: temp record %s: %w", name, err) + return "", fmt.Errorf("lifecycle: temp record %s: %w", name, err) } - defer os.Remove(f.Name()) + defer func() { + if resultErr != nil { + _ = os.Remove(f.Name()) + } + }() if _, err := f.Write(raw); err != nil { _ = f.Close() - return fmt.Errorf("lifecycle: write record %s: %w", name, err) + return "", fmt.Errorf("lifecycle: write record %s: %w", name, err) } hooks := durableRecordHooksForTest.Load() fileSync := f.Sync if hooks != nil && hooks.fileSync != nil { fileSync = func() error { return hooks.fileSync(f) } } - if err := fileSync(); err != nil { - _ = f.Close() - return fmt.Errorf("lifecycle: sync record %s: %w", name, err) + if syncFile { + if err := fileSync(); err != nil { + _ = f.Close() + return "", fmt.Errorf("lifecycle: sync record %s: %w", name, err) + } } if err := f.Close(); err != nil { - return fmt.Errorf("lifecycle: close record %s: %w", name, err) - } - if hooks != nil && hooks.crash != nil { - hooks.crash("before-rename") - } - if err := os.Rename(f.Name(), filepath.Join(dir, name)); err != nil { - return fmt.Errorf("lifecycle: rename record %s: %w", name, err) - } - if hooks != nil && hooks.crash != nil { - hooks.crash("after-rename") + return "", fmt.Errorf("lifecycle: close record %s: %w", name, err) } + return f.Name(), nil +} + +func syncRecordDirectory(dir string) error { + hooks := durableRecordHooksForTest.Load() dirSync := syncBindingParent if hooks != nil && hooks.dirSync != nil { dirSync = hooks.dirSync } if err := dirSync(dir); err != nil { - return fmt.Errorf("lifecycle: sync record directory %s: %w", name, err) + return fmt.Errorf("lifecycle: sync record directory %s: %w", dir, err) } return nil } diff --git a/seaweed-block/core/lifecycle/record_syncfs_linux.go b/seaweed-block/core/lifecycle/record_syncfs_linux.go new file mode 100644 index 0000000000..045d53033c --- /dev/null +++ b/seaweed-block/core/lifecycle/record_syncfs_linux.go @@ -0,0 +1,39 @@ +//go:build linux + +package lifecycle + +import ( + "os" + "strconv" + "strings" + + "golang.org/x/sys/unix" +) + +var recordBatchSyncfsSupported = detectRecordSyncfs() + +func detectRecordSyncfs() bool { + var u unix.Utsname + if unix.Uname(&u) != nil { + return false + } + return kernelHasSyncfsErrors(unix.ByteSliceToString(u.Release[:])) +} + +func kernelHasSyncfsErrors(release string) bool { + parts := strings.SplitN(release, ".", 3) + if len(parts) < 2 { + return false + } + major, err := strconv.Atoi(parts[0]) + if err != nil { + return false + } + minor, err := strconv.Atoi(parts[1]) + if err != nil { + return false + } + return major > 5 || major == 5 && minor >= 8 +} + +func syncRecordFilesystem(fd *os.File) error { return unix.Syncfs(int(fd.Fd())) } diff --git a/seaweed-block/core/lifecycle/record_syncfs_other.go b/seaweed-block/core/lifecycle/record_syncfs_other.go new file mode 100644 index 0000000000..c941ad7692 --- /dev/null +++ b/seaweed-block/core/lifecycle/record_syncfs_other.go @@ -0,0 +1,12 @@ +//go:build !linux + +package lifecycle + +import ( + "fmt" + "os" +) + +const recordBatchSyncfsSupported = false + +func syncRecordFilesystem(*os.File) error { return fmt.Errorf("syncfs unavailable on this platform") } diff --git a/seaweed-block/core/lifecycle/remove_retry_test.go b/seaweed-block/core/lifecycle/remove_retry_test.go new file mode 100644 index 0000000000..7dbfea3f07 --- /dev/null +++ b/seaweed-block/core/lifecycle/remove_retry_test.go @@ -0,0 +1,85 @@ +package lifecycle + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFailedRemoveKeepsRecordForRetry(t *testing.T) { + for _, kind := range []string{"node", "placement", "volume"} { + t.Run(kind, func(t *testing.T) { + dir := t.TempDir() + var remove func() error + var present func() bool + switch kind { + case "node": + s, err := OpenNodeInventoryStore(dir) + if err != nil { + t.Fatal(err) + } + if _, err := s.RegisterNode(NodeRegistration{ServerID: "v", Addr: "127.0.0.1:19001"}); err != nil { + t.Fatal(err) + } + remove = func() error { return s.RemoveNode("v") } + present = func() bool { _, a := s.GetNode("v"); _, b := s.GetNodeSnapshot("v"); return a && b } + case "placement": + s, err := OpenPlacementIntentStore(dir) + if err != nil { + t.Fatal(err) + } + if _, err := s.ApplyPlan(PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + remove = func() error { return s.DeletePlacement("v") } + present = func() bool { _, a := s.GetPlacement("v"); _, b := s.GetPlacementSnapshot("v"); return a && b } + case "volume": + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if _, err := s.CreateVolume(VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + remove = func() error { return s.DeleteVolume("v") } + present = func() bool { _, a := s.GetVolume("v"); _, b := s.GetVolumeSnapshot("v"); return a && b } + } + path := filepath.Join(dir, "v.json") + backup := path + ".saved" + if err := os.Rename(path, backup); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + blocker := filepath.Join(path, "blocker") + if err := os.WriteFile(blocker, []byte("fixture"), 0600); err != nil { + t.Fatal(err) + } + if err := remove(); err == nil { + t.Fatal("nonempty-directory removal succeeded") + } + if !present() { + t.Fatal("failed removal hid retry record or snapshot") + } + if err := os.Remove(blocker); err != nil { + t.Fatal(err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Rename(backup, path); err != nil { + t.Fatal(err) + } + if err := remove(); err != nil { + t.Fatalf("later removal retry: %v", err) + } + if present() { + t.Fatal("successful removal left record present") + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("record file survived successful retry: %v", err) + } + }) + } +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 7ea6a7c77f..289b02a86b 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -67,9 +67,11 @@ type VolumeRecord struct { // FileStore persists one JSON record per volume ID. type FileStore struct { - mu sync.Mutex - dir string - records map[string]VolumeRecord + mu sync.Mutex + dir string + writeErr error // a failed put requires reopen before another mutation + onPersistenceFailure PersistenceFailureHandler + records map[string]VolumeRecord // snap mirrors records as an immutable copy, republished at every change // of records, for lock-free renewal-path reads. snap atomic.Pointer[map[string]VolumeRecord] @@ -97,6 +99,14 @@ func (s *FileStore) GetVolumeSnapshot(volumeID string) (VolumeRecord, bool) { return rec, ok } +// SetPersistenceFailureHandler installs the process host policy before serving. +// The callback runs under the writer mutex and must not reenter the store. +func (s *FileStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) { + s.mu.Lock() + defer s.mu.Unlock() + s.onPersistenceFailure = handler +} + // OpenFileStore opens or creates a lifecycle intent store. func OpenFileStore(dir string) (*FileStore, error) { if dir == "" { @@ -127,6 +137,11 @@ func OpenFileStore(dir string) (*FileStore, error) { if err := s.load(); err != nil { return nil, err } + // Visible names can come from a failed directory barrier. Recover their + // durability before publication or an equal create can acknowledge them. + if err := syncRecordDirectory(dir); err != nil { + return nil, &RecordPersistenceError{Store: dir, Record: "", Err: err} + } s.publishLocked() return s, nil } @@ -137,6 +152,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { spec = normalizeVolumeSpec(spec) s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return VolumeRecord{}, err + } if existing, ok := s.records[spec.VolumeID]; ok { if existing.Spec.SourceVolume != spec.SourceVolume || existing.Spec.SourceLayoutID != spec.SourceLayoutID || existing.Spec.SourceSnapshot != spec.SourceSnapshot || existing.Spec.CreateRequestID != spec.CreateRequestID { return VolumeRecord{}, ErrVolumeConflict @@ -221,6 +239,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRecord, error) { s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return VolumeRecord{}, err + } rec, ok := s.records[volumeID] if !ok { return VolumeRecord{}, ErrVolumeNotFound @@ -301,6 +322,9 @@ func (s *FileStore) settlePendingLayoutIDLocked(rec VolumeRecord) (VolumeRecord, func (s *FileStore) MarkStoreReady(volumeID, layoutID string) (VolumeRecord, error) { s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return VolumeRecord{}, err + } rec, ok := s.records[volumeID] if !ok { return VolumeRecord{}, ErrVolumeNotFound @@ -362,11 +386,14 @@ func (s *FileStore) DeleteVolume(volumeID string) error { } s.mu.Lock() defer s.mu.Unlock() - delete(s.records, volumeID) - s.publishLocked() + if err := recoveryRequired(s.writeErr); err != nil { + return err + } if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: remove %s: %w", volumeID, err) } + delete(s.records, volumeID) + s.publishLocked() return nil } @@ -381,6 +408,9 @@ func (s *FileStore) AttachVolume(volumeID, nodeID string) (VolumeRecord, error) } s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return VolumeRecord{}, err + } rec, ok := s.records[volumeID] if !ok { return VolumeRecord{}, ErrVolumeNotFound @@ -405,6 +435,9 @@ func (s *FileStore) DetachVolume(volumeID, nodeID string) (VolumeRecord, error) } s.mu.Lock() defer s.mu.Unlock() + if err := recoveryRequired(s.writeErr); err != nil { + return VolumeRecord{}, err + } rec, ok := s.records[volumeID] if !ok { return VolumeRecord{}, ErrVolumeNotFound @@ -480,7 +513,11 @@ func (s *FileStore) putLocked(rec VolumeRecord) error { if err != nil { return fmt.Errorf("lifecycle: marshal %s: %w", rec.Spec.VolumeID, err) } - return writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw) + err = writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw) + if err != nil { + latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure) + } + return err } func (s *FileStore) path(volumeID string) string { diff --git a/seaweed-block/core/lifecycle/store_parent_sync_test.go b/seaweed-block/core/lifecycle/store_parent_sync_test.go index 9897d3ed98..5ad2aa3df5 100644 --- a/seaweed-block/core/lifecycle/store_parent_sync_test.go +++ b/seaweed-block/core/lifecycle/store_parent_sync_test.go @@ -60,6 +60,8 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { want = append(want, "/"+strings.Join(parts[:n], "/")) } want = append(want, "/") + ancestor := want[len(want)-2] + want = append(want, abs) var calls []string var warnings bytes.Buffer log.SetOutput(&warnings) @@ -68,7 +70,7 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) { fault := &os.PathError{Op: "open", Path: want[0], Err: os.ErrPermission} syncBindingParent = func(path string) error { calls = append(calls, path) - if shape == "ancestor-permission" && path == want[len(want)-2] { + if shape == "ancestor-permission" && path == ancestor { return &os.PathError{Op: "open", Path: path, Err: os.ErrPermission} } if failFirst { diff --git a/seaweed-block/core/lifecycle/volume_recovery_test.go b/seaweed-block/core/lifecycle/volume_recovery_test.go new file mode 100644 index 0000000000..407db0b2bd --- /dev/null +++ b/seaweed-block/core/lifecycle/volume_recovery_test.go @@ -0,0 +1,111 @@ +//go:build linux + +package lifecycle + +import ( + "context" + "errors" + "os" + "os/exec" + "reflect" + "testing" + "time" +) + +func TestVolumeEqualityRequiresRecovery(t *testing.T) { + for _, mode := range []string{"reopen", "failed-put"} { + t.Run(mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestVolumeRecoveryChild$", "-test.timeout=8s") + cmd.Env = append(os.Environ(), "VOLUME_RECOVERY_MODE="+mode) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("volume recovery: %v context=%v\n%s", err, ctx.Err(), out) + } + }) + } +} + +func TestVolumeRecoveryChild(t *testing.T) { + mode := os.Getenv("VOLUME_RECOVERY_MODE") + if mode == "" { + t.Skip("isolated recovery hooks") + } + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + rec, err := s.CreateVolume(spec) + if err != nil { + t.Fatal(err) + } + if _, err := s.MarkStoreReady("v", rec.Spec.LayoutID); err != nil { + t.Fatal(err) + } + old, _ := s.GetVolumeSnapshot("v") + fault := errors.New("injected volume directory barrier failure") + callbacks := 0 + s.SetPersistenceFailureHandler(func(failure *RecordPersistenceError) { + callbacks++ + if s.writeErr == nil || failure.Store != dir || failure.Record != "v.json" || !errors.Is(failure, fault) { + t.Fatalf("incorrect volume policy context: %+v", failure) + } + }) + durableRecordHooksForTest.Store(&durableRecordHooks{dirSync: func(string) error { return fault }}) + defer durableRecordHooksForTest.Store(nil) + if mode == "reopen" { + if _, err := OpenFileStore(dir); !errors.Is(err, fault) { + t.Fatalf("loaded volume published without recovery barrier: %v", err) + } + durableRecordHooksForTest.Store(nil) + reopened, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if got, _ := reopened.GetVolumeSnapshot("v"); got != old { + t.Fatal("recovery changed volume") + } + return + } + if _, err := s.AttachVolume("v", "node"); !errors.Is(err, fault) { + t.Fatalf("attachment did not fail at barrier: %v", err) + } + if callbacks != 1 { + t.Fatalf("volume failure callbacks=%d want1", callbacks) + } + if got, _ := s.GetVolumeSnapshot("v"); got != old { + t.Fatal("failed attach published") + } + durableRecordHooksForTest.Store(nil) + if _, err := s.CreateVolume(spec); !errors.Is(err, ErrLifecycleRecoveryRequired) { + t.Fatalf("equal create must refuse after possibly-applied failure: %v", err) + } + _, redrawErr := s.RedrawPendingLayoutID("v", rec.Spec.LayoutID) + _, markErr := s.MarkStoreReady("v", rec.Spec.LayoutID) + _, attachErr := s.AttachVolume("v", "node") + _, detachErr := s.DetachVolume("v", "node") + for _, err := range []error{redrawErr, markErr, attachErr, detachErr, s.DeleteVolume("v")} { + if !errors.Is(err, ErrLifecycleRecoveryRequired) { + t.Fatalf("mutation after uncertainty: %v", err) + } + } + reopened, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if got, _ := reopened.GetVolumeSnapshot("v"); got.AttachedTo != "node" { + t.Fatal("fixture did not retain renamed attachment") + } + if _, err := reopened.DetachVolume("v", "node"); err != nil { + t.Fatal(err) + } + again, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + if got, _ := again.GetVolumeSnapshot("v"); !reflect.DeepEqual(got, old) { + t.Fatal("recovered successful detach differs on disk") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 15434dcbc8..a0711ff4cc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -48,6 +48,43 @@ The design is described in three documents, and this one collects their machines Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. +### Lifecycle record I/O and supervised master recovery + +This is the process projection of `INV-LIFECYCLE-STORE-DURABLE-001` and +`INV-LIFECYCLE-FAILSTOP-001`; it adds no record format or authority state. + +```mermaid +stateDiagram-v2 + [*] --> Recovering: supervisor starts master + Recovering --> Ready: complete records loaded, directory barriers succeed + Ready --> Ready: changed files synced, renamed, directory synced + Ready --> Faulted: record put/import persistence failure + Recovering --> Faulted: recovery directory sync failure + Faulted --> Exited: one ERROR attempt, exit 1 within 1 s + Exited --> Recovering: supervisor restarts +``` + +A store latches the error before calling the process policy. A failed step may +leave a mix of complete old and new files; recovery syncs their directory and +startup reconciles the declarative import before serving. Temporary files are +not records. On Linux >= 5.8, startup import opens the records-directory fd +before writing, writes and closes every changed temp, calls one `syncfs`, then +renames all temps and syncs the directory before publication. A failed `syncfs` +is never retried within the step: its writeback error may have been consumed. +Recovery writes fresh temps. Older kernels and other platforms retain per-file +fsync before rename; startup reports the chosen path. The filesystem-wide sync +can also wait for unrelated writeback on that filesystem. +The executable arms a one-second process-exit timer before logging +and exits immediately after the log returns, rather than waiting for graceful +shutdown behind a writer. Embedders without this process policy must reopen a +failed store before any further mutation. Removal errors do not invoke this +policy: the in-memory record and its published snapshot stay present until +removal succeeds, so a later retirement tick can retry. This is covered by +`TestFailedRemoveKeepsRecordForRetry` and +`TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick`. +A successful removal still has the separate directory-sync limitation +recorded below. + ### M1 walstore: open, recover, serve, fault The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). @@ -971,7 +1008,9 @@ Notes: | `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE | | `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestACleanMoveReleasesTheTopologyHome`, `TestTheTopologyHomeHoldsTheVolumeBeforeAMove`, `TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove` (`core/host/master/served_topology_move_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE | +| `INV-NODE-REGISTRATION-FRESHNESS-001` | Replaying a node registration with unchanged non-time fields preserves its stored SeenAt and does not rewrite its record. A restart is not a fresh observation; a live heartbeat supplies freshness independently. | M2 lifecycle registration replay (no authority transition) | `core/lifecycle/node_inventory.go` `RegisterNode`; `core/host/master/observation_snapshot.go` `nodeHeartbeat`; `core/lifecycle/verified_placement.go` `VerifyPlacementIntent` | `TestUnchangedNodeRestartDoesNotRefreshAStaleObservation` (`core/lifecycle/node_import_freshness_test.go`); `TestObservationNodesReportTheNewestHeartbeat` (`core/host/master/observation_heartbeat_test.go`); live-holder process restart qualification pending | Observation time is evidence, not authority; unchanged declaration is not an observation | STUB | +| `INV-LIFECYCLE-STORE-DURABLE-001` | A successful record put/import publishes only after complete replacement records and their directory are durable. Open syncs the records directory before publication. A possibly-applied failure blocks mutations until reopen; recovery reconciles complete old/new records. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `node_inventory.go` `ImportNodes`; `placement_intent.go` `ImportPlans`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`); `TestImportStepSyncsChangedFilesThenOneDirectory` (`core/lifecycle/import_step_sync_test.go`); `TestImportSyncfsFailureAndOrdering`, `TestImportSyncfsReturnedFailurePolicyAndReplay`, `TestImportSyncfsCrashBoundaries`, `TestSyncfsKernelGate` (`core/lifecycle/import_syncfs_test.go`); `TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk` (`core/lifecycle/import_recovery_test.go`); `TestVolumeEqualityRequiresRecovery` (`core/lifecycle/volume_recovery_test.go`) | Lifecycle record publication, including startup-step durability barrier | ACTIVE | +| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits nonzero within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | | `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | | `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners bind only loopback: --listen without mutual TLS, and the runtime HTTP listener always; a non-loopback address, and --insecure-external-bind, are refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_PlaintextControlListenersStayOnLoopback`, `TestManifests_NoPlaintextExternalBlockmasterBind` (`cmd/blockmaster/external_bind_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | diff --git a/seaweed-block/docs/operations-manual.md b/seaweed-block/docs/operations-manual.md index 6156637a3a..02d09fb2b2 100644 --- a/seaweed-block/docs/operations-manual.md +++ b/seaweed-block/docs/operations-manual.md @@ -242,6 +242,14 @@ with its size and home placement. A volume's record comes from the cluster spec: blockmaster reads the cluster spec only when it starts. After editing the spec, run `sudo systemctl restart sw-blockmaster`. Serving volumes keep serving across that restart. +blockmaster must run under systemd or an equivalent restart supervisor. A lifecycle +record write or recovery-directory sync failure attempts one `ERROR` naming the store, +record and error, ending with `exiting so the supervisor restarts from durable state`, +and exits with status 1. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped +`sw-blockmaster.service` has `Restart=on-failure` and `RestartSec=5s`; restart reloads +complete records through the recovery barriers before serving again. + + ## 3. Create and attach a volume 1. **Add the volume to the cluster spec** with its `size_bytes` (edit it as root, as in section 2), and restart diff --git a/seaweed-block/docs/time-bounds.tsv b/seaweed-block/docs/time-bounds.tsv index 55cbde057c..f6bf33e297 100644 --- a/seaweed-block/docs/time-bounds.tsv +++ b/seaweed-block/docs/time-bounds.tsv @@ -201,6 +201,7 @@ core/host/master/host.go New http.Server.ReadHeaderTimeout 1 per-call NONE: no m core/host/master/host.go New http.Server.ReadTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection core/host/master/host.go New http.Server.WriteTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection core/host/master/host.go New http.Server.IdleTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection +core/host/master/lifecycle_failure.go lifecycleFailStop time.AfterFunc 1 availability-contract NONE: process-fault exit projection of INV-LIFECYCLE-FAILSTOP-001, no wire state one-second exit deadline armed before logger; independent of blocked sink core/host/master/probe_round.go roundEvidenceProvider.round time.NewTimer 1 per-call FencingRound.Deliver; FencingRound.Open one probe round's evidence wait core/host/master/services.go services.deleteHolderEvidence context.WithTimeout 1 per-call FormatGate.Report one RPC or request core/host/master/spec_retirement.go Host.reconcileDeletedSpecVolumes context.WithTimeout 1 per-call DeleteRetire.ReadOK one fresh HEAD read after the no-live-lease barrier