diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index a0015447bb..249ead1fac 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -86,7 +86,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume-unheld") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -129,6 +129,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsFrontendPublicationExecutor(args[2:], stdout, stderr) case "chunk": return runOpsChunk(args[2:], stdout, stderr) + case "volume-unheld": + return runOpsVolumeUnheld(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -2296,6 +2298,7 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") + fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") } func emptyCLI(value string) string { diff --git a/seaweed-block/cmd/sw-block/volume_unheld.go b/seaweed-block/cmd/sw-block/volume_unheld.go new file mode 100644 index 0000000000..81d2c12d0e --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld.go @@ -0,0 +1,54 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "io" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const volumeUnheldUsage = `usage: sw-block ops volume-unheld --path + +Exit 0 only when no process on THIS host holds the v3 volume file's lock +(the lock every v3 owner holds while its store is open; the kernel releases +it when the owner process exits). Exit 1: held. Exit 2: unknown (missing +file, not a v3 volume, lock error) or bad usage. + +This proof is per host and for local filesystems only. It says nothing about +another host, and nothing on a network or shared mount. It does not prove the +owner process is dead: host cleanup must require BOTH this command's exit 0 +AND the host tooling's own check that the recorded owner process is gone. + +The probe holds the lock only for an instant and reserves nothing: it does not +keep a new owner out after it returns, and an owner opening the volume at that +instant is refused. Run it only when the owner is believed gone. +` + +// runOpsVolumeUnheld is `sw-block ops volume-unheld`. +func runOpsVolumeUnheld(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops volume-unheld", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, volumeUnheldUsage) } + path := fs.String("path", "", "the volume file") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if *path == "" || fs.NArg() != 0 { + fmt.Fprint(stderr, volumeUnheldUsage) + return ops.VolumeStatusExitInvalid + } + switch err := storage.ProbeVolumeUnheld(*path); { + case err == nil: + fmt.Fprintf(stdout, "unheld: no process on this host holds %s (local proof only; also check the owner process is gone)\n", *path) + return ops.VolumeStatusExitOK + case errors.Is(err, storage.ErrVolumeHeld): + fmt.Fprintf(stdout, "held: a live process on this host holds %s\n", *path) + return ops.VolumeStatusExitUnhealthy + default: + fmt.Fprintf(stderr, "unknown: %v\n", err) + return ops.VolumeStatusExitInvalid + } +} diff --git a/seaweed-block/cmd/sw-block/volume_unheld_test.go b/seaweed-block/cmd/sw-block/volume_unheld_test.go new file mode 100644 index 0000000000..868f276778 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// `sw-block ops volume-unheld` exits 0 only for an unheld v3 volume: 1 while +// a store holds it, 2 for unknown (missing, not v3) and bad usage. The +// usage states the per-host, local-only limit and the second check. +func TestOpsVolumeUnheldExitCodes(t *testing.T) { + path := filepath.Join(t.TempDir(), "v.bin") + s, err := storage.CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + closed := false + t.Cleanup(func() { + if !closed { + _ = s.Close() + } + }) + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + runIt := func(args ...string) (int, string, string) { + var out, errOut bytes.Buffer + code := run(append([]string{"ops", "volume-unheld"}, args...), &out, &errOut) + return code, out.String(), errOut.String() + } + if code, out, _ := runIt("--path", path); code != 1 || !strings.HasPrefix(out, "held:") { + t.Fatalf("open store: exit %d %q; want 1 held", code, out) + } + closed = true + if err := s.Close(); err != nil { + t.Fatal(err) + } + if code, out, _ := runIt("--path", path); code != 0 || !strings.HasPrefix(out, "unheld:") { + t.Fatalf("closed store: exit %d %q; want 0 unheld", code, out) + } + for name, args := range map[string][]string{ + "missing": {"--path", filepath.Join(t.TempDir(), "missing.bin")}, + "not v3": {"--path", junk}, + "no path": nil, + "extra arg": {"--path", path, "x"}, + } { + if code, out, _ := runIt(args...); code != 2 || strings.HasPrefix(out, "unheld") { + t.Fatalf("%s: exit %d %q; want 2", name, code, out) + } + } + _, _, usage := runIt() + for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH", "reserves nothing", "is refused"} { + if !strings.Contains(usage, want) { + t.Fatalf("usage lacks %q:\n%s", want, usage) + } + } +} diff --git a/seaweed-block/core/storage/volume_unheld.go b/seaweed-block/core/storage/volume_unheld.go new file mode 100644 index 0000000000..b3f9709a9e --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld.go @@ -0,0 +1,56 @@ +package storage + +import ( + "errors" + "fmt" + "os" +) + +// ErrVolumeHeld: a live process on this host holds the volume file's lock. +var ErrVolumeHeld = errors.New("storage: volume held by a live owner on this host") + +// ProbeVolumeUnheld reports whether no process on THIS host holds the v3 +// volume file at path. It takes and releases the exclusive, nonblocking +// advisory lock that every v3 owner holds for as long as its store is open; +// the kernel releases that lock when the owner's process exits. +// +// nil: unheld. ErrVolumeHeld: held. Any other error: unknown (missing file, +// not a v3 volume, the lock call failed); treat it as not proven. +// +// The proof is per host and for local filesystems only: it says nothing +// about a process on another host, and nothing on a network or shared mount, +// where advisory lock semantics vary. It covers the file at path when the +// probe opens it, not a file renamed away earlier. It is not proof the owner +// process is dead; host cleanup must check that separately. The probe holds +// the lock only for an instant and leaves no reservation behind, so it does +// not keep a new owner out; an owner opening the volume in that instant is +// refused with ErrWALStoreLocked: probe only when the owner is believed gone. +func ProbeVolumeUnheld(path string) error { + // One descriptor for both steps, locked first: the answer is about the + // file this descriptor opened, whatever the path names afterwards, and + // on Windows an owner's byte lock would refuse a read made before ours. + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() // closing releases the probe's lock + if hook := testProbeUnheldAfterOpen; hook != nil { + hook() + } + switch err := LockWALStoreFile(f); { + case errors.Is(err, ErrWALStoreLocked): + return ErrVolumeHeld // held, whatever the file is: the safe answer + case err != nil: + return err + } + // Only a v3 owner takes the lock; for any other file a free lock proves + // nothing. + if err := probeWALStoreV3At(f); err != nil { + return fmt.Errorf("storage: %s is not a v3 volume, unheld cannot be proven: %w", path, err) + } + return nil +} + +// testProbeUnheldAfterOpen, test-only, runs in ProbeVolumeUnheld after the +// open, before the lock. +var testProbeUnheldAfterOpen func() diff --git a/seaweed-block/core/storage/volume_unheld_test.go b/seaweed-block/core/storage/volume_unheld_test.go new file mode 100644 index 0000000000..7a23e26b7f --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld_test.go @@ -0,0 +1,180 @@ +package storage + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func createClosedV3Volume(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "v.bin") + s, err := CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + return path +} + +// A closed v3 volume is unheld, and the probe leaves it openable (it +// released its own lock). +func TestProbeVolumeUnheldClosedVolume(t *testing.T) { + path := createClosedV3Volume(t) + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("closed volume: %v; want unheld", err) + } + s, err := OpenWALStore(path) + if err != nil { + t.Fatalf("open after the probe: %v", err) + } + _ = s.Close() +} + +// An open store holds the volume: the probe says held (also from another +// descriptor in the same process), and unheld once the store is closed. +func TestProbeVolumeUnheldOpenStoreIsHeld(t *testing.T) { + path := createClosedV3Volume(t) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { + _ = s.Close() + t.Fatalf("open store: %v; want ErrVolumeHeld", err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("after close: %v; want unheld", err) + } +} + +// Unknown is neither unheld nor held: a missing file and a file that is not +// a v3 volume (its owner would not take the lock). +func TestProbeVolumeUnheldUnknown(t *testing.T) { + missing := filepath.Join(t.TempDir(), "missing.bin") + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + for name, path := range map[string]string{"missing": missing, "not v3": junk} { + if err := ProbeVolumeUnheld(path); err == nil || errors.Is(err, ErrVolumeHeld) { + t.Fatalf("%s: %v; want an unknown (non-nil, not held) result", name, err) + } + } +} + +const unheldHelperEnv = "SWBLOCK_UNHELD_HELPER_PATH" + +// TestProbeVolumeUnheldHelper is the holder process of the test below: it +// opens the store, says so, and waits to be killed. +func TestProbeVolumeUnheldHelper(t *testing.T) { + path := os.Getenv(unheldHelperEnv) + if path == "" { + t.Skip("helper process only") + } + s, err := OpenWALStore(path) + if err != nil { + os.Stdout.WriteString("OPEN-FAILED " + err.Error() + "\n") + os.Exit(3) + } + defer s.Close() + os.Stdout.WriteString("HOLDING\n") + time.Sleep(time.Minute) + os.Exit(4) +} + +// The property cleanup relies on: a volume held by another process is held, +// and becomes unheld when that process dies without closing it (the kernel +// releases the lock). +func TestProbeVolumeUnheldHolderProcessDies(t *testing.T) { + path := createClosedV3Volume(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProbeVolumeUnheldHelper$", "-test.count=1") + cmd.Env = append(os.Environ(), unheldHelperEnv+"="+path) + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + exited := make(chan struct{}) + // Reaped on every path; the cleanup kills the holder and joins its reaper. + go func() { _ = cmd.Wait(); close(exited) }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-exited: + case <-time.After(10 * time.Second): + t.Error("holder process not reaped") + } + }) + ready := make(chan string, 1) + go func() { + buf := make([]byte, 256) + n, _ := out.Read(buf) + ready <- string(buf[:n]) + }() + select { + case line := <-ready: + if !strings.Contains(line, "HOLDING") { + t.Fatalf("holder: %q", line) + } + case <-time.After(30 * time.Second): + t.Fatal("holder never opened the volume") + } + if err := ProbeVolumeUnheld(path); !errors.Is(err, ErrVolumeHeld) { + t.Fatalf("held by a live process: %v; want ErrVolumeHeld", err) + } + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + select { + case <-exited: + case <-time.After(10 * time.Second): + t.Fatal("holder did not exit after kill") + } + if err := ProbeVolumeUnheld(path); err != nil { + t.Fatalf("after the holder died: %v; want unheld", err) + } +} + +// The answer is about the file the probe opened: a held volume whose path is +// replaced (by an unlocked non-v3 file) between the probe's open and its lock +// is still reported held, never unheld. +func TestProbeVolumeUnheldDecidesOnTheOpenedFile(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("an open file cannot be renamed over on Windows") + } + path := createClosedV3Volume(t) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + junk := filepath.Join(filepath.Dir(path), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + replaced := false + testProbeUnheldAfterOpen = func() { + replaced = os.Rename(junk, path) == nil + } + t.Cleanup(func() { testProbeUnheldAfterOpen = nil }) + err = ProbeVolumeUnheld(path) + if !replaced { + t.Fatal("fixture: the path was not replaced after the open") + } + if !errors.Is(err, ErrVolumeHeld) { + t.Fatalf("held volume replaced at its path mid-probe: %v; want ErrVolumeHeld", err) + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index ea7f8d68fd..5b395c8fff 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -165,14 +165,19 @@ func ProbeWALStoreV3(path string) error { return err } defer f.Close() + return probeWALStoreV3At(f) +} + +// probeWALStoreV3At is ProbeWALStoreV3 on an already open file. +func probeWALStoreV3At(r io.ReaderAt) error { a, b := make([]byte, slotSizeV3), make([]byte, slotSizeV3) - if _, err := f.ReadAt(a, 0); err != nil { + if _, err := r.ReadAt(a, 0); err != nil { return err } - if _, err := f.ReadAt(b, slotBOffsetV3); err != nil { + if _, err := r.ReadAt(b, slotBOffsetV3); err != nil { return err } - _, _, err = selectSlotV3(a, b, nil) + _, _, err := selectSlotV3(a, b, nil) return err }