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..8d72c84b1f --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld.go @@ -0,0 +1,50 @@ +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. +` + +// 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..bedae3cef7 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld_test.go @@ -0,0 +1,56 @@ +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) + } + 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) + } + 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"} { + 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..c42e74b58e --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld.go @@ -0,0 +1,44 @@ +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 is not proof the owner process is +// dead; host cleanup must check that separately. The probe holds the lock +// only for an instant, but 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 { + // Only a v3 owner takes the lock; for any other file a free lock proves + // nothing. + if err := ProbeWALStoreV3(path); err != nil { + return fmt.Errorf("storage: %s is not a v3 volume, unheld cannot be proven: %w", path, err) + } + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() // closing releases the probe's lock + switch err := LockWALStoreFile(f); { + case errors.Is(err, ErrWALStoreLocked): + return ErrVolumeHeld + case err != nil: + return err + } + return nil +} 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..97fcee13aa --- /dev/null +++ b/seaweed-block/core/storage/volume_unheld_test.go @@ -0,0 +1,147 @@ +package storage + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "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{}) + t.Cleanup(func() { // kill and reap the holder, bounded + _ = 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) + } + go func() { _ = cmd.Wait(); close(exited) }() + 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) + } +}