Files
seaweedfs/seaweed-block/cmd/sw-block/mini.go
T

637 lines
23 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// sw-block mini starts the single-host configuration in one command, after
// SeaweedFS's `weed mini`: weed (when found), blockmaster and one
// blockvolume, with the standalone page's flags. It prints every command it
// runs, never runs sudo or nvme connect (it prints the connect command), and
// stops every child when interrupted or when one of them exits.
const miniUsage = `usage: sw-block mini [--dir ./swb-mini] [--reuse] [--weed PATH] [--bin DIR] [--size 256MiB] [--nqn NQN] [--port-shift N]
Starts weed mini (when a weed binary is found: --weed, else PATH), blockmaster
and one blockvolume (v1) on loopback, and prints every command it runs. With
weed the volume is walstore-chunk with the chunk control endpoint, so
snapshots work at once (a restore into a new volume needs the standalone
setup); without weed it is walstore (no snapshots). Ctrl-C stops everything
it started.`
// miniPorts are the loopback ports mini uses: the standalone page's, and
// weed mini's defaults. Tests move them.
type miniPorts struct {
Master int // blockmaster
Data, Ctrl, Status int // blockvolume
NVMe int
// weed mini's listeners (HTTP and gRPC of master, volume and filer),
// all set explicitly: its S3, WebDAV and admin UI are turned off.
WeedMaster, WeedMasterG, WeedVolume, WeedVolumeG, WeedFiler, WeedFG int
// weed mini always runs its admin server (-admin.ui=false only hides the
// UI): its HTTP and worker gRPC ports are set too; its legacy pair is off.
WeedAdmin, WeedAdminG int
}
// shifted moves every port by n (--port-shift), for a host where a default
// port is taken or to run a second mini beside the first.
func (p miniPorts) shifted(n int) miniPorts {
return miniPorts{Master: p.Master + n, Data: p.Data + n, Ctrl: p.Ctrl + n, Status: p.Status + n, NVMe: p.NVMe + n,
WeedMaster: p.WeedMaster + n, WeedMasterG: p.WeedMasterG + n, WeedVolume: p.WeedVolume + n, WeedVolumeG: p.WeedVolumeG + n,
WeedFiler: p.WeedFiler + n, WeedFG: p.WeedFG + n, WeedAdmin: p.WeedAdmin + n, WeedAdminG: p.WeedAdminG + n}
}
// weed are weed mini's ports, as mini sets and checks them.
func (p miniPorts) weed() []int {
return []int{p.WeedMaster, p.WeedMasterG, p.WeedVolume, p.WeedVolumeG, p.WeedFiler, p.WeedFG, p.WeedAdmin, p.WeedAdminG}
}
var defaultMiniPorts = miniPorts{Master: 9180, Data: 9201, Ctrl: 9202, Status: 9203, NVMe: 4420,
WeedMaster: 9333, WeedMasterG: 19333, WeedVolume: 9340, WeedVolumeG: 19340, WeedFiler: 8888, WeedFG: 18888,
WeedAdmin: 12535, WeedAdminG: 22535}
// miniStartWait bounds each child's readiness, and miniResolveWait the
// layout id lookup; miniStopWait bounds a child's exit after SIGTERM.
var (
miniStartWait = 30 * time.Second
miniResolveWait = 60 * time.Second
miniStopWait = 10 * time.Second
)
type miniConfig struct {
Dir, Bin, Weed, NQN string
Reuse bool
SizeBytes uint64
PortShift int
Ports miniPorts
// Explicit names the flags given on the command line (fs.Visit); a
// --reuse refuses one that differs from the recorded run.
Explicit map[string]bool
}
// miniRecord is what a fresh start records in <dir>/mini.json and --reuse
// starts again with: the volume's size, the ports, the mode and its weed,
// and the NQN.
type miniRecord struct {
SizeBytes uint64 `json:"size_bytes"`
PortShift int `json:"port_shift"`
Weed string `json:"weed,omitempty"` // empty: walstore, no weed
NQN string `json:"nqn"`
Bin string `json:"bin"` // the directory of blockmaster and blockvolume, absolute
}
const miniRecordFile = "mini.json"
func writeMiniRecord(dir string, r miniRecord) error {
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
return err
}
return os.WriteFile(filepath.Join(dir, miniRecordFile), append(b, '\n'), 0o644)
}
// reuseMiniRecord loads the recorded run into c: a flag given now must agree
// with the record, and a recorded weed must still be there (never a silent
// fall back to walstore).
func reuseMiniRecord(c *miniConfig, weedFound string) (string, error) {
b, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
return "", fmt.Errorf("--reuse: %s has no %s (it was not started by sw-block mini): %w", c.Dir, miniRecordFile, err)
}
var r miniRecord
if err := json.Unmarshal(b, &r); err != nil {
return "", fmt.Errorf("--reuse: %s/%s: %w", c.Dir, miniRecordFile, err)
}
differs := func(flag string, now, then any) error {
if c.Explicit[flag] && fmt.Sprint(now) != fmt.Sprint(then) {
return fmt.Errorf("--reuse: --%s %v differs from this dir's run (%v); drop it to reuse the run as recorded", flag, now, then)
}
return nil
}
for _, e := range []error{differs("size", c.SizeBytes, r.SizeBytes), differs("port-shift", c.PortShift, r.PortShift),
differs("nqn", c.NQN, r.NQN), differs("weed", c.Weed, r.Weed), differs("bin", c.Bin, r.Bin)} {
if e != nil {
return "", e
}
}
if r.Weed != "" {
if st, err := os.Stat(r.Weed); err != nil || st.IsDir() {
return "", fmt.Errorf("--reuse: this dir's run used weed %s, which is not there now (pass it again with --weed, or start a new dir)", r.Weed)
}
}
if c.Explicit["weed"] == false && weedFound != "" && r.Weed == "" {
return "", fmt.Errorf("--reuse: this dir's run is walstore (no weed); a weed is found now: start a new dir for walstore-chunk")
}
c.SizeBytes, c.NQN, c.Weed = r.SizeBytes, r.NQN, r.Weed
if r.Bin != "" {
c.Bin = r.Bin
}
if r.PortShift != c.PortShift {
c.Ports = defaultMiniPorts.shifted(r.PortShift)
c.PortShift = r.PortShift
}
return r.Weed, nil
}
const (
miniVolume = "v1"
miniServer = "s1"
miniReplica = "r1"
miniBlockSize = 4096
miniChunkPath = "/swblock/chunks"
)
func loopback(port int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) }
// miniWeedArgs is weed mini bound to loopback only (-ip.bind; -ip alone is
// just the advertised address), its data under the run's dir, every
// listener's port explicit, and its S3, WebDAV and admin UI off.
func miniWeedArgs(c miniConfig) []string {
port := func(f string, p int) string { return "-" + f + "=" + strconv.Itoa(p) }
return []string{"mini", "-dir=" + filepath.Join(c.Dir, "weed"), "-ip=127.0.0.1", "-ip.bind=127.0.0.1",
port("master.port", c.Ports.WeedMaster), port("master.port.grpc", c.Ports.WeedMasterG),
port("volume.port", c.Ports.WeedVolume), port("volume.port.grpc", c.Ports.WeedVolumeG),
port("filer.port", c.Ports.WeedFiler), port("filer.port.grpc", c.Ports.WeedFG),
port("admin.port", c.Ports.WeedAdmin), port("admin.port.grpc", c.Ports.WeedAdminG), "-admin.port.legacy=0",
"-s3=false", "-webdav=false", "-admin.ui=false"}
}
// miniMasterArgs is blockmaster as the standalone page runs it: with a chunk
// store (chunk), the lifecycle store, the cluster spec and the workspace RPC
// the walstore-chunk volume needs; without, the page's walstore topology.
func miniMasterArgs(c miniConfig, chunk bool) []string {
if !chunk {
return []string{"--authority-store", filepath.Join(c.Dir, "master"), "--listen", loopback(c.Ports.Master),
"--topology", filepath.Join(c.Dir, "topology.yaml"), "--expected-slots-per-volume", "1"}
}
return []string{"--authority-store", filepath.Join(c.Dir, "master", "authority"), "--lifecycle-store", filepath.Join(c.Dir, "master", "lifecycle"),
"--cluster-spec", filepath.Join(c.Dir, "cluster-spec.yaml"), "--expected-slots-per-volume", "1", "--listen", loopback(c.Ports.Master),
"--workspace-rpc", "--chunk-filer", loopback(c.Ports.WeedFG), "--chunk-path", miniChunkPath}
}
// 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 {
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 v
}
// miniTopology and miniClusterSpec place v1 on s1/r1.
func miniTopology() string {
return fmt.Sprintf("volumes:\n - volume_id: %s\n slots:\n - replica_id: %s\n server_id: %s\n", miniVolume, miniReplica, miniServer)
}
func miniClusterSpec(c miniConfig) string {
return fmt.Sprintf("nodes:\n - server_id: %s\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n",
miniServer, loopback(c.Ports.Data), loopback(c.Ports.Ctrl), miniVolume, c.SizeBytes, miniServer, miniReplica)
}
// miniBanner is the fallback's first lines.
func miniBanner() string {
return `sw-block mini: no SeaweedFS "weed" binary found (--weed, or PATH).
sw-block mini: starting walstore: NO snapshots, NO restore. This is NOT the supported configuration.
sw-block mini: get weed from https://github.com/seaweedfs/seaweedfs/releases and pass --weed PATH.
`
}
func parseSize(s string) (uint64, error) {
units := []struct {
suffix string
mult uint64
}{{"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10}, {"G", 1 << 30}, {"M", 1 << 20}, {"K", 1 << 10}, {"", 1}}
for _, u := range units {
if strings.HasSuffix(s, u.suffix) {
n, err := strconv.ParseUint(strings.TrimSuffix(s, u.suffix), 10, 64)
if err != nil || n == 0 || n > ^uint64(0)/u.mult {
return 0, fmt.Errorf("invalid --size %q", s)
}
b := n * u.mult
if b%miniBlockSize != 0 {
return 0, fmt.Errorf("--size %q is not a multiple of %d bytes", s, miniBlockSize)
}
return b, nil
}
}
return 0, fmt.Errorf("invalid --size %q", s)
}
// miniChild is one started process.
type miniChild struct {
name string
cmd *exec.Cmd
done chan struct{}
err error
}
func (c *miniChild) exited() bool {
select {
case <-c.done:
return true
default:
return false
}
}
type miniRun struct {
cfg miniConfig
out, log io.Writer
children []*miniChild
}
// start prints the command, then starts it with its output in <dir>/<name>.log.
func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
fmt.Fprintf(r.out, "+ %s %s\n", bin, strings.Join(args, " "))
lf, err := os.Create(filepath.Join(r.cfg.Dir, name+".log"))
if err != nil {
return nil, err
}
cmd := exec.Command(bin, args...)
cmd.Stdout, cmd.Stderr, cmd.Stdin = lf, lf, nil
if err := cmd.Start(); err != nil {
lf.Close()
return nil, fmt.Errorf("start %s: %w", name, err)
}
c := &miniChild{name: name, cmd: cmd, done: make(chan struct{})}
go func() {
c.err = cmd.Wait()
lf.Close()
close(c.done)
}()
r.children = append(r.children, c)
return c, nil
}
// ready waits until every port listens, while c is alive, bounded.
func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
deadline := time.Now().Add(miniStartWait)
var lastErr error
for {
if d := r.dead(); d != nil {
return fmt.Errorf("%s exited during startup: %v (see %s.log)", d.name, d.err, d.name)
}
up := true
for _, p := range ports {
conn, err := net.DialTimeout("tcp", loopback(p), 200*time.Millisecond)
if err != nil {
lastErr = answer.Record(answer.Unsent, err) // TCP probe writes no application request
up = false
break
}
conn.Close()
}
if up {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log): %w", c.name, miniStartWait, ports, c.name, answer.Present(lastErr, answer.Ops))
}
select {
case <-ctx.Done():
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
case <-time.After(250 * time.Millisecond):
}
}
}
// dead is the first child that has exited, if any.
func (r *miniRun) dead() *miniChild {
for _, c := range r.children {
if c.exited() {
return c
}
}
return nil
}
// stop ends every child still running, the last started first: SIGTERM,
// a bounded wait, then SIGKILL. It is safe to call again.
func (r *miniRun) stop() {
for i := len(r.children) - 1; i >= 0; i-- {
c := r.children[i]
if c.exited() {
continue
}
fmt.Fprintf(r.out, "sw-block mini: stopping %s (pid %d)\n", c.name, c.cmd.Process.Pid)
if err := c.cmd.Process.Signal(syscall.SIGTERM); err != nil {
_ = c.cmd.Process.Kill()
}
select {
case <-c.done:
case <-time.After(miniStopWait):
fmt.Fprintf(r.out, "sw-block mini: %s did not exit within %s: killing it\n", c.name, miniStopWait)
_ = c.cmd.Process.Kill()
<-c.done
}
}
}
// tail prints the last lines of each child's log.
func (r *miniRun) tail(n int) {
for _, c := range r.children {
b, err := os.ReadFile(filepath.Join(r.cfg.Dir, c.name+".log"))
if err != nil {
continue
}
lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n")
if len(lines) > n {
lines = lines[len(lines)-n:]
}
fmt.Fprintf(r.log, "--- %s.log (last %d lines)\n%s\n", c.name, len(lines), strings.Join(lines, "\n"))
}
}
func runMini(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block mini", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.Usage = func() { fmt.Fprintln(stderr, miniUsage) }
cfg := miniConfig{Ports: defaultMiniPorts}
var size string
var shift int
fs.StringVar(&cfg.Dir, "dir", "./swb-mini", "data directory (refused if it exists, unless --reuse)")
fs.BoolVar(&cfg.Reuse, "reuse", false, "start again on an existing --dir")
fs.StringVar(&cfg.Weed, "weed", "", "SeaweedFS weed binary (default: weed on PATH)")
fs.StringVar(&cfg.Bin, "bin", "", "directory holding blockmaster and blockvolume (default: sw-block's own)")
fs.StringVar(&size, "size", "256MiB", "size of volume v1")
fs.StringVar(&cfg.NQN, "nqn", "nqn.2026-05.io.seaweedfs:v1", "NVMe subsystem NQN of v1")
fs.IntVar(&shift, "port-shift", 0, "move every port by this many (for a host where a default port is taken)")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 {
if err == nil {
fs.Usage()
}
return ops.VolumeStatusExitInvalid
}
if shift < 0 || shift > 10000 {
fmt.Fprintf(stderr, "sw-block mini: --port-shift %d out of range 0..10000\n", shift)
return ops.VolumeStatusExitInvalid
}
cfg.Ports, cfg.PortShift = cfg.Ports.shifted(shift), shift
cfg.Explicit = map[string]bool{}
fs.Visit(func(f *flag.Flag) { cfg.Explicit[f.Name] = true })
var err error
if cfg.SizeBytes, err = parseSize(size); err != nil {
fmt.Fprintf(stderr, "sw-block mini: %v\n", err)
return ops.VolumeStatusExitInvalid
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
code, err := mini(ctx, cfg, stdout, stderr)
if err != nil {
fmt.Fprintf(stderr, "sw-block mini: %v\n", err)
}
return code
}
// mini runs the configuration until ctx ends or a child exits.
func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, error) {
weed := cfg.Weed
if weed == "" {
weed, _ = exec.LookPath("weed")
} else if st, err := os.Stat(weed); err != nil || st.IsDir() {
return ops.VolumeStatusExitInvalid, fmt.Errorf("--weed %s not found", weed)
}
// A reuse takes the recorded run (its binaries included) before any
// lookup; a fresh start finds the binaries next to sw-block by default.
if cfg.Reuse {
if st, err := os.Stat(cfg.Dir); err != nil || !st.IsDir() {
return ops.VolumeStatusExitInvalid, fmt.Errorf("--reuse: %s is not an existing directory", cfg.Dir)
}
w, err := reuseMiniRecord(&cfg, weed)
if err != nil {
return ops.VolumeStatusExitInvalid, err
}
weed = w
}
if cfg.Bin == "" {
exe, err := os.Executable()
if err != nil {
return 1, fmt.Errorf("locate sw-block: %w (pass --bin)", err)
}
cfg.Bin = filepath.Dir(exe)
}
if abs, err := filepath.Abs(cfg.Bin); err == nil {
cfg.Bin = abs
}
master, volume := filepath.Join(cfg.Bin, "blockmaster"), filepath.Join(cfg.Bin, "blockvolume")
for _, b := range []string{master, volume} {
if st, err := os.Stat(b); err != nil || st.IsDir() {
return ops.VolumeStatusExitInvalid, fmt.Errorf("%s not found (pass --bin DIR)", b)
}
}
chunk := weed != ""
if !chunk {
fmt.Fprint(stdout, miniBanner())
}
ports := []int{cfg.Ports.Master, cfg.Ports.Data, cfg.Ports.Ctrl, cfg.Ports.Status, cfg.Ports.NVMe}
if chunk {
ports = append(ports, cfg.Ports.weed()...)
}
for _, p := range ports {
l, err := net.Listen("tcp", loopback(p))
if err != nil {
return ops.VolumeStatusExitInvalid, fmt.Errorf("port %d is in use: %v (move every port with --port-shift N)", p, err)
}
l.Close()
}
// The dir is claimed before anything is written: a fresh one by one
// exclusive mkdir, a reused one must exist; then a lock held for the run
// refuses a second mini on it.
if !cfg.Reuse {
if err := os.MkdirAll(filepath.Dir(filepath.Clean(cfg.Dir)), 0o755); err != nil {
return 1, err
}
if err := os.Mkdir(cfg.Dir, 0o755); err != nil {
if errors.Is(err, os.ErrExist) {
return ops.VolumeStatusExitInvalid, fmt.Errorf("%s exists: refusing to start over it (pass --reuse to start again on it, or another --dir)", cfg.Dir)
}
return 1, err
}
}
unlock, err := miniLock(cfg.Dir)
if err != nil {
return ops.VolumeStatusExitInvalid, err
}
defer unlock()
if !cfg.Reuse {
if err := writeMiniRecord(cfg.Dir, miniRecord{SizeBytes: cfg.SizeBytes, PortShift: cfg.PortShift, Weed: weed, NQN: cfg.NQN, Bin: cfg.Bin}); err != nil {
return 1, err
}
}
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol")} {
if err := os.MkdirAll(d, 0o755); err != nil {
return 1, err
}
}
r := &miniRun{cfg: cfg, out: stdout, log: stderr}
defer r.stop()
fail := func(err error) (int, error) {
r.tail(20)
return 1, err
}
if chunk {
if err := os.MkdirAll(filepath.Join(cfg.Dir, "weed"), 0o755); err != nil {
return 1, err
}
c, err := r.start("weed", weed, miniWeedArgs(cfg))
if err != nil {
return fail(err)
}
if err := r.ready(ctx, c, cfg.Ports.weed()...); err != nil {
return fail(err)
}
if err := os.WriteFile(filepath.Join(cfg.Dir, "cluster-spec.yaml"), []byte(miniClusterSpec(cfg)), 0o644); err != nil {
return fail(err)
}
} else if err := os.WriteFile(filepath.Join(cfg.Dir, "topology.yaml"), []byte(miniTopology()), 0o644); err != nil {
return fail(err)
}
mc, err := r.start("blockmaster", master, miniMasterArgs(cfg, chunk))
if err != nil {
return fail(err)
}
if err := r.ready(ctx, mc, cfg.Ports.Master); err != nil {
return fail(err)
}
layoutID := ""
if chunk {
fmt.Fprintf(stdout, "+ sw-block ops volume resolve --master %s %s\n", loopback(cfg.Ports.Master), miniVolume)
deadline := time.Now().Add(miniResolveWait)
for {
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
id, err := resolveVolumeID(rctx, loopback(cfg.Ports.Master), miniVolume)
rcancel()
if err == nil {
layoutID = id.String()
break
}
if d := r.dead(); d != nil {
return fail(fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, miniVolume, d.err))
}
if ctx.Err() != nil || time.Now().After(deadline) {
return fail(fmt.Errorf("resolve %s's layout id: %v", miniVolume, err))
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
}
vc, err := r.start("blockvolume", volume, miniVolumeArgs(cfg, chunk, layoutID))
if err != nil {
return fail(err)
}
if err := r.ready(ctx, vc, cfg.Ports.Status, cfg.Ports.NVMe); err != nil {
return fail(err)
}
miniNextSteps(stdout, cfg, chunk)
for {
for _, c := range r.children {
if c.exited() {
miniBeforeStop(stdout, cfg)
r.stop()
miniAfterStop(stdout, cfg)
return fail(fmt.Errorf("%s exited: %v; stopped the others", c.name, c.err))
}
}
select {
case <-ctx.Done():
fmt.Fprintln(stdout, "sw-block mini: interrupted: stopping")
miniBeforeStop(stdout, cfg)
r.stop()
miniAfterStop(stdout, cfg)
return 0, nil
case <-time.After(500 * time.Millisecond):
}
}
}
// miniCommands are the sw-block commands mini prints for the user to run
// next (without the leading "sw-block"): only commands this binary has.
func miniCommands(c miniConfig, chunk bool) [][]string {
if !chunk {
return nil
}
m, f := loopback(c.Ports.Master), loopback(c.Ports.WeedFG)
return [][]string{
{"ops", "workspace", "show", "--master", m, "--volume", miniVolume},
{"ops", "chunk", "snapshots", "--master", m, "--volume", miniVolume, "--chunk-filer", f},
{"ops", "chunk", "snapshot", "--volume", miniVolume, "--name", "first", "--status-addr", loopback(c.Ports.Status)},
}
}
func miniDisconnect(c miniConfig) string {
return "sudo nvme disconnect -n " + shQuote(c.NQN)
}
// shQuote is s as one POSIX shell word: as is when it has only safe
// characters, else single-quoted, so a printed command with a path that has
// a space or a quote runs as printed.
func shQuote(s string) string {
if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// miniResume is the command that starts the recorded run in c.Dir again.
func miniResume(c miniConfig) string {
return "sw-block mini --dir " + shQuote(c.Dir) + " --reuse"
}
// miniNextSteps prints what to run next; mini runs none of it.
func miniNextSteps(w io.Writer, c miniConfig, chunk bool) {
mode := map[bool]string{true: "walstore-chunk on weed mini", false: "walstore, no snapshots"}[chunk]
fmt.Fprintf(w, "\nsw-block mini: running (%s). Ctrl-C stops everything it started. Logs: %s/*.log\n", mode, shQuote(c.Dir))
fmt.Fprintln(w, "sw-block mini: trial setup: one host, loopback, no authentication.")
fmt.Fprintf(w, "\nAttach v1 (mini does not do this for you):\n sudo nvme connect -t tcp -a 127.0.0.1 -s %d -n %s --ctrl-loss-tmo=180 --reconnect-delay=2\n", c.Ports.NVMe, shQuote(c.NQN))
fmt.Fprintf(w, "Before stopping mini: unmount anything on v1, then\n %s\n(else a mounted filesystem sits on a stopped target while the kernel retries for 3 minutes)\n", miniDisconnect(c))
fmt.Fprintf(w, "\nStatus:\n curl -s 'http://%s/status?volume=%s'\n", loopback(c.Ports.Status), miniVolume)
if !chunk {
fmt.Fprintln(w, "\nsw-block mini: no chunk store: snapshots unavailable (run with weed for snapshots and restore)")
return
}
cmds := miniCommands(c, chunk)
fmt.Fprintf(w, "\nCheck the volume:\n sw-block %s\n sw-block %s\n", strings.Join(cmds[0], " "), strings.Join(cmds[1], " "))
fmt.Fprintf(w, "\nSnapshot:\n sw-block %s\n", strings.Join(cmds[2], " "))
fmt.Fprintf(w, "\nSeaweedFS itself: weed shell -master=%s\n", loopback(c.Ports.WeedMaster))
}
// miniBeforeStop reminds the user, before the target goes away, to have
// disconnected v1.
func miniBeforeStop(w io.Writer, c miniConfig) {
fmt.Fprintf(w, "sw-block mini: if v1 is connected: unmount it, then %s\n", miniDisconnect(c))
}
// miniAfterStop says where the data is and how to resume it.
func miniAfterStop(w io.Writer, c miniConfig) {
fmt.Fprintf(w, "sw-block mini: stopped. The data stays in %s. This starts it again, with this run's size, ports, mode, NQN and binaries (recorded in %s):\n %s\n", c.Dir, miniRecordFile, miniResume(c))
}