Merge pull request #735 from seaweedfs/feat/volume-start-stop

feat(sw-block): volume start and volume stop
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-28 21:39:01 -08:00
commit 6d63003461
8 files changed
+1574 -10

No files matched your search

+3
View File
@@ -79,6 +79,9 @@ func run(args []string, stdout, stderr io.Writer) int {
if args[0] == "mini" {
return runMini(args[1:], stdout, stderr)
}
if args[0] == "volume" {
return runVolume(args[1:], stdout, stderr)
}
if args[0] != "ops" {
fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0])
usage(stderr)
+13 -10
View File
@@ -187,17 +187,20 @@ func miniMasterArgs(c miniConfig, chunk bool) []string {
// miniVolumeArgs is blockvolume as swb_start runs it, plus, with a chunk
// store, the walstore-chunk settings and the volume's layout id.
func miniVolumeArgs(c miniConfig, chunk bool, layoutID string) []string {
args := []string{"--master", loopback(c.Ports.Master), "--server-id", miniServer, "--volume-id", miniVolume, "--replica-id", miniReplica,
"--data-addr", loopback(c.Ports.Data), "--ctrl-addr", loopback(c.Ports.Ctrl), "--status-addr", loopback(c.Ports.Status),
"--durable-root", filepath.Join(c.Dir, "vol")}
blocks := strconv.FormatUint(c.SizeBytes/miniBlockSize, 10)
if !chunk {
args = append(args, "--durable-impl", "walstore", "--durable-blocks", blocks)
} else {
args = append(args, "--durable-impl", "walstore-chunk", "--durable-blocks", blocks, "--durable-blocksize", strconv.Itoa(miniBlockSize),
"--chunk-filer", loopback(c.Ports.WeedFG), "--chunk-path", miniChunkPath, "--chunk-control-endpoint", "--workspace-lease", "--layout-id", layoutID)
return miniVolumeSpec(c, chunk, layoutID).args()
}
// miniVolumeSpec is mini's v1: the same settings volume start writes for a
// unit (volumeSpec), on loopback under the run's dir.
func miniVolumeSpec(c miniConfig, chunk bool, layoutID string) volumeSpec {
v := volumeSpec{Master: loopback(c.Ports.Master), ServerID: miniServer, VolumeID: miniVolume, ReplicaID: miniReplica,
DataAddr: loopback(c.Ports.Data), CtrlAddr: loopback(c.Ports.Ctrl), StatusAddr: loopback(c.Ports.Status),
DurableRoot: filepath.Join(c.Dir, "vol"), Blocks: c.SizeBytes / miniBlockSize,
NVMeListen: loopback(c.Ports.NVMe), NQN: c.NQN}
if chunk {
v.Chunk, v.BlockSize, v.ChunkFiler, v.ChunkPath, v.LayoutID = true, miniBlockSize, loopback(c.Ports.WeedFG), miniChunkPath, layoutID
}
return append(args, "--nvme-listen", loopback(c.Ports.NVMe), "--nvme-subsysnqn", c.NQN)
return v
}
// miniTopology and miniClusterSpec place v1 on s1/r1.
+110
View File
@@ -0,0 +1,110 @@
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
// volumeSpec is one blockvolume's settings, the one source of both forms
// they take: the flags sw-block mini passes to its blockvolume child
// (args), and the settings file volume start writes for the
// sw-blockvolume@<volume> unit (env), whose ExecStart passes each key to
// the same flag. A test renders env through the shipped unit and compares
// it with args, so the two cannot drift.
type volumeSpec struct {
Master, ServerID, VolumeID, ReplicaID string
DataAddr, CtrlAddr, StatusAddr string
DurableRoot string
Blocks uint64
BlockSize int // 0: blockvolume's default (walstore)
Chunk bool
ChunkFiler, ChunkPath, LayoutID string // with Chunk
NVMeListen, NQN string
ISCSIListen, IQN string // optional (volume start)
}
// args are the blockvolume flags, in the order mini has always passed them.
func (v volumeSpec) args() []string {
a := []string{"--master", v.Master, "--server-id", v.ServerID, "--volume-id", v.VolumeID, "--replica-id", v.ReplicaID,
"--data-addr", v.DataAddr, "--ctrl-addr", v.CtrlAddr, "--status-addr", v.StatusAddr, "--durable-root", v.DurableRoot}
blocks := strconv.FormatUint(v.Blocks, 10)
if !v.Chunk {
a = append(a, "--durable-impl", "walstore", "--durable-blocks", blocks)
} else {
a = append(a, "--durable-impl", "walstore-chunk", "--durable-blocks", blocks, "--durable-blocksize", strconv.Itoa(v.BlockSize),
"--chunk-filer", v.ChunkFiler, "--chunk-path", v.ChunkPath, "--chunk-control-endpoint", "--workspace-lease", "--layout-id", v.LayoutID)
}
a = append(a, "--nvme-listen", v.NVMeListen, "--nvme-subsysnqn", v.NQN)
if v.ISCSIListen != "" {
a = append(a, "--iscsi-listen", v.ISCSIListen, "--iscsi-iqn", v.IQN)
}
return a
}
// blockvolumeEnvDefaults are deploy/config/blockvolume.env's values (a test
// keeps them equal): what the unit passes for a key the spec does not set.
var blockvolumeEnvDefaults = map[string]string{
"SWB_MASTER_ADDR": "127.0.0.1:9180", "SWB_SERVER_ID": "s1", "SWB_VOLUME_ID": "v1", "SWB_REPLICA_ID": "r1",
"SWB_DATA_ADDR": "127.0.0.1:9201", "SWB_CTRL_ADDR": "127.0.0.1:9202", "SWB_STATUS_ADDR": "127.0.0.1:9203",
"SWB_HEARTBEAT_INTERVAL": "2s", "SWB_RECOVER_TIMEOUT": "30s",
"SWB_DURABLE_ROOT": "/var/lib/sw-block-volume/volumes", "SWB_DURABLE_IMPL": "walstore",
"SWB_DURABLE_BLOCKS": "65536", "SWB_DURABLE_BLOCKSIZE": "4096",
"SWB_NVME_LISTEN": "127.0.0.1:4420", "SWB_NVME_SUBSYSNQN": "nqn.2026-05.io.seaweedfs:v1", "SWB_NVME_NS": "1",
"SWB_NVME_MAX_H2C_DATA_LENGTH": "0", "SWB_UBLK_DEVICE": "-1", "SWB_UBLK_QUEUES": "0", "SWB_UBLK_QUEUE_DEPTH": "0",
"SWB_ISCSI_LISTEN": "", "SWB_ISCSI_IQN": "", "SWB_ISCSI_PORTAL_ADDR": "", "SWB_ISCSI_LUN": "0", "SWB_ISCSI_DATAOUT_TIMEOUT": "0",
"SWB_REPLICATION_ACK": "best-effort", "SWB_WAL_RETENTION_LSNS": "0", "SWB_RECOVERY_MODE": "legacy",
"SWB_DEGRADED_PROBE_INTERVAL": "0", "SWB_DEGRADED_PROBE_COOLDOWN_BASE": "5s", "SWB_DEGRADED_PROBE_COOLDOWN_CAP": "60s",
"SWB_CHUNK_FILER": "", "SWB_CHUNK_PATH": "/swblock/chunks", "SWB_CHUNK_COLLECTION": "", "SWB_CHUNK_REPLICATION": "",
"SWB_CHUNK_CAPTURE_INTERVAL": "0", "SWB_CHUNK_SNAPSHOT_SCHEDULE": "daily:7", "SWB_CHUNK_UPLOAD_CONCURRENCY": "8",
"SWB_CHUNK_CONTROL_ENDPOINT": "false", "SWB_WORKSPACE_LEASE": "false", "SWB_VOLUME_EXTRA_ARGS": "",
}
// env is the unit's settings file for v: every key of the shipped
// defaults, with the spec's values over them. The layout id has no key of
// its own: it goes in SWB_VOLUME_EXTRA_ARGS.
func (v volumeSpec) env() map[string]string {
e := make(map[string]string, len(blockvolumeEnvDefaults))
for k, val := range blockvolumeEnvDefaults {
e[k] = val
}
set := map[string]string{
"SWB_MASTER_ADDR": v.Master, "SWB_SERVER_ID": v.ServerID, "SWB_VOLUME_ID": v.VolumeID, "SWB_REPLICA_ID": v.ReplicaID,
"SWB_DATA_ADDR": v.DataAddr, "SWB_CTRL_ADDR": v.CtrlAddr, "SWB_STATUS_ADDR": v.StatusAddr,
"SWB_DURABLE_ROOT": v.DurableRoot, "SWB_DURABLE_IMPL": "walstore", "SWB_DURABLE_BLOCKS": strconv.FormatUint(v.Blocks, 10),
"SWB_NVME_LISTEN": v.NVMeListen, "SWB_NVME_SUBSYSNQN": v.NQN,
"SWB_ISCSI_LISTEN": v.ISCSIListen, "SWB_ISCSI_IQN": v.IQN,
}
if v.Chunk {
set["SWB_DURABLE_IMPL"] = "walstore-chunk"
set["SWB_DURABLE_BLOCKSIZE"] = strconv.Itoa(v.BlockSize)
set["SWB_CHUNK_FILER"], set["SWB_CHUNK_PATH"] = v.ChunkFiler, v.ChunkPath
set["SWB_CHUNK_CONTROL_ENDPOINT"], set["SWB_WORKSPACE_LEASE"] = "true", "true"
set["SWB_VOLUME_EXTRA_ARGS"] = "--layout-id " + v.LayoutID
}
for k, val := range set {
e[k] = val
}
return e
}
// renderEnv is a settings file: KEY=VALUE lines in key order, each value
// quoted for systemd's EnvironmentFile when it is not plain.
func renderEnv(header string, e map[string]string) string {
keys := make([]string, 0, len(e))
for k := range e {
keys = append(keys, k)
}
sort.Strings(keys)
var b strings.Builder
b.WriteString(header)
for _, k := range keys {
val := e[k]
if strings.ContainsAny(val, " \t\"'\\$#") {
val = strconv.Quote(val)
}
fmt.Fprintf(&b, "%s=%s\n", k, val)
}
return b.String()
}
+554
View File
@@ -0,0 +1,554 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
)
// The whole-job volume commands: each runs on the volume's host, prints
// every step before it runs it, and stops at the first step that answers
// otherwise than expected, saying how to go on. A volume is an instance of
// the sw-blockvolume@ unit; its settings file is the only state they keep.
// The sentence volume stop ends with (and the help and the page say): what
// it promises, and only that.
const stopRecoveryPoint = "recovery point in the object store: the cut at %s; writes after it are on this host only"
const volumeUsage = `usage: sudo sw-block volume start <volume> [flags]
sudo sw-block volume stop <volume> [--force] [--no-cut] [--timeout 2m]
start: an existing volume (in the cluster spec) as the systemd unit
sw-blockvolume@<volume>: writes /etc/sw-block/volumes/<volume>.env, resolves
the volume's layout id (with --chunk-filer), starts the unit, waits until it
serves, and prints the connect command. A new volume, until volume start
can create one: add it to blockmaster's cluster spec and restart blockmaster
(the standalone page's "Required setup"), then volume start.
stop: refuses while a guest is connected (unless --force), takes a cut,
refuses when the cut failed or its outcome is unknown (unless --no-cut),
stops the unit, and ends with: "` + stopRecoveryPoint + `".`
// volumeHelp is the usage, with the stop sentence's time shown as <time>.
func volumeHelp() string { return strings.Replace(volumeUsage, "%s", "<time>", 1) }
// verbEnv is where the commands act: the CLI fixes it (runVolume); tests
// give their own directory, systemctl and clock.
type verbEnv struct {
EtcDir string // the settings files (/etc/sw-block/volumes)
Systemctl func(ctx context.Context, args ...string) (string, error) // runs systemctl, returns its output
HTTP *http.Client
Now func() time.Time // the time the commands print (the cut's)
Poll time.Duration // between readiness reads
Step func(name string) error // called before each step; nil in the CLI
}
func (e verbEnv) step(out io.Writer, name, what string) error {
fmt.Fprintf(out, "+ %s\n", what)
if e.Step != nil {
return e.Step(name)
}
return nil
}
var volumeNameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
func volumeUnit(v string) string { return "sw-blockvolume@" + v + ".service" }
// unitState is systemctl is-active's answer for unit. is-active exits
// non-zero for every state but active, so its output decides: a known state
// word is the answer; anything else (systemctl missing, a bus error) is an
// error and certifies no state.
func unitState(ctx context.Context, env verbEnv, unit string) (string, error) {
out, err := env.Systemctl(ctx, "is-active", unit)
switch out {
case "active", "inactive", "failed", "activating", "deactivating", "reloading", "refreshing", "maintenance":
return out, nil
}
return "", fmt.Errorf("systemctl is-active %s: %q (%v)", unit, out, err)
}
// unitStopped: only inactive and failed are a stopped unit.
func unitStopped(state string) bool { return state == "inactive" || state == "failed" }
func runVolume(args []string, stdout, stderr io.Writer) int {
if len(args) < 2 || (args[0] != "start" && args[0] != "stop") {
fmt.Fprintln(stderr, volumeHelp())
return ops.VolumeStatusExitInvalid
}
if os.Geteuid() != 0 {
fmt.Fprintf(stderr, "sw-block volume %s: needs root (systemctl and /etc/sw-block): run with sudo\n", args[0])
return ops.VolumeStatusExitInvalid
}
env := verbEnv{EtcDir: "/etc/sw-block/volumes", HTTP: &http.Client{Timeout: 10 * time.Second}, Now: time.Now, Poll: time.Second,
Systemctl: func(ctx context.Context, a ...string) (string, error) {
out, err := exec.CommandContext(ctx, "systemctl", a...).CombinedOutput()
return strings.TrimSpace(string(out)), err
}}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
if args[0] == "start" {
spec, opts, err := parseVolumeStart(args[1:], stderr)
if err != nil {
return ops.VolumeStatusExitInvalid
}
return volumeStart(ctx, env, spec, opts, stdout, stderr)
}
opts, err := parseVolumeStop(args[1:], stderr)
if err != nil {
return ops.VolumeStatusExitInvalid
}
return volumeStop(ctx, env, opts, stdout, stderr)
}
type startOpts struct {
Replace bool
Wait time.Duration
}
func parseVolumeStart(args []string, stderr io.Writer) (volumeSpec, startOpts, error) {
fs := flag.NewFlagSet("sw-block volume start", flag.ContinueOnError)
fs.SetOutput(stderr)
var v volumeSpec
var o startOpts
var size string
fs.StringVar(&v.Master, "master", "127.0.0.1:9180", "blockmaster address")
fs.StringVar(&v.ServerID, "server-id", "", "this host's server id in the cluster spec (required)")
fs.StringVar(&v.ReplicaID, "replica-id", "", "the volume's replica id on this host (required)")
fs.StringVar(&v.DataAddr, "data-addr", "", "replication data address (required)")
fs.StringVar(&v.CtrlAddr, "ctrl-addr", "", "replication control address (required)")
fs.StringVar(&v.StatusAddr, "status-addr", "", "status address, loopback (required)")
fs.StringVar(&v.DurableRoot, "durable-root", "", "local data directory (default /var/lib/sw-block-volume/<volume>, the unit's state directory)")
fs.StringVar(&size, "size", "", "volume size, the cluster spec's (required): 256MiB, 1GiB, ...")
fs.StringVar(&v.NVMeListen, "nvme-listen", "", "NVMe/TCP listen address (required)")
fs.StringVar(&v.NQN, "nqn", "", "NVMe subsystem NQN (default nqn.2026-05.io.seaweedfs:<volume>)")
fs.StringVar(&v.ISCSIListen, "iscsi-listen", "", "iSCSI listen address (optional)")
fs.StringVar(&v.IQN, "iqn", "", "iSCSI target IQN (with --iscsi-listen)")
fs.StringVar(&v.ChunkFiler, "chunk-filer", "", "SeaweedFS filer gRPC address: walstore-chunk (snapshots, restore); without it walstore")
fs.StringVar(&v.ChunkPath, "chunk-path", "/swblock/chunks", "chunk store path on the filer")
fs.BoolVar(&o.Replace, "replace", false, "replace a different settings file (the unit must be stopped)")
fs.DurationVar(&o.Wait, "wait", 2*time.Minute, "how long to wait until the volume serves")
if err := fs.Parse(volumeArgsFirst(args)); err != nil {
return v, o, err
}
if fs.NArg() != 1 {
fmt.Fprintln(stderr, volumeHelp())
return v, o, errors.New("one volume")
}
v.VolumeID = fs.Arg(0)
bad := func(msg string) (volumeSpec, startOpts, error) {
fmt.Fprintf(stderr, "sw-block volume start: %s\n", msg)
return v, o, errors.New(msg)
}
if !volumeNameRE.MatchString(v.VolumeID) {
return bad(fmt.Sprintf("volume name %q: letters, digits, '.', '_', '-' (a systemd instance name)", v.VolumeID))
}
for _, r := range []struct{ name, val string }{{"--server-id", v.ServerID}, {"--replica-id", v.ReplicaID}, {"--data-addr", v.DataAddr},
{"--ctrl-addr", v.CtrlAddr}, {"--status-addr", v.StatusAddr}, {"--size", size}, {"--nvme-listen", v.NVMeListen}} {
if r.val == "" {
return bad(r.name + " is required")
}
}
if (v.ISCSIListen == "") != (v.IQN == "") {
return bad("--iscsi-listen and --iqn go together")
}
b, err := parseSize(size)
if err != nil || b%4096 != 0 {
return bad(fmt.Sprintf("--size %q: a positive multiple of 4KiB", size))
}
v.Blocks = b / 4096
if v.DurableRoot == "" {
v.DurableRoot = "/var/lib/sw-block-volume/" + v.VolumeID
}
if v.NQN == "" {
v.NQN = "nqn.2026-05.io.seaweedfs:" + v.VolumeID
}
if v.ChunkFiler != "" {
v.Chunk, v.BlockSize = true, 4096
}
return v, o, nil
}
// volumeArgsFirst lets the volume name come before the flags too.
func volumeArgsFirst(args []string) []string {
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
return append(append([]string{}, args[1:]...), args[0])
}
return args
}
// volumeStart runs start's steps. An identical re-run is safe: each step is
// done again or found done.
func volumeStart(ctx context.Context, env verbEnv, v volumeSpec, o startOpts, stdout, stderr io.Writer) int {
fail := func(step, msg, next string) int {
fmt.Fprintf(stderr, "sw-block volume start: %s: %s\n", step, msg)
if next != "" {
fmt.Fprintf(stderr, "sw-block volume start: %s\n", next)
}
return 1
}
unit := volumeUnit(v.VolumeID)
if v.Chunk {
if err := env.step(stdout, "resolve", "resolve "+v.VolumeID+"'s layout id at "+v.Master); err != nil {
return fail("resolve", err.Error(), "run the same command again")
}
id, err := resolveVolumeID(ctx, v.Master, v.VolumeID)
if err != nil {
return fail("resolve", err.Error(), "is "+v.VolumeID+" in blockmaster's cluster spec, and blockmaster running? (volume start starts an existing volume)")
}
v.LayoutID = id.String()
}
path := filepath.Join(env.EtcDir, v.VolumeID+".env")
if err := env.step(stdout, "settings", "write "+path); err != nil {
return fail("settings", err.Error(), "run the same command again")
}
body := renderEnv("# sw-block volume start "+v.VolumeID+": settings of "+unit+"\n", v.env())
old, err := os.ReadFile(path)
switch {
case err == nil && string(old) == body:
fmt.Fprintln(stdout, " unchanged")
case err == nil && !o.Replace:
return fail("settings", path+" exists with other settings", "pass --replace to replace it (stop the volume first), or start another volume")
case err != nil && !errors.Is(err, os.ErrNotExist):
return fail("settings", err.Error(), "")
default:
if err == nil { // --replace: only over a stopped unit
st, serr := unitState(ctx, env, unit)
if serr != nil {
return fail("settings", "cannot tell whether "+unit+" is stopped: "+serr.Error(), "check systemctl, then run the same command again")
}
if !unitStopped(st) {
return fail("settings", unit+" is "+st, "stop it first: sudo sw-block volume stop "+v.VolumeID)
}
}
if err := writeFileAtomic(path, []byte(body), 0o640); err != nil {
return fail("settings", err.Error(), "")
}
}
if err := env.step(stdout, "unit", "systemctl enable --now "+unit); err != nil {
return fail("unit", err.Error(), "run the same command again")
}
if out, err := env.Systemctl(ctx, "enable", "--now", unit); err != nil {
return fail("unit", fmt.Sprintf("%v: %s", err, out), "see: journalctl -u "+unit)
}
if err := env.step(stdout, "serve", fmt.Sprintf("wait until %s serves (up to %s)", v.VolumeID, o.Wait)); err != nil {
return fail("serve", err.Error(), "run the same command again")
}
deadline := time.Now().Add(o.Wait) // real time: env.Now dates only what the commands print
for {
ok, why := frontendReady(ctx, env, v.StatusAddr, v.VolumeID)
if ok {
break
}
if st, serr := unitState(ctx, env, unit); serr == nil && unitStopped(st) {
return fail("serve", unit+" is "+st, "see: journalctl -u "+unit)
}
if ctx.Err() != nil || !time.Now().Before(deadline) {
return fail("serve", fmt.Sprintf("not serving after %s: %s", o.Wait, why), "the unit keeps running; see: journalctl -u "+unit+", and run the same command again to wait")
}
select {
case <-ctx.Done():
case <-time.After(env.Poll):
}
}
fmt.Fprintf(stdout, "\nsw-block volume start: %s serves (%s).\n", v.VolumeID, unit)
fmt.Fprintf(stdout, "Connect:\n sudo nvme connect -t tcp -a %s -s %s -n %s --ctrl-loss-tmo=180 --reconnect-delay=2\n",
shQuote(hostOf(v.NVMeListen)), shQuote(portOf(v.NVMeListen)), shQuote(v.NQN))
if v.ISCSIListen != "" {
fmt.Fprintf(stdout, " sudo iscsiadm -m discovery -t sendtargets -p %s\n", shQuote(v.ISCSIListen))
}
fmt.Fprintf(stdout, "Before stopping: unmount it, then sudo nvme disconnect -n %s; then sudo sw-block volume stop %s\n", shQuote(v.NQN), v.VolumeID)
return 0
}
func hostOf(addr string) string {
if i := strings.LastIndex(addr, ":"); i >= 0 {
return addr[:i]
}
return addr
}
func portOf(addr string) string {
if i := strings.LastIndex(addr, ":"); i >= 0 {
return addr[i+1:]
}
return ""
}
func writeFileAtomic(path string, data []byte, mode os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, mode); err != nil {
return err
}
return os.Rename(tmp, path)
}
func getJSON(ctx context.Context, env verbEnv, url string, into any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := env.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return fmt.Errorf("%s: http %d: %s", url, resp.StatusCode, strings.TrimSpace(string(b)))
}
return json.NewDecoder(resp.Body).Decode(into)
}
// frontendReady: /status names this volume, Healthy, and FrontendPrimaryReady
// (the frontend admits guest I/O); Healthy alone is not enough (a refused
// durable admission, a missing workspace lease or an ACK-profile refusal
// clears only readiness). why is the reason it is not ready yet.
func frontendReady(ctx context.Context, env verbEnv, statusAddr, volume string) (bool, string) {
var st struct {
VolumeID string
Healthy bool
FrontendPrimaryReady bool
NotReadyReason string
}
if err := getJSON(ctx, env, "http://"+statusAddr+"/status?volume="+volume, &st); err != nil {
return false, "status unreadable: " + err.Error()
}
switch {
case st.VolumeID != volume:
return false, fmt.Sprintf("status names volume %q", st.VolumeID)
case !st.Healthy:
return false, "not Healthy: " + st.NotReadyReason
case !st.FrontendPrimaryReady:
return false, "Healthy, frontend not ready: " + st.NotReadyReason
}
return true, ""
}
type stopOpts struct {
Volume string
Force, NoCut bool
Timeout time.Duration
}
func parseVolumeStop(args []string, stderr io.Writer) (stopOpts, error) {
fs := flag.NewFlagSet("sw-block volume stop", flag.ContinueOnError)
fs.SetOutput(stderr)
var o stopOpts
fs.BoolVar(&o.Force, "force", false, "stop although a guest is connected (it gets I/O errors), or although whether one is connected cannot be read")
fs.BoolVar(&o.NoCut, "no-cut", false, "stop without a cut (or although the cut failed): the recovery point in the object store does not move")
fs.DurationVar(&o.Timeout, "timeout", 2*time.Minute, "bound on the cut")
if err := fs.Parse(volumeArgsFirst(args)); err != nil {
return o, err
}
if fs.NArg() != 1 || !volumeNameRE.MatchString(fs.Arg(0)) {
fmt.Fprintln(stderr, volumeHelp())
return o, errors.New("one volume")
}
o.Volume = fs.Arg(0)
return o, nil
}
// readEnvFile reads a settings file volume start wrote.
func readEnvFile(path string) (map[string]string, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
e := map[string]string{}
for _, line := range strings.Split(string(b), "\n") {
k, val, ok := strings.Cut(strings.TrimSpace(line), "=")
if !ok || strings.HasPrefix(k, "#") {
continue
}
if uq, err := strconv.Unquote(val); err == nil {
val = uq
}
e[k] = val
}
return e, nil
}
// volumeStop runs stop's steps: guests, cut, unit. Every refusal stops
// before the unit is touched.
func volumeStop(ctx context.Context, env verbEnv, o stopOpts, stdout, stderr io.Writer) int {
refuse := func(step, msg string) int {
fmt.Fprintf(stderr, "sw-block volume stop: %s: %s\n", step, msg)
return ops.VolumeStatusExitInvalid
}
unit := volumeUnit(o.Volume)
e, err := readEnvFile(filepath.Join(env.EtcDir, o.Volume+".env"))
if err != nil {
return refuse("settings", fmt.Sprintf("%v (was %s started with sudo sw-block volume start?)", err, o.Volume))
}
status := e["SWB_STATUS_ADDR"]
st, serr := unitState(ctx, env, unit)
switch {
case serr != nil:
return refuse("unit", "cannot tell whether "+unit+" runs: "+serr.Error()+"; nothing was done")
case unitStopped(st):
fmt.Fprintf(stdout, "sw-block volume stop: %s is not running (%s): nothing to cut or stop\n", unit, st)
return 0
}
if st != "active" {
// activating, deactivating, reloading: a holder may still be live,
// so the guest read and the cut stay; if the holder is down they
// refuse, and --force --no-cut stops the unit anyway.
fmt.Fprintf(stdout, " %s is %s: a holder may still run; if it does not, the steps below refuse and --force --no-cut stops the unit\n", unit, st)
}
if err := env.step(stdout, "guests", "read the guests connected to "+o.Volume); err != nil {
return refuse("guests", err.Error())
}
var g struct {
Frontends map[string]int `json:"frontends"`
Connected int `json:"connected"`
}
gerr := getJSON(ctx, env, "http://"+status+"/status/guests?volume="+o.Volume, &g)
switch {
case gerr != nil && !o.Force:
return refuse("guests", fmt.Sprintf("cannot read whether a guest is connected: %v; pass --force to stop anyway", gerr))
case gerr == nil && g.Connected > 0 && !o.Force:
return refuse("guests", fmt.Sprintf("%d guest connection(s) %v: disconnect them first (unmount, then sudo nvme disconnect, or iscsiadm logout); "+
"stopping now gives a connected guest I/O errors. A host that vanished (killed, partitioned) still counts until its TCP connection closes: "+
"if you know no guest uses %s, --force stops it. This protects the guest; it does not make the stop complete.", g.Connected, g.Frontends, o.Volume))
case gerr == nil && g.Connected > 0:
fmt.Fprintf(stdout, " %d guest connection(s) %v; stopping anyway (--force): they get I/O errors\n", g.Connected, g.Frontends)
case gerr != nil:
fmt.Fprintf(stdout, " guests unknown (%v); stopping anyway (--force)\n", gerr)
default:
fmt.Fprintln(stdout, " none connected (as counted: NVMe/TCP and iSCSI)")
}
chunk := e["SWB_DURABLE_IMPL"] == "walstore-chunk"
final := ""
switch {
case !chunk:
final = "walstore: no object store; all data is on this host only"
case o.NoCut:
fmt.Fprintln(stdout, "+ no cut (--no-cut)")
final = "no cut taken (--no-cut): " + lastConfirmedCut(ctx, env, status, o.Volume) + "; writes after it are on this host only"
default:
if err := env.step(stdout, "cut", "cut "+o.Volume+" (publish to the object store)"); err != nil {
return refuse("cut", err.Error())
}
// The time printed is taken before the request: the cut's barrier is
// no earlier, so "writes after it" never claims a write the cut missed.
cutAt := env.Now()
res, err := volumeCut(ctx, env, status, o.Volume, o.Timeout)
if err != nil {
return refuse("cut", fmt.Sprintf("%v. Nothing was stopped; the local data is safe on this host; %s. "+
"A cut that timed out keeps what it uploaded: running the same command again continues from it. "+
"Or pass --no-cut to stop without a cut.", err, lastConfirmedCut(ctx, env, status, o.Volume)))
}
fmt.Fprintf(stdout, " cut: LSN %d, head generation %d (the time below is the request's start; the cut covers every write before it)\n", *res.CutLSN, *res.HeadGen)
final = fmt.Sprintf(stopRecoveryPoint, cutAt.UTC().Format(time.RFC3339))
}
return stopUnit(ctx, env, unit, o.Volume, final, stdout, stderr)
}
// stopUnit is stop's last step: systemctl stop, then the closing lines.
func stopUnit(ctx context.Context, env verbEnv, unit, volume, final string, stdout, stderr io.Writer) int {
if err := env.step(stdout, "unit", "systemctl stop "+unit); err != nil {
fmt.Fprintf(stderr, "sw-block volume stop: unit: %v\n", err)
return ops.VolumeStatusExitInvalid
}
if out, err := env.Systemctl(ctx, "stop", unit); err != nil {
fmt.Fprintf(stderr, "sw-block volume stop: unit: %v: %s (see: journalctl -u %s; run the same command again)\n", err, out, unit)
return 1
}
fmt.Fprintf(stdout, "sw-block volume stop: %s stopped; sudo sw-block volume start %s (the same flags) starts it again\n", unit, volume)
fmt.Fprintln(stdout, final)
return 0
}
// cutAnswer is the part of POST /chunk/cut's success body volume stop checks.
type cutAnswer struct {
VolumeID string `json:"volumeID"`
CutLSN *uint64 `json:"cutLSN"` // required (0 is a legitimate empty volume's)
HeadGen *uint64 `json:"headGen"` // required
}
// volumeCut is POST /chunk/cut, one request bounded by timeout. Only a
// complete success answer for this volume is a cut; a refusal is an error,
// and anything else (no answer, a timeout, an unreadable or foreign answer,
// outcome_unknown) is an unknown outcome: the cut may have published.
func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout time.Duration) (cutAnswer, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
body, _ := json.Marshal(map[string]any{"volumeID": volume, "timeoutMs": timeout.Milliseconds()})
unknown := func(why string) (cutAnswer, error) {
return cutAnswer{}, fmt.Errorf("the cut's outcome is unknown (%s): it may have published", why)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://"+status+"/chunk/cut", bytes.NewReader(body))
if err != nil {
return cutAnswer{}, err
}
req.Header.Set("Content-Type", "application/json")
client := *env.HTTP
client.Timeout = timeout + 5*time.Second
resp, err := client.Do(req)
if err != nil {
return unknown(err.Error())
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if err != nil {
return unknown("answer unreadable: " + err.Error())
}
if resp.StatusCode != http.StatusOK {
var eb struct{ Code, Message string }
if json.Unmarshal(b, &eb) != nil || eb.Code == "" || eb.Code == "outcome_unknown" {
return unknown(fmt.Sprintf("http %d %s %s", resp.StatusCode, eb.Code, strings.TrimSpace(eb.Message)))
}
return cutAnswer{}, fmt.Errorf("the cut was refused: http %d %s %s", resp.StatusCode, eb.Code, eb.Message)
}
var a cutAnswer
if err := json.Unmarshal(b, &a); err != nil {
return unknown("answer not a cut: " + err.Error())
}
if a.VolumeID != volume {
return unknown(fmt.Sprintf("answer names volume %q", a.VolumeID))
}
if a.CutLSN == nil || a.HeadGen == nil {
return unknown("answer lacks cutLSN or headGen")
}
return a, nil
}
// lastConfirmedCut says when the holder last confirmed a cut (in its
// memory: none after a restart). It is the last confirmed one, not proof
// that a cut since did not land.
func lastConfirmedCut(ctx context.Context, env verbEnv, status, volume string) string {
var d struct {
Volumes []struct {
Chunk *struct{ Stats struct{ LastCutNs int64 } }
}
}
if err := getJSON(ctx, env, "http://"+status+"/status/durable?volume="+volume, &d); err != nil || len(d.Volumes) == 0 || d.Volumes[0].Chunk == nil {
return "the last confirmed cut could not be read"
}
ns := d.Volumes[0].Chunk.Stats.LastCutNs
if ns == 0 {
return "no cut confirmed since the holder's restart (age unknown (since restart))"
}
at := time.Unix(0, ns).UTC()
return fmt.Sprintf("the last confirmed cut was at %s, %s ago", at.Format(time.RFC3339), env.Now().Sub(at).Round(time.Second))
}
@@ -0,0 +1,810 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// --- the shared builder against the shipped unit ---
// unitFlags renders the template unit's ExecStart for one instance: each
// "--flag=${KEY}" takes the settings file's value, "--volume-id=%i" the
// instance name, and $SWB_VOLUME_EXTRA_ARGS adds its words.
func unitFlags(t *testing.T, instance string, env map[string]string) map[string]string {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "deploy", "systemd", "sw-blockvolume@.service"))
if err != nil {
t.Fatal(err)
}
flags := map[string]string{}
re := regexp.MustCompile(`--([a-z0-9-]+)=(\$\{([A-Z0-9_]+)\}|%i)`)
for _, m := range re.FindAllStringSubmatch(string(raw), -1) {
if m[2] == "%i" {
flags[m[1]] = instance
} else {
flags[m[1]] = env[m[3]]
}
}
if !strings.Contains(string(raw), "$SWB_VOLUME_EXTRA_ARGS") {
t.Fatal("the unit no longer passes $SWB_VOLUME_EXTRA_ARGS")
}
extra := strings.Fields(env["SWB_VOLUME_EXTRA_ARGS"])
for i := 0; i+1 < len(extra); i += 2 {
flags[strings.TrimPrefix(extra[i], "--")] = extra[i+1]
}
return flags
}
// argFlags is args() as flag -> value (a bare boolean flag is "true").
func argFlags(args []string) map[string]string {
out := map[string]string{}
for i := 0; i < len(args); i++ {
name := strings.TrimPrefix(args[i], "--")
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") {
out[name] = args[i+1]
i++
} else {
out[name] = "true"
}
}
return out
}
func testSpecs() map[string]volumeSpec {
base := volumeSpec{Master: "10.0.0.1:9180", ServerID: "s7", VolumeID: "vol-a", ReplicaID: "r3",
DataAddr: "10.0.0.7:9201", CtrlAddr: "10.0.0.7:9202", StatusAddr: "127.0.0.1:9203",
DurableRoot: "/var/lib/sw-block-volume/vol-a", Blocks: 262144, NVMeListen: "10.0.0.7:4420", NQN: "nqn.2026-05.io.seaweedfs:vol-a"}
chunk := base
chunk.Chunk, chunk.BlockSize, chunk.ChunkFiler, chunk.ChunkPath, chunk.LayoutID = true, 4096, "10.0.0.2:18888", "/swblock/chunks", "00112233445566778899aabbccddeeff"
iscsi := chunk
iscsi.ISCSIListen, iscsi.IQN = "10.0.0.7:3260", "iqn.2026-05.io.seaweedfs:vol-a"
return map[string]volumeSpec{"walstore": base, "walstore-chunk": chunk, "with-iscsi": iscsi}
}
// What volume start writes, passed through the shipped unit, is the flags
// mini passes for the same settings: every flag of args() reaches
// blockvolume with the same value. Control: a settings value changed after
// rendering is seen.
func TestVolumeSettingsThroughTheUnitAreMinisFlags(t *testing.T) {
for name, v := range testSpecs() {
got := unitFlags(t, v.VolumeID, v.env())
for flag, want := range argFlags(v.args()) {
if got[flag] != want {
t.Errorf("%s: --%s through the unit is %q; mini passes %q", name, flag, got[flag], want)
}
}
}
v := testSpecs()["walstore-chunk"]
e := v.env()
e["SWB_STATUS_ADDR"] = "127.0.0.1:1"
if unitFlags(t, v.VolumeID, e)["status-addr"] == argFlags(v.args())["status-addr"] {
t.Fatal("control: a changed settings value was not seen")
}
}
// The defaults volume start fills in are the shipped settings file's.
func TestBlockvolumeEnvDefaultsAreTheShippedFile(t *testing.T) {
shipped, err := readEnvFile(filepath.Join("..", "..", "deploy", "config", "blockvolume.env"))
if err != nil {
t.Fatal(err)
}
if len(shipped) != len(blockvolumeEnvDefaults) {
t.Errorf("deploy/config/blockvolume.env has %d keys, blockvolumeEnvDefaults %d", len(shipped), len(blockvolumeEnvDefaults))
}
for k, v := range shipped {
if got, ok := blockvolumeEnvDefaults[k]; !ok || got != v {
t.Errorf("%s: shipped %q, blockvolumeEnvDefaults %q (present %v)", k, v, got, ok)
}
}
}
// A settings file reads back as written, quoted values included.
func TestRenderEnvRoundTrips(t *testing.T) {
e := testSpecs()["with-iscsi"].env()
e["SWB_CHUNK_COLLECTION"] = `a "quoted" $value # x`
path := filepath.Join(t.TempDir(), "v.env")
if err := os.WriteFile(path, []byte(renderEnv("# h\n", e)), 0o600); err != nil {
t.Fatal(err)
}
back, err := readEnvFile(path)
if err != nil {
t.Fatal(err)
}
for k, v := range e {
if back[k] != v {
t.Errorf("%s: wrote %q, read %q", k, v, back[k])
}
}
}
// --- a fake host: systemctl and the volume's status server ---
type fakeHost struct {
mu sync.Mutex
unit string // "inactive", "active", "failed"
calls []string
failStart bool
failStop bool
healthy atomic.Bool
notReady atomic.Bool // Healthy, but the frontend does not admit I/O
queryErr bool // systemctl is-active cannot answer
guests atomic.Int64
noGuests atomic.Bool // /status/guests answers 404
cutMode atomic.Value // "ok", "fail", "hang"
cuts atomic.Int64
published atomic.Int64 // cuts the fake published although their answer was lost
lastCutNs atomic.Int64
srv *httptest.Server
}
func newFakeHost(t *testing.T) *fakeHost {
h := &fakeHost{unit: "inactive"}
h.cutMode.Store("ok")
mux := http.NewServeMux()
mux.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
ready := h.healthy.Load() && !h.notReady.Load()
reason := ""
if !ready {
reason = "durable_admission_refused"
}
_ = json.NewEncoder(w).Encode(map[string]any{"VolumeID": "vol-a", "Healthy": h.healthy.Load(), "FrontendPrimaryReady": ready, "NotReadyReason": reason})
})
mux.HandleFunc("/status/guests", func(w http.ResponseWriter, r *http.Request) {
if h.noGuests.Load() {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
n := int(h.guests.Load())
_ = json.NewEncoder(w).Encode(map[string]any{"volumeID": "vol-a", "frontends": map[string]int{"nvme": n}, "connected": n})
})
mux.HandleFunc("/status/durable", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"Volumes": []any{map[string]any{"Chunk": map[string]any{"Stats": map[string]any{"LastCutNs": h.lastCutNs.Load()}}}}})
})
mux.HandleFunc("/chunk/cut", func(w http.ResponseWriter, r *http.Request) {
h.cuts.Add(1)
switch h.cutMode.Load().(string) {
case "fail":
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(map[string]any{"code": "not_primary", "message": "not the primary"})
case "drop": // published (the holder confirms it), then the answer is lost
h.lastCutNs.Store(time.Date(2026, 11, 28, 22, 59, 0, 0, time.UTC).UnixNano())
h.published.Add(1)
if hj, ok := w.(http.Hijacker); ok {
c, _, _ := hj.Hijack()
_ = c.Close()
}
case "malformed":
_, _ = io.WriteString(w, `{"volumeID": "vol-a", "cutL`)
case "foreign":
_ = json.NewEncoder(w).Encode(map[string]any{"volumeID": "vol-b", "cutLSN": 9})
case "unknown-code":
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(map[string]any{"code": "outcome_unknown", "message": "the HEAD write's result is not known"})
case "hang": // past the command's timeout; bounded so the server can close
select {
case <-r.Context().Done():
case <-time.After(2 * time.Second):
}
case "missing-fields":
_ = json.NewEncoder(w).Encode(map[string]any{"volumeID": "vol-a"})
case "zero":
_ = json.NewEncoder(w).Encode(map[string]any{"volumeID": "vol-a", "cutLSN": 0, "headGen": 1})
default:
_ = json.NewEncoder(w).Encode(map[string]any{"volumeID": "vol-a", "cutLSN": 9, "headGen": 4})
}
})
h.srv = httptest.NewServer(mux)
t.Cleanup(h.srv.Close)
return h
}
func (h *fakeHost) addr() string { return strings.TrimPrefix(h.srv.URL, "http://") }
func (h *fakeHost) systemctl(_ context.Context, args ...string) (string, error) {
h.mu.Lock()
defer h.mu.Unlock()
h.calls = append(h.calls, strings.Join(args, " "))
switch args[0] {
case "is-active":
if h.queryErr {
return "Failed to connect to bus", errors.New("exit status 1")
}
return h.unit, errors.New("exit status 3") // is-active exits non-zero unless active; the output decides
case "set-state": // test only: put the unit in a state
h.unit = args[1]
case "enable":
if h.failStart {
h.unit = "failed"
return "Job failed", errors.New("exit status 1")
}
h.unit = "active"
h.healthy.Store(true)
case "stop":
if h.failStop {
return "Job failed", errors.New("exit status 1")
}
h.unit = "inactive"
h.healthy.Store(false)
}
return "", nil
}
func (h *fakeHost) called(prefix string) int {
h.mu.Lock()
defer h.mu.Unlock()
n := 0
for _, c := range h.calls {
if strings.HasPrefix(c, prefix) {
n++
}
}
return n
}
func (h *fakeHost) env(t *testing.T) verbEnv {
return verbEnv{EtcDir: t.TempDir(), Systemctl: h.systemctl, HTTP: &http.Client{Timeout: 5 * time.Second},
Now: func() time.Time { return time.Date(2026, 11, 28, 23, 0, 0, 0, time.UTC) }, Poll: 10 * time.Millisecond}
}
func (h *fakeHost) spec(chunk bool) volumeSpec {
v := testSpecs()["walstore"]
if chunk {
v = testSpecs()["walstore-chunk"]
}
v.StatusAddr = h.addr()
return v
}
func stubResolve(t *testing.T, id string, err error) {
old := resolveVolumeID
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
if err != nil {
return layout.VolumeID{}, err
}
return layout.ParseVolumeID(id)
}
t.Cleanup(func() { resolveVolumeID = old })
}
func runStart(env verbEnv, v volumeSpec, o startOpts) (int, string, string) {
var out, errb bytes.Buffer
code := volumeStart(context.Background(), env, v, o, &out, &errb)
return code, out.String(), errb.String()
}
func runStop(env verbEnv, o stopOpts) (int, string, string) {
var out, errb bytes.Buffer
code := volumeStop(context.Background(), env, o, &out, &errb)
return code, out.String(), errb.String()
}
// --- volume start ---
// start writes the settings file (the layout id resolved from the master
// for walstore-chunk), starts the unit, waits until the volume serves, and
// prints the connect command; an identical re-run finds it done.
func TestVolumeStartStartsTheUnitAndWaitsUntilItServes(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
stubResolve(t, "00112233445566778899aabbccddeeff", nil)
v := h.spec(true)
v.LayoutID = ""
code, out, errs := runStart(env, v, startOpts{Wait: 5 * time.Second})
if code != 0 {
t.Fatalf("start: %d %s", code, errs)
}
written, err := readEnvFile(filepath.Join(env.EtcDir, "vol-a.env"))
if err != nil {
t.Fatal(err)
}
if written["SWB_VOLUME_EXTRA_ARGS"] != "--layout-id 00112233445566778899aabbccddeeff" || written["SWB_DURABLE_IMPL"] != "walstore-chunk" {
t.Fatalf("settings: %v", written)
}
if h.called("enable --now sw-blockvolume@vol-a.service") != 1 {
t.Fatalf("systemctl calls: %v", h.calls)
}
for _, want := range []string{"+ resolve", "+ write", "+ systemctl enable --now", "+ wait until", "serves", "sudo nvme connect -t tcp -a 10.0.0.7 -s 4420 -n nqn.2026-05.io.seaweedfs:vol-a"} {
if !strings.Contains(out, want) {
t.Fatalf("output lacks %q:\n%s", want, out)
}
}
if code, out, errs := runStart(env, v, startOpts{Wait: 5 * time.Second}); code != 0 || !strings.Contains(out, "unchanged") {
t.Fatalf("identical re-run: %d %s %s", code, out, errs)
}
}
// start refuses other settings over a volume's file unless --replace, and
// --replace while the unit runs; a unit that fails, a volume that never
// serves within --wait, and a layout id that cannot be resolved each stop
// start at their step.
func TestVolumeStartRefusals(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
v := h.spec(false)
if code, _, errs := runStart(env, v, startOpts{Wait: time.Second}); code != 0 {
t.Fatalf("setup: %s", errs)
}
other := v
other.NVMeListen = "10.0.0.7:4421"
if code, _, errs := runStart(env, other, startOpts{Wait: time.Second}); code == 0 || !strings.Contains(errs, "--replace") {
t.Fatalf("other settings: %d %s; want a refusal naming --replace", code, errs)
}
if code, _, errs := runStart(env, other, startOpts{Wait: time.Second, Replace: true}); code == 0 || !strings.Contains(errs, "is active") {
t.Fatalf("--replace while running: %d %s; want a refusal", code, errs)
}
before, _ := os.ReadFile(filepath.Join(env.EtcDir, "vol-a.env"))
if !strings.Contains(string(before), "4420") {
t.Fatal("a refused start changed the settings file")
}
f := newFakeHost(t)
f.failStart = true
if code, _, errs := runStart(f.env(t), f.spec(false), startOpts{Wait: time.Second}); code == 0 || !strings.Contains(errs, "journalctl -u sw-blockvolume@vol-a.service") {
t.Fatalf("unit failing: %d %s", code, errs)
}
n := newFakeHost(t)
ne := n.env(t)
ne.Systemctl = func(ctx context.Context, a ...string) (string, error) { // starts, never serves
out, err := n.systemctl(ctx, a...)
n.healthy.Store(false)
return out, err
}
if code, _, errs := runStart(ne, n.spec(false), startOpts{Wait: 50 * time.Millisecond}); code == 0 || !strings.Contains(errs, "not serving after") {
t.Fatalf("never serving: %d %s", code, errs)
}
r := newFakeHost(t)
stubResolve(t, "", errors.New("volume vol-a not found"))
re := r.env(t)
if code, _, errs := runStart(re, r.spec(true), startOpts{Wait: time.Second}); code == 0 || !strings.Contains(errs, "existing volume") {
t.Fatalf("unresolvable: %d %s", code, errs)
}
if _, err := os.Stat(filepath.Join(re.EtcDir, "vol-a.env")); !os.IsNotExist(err) || r.called("enable") != 0 {
t.Fatal("an unresolvable volume got a settings file or a unit start")
}
}
// --- volume stop ---
func startedHost(t *testing.T, chunk bool) (*fakeHost, verbEnv) {
h := newFakeHost(t)
env := h.env(t)
stubResolve(t, "00112233445566778899aabbccddeeff", nil)
if code, _, errs := runStart(env, h.spec(chunk), startOpts{Wait: time.Second}); code != 0 {
t.Fatalf("setup start: %s", errs)
}
return h, env
}
// stop with no guest: cut, then the unit stops, and the output ends with
// the recovery-point sentence at the cut's time.
func TestVolumeStopCutsThenStopsAndSaysWhatItPromises(t *testing.T) {
h, env := startedHost(t, true)
code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second})
if code != 0 {
t.Fatalf("stop: %d %s", code, errs)
}
if h.cuts.Load() != 1 || h.called("stop sw-blockvolume@vol-a.service") != 1 {
t.Fatalf("cuts %d, calls %v", h.cuts.Load(), h.calls)
}
lines := strings.Split(strings.TrimSpace(out), "\n")
if want := "recovery point in the object store: the cut at 2026-11-28T23:00:00Z; writes after it are on this host only"; lines[len(lines)-1] != want {
t.Fatalf("last line %q; want %q", lines[len(lines)-1], want)
}
if strings.Index(out, "+ cut") > strings.Index(out, "+ systemctl stop") {
t.Fatal("the unit was stopped before the cut")
}
if code, out, _ := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || !strings.Contains(out, "not running") || h.cuts.Load() != 1 {
t.Fatalf("second stop: %d %s (cuts %d)", code, out, h.cuts.Load())
}
}
// Every refusal stops before the unit: a connected guest (unless --force),
// guests that cannot be read (unless --force), a failed cut and a cut whose
// outcome is unknown (unless --no-cut), and an unknown volume.
func TestVolumeStopRefusalsLeaveTheUnitRunning(t *testing.T) {
cases := []struct {
name string
set func(h *fakeHost)
opts stopOpts
want string
cutWant int64
}{
{"guest connected", func(h *fakeHost) { h.guests.Store(1) }, stopOpts{}, "vanished", 0},
{"guests unreadable", func(h *fakeHost) { h.noGuests.Store(true) }, stopOpts{}, "cannot read whether a guest is connected", 0},
{"cut failed", func(h *fakeHost) {
h.cutMode.Store("fail")
h.lastCutNs.Store(time.Date(2026, 11, 28, 22, 50, 0, 0, time.UTC).UnixNano())
},
stopOpts{}, "the last confirmed cut was at 2026-11-28T22:50:00Z, 10m0s ago", 1},
{"cut failed after a restart", func(h *fakeHost) { h.cutMode.Store("fail") }, stopOpts{}, "age unknown (since restart)", 1},
{"cut outcome unknown", func(h *fakeHost) { h.cutMode.Store("hang") }, stopOpts{Timeout: 100 * time.Millisecond}, "outcome is unknown", 1},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
h, env := startedHost(t, true)
c.set(h)
o := c.opts
o.Volume = "vol-a"
if o.Timeout == 0 {
o.Timeout = time.Second
}
code, _, errs := runStop(env, o)
if code != 2 || !strings.Contains(errs, c.want) {
t.Fatalf("exit %d, stderr %s; want 2 and %q", code, errs, c.want)
}
if h.called("stop ") != 0 || h.cuts.Load() != c.cutWant {
t.Fatalf("a refusal touched the unit or cut wrongly: calls %v, cuts %d", h.calls, h.cuts.Load())
}
})
}
h := newFakeHost(t)
if code, _, errs := runStop(h.env(t), stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 2 || !strings.Contains(errs, "volume start") {
t.Fatalf("unknown volume: %d %s", code, errs)
}
}
// --force stops with a guest connected (it says the guest gets I/O errors);
// --no-cut stops without a cut and says the recovery point did not move; a
// walstore volume has no object store and says so.
func TestVolumeStopForceNoCutAndWalstore(t *testing.T) {
h, env := startedHost(t, true)
h.guests.Store(2)
if code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Force: true, Timeout: time.Second}); code != 0 || !strings.Contains(out, "I/O errors") || h.called("stop ") != 1 {
t.Fatalf("--force: %d %s %s", code, out, errs)
}
n, nenv := startedHost(t, true)
n.cutMode.Store("fail")
code, out, errs := runStop(nenv, stopOpts{Volume: "vol-a", NoCut: true, Timeout: time.Second})
if code != 0 || n.cuts.Load() != 0 || n.called("stop ") != 1 || !strings.Contains(out, "no cut taken (--no-cut)") || !strings.Contains(out, "since restart") {
t.Fatalf("--no-cut: %d %s %s (cuts %d)", code, out, errs, n.cuts.Load())
}
w, wenv := startedHost(t, false)
if code, out, _ := runStop(wenv, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || w.cuts.Load() != 0 || !strings.Contains(out, "walstore: no object store") {
t.Fatalf("walstore: %d %s", code, out)
}
f, fenv := startedHost(t, true)
f.failStop = true
if code, _, errs := runStop(fenv, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 1 || !strings.Contains(errs, "journalctl") {
t.Fatalf("systemctl stop failing: %d %s", code, errs)
}
}
// --- interrupted at every step, then run again ---
// An interrupt before any step of start leaves a state the same command
// completes; one before any step of stop leaves the unit running (or, at
// the last step, cut but running), and the same command completes.
func TestVolumeVerbsInterruptedAtEveryStepComplete(t *testing.T) {
for _, step := range []string{"resolve", "settings", "unit", "serve"} {
t.Run("start/"+step, func(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
stubResolve(t, "00112233445566778899aabbccddeeff", nil)
env.Step = func(name string) error {
if name == step {
return errors.New("interrupted")
}
return nil
}
if code, _, _ := runStart(env, h.spec(true), startOpts{Wait: time.Second}); code == 0 {
t.Fatal("an interrupted start succeeded")
}
env.Step = nil
if code, _, errs := runStart(env, h.spec(true), startOpts{Wait: time.Second}); code != 0 {
t.Fatalf("re-run after an interrupt at %s: %s", step, errs)
}
})
}
for _, step := range []string{"guests", "cut", "unit"} {
t.Run("stop/"+step, func(t *testing.T) {
h, env := startedHost(t, true)
env.Step = func(name string) error {
if name == step {
return errors.New("interrupted")
}
return nil
}
if code, _, _ := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code == 0 {
t.Fatal("an interrupted stop succeeded")
}
if h.called("stop ") != 0 {
t.Fatalf("interrupted at %s, the unit was stopped", step)
}
env.Step = nil
if code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || !strings.Contains(out, "recovery point in the object store") {
t.Fatalf("re-run after an interrupt at %s: %d %s", step, code, errs)
}
})
}
}
// --- the CLI ---
// Without root both commands refuse before any step, naming sudo.
func TestVolumeCommandsNeedRoot(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("running as root")
}
for _, verb := range []string{"start", "stop"} {
var out, errb bytes.Buffer
if code := run([]string{"volume", verb, "vol-a"}, &out, &errb); code != 2 || !strings.Contains(errb.String(), "run with sudo") || out.Len() != 0 {
t.Fatalf("volume %s without root: %d %q %q", verb, code, out.String(), errb.String())
}
}
}
// The help says the stop sentence, word for word.
func TestVolumeHelpSaysTheStopSentence(t *testing.T) {
if !strings.Contains(volumeHelp(), strings.Replace(stopRecoveryPoint, "%s", "<time>", 1)) {
t.Fatal("the help does not carry the stop sentence")
}
}
// Start's flags: required ones refused when missing, the name checked, the
// size a multiple of 4KiB, defaults derived from the volume.
func TestVolumeStartFlags(t *testing.T) {
ok := []string{"vol-a", "--server-id", "s1", "--replica-id", "r1", "--data-addr", "a:1", "--ctrl-addr", "a:2", "--status-addr", "127.0.0.1:3", "--size", "1GiB", "--nvme-listen", "a:4420"}
v, _, err := parseVolumeStart(ok, &bytes.Buffer{})
if err != nil || v.Blocks != 262144 || v.DurableRoot != "/var/lib/sw-block-volume/vol-a" || v.NQN != "nqn.2026-05.io.seaweedfs:vol-a" || v.Chunk {
t.Fatalf("parse %+v %v", v, err)
}
for name, args := range map[string][]string{
"missing --server-id": append([]string{"vol-a"}, ok[3:]...),
"bad name": append([]string{"vol/a"}, ok[1:]...),
"odd size": append(append([]string{}, ok[:12]...), "1000", "--nvme-listen", "a:4420"),
"iscsi half": append(append([]string{}, ok...), "--iscsi-listen", "a:3260"),
} {
if _, _, err := parseVolumeStart(args, &bytes.Buffer{}); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
// Both supervisors take the host volume lock in its fixed directory:
// neither mini's blockvolume flags nor the unit's ExecStart move it with
// the test-only flag (blockvolume refuses that flag under systemd too).
func TestMiniAndTheUnitKeepTheHostVolumeLock(t *testing.T) {
const testOnly = "volume-lock-dir-test-only"
raw, err := os.ReadFile(filepath.Join("..", "..", "deploy", "systemd", "sw-blockvolume@.service"))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(raw), testOnly) {
t.Fatal("the unit moves the host volume lock")
}
for name, v := range testSpecs() {
if strings.Contains(strings.Join(v.args(), " "), testOnly) || strings.Contains(renderEnv("", v.env()), testOnly) {
t.Fatalf("%s: mini's flags or the settings move the host volume lock", name)
}
}
}
// The page says the stop sentence word for word, as the help does.
func TestVolumePageSaysTheStopSentence(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "docs", "standalone-deployment.md"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), strings.Replace(stopRecoveryPoint, "%s", "<time>", 1)) {
t.Fatal("docs/standalone-deployment.md does not carry the stop sentence")
}
}
// A transitional unit (activating, deactivating, reloading) may have a live
// holder: stop keeps the guest read and the cut. Live: it refuses for a
// guest, otherwise cuts and stops. Down (status unreadable): it refuses,
// and --force --no-cut stops it. Only inactive and failed are nothing to
// stop.
func TestVolumeStopKeepsItsChecksForATransitionalUnit(t *testing.T) {
for _, st := range []string{"activating", "deactivating", "reloading"} {
h, env := startedHost(t, true)
_, _ = h.systemctl(context.Background(), "set-state", st)
h.guests.Store(1)
if code, _, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 2 || h.called("stop ") != 0 || !strings.Contains(errs, "guest connection") {
t.Fatalf("%s with a guest: %d %s; want the guest refusal", st, code, errs)
}
h.guests.Store(0)
if code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || h.cuts.Load() != 1 || h.called("stop ") != 1 || !strings.Contains(out, "recovery point in the object store") {
t.Fatalf("%s, live holder: %d %s %s (cuts %d)", st, code, out, errs, h.cuts.Load())
}
d, denv := startedHost(t, true)
_, _ = d.systemctl(context.Background(), "set-state", st)
d.srv.Close() // the holder is down: status unreadable
if code, _, errs := runStop(denv, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 2 || d.called("stop ") != 0 {
t.Fatalf("%s, holder down: %d %s; want a refusal", st, code, errs)
}
if code, out, errs := runStop(denv, stopOpts{Volume: "vol-a", Force: true, NoCut: true, Timeout: time.Second}); code != 0 || d.called("stop ") != 1 || !strings.Contains(out, "no cut taken") {
t.Fatalf("%s, holder down, --force --no-cut: %d %s %s", st, code, out, errs)
}
}
for _, st := range []string{"inactive", "failed"} {
h, env := startedHost(t, true)
_, _ = h.systemctl(context.Background(), "set-state", st)
if code, out, _ := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || h.called("stop ") != 0 || !strings.Contains(out, "nothing to cut or stop") {
t.Fatalf("%s: %d %s; want nothing to stop", st, code, out)
}
}
}
// A zero cut LSN (an empty volume) with a head generation is a complete
// answer; a success answer without the fields is not (above).
func TestVolumeStopAcceptsAZeroLSNCut(t *testing.T) {
h, env := startedHost(t, true)
h.cutMode.Store("zero")
if code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || !strings.Contains(out, "cut: LSN 0, head generation 1") {
t.Fatalf("zero LSN: %d %s %s", code, out, errs)
}
}
// The cut time printed is the one taken before the cut's request, never a
// later reading: the barrier is no earlier than it.
func TestVolumeStopPrintsTheTimeTakenBeforeTheCut(t *testing.T) {
h, env := startedHost(t, true)
var calls atomic.Int64
base := time.Date(2026, 11, 28, 23, 0, 0, 0, time.UTC)
env.Now = func() time.Time { return base.Add(time.Duration(calls.Add(1)) * time.Minute) }
cutsBefore := h.cuts.Load()
var seenAtCut atomic.Int64
env.Step = func(name string) error {
if name == "unit" {
seenAtCut.Store(calls.Load())
}
return nil
}
code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second})
if code != 0 || h.cuts.Load() != cutsBefore+1 {
t.Fatalf("stop: %d %s", code, errs)
}
lines := strings.Split(strings.TrimSpace(out), "\n")
last := lines[len(lines)-1]
if want := base.Add(time.Minute).Format(time.RFC3339); !strings.Contains(last, "the cut at "+want) {
t.Fatalf("last line %q; want the time read before the cut (%s)", last, want)
}
}
// A timed-out cut's refusal says its progress is kept, and the help says
// how to add a new volume until volume start can create one.
func TestVolumeTextsForTimeoutsAndNewVolumes(t *testing.T) {
h, env := startedHost(t, true)
h.cutMode.Store("hang")
if _, _, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: 100 * time.Millisecond}); !strings.Contains(errs, "keeps what it uploaded") {
t.Fatalf("timed-out cut: %s", errs)
}
if !strings.Contains(volumeHelp(), "cluster spec and restart blockmaster") {
t.Fatal("the help does not say how to add a new volume")
}
}
// start waits for the frontend to admit I/O, not authority Healthy alone:
// Healthy with FrontendPrimaryReady false is not serving (the reason is
// said), and the same start succeeds once it is ready.
func TestVolumeStartWaitsForFrontendReadiness(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
h.notReady.Store(true)
code, _, errs := runStart(env, h.spec(false), startOpts{Wait: 100 * time.Millisecond})
if code == 0 || !strings.Contains(errs, "frontend not ready: durable_admission_refused") {
t.Fatalf("Healthy, not ready: %d %s; want a failure naming the reason", code, errs)
}
go func() { time.Sleep(50 * time.Millisecond); h.notReady.Store(false) }()
if code, out, errs := runStart(env, h.spec(false), startOpts{Wait: 5 * time.Second}); code != 0 || !strings.Contains(out, "serves") {
t.Fatalf("ready later: %d %s %s", code, out, errs)
}
}
// A state systemctl cannot report certifies nothing: stop refuses and does
// nothing, and --replace is refused; a transitional unit is not stopped
// for --replace either.
func TestVolumeUnitStateErrorsAndTransitionsAreNotStopped(t *testing.T) {
h, env := startedHost(t, true)
h.mu.Lock()
h.queryErr = true
h.mu.Unlock()
if code, _, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 2 || !strings.Contains(errs, "cannot tell whether") || h.called("stop ") != 0 || h.cuts.Load() != 0 {
t.Fatalf("stop with an unreadable unit state: %d %s", code, errs)
}
other := h.spec(true)
other.NVMeListen = "10.0.0.7:4421"
if code, _, errs := runStart(env, other, startOpts{Wait: time.Second, Replace: true}); code == 0 || !strings.Contains(errs, "cannot tell whether") {
t.Fatalf("--replace with an unreadable unit state: %d %s", code, errs)
}
h.mu.Lock()
h.queryErr = false
h.unit = "activating"
h.mu.Unlock()
if code, _, errs := runStart(env, other, startOpts{Wait: time.Second, Replace: true}); code == 0 || !strings.Contains(errs, "is activating") {
t.Fatalf("--replace while activating: %d %s", code, errs)
}
}
// Only a complete success answer for this volume is a cut. A published cut
// whose answer is lost, a truncated answer, another volume's answer and
// outcome_unknown are each an unknown outcome: stop refuses, says the cut
// may have published, stops nothing; the same command then completes.
func TestVolumeStopUnknownCutAnswersRefuse(t *testing.T) {
for _, mode := range []string{"drop", "malformed", "foreign", "unknown-code", "missing-fields"} {
t.Run(mode, func(t *testing.T) {
h, env := startedHost(t, true)
h.cutMode.Store(mode)
code, _, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second})
if code != 2 || !strings.Contains(errs, "may have published") || h.called("stop ") != 0 {
t.Fatalf("%s: %d %s (calls %v)", mode, code, errs, h.calls)
}
if mode == "drop" && (h.published.Load() != 1 || !strings.Contains(errs, "the last confirmed cut was at 2026-11-28T22:59:00Z")) {
t.Fatalf("drop: published %d; the refusal must report the holder's confirmed cut: %s", h.published.Load(), errs)
}
if strings.Contains(errs, "did not move") {
t.Fatalf("%s: the refusal claims the recovery point did not move: %s", mode, errs)
}
h.cutMode.Store("ok")
if code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second}); code != 0 || !strings.Contains(out, "recovery point in the object store") {
t.Fatalf("%s: re-run: %d %s", mode, code, errs)
}
})
}
}
// A guest that connects after the guest read does not stop the stop (the
// read is an observation, not admission control); the closing line still
// promises only the cut, writes after it being on this host.
func TestVolumeStopGuestConnectingAfterTheRead(t *testing.T) {
h, env := startedHost(t, true)
env.Step = func(name string) error {
if name == "cut" {
h.guests.Store(1) // connects between the read and the cut
}
return nil
}
code, out, errs := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second})
if code != 0 || !strings.Contains(out, "none connected (as counted") || !strings.Contains(out, "writes after it are on this host only") {
t.Fatalf("guest after the read: %d %s %s", code, out, errs)
}
}
// unitOnlyFlags are the flags the unit passes that mini does not: the
// shipped settings file's defaults, which mini leaves to blockvolume's own.
// They are listed, not compared: the two supervisors differ on exactly
// these (the degraded probe interval is the one whose value differs from
// blockvolume's default: 0 in the shipped file, 5s in blockvolume).
var unitOnlyFlags = []string{"chunk-capture-interval", "chunk-collection", "chunk-replication", "chunk-snapshot-schedule",
"chunk-upload-concurrency", "degraded-probe-cooldown-base", "degraded-probe-cooldown-cap", "degraded-probe-interval",
"heartbeat-interval", "iscsi-dataout-timeout", "iscsi-lun", "iscsi-portal-addr", "nvme-max-h2c-data-length", "nvme-ns",
"recover-timeout", "recovery-mode", "replication-ack", "ublk-device", "ublk-queue-depth", "ublk-queues", "wal-retention-lsns"}
// Every flag the unit passes is either one mini passes too (compared above)
// or in unitOnlyFlags: a new unit flag must be classified here.
func TestTheUnitOnlyFlagsAreListed(t *testing.T) {
v := testSpecs()["with-iscsi"]
mini := argFlags(v.args())
listed := map[string]bool{}
for _, f := range unitOnlyFlags {
listed[f] = true
}
for flag := range unitFlags(t, v.VolumeID, v.env()) {
if _, ok := mini[flag]; !ok && !listed[flag] {
t.Errorf("the unit passes --%s, which mini does not and unitOnlyFlags does not list", flag)
}
}
for f := range listed {
if _, ok := mini[f]; ok {
t.Errorf("--%s is listed as unit-only but mini passes it", f)
}
}
}
@@ -0,0 +1,54 @@
package durable_test
import (
"errors"
"runtime"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// One supervisor per durable root (sw-block mini and the
// sw-blockvolume@ unit): a second process opening a volume on a root a
// live process serves is refused, by the host volume lock and, with that
// lock off, by the store's own lock on its root. Neither can serve beside
// the other.
func TestASecondSupervisorOnOneDurableRootIsRefused(t *testing.T) {
for _, hostLock := range []bool{true, false} {
fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks)
root, lockDir := t.TempDir(), t.TempDir()
open := func() (*durable.DurableProvider, error) {
cfg := durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: root,
HostVolumeLock: hostLock, VolumeLockDirTestOnly: lockDir,
BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
}
fixture.Configure(&cfg)
p, err := durable.NewDurableProvider(cfg, v1View())
if err != nil {
return nil, err
}
t.Cleanup(func() { _ = p.Close() })
_, err = p.EnsureStorage("v1")
return p, err
}
first, err := open() // mini's blockvolume, say
if err != nil {
t.Fatalf("host lock %v: first: %v", hostLock, err)
}
_, err = open() // the unit on the same root
// Windows' byte-range lock fails the store's first read instead
// (still a refusal); elsewhere the store's lock answers.
if err == nil || (runtime.GOOS != "windows" && !errors.Is(err, storage.ErrWALStoreLocked)) {
t.Fatalf("host lock %v: a second supervisor on the root: %v; want a refusal (%v)", hostLock, err, storage.ErrWALStoreLocked)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
if _, err := open(); err != nil {
t.Fatalf("host lock %v: after the first stopped, the root could not be opened: %v", hostLock, err)
}
}
}
@@ -33,6 +33,13 @@ func TestLayoutIdentityWriterAndReaders(t *testing.T) {
// TestOpsVolumeCreateRefusesUnreadyOrMismatchedAnswers probes malformed identity replies before binding or placement.
"cmd/sw-block/volume_create.go runOpsVolumeCreate": true,
"core/rpc/lifecycleclient/identity.go ResolveVolume": true,
// TestMiniChunkCommandsArePinned pins the layout id mini passes its blockvolume child.
"cmd/sw-block/mini.go miniVolumeSpec": true,
// TestVolumeSettingsThroughTheUnitAreMinisFlags: the layout id reaches blockvolume the same through mini's flags and the unit's settings.
"cmd/sw-block/volume_spec.go args": true,
"cmd/sw-block/volume_spec.go env": true,
// TestVolumeStartStartsTheUnitAndWaitsUntilItServes writes the resolved id; TestVolumeStartRefusals refuses an unresolvable one with no settings file.
"cmd/sw-block/volume_verbs.go volumeStart": true,
}
seen := map[string]bool{}
root := filepath.Join("..", "..")
@@ -487,6 +487,29 @@ sw-block mini --dir ./swb-mini # blockmaster and blockvolume next to sw
mini uses the commands of the sections below; the steps there remain the way to run each piece yourself.
## Volume start and stop (systemd)
`sw-block volume start` and `sw-block volume stop` run one volume as an instance of the template unit `sw-blockvolume@<volume>.service` (`deploy/systemd/sw-blockvolume@.service`). Each is one command for the whole job; each prints every step before it runs it and stops at the first step that answers otherwise than expected, saying how to go on. Both need root (`sudo`): they write under `/etc/sw-block` and run `systemctl`.
**`sudo sw-block volume start <volume> --server-id S --replica-id R --data-addr A --ctrl-addr A --status-addr 127.0.0.1:P --size 1GiB --nvme-listen A [--chunk-filer F]`**
- It starts an **existing volume**: one already in blockmaster's cluster spec. Creating a volume from this command comes later; until then, for a new volume add it to the cluster spec and restart blockmaster (see "Required setup" above), then run `volume start`.
- It writes `/etc/sw-block/volumes/<volume>.env` (the keys of `deploy/config/blockvolume.env`), resolves the volume's layout id at `--master` (with `--chunk-filer`: walstore-chunk), runs `systemctl enable --now`, waits until `/status` reports the volume Healthy (`--wait`, default 2m), and prints the connect command.
- The unit's volume id is its instance name; the local data goes to `/var/lib/sw-block-volume/<volume>` unless `--durable-root` says otherwise.
- The same command again is safe. Other settings over an existing file are refused unless `--replace`, and `--replace` is refused while the unit runs.
**`sudo sw-block volume stop <volume> [--force] [--no-cut] [--timeout 2m]`**
1. **Guests.** It refuses while a guest is connected (`/status/guests`: NVMe/TCP hosts and iSCSI sessions), unless `--force`. This protects a connected guest from I/O errors; it is not a completeness guarantee. A host that vanished (a killed VM, a partitioned host) still counts until its TCP connection closes: when you know nothing uses the volume, `--force` stops it. ublk and NVMe/RDMA guests are not counted.
2. **Cut.** It takes a cut (walstore-chunk). When the cut fails or its outcome is unknown, it refuses and stops nothing: the local data is safe on this host, and the message gives the age of the object store's recovery point (from the holder's last cut; "age unknown (since restart)" after a restart). A cut that timed out keeps what it uploaded, so running the same command again continues from it. `--no-cut` stops without a cut. The time in the closing line is taken before the cut's request, so the cut covers every write before it.
3. **Unit.** It runs `systemctl stop`. Only an `inactive` or `failed` unit is "nothing to stop". A unit in a transitional state (`activating`, `deactivating`, `reloading`) may still have a live holder, so the guest read and the cut stay; if the holder is down they refuse, and `--force --no-cut` stops the unit. The unit stays enabled, so it starts again at boot; `volume start` with the same flags starts it now.
Its output ends with what it promises, and only that:
```text
recovery point in the object store: the cut at <time>; writes after it are on this host only
```
A walstore volume (no `--chunk-filer`) has no object store; its stop says so. `sw-block mini` stays a foreground trial with its own children; a mini and a unit cannot both serve one volume on a host (the host volume lock, and the store's lock on its root).
## First volume (read-only check)
Start one local volume, attach it over NVMe/TCP on loopback, and look at the