mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
The resume command (now on its own line), the connect and disconnect commands and the logs path quote the dir and NQN for a POSIX shell, so a --dir with a space or a quote gives a line that runs as printed. Tests: shQuote round-trips through a shell-word split; the printed resume line, split as a shell splits it, reaches a spaced dir's recorded run, while the unquoted line does not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
803 lines
28 KiB
Go
803 lines
28 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// TestMain lets the test binary stand in for blockmaster and blockvolume:
|
|
// with SWB_MINI_FAKE_CHILD set it listens on the ports its flags name and
|
|
// waits for SIGTERM (or, with SWB_MINI_FAKE_CHILD=die-<name>, the named
|
|
// child exits a moment after it is ready).
|
|
func TestMain(m *testing.M) {
|
|
if mode := os.Getenv("SWB_MINI_FAKE_CHILD"); mode != "" {
|
|
os.Exit(fakeMiniChild(mode))
|
|
}
|
|
os.Exit(m.Run())
|
|
}
|
|
|
|
func fakeMiniChild(mode string) int {
|
|
name := filepath.Base(os.Args[0])
|
|
var ls []net.Listener
|
|
listen := func(addr string) bool {
|
|
l, err := net.Listen("tcp", addr)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
ls = append(ls, l)
|
|
return true
|
|
}
|
|
for i, a := range os.Args {
|
|
if (a == "--listen" || a == "--status-addr" || a == "--nvme-listen") && i+1 < len(os.Args) && !listen(os.Args[i+1]) {
|
|
return 3
|
|
}
|
|
if k, v, ok := strings.Cut(a, "="); ok && strings.HasPrefix(k, "-") && strings.Contains(k, ".port") && !listen("127.0.0.1:"+v) {
|
|
return 3
|
|
}
|
|
}
|
|
defer func() {
|
|
for _, l := range ls {
|
|
l.Close()
|
|
}
|
|
}()
|
|
term := make(chan os.Signal, 1)
|
|
signal.Notify(term, syscall.SIGTERM)
|
|
if mode == "die-"+name {
|
|
time.Sleep(500 * time.Millisecond)
|
|
return 9
|
|
}
|
|
<-term
|
|
return 0
|
|
}
|
|
|
|
// The standalone page's swb_start block, as flag -> value (a flag without a
|
|
// value maps to "").
|
|
func pageFlags(t *testing.T, binary string) map[string]string {
|
|
t.Helper()
|
|
b, err := os.ReadFile(filepath.Join("..", "..", "docs", "standalone-deployment.md"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
doc := strings.ReplaceAll(string(b), "\r\n", "\n")
|
|
i := strings.Index(doc, "../"+binary+" ")
|
|
if i < 0 {
|
|
t.Fatalf("no ../%s command in the page", binary)
|
|
}
|
|
line := doc[i:]
|
|
end := strings.Index(line, "&\n")
|
|
if end < 0 {
|
|
t.Fatalf("../%s command has no end", binary)
|
|
}
|
|
cmd := strings.ReplaceAll(line[:end], "\\\n", " ")
|
|
cmd = cmd[:strings.Index(cmd, ">")]
|
|
return flagMap(strings.Fields(cmd)[1:])
|
|
}
|
|
|
|
func flagMap(args []string) map[string]string {
|
|
out := map[string]string{}
|
|
for i := 0; i < len(args); i++ {
|
|
if !strings.HasPrefix(args[i], "--") {
|
|
continue
|
|
}
|
|
v := ""
|
|
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") {
|
|
v = strings.Trim(args[i+1], `"`)
|
|
i++
|
|
}
|
|
out[args[i-boolToInt(v != "")]] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
func boolToInt(b bool) int {
|
|
if b {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// isPath reports whether a page value is a path (mini puts paths under its
|
|
// --dir instead of the page's ./).
|
|
func isPath(v string) bool { return strings.HasPrefix(v, "./") }
|
|
|
|
// Without weed, mini runs blockmaster and blockvolume with exactly the
|
|
// standalone page's swb_start flags: the same names and, apart from paths
|
|
// (under --dir) and the size-derived block count, the same values.
|
|
func TestMiniWalstoreFlagsAreThePage(t *testing.T) {
|
|
cfg := miniConfig{Dir: "/tmp/m", NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: defaultMiniPorts}
|
|
for _, c := range []struct {
|
|
binary string
|
|
args []string
|
|
}{
|
|
{"blockmaster", miniMasterArgs(cfg, false)},
|
|
{"blockvolume", miniVolumeArgs(cfg, false, "")},
|
|
} {
|
|
page, got := pageFlags(t, c.binary), flagMap(c.args)
|
|
for f, pv := range page {
|
|
gv, ok := got[f]
|
|
switch {
|
|
case !ok:
|
|
t.Errorf("%s: the page passes %s; mini does not", c.binary, f)
|
|
case f == "--nvme-subsysnqn" && pv == "$NQN":
|
|
if gv != cfg.NQN {
|
|
t.Errorf("%s %s: mini %q, want the NQN %q", c.binary, f, gv, cfg.NQN)
|
|
}
|
|
case isPath(pv):
|
|
if !strings.HasPrefix(gv, filepath.Clean(cfg.Dir)) {
|
|
t.Errorf("%s %s: mini %q is not under --dir", c.binary, f, gv)
|
|
}
|
|
case gv != pv:
|
|
t.Errorf("%s %s: mini %q, the page %q", c.binary, f, gv, pv)
|
|
}
|
|
}
|
|
for f := range got {
|
|
if _, ok := page[f]; !ok {
|
|
t.Errorf("%s: mini passes %s; the page's swb_start does not", c.binary, f)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// With weed, every flag mini passes is one the page documents.
|
|
func TestMiniChunkFlagsAreDocumented(t *testing.T) {
|
|
b, err := os.ReadFile(filepath.Join("..", "..", "docs", "standalone-deployment.md"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
doc := string(b)
|
|
cfg := miniConfig{Dir: "/tmp/m", NQN: "n", SizeBytes: 256 << 20, Ports: defaultMiniPorts}
|
|
for _, args := range [][]string{miniMasterArgs(cfg, true), miniVolumeArgs(cfg, true, "00112233445566778899aabbccddeeff")} {
|
|
for f := range flagMap(args) {
|
|
if !strings.Contains(doc, "`"+f) && !strings.Contains(doc, f+" ") {
|
|
t.Errorf("mini passes %s, which the standalone page does not document", f)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestMiniSize(t *testing.T) {
|
|
for in, want := range map[string]uint64{"256MiB": 256 << 20, "1GiB": 1 << 30, "4096": 4096, "2M": 2 << 20} {
|
|
if got, err := parseSize(in); err != nil || got != want {
|
|
t.Errorf("parseSize(%q) = %d %v, want %d", in, got, err, want)
|
|
}
|
|
}
|
|
for _, in := range []string{"", "0", "-1MiB", "100", "1.5GiB", "abc", "17179869184GiB", "17179869185GiB", "18446744073709551615K"} {
|
|
if _, err := parseSize(in); err == nil {
|
|
t.Errorf("parseSize(%q) accepted", in)
|
|
}
|
|
}
|
|
}
|
|
|
|
// fakeBin makes a directory whose blockmaster and blockvolume are copies of
|
|
// the test binary (see TestMain).
|
|
func fakeBin(t *testing.T) string {
|
|
t.Helper()
|
|
self, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
raw, err := os.ReadFile(self)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dir := t.TempDir()
|
|
for _, n := range []string{"blockmaster", "blockvolume", "weed"} {
|
|
if err := os.WriteFile(filepath.Join(dir, n), raw, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
return dir
|
|
}
|
|
|
|
func freePorts(t *testing.T) miniPorts {
|
|
t.Helper()
|
|
var ps []int
|
|
var ls []net.Listener
|
|
for i := 0; i < 13; i++ {
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ls = append(ls, l)
|
|
ps = append(ps, l.Addr().(*net.TCPAddr).Port)
|
|
}
|
|
for _, l := range ls {
|
|
l.Close()
|
|
}
|
|
return miniPorts{Master: ps[0], Data: ps[1], Ctrl: ps[2], Status: ps[3], NVMe: ps[4],
|
|
WeedMaster: ps[5], WeedMasterG: ps[6], WeedVolume: ps[7], WeedVolumeG: ps[8], WeedFiler: ps[9], WeedFG: ps[10],
|
|
WeedAdmin: ps[11], WeedAdminG: ps[12]}
|
|
}
|
|
|
|
// The refusals happen before anything starts: an existing --dir without
|
|
// --reuse, a missing binary, a busy port. Without weed the banner comes
|
|
// first.
|
|
func TestMiniRefusesBeforeStarting(t *testing.T) {
|
|
t.Setenv("PATH", t.TempDir()) // no weed on PATH
|
|
bin := fakeBin(t)
|
|
base := func() miniConfig {
|
|
return miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
|
}
|
|
t.Run("existing dir", func(t *testing.T) {
|
|
c := base()
|
|
if err := os.MkdirAll(c.Dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var out bytes.Buffer
|
|
code, err := mini(context.Background(), c, &out, io.Discard)
|
|
if code == 0 || err == nil || !strings.Contains(err.Error(), "--reuse") {
|
|
t.Fatalf("existing dir: code %d err %v; want a refusal naming --reuse", code, err)
|
|
}
|
|
if !strings.HasPrefix(out.String(), miniBanner()) {
|
|
t.Fatalf("the fallback banner is not the first output:\n%s", out.String())
|
|
}
|
|
})
|
|
t.Run("missing binary", func(t *testing.T) {
|
|
c := base()
|
|
c.Bin = t.TempDir()
|
|
if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "blockmaster") {
|
|
t.Fatalf("missing blockmaster: code %d err %v", code, err)
|
|
}
|
|
})
|
|
t.Run("busy port", func(t *testing.T) {
|
|
c := base()
|
|
l, err := net.Listen("tcp", loopback(c.Ports.NVMe))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer l.Close()
|
|
code, err := mini(context.Background(), c, io.Discard, io.Discard)
|
|
if code == 0 || err == nil || !strings.Contains(err.Error(), strconv.Itoa(c.Ports.NVMe)) {
|
|
t.Fatalf("busy port: code %d err %v", code, err)
|
|
}
|
|
if _, err := os.Stat(c.Dir); err == nil {
|
|
t.Fatal("a refused start created --dir")
|
|
}
|
|
})
|
|
}
|
|
|
|
type syncBuf struct {
|
|
mu sync.Mutex
|
|
b bytes.Buffer
|
|
}
|
|
|
|
func (s *syncBuf) Write(p []byte) (int, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.b.Write(p)
|
|
}
|
|
|
|
func (s *syncBuf) String() string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.b.String()
|
|
}
|
|
|
|
func waitOutput(t *testing.T, out *syncBuf, want string) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(20 * time.Second)
|
|
for !strings.Contains(out.String(), want) {
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("no %q in mini's output:\n%s", want, out.String())
|
|
}
|
|
time.Sleep(50 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
// pidsOf returns the pid of each "+ <bin>/<name>" child mini started, from
|
|
// the stop lines it printed.
|
|
var stoppedRE = regexp.MustCompile(`stopping (\w+) \(pid (\d+)\)`)
|
|
|
|
// Ctrl-C stops every child, the last started first, and leaves none running;
|
|
// mini prints each command before it runs it and the connect command, which
|
|
// it does not run.
|
|
func TestMiniInterruptStopsEveryChild(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("signals and listening children: Linux")
|
|
}
|
|
t.Setenv("PATH", t.TempDir())
|
|
t.Setenv("SWB_MINI_FAKE_CHILD", "serve")
|
|
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: fakeBin(t), NQN: "nqn.test:v1", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
out := &syncBuf{}
|
|
done := make(chan int, 1)
|
|
go func() { code, _ := mini(ctx, c, out, io.Discard); done <- code }()
|
|
joined := false
|
|
t.Cleanup(func() { // registered before any assertion: a failure never leaks mini or its children
|
|
cancel()
|
|
if !joined {
|
|
select {
|
|
case <-done:
|
|
case <-time.After(30 * time.Second):
|
|
t.Error("mini did not stop at cleanup")
|
|
}
|
|
}
|
|
})
|
|
waitOutput(t, out, "sw-block mini: running")
|
|
for _, want := range []string{"+ " + filepath.Join(c.Bin, "blockmaster") + " ", "+ " + filepath.Join(c.Bin, "blockvolume") + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
|
|
"sw-block mini: no chunk store: snapshots unavailable", "trial setup: one host, loopback, no authentication"} {
|
|
if !strings.Contains(out.String(), want) {
|
|
t.Fatalf("output lacks %q:\n%s", want, out.String())
|
|
}
|
|
}
|
|
cancel()
|
|
select {
|
|
case code := <-done:
|
|
joined = true
|
|
if code != 0 {
|
|
t.Fatalf("interrupted mini exited %d", code)
|
|
}
|
|
case <-time.After(30 * time.Second):
|
|
t.Fatal("mini did not stop")
|
|
}
|
|
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + miniResume(c) + "\n"} {
|
|
if !strings.Contains(out.String(), want) {
|
|
t.Fatalf("at stop, output lacks %q:\n%s", want, out.String())
|
|
}
|
|
}
|
|
if strings.Contains(out.String(), "cluster.check") || strings.Contains(out.String(), "sw-block shell") {
|
|
t.Fatal("mini prints a check or a shell this binary does not have")
|
|
}
|
|
stops := stoppedRE.FindAllStringSubmatch(out.String(), -1)
|
|
if len(stops) != 2 || stops[0][1] != "blockvolume" || stops[1][1] != "blockmaster" {
|
|
t.Fatalf("stop order %v; want blockvolume then blockmaster", stops)
|
|
}
|
|
for _, s := range stops {
|
|
pid, _ := strconv.Atoi(s[2])
|
|
if processAlive(pid) {
|
|
t.Fatalf("%s (pid %d) still runs after mini stopped", s[1], pid)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A child that exits stops the others, and mini exits non-zero.
|
|
func TestMiniDeadChildStopsTheRest(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("signals and listening children: Linux")
|
|
}
|
|
t.Setenv("PATH", t.TempDir())
|
|
t.Setenv("SWB_MINI_FAKE_CHILD", "die-blockvolume")
|
|
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: fakeBin(t), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
|
out := &syncBuf{}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
defer cancel()
|
|
code, err := mini(ctx, c, out, io.Discard)
|
|
if code == 0 || err == nil || !strings.Contains(err.Error(), "blockvolume") {
|
|
t.Fatalf("a dead blockvolume: code %d err %v; want a non-zero exit naming it", code, err)
|
|
}
|
|
stops := stoppedRE.FindAllStringSubmatch(out.String(), -1)
|
|
if len(stops) != 1 || stops[0][1] != "blockmaster" {
|
|
t.Fatalf("stopped %v; want blockmaster stopped after blockvolume died", stops)
|
|
}
|
|
pid, _ := strconv.Atoi(stops[0][2])
|
|
if processAlive(pid) {
|
|
t.Fatalf("blockmaster (pid %d) still runs", pid)
|
|
}
|
|
}
|
|
|
|
// processAlive reports whether pid still runs (signal 0).
|
|
func processAlive(pid int) bool {
|
|
p, err := os.FindProcess(pid)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return p.Signal(syscall.Signal(0)) == nil
|
|
}
|
|
|
|
// Every sw-block command mini prints is one this binary parses: run against
|
|
// ports where nothing listens, it may fail to connect, never on its flags.
|
|
// A control with an unknown flag shows the check sees a flag error.
|
|
func TestMiniPrintedCommandsParse(t *testing.T) {
|
|
c := miniConfig{Dir: t.TempDir(), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
|
cmds := miniCommands(c, true)
|
|
if len(cmds) == 0 {
|
|
t.Fatal("no commands")
|
|
}
|
|
flagError := func(args []string) (bool, string) {
|
|
var errb bytes.Buffer
|
|
run(args, io.Discard, &errb)
|
|
e := errb.String()
|
|
return strings.Contains(e, "flag provided but not defined") || strings.Contains(e, "usage:"), e
|
|
}
|
|
for _, args := range cmds {
|
|
if bad, e := flagError(args); bad {
|
|
t.Errorf("sw-block %s: refused its own flags: %s", strings.Join(args, " "), e)
|
|
}
|
|
}
|
|
if bad, _ := flagError(append(append([]string{}, cmds[0]...), "--no-such-flag")); !bad {
|
|
t.Fatal("control: an unknown flag was not reported as a flag error")
|
|
}
|
|
if miniCommands(c, false) != nil {
|
|
t.Fatal("without weed mini prints sw-block commands that need a chunk store")
|
|
}
|
|
}
|
|
|
|
// wantChunkCommands is the supported configuration's three commands, pinned
|
|
// value for value; only the run's dir, the minted layout id and the ports
|
|
// (here the defaults) vary between runs.
|
|
func wantChunkCommands(dir, id string) map[string][]string {
|
|
return map[string][]string{
|
|
"weed": {"mini", "-dir=" + filepath.Join(dir, "weed"), "-ip=127.0.0.1", "-ip.bind=127.0.0.1",
|
|
"-master.port=9333", "-master.port.grpc=19333", "-volume.port=9340", "-volume.port.grpc=19340",
|
|
"-filer.port=8888", "-filer.port.grpc=18888", "-admin.port=12535", "-admin.port.grpc=22535", "-admin.port.legacy=0",
|
|
"-s3=false", "-webdav=false", "-admin.ui=false"},
|
|
"blockmaster": {"--authority-store", filepath.Join(dir, "master", "authority"), "--lifecycle-store", filepath.Join(dir, "master", "lifecycle"),
|
|
"--cluster-spec", filepath.Join(dir, "cluster-spec.yaml"), "--expected-slots-per-volume", "1", "--listen", "127.0.0.1:9180",
|
|
"--workspace-rpc", "--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks"},
|
|
"blockvolume": {"--master", "127.0.0.1:9180", "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
|
|
"--data-addr", "127.0.0.1:9201", "--ctrl-addr", "127.0.0.1:9202", "--status-addr", "127.0.0.1:9203",
|
|
"--durable-root", filepath.Join(dir, "vol"), "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096",
|
|
"--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks", "--chunk-control-endpoint", "--workspace-lease", "--layout-id", id,
|
|
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"},
|
|
}
|
|
}
|
|
|
|
func sameArgs(a, b []string) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
for i := range a {
|
|
if a[i] != b[i] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// With weed, mini's weed, blockmaster and blockvolume commands are exactly
|
|
// the pinned ones; controls: a changed value and a dropped required flag
|
|
// are seen.
|
|
func TestMiniChunkCommandsArePinned(t *testing.T) {
|
|
dir, id := "/tmp/m", "00112233445566778899aabbccddeeff"
|
|
cfg := miniConfig{Dir: dir, NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: defaultMiniPorts}
|
|
got := map[string][]string{"weed": miniWeedArgs(cfg), "blockmaster": miniMasterArgs(cfg, true), "blockvolume": miniVolumeArgs(cfg, true, id)}
|
|
want := wantChunkCommands(dir, id)
|
|
for name, w := range want {
|
|
if !sameArgs(got[name], w) {
|
|
t.Errorf("%s with weed:\n got %q\n want %q", name, got[name], w)
|
|
}
|
|
}
|
|
slots := append([]string{}, want["blockmaster"]...)
|
|
slots[7] = "2" // --expected-slots-per-volume
|
|
if sameArgs(slots, want["blockmaster"]) {
|
|
t.Fatal("control: a changed value compares equal")
|
|
}
|
|
dropped := append([]string{}, want["weed"][:3]...)
|
|
dropped = append(dropped, want["weed"][4:]...) // without -ip.bind
|
|
if sameArgs(dropped, want["weed"]) {
|
|
t.Fatal("control: a dropped flag compares equal")
|
|
}
|
|
}
|
|
|
|
// --port-shift moves every port, weed's included.
|
|
func TestMiniPortShiftMovesEveryPort(t *testing.T) {
|
|
a, b := defaultMiniPorts, defaultMiniPorts.shifted(1000)
|
|
all := func(p miniPorts) []int { return append([]int{p.Master, p.Data, p.Ctrl, p.Status, p.NVMe}, p.weed()...) }
|
|
pa, pb := all(a), all(b)
|
|
for i := range pa {
|
|
if pb[i] != pa[i]+1000 {
|
|
t.Fatalf("port %d not shifted: %d -> %d", i, pa[i], pb[i])
|
|
}
|
|
}
|
|
if len(pa) != 13 {
|
|
t.Fatalf("%d ports; mini owns 13", len(pa))
|
|
}
|
|
}
|
|
|
|
// With weed, a busy port of weed's (here its master gRPC, one weed would
|
|
// otherwise pick by itself) is refused before anything starts.
|
|
func TestMiniRefusesABusyWeedPort(t *testing.T) {
|
|
bin := fakeBin(t)
|
|
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: filepath.Join(bin, "weed"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
|
l, err := net.Listen("tcp", loopback(c.Ports.WeedMasterG))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer l.Close()
|
|
code, err := mini(context.Background(), c, io.Discard, io.Discard)
|
|
if code == 0 || err == nil || !strings.Contains(err.Error(), strconv.Itoa(c.Ports.WeedMasterG)) {
|
|
t.Fatalf("busy weed master gRPC port: code %d err %v", code, err)
|
|
}
|
|
}
|
|
|
|
// One mini per dir: a second start on a dir another mini holds is refused
|
|
// before it writes, fresh or with --reuse; --reuse of a dir that does not
|
|
// exist is refused too.
|
|
func TestMiniDirIsOwnedByOneMini(t *testing.T) {
|
|
t.Setenv("PATH", t.TempDir())
|
|
bin := fakeBin(t)
|
|
dir := filepath.Join(t.TempDir(), "run")
|
|
if err := os.Mkdir(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
unlock, err := miniLock(dir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer unlock()
|
|
c := miniConfig{Dir: dir, Bin: bin, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t), Reuse: true}
|
|
if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "in use") {
|
|
t.Fatalf("--reuse of a held dir: code %d err %v; want a refusal", code, err)
|
|
}
|
|
if entries, _ := os.ReadDir(dir); len(entries) != 2 { // the lock and the record only
|
|
t.Fatalf("the refused start wrote into the held dir: %v", entries)
|
|
}
|
|
c.Reuse = false
|
|
if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "--reuse") {
|
|
t.Fatalf("fresh start on a held dir: code %d err %v; want a refusal", code, err)
|
|
}
|
|
c.Dir, c.Reuse = filepath.Join(t.TempDir(), "absent"), true
|
|
if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "not an existing directory") {
|
|
t.Fatalf("--reuse of an absent dir: code %d err %v", code, err)
|
|
}
|
|
}
|
|
|
|
// A weed that dies while mini waits for blockmaster's layout id stops the
|
|
// rest at once, not at the resolve's 60 s bound.
|
|
func TestMiniWeedDyingDuringStartupStopsTheRest(t *testing.T) {
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("signals and listening children: Linux")
|
|
}
|
|
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
|
|
bin := fakeBin(t)
|
|
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: filepath.Join(bin, "weed"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
defer cancel()
|
|
out := &syncBuf{}
|
|
start := time.Now()
|
|
code, err := mini(ctx, c, out, io.Discard)
|
|
if code == 0 || err == nil || !strings.Contains(err.Error(), "weed") {
|
|
t.Fatalf("weed died during startup: code %d err %v; want a failure naming weed", code, err)
|
|
}
|
|
if took := time.Since(start); took > 20*time.Second {
|
|
t.Fatalf("the death was seen after %s; want at once", took)
|
|
}
|
|
for _, s := range stoppedRE.FindAllStringSubmatch(out.String(), -1) {
|
|
pid, _ := strconv.Atoi(s[2])
|
|
if processAlive(pid) {
|
|
t.Fatalf("%s (pid %d) still runs", s[1], pid)
|
|
}
|
|
}
|
|
}
|
|
|
|
// --reuse starts the recorded run again: its size, ports, mode (its weed)
|
|
// and NQN, whatever the defaults are; a flag that differs from the record
|
|
// is refused, and so are a recorded weed that is gone and a walstore run
|
|
// while a weed is found.
|
|
func TestMiniReuseRestoresTheRecordedRun(t *testing.T) {
|
|
weed := filepath.Join(t.TempDir(), "weed")
|
|
if err := os.WriteFile(weed, []byte("x"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
bin := t.TempDir()
|
|
rec := miniRecord{SizeBytes: 1 << 30, PortShift: 1000, Weed: weed, NQN: "nqn.custom:v1", Bin: bin}
|
|
dir := t.TempDir()
|
|
if err := writeMiniRecord(dir, rec); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defaults := func() miniConfig {
|
|
return miniConfig{Dir: dir, NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: defaultMiniPorts, Reuse: true, Explicit: map[string]bool{}}
|
|
}
|
|
c := defaults()
|
|
got, err := reuseMiniRecord(&c, "")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got != weed || c.Weed != weed || c.SizeBytes != rec.SizeBytes || c.NQN != rec.NQN || c.PortShift != 1000 || c.Ports != defaultMiniPorts.shifted(1000) || c.Bin != bin {
|
|
t.Fatalf("reuse loaded %+v (weed %q); want the recorded run %+v", c, got, rec)
|
|
}
|
|
c = defaults()
|
|
c.Explicit["size"] = true
|
|
if _, err := reuseMiniRecord(&c, ""); err == nil || !strings.Contains(err.Error(), "--size") {
|
|
t.Fatalf("a --size that differs from the record: %v; want a refusal", err)
|
|
}
|
|
c = defaults()
|
|
c.Bin, c.Explicit["bin"] = t.TempDir(), true
|
|
if _, err := reuseMiniRecord(&c, ""); err == nil || !strings.Contains(err.Error(), "--bin") {
|
|
t.Fatalf("a --bin that differs from the record: %v; want a refusal", err)
|
|
}
|
|
c = defaults()
|
|
c.SizeBytes, c.Explicit["size"] = rec.SizeBytes, true
|
|
if _, err := reuseMiniRecord(&c, ""); err != nil {
|
|
t.Fatalf("a --size equal to the record: %v", err)
|
|
}
|
|
if err := os.Remove(weed); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c = defaults()
|
|
if _, err := reuseMiniRecord(&c, ""); err == nil || !strings.Contains(err.Error(), "not there now") {
|
|
t.Fatalf("a recorded weed that is gone: %v; want a refusal, not a walstore fall back", err)
|
|
}
|
|
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c = defaults()
|
|
if _, err := reuseMiniRecord(&c, "/usr/bin/weed"); err == nil || !strings.Contains(err.Error(), "walstore") {
|
|
t.Fatalf("a walstore run reused while a weed is found: %v; want a refusal", err)
|
|
}
|
|
c = defaults()
|
|
if _, err := reuseMiniRecord(&miniConfig{Dir: t.TempDir(), Explicit: map[string]bool{}}, ""); err == nil {
|
|
t.Fatal("a dir without a record was reused")
|
|
}
|
|
_ = c
|
|
}
|
|
|
|
// End to end through mini: a run started with an explicit --bin records it,
|
|
// and a bare --reuse finds the same binaries (none are next to the test
|
|
// binary), stopping before any start only on its busy port.
|
|
func TestMiniReuseFindsTheRecordedBinaries(t *testing.T) {
|
|
t.Setenv("PATH", t.TempDir())
|
|
bin := fakeBin(t)
|
|
dir := filepath.Join(t.TempDir(), "run")
|
|
ports := freePorts(t)
|
|
c := miniConfig{Dir: dir, Bin: bin, NQN: "n", SizeBytes: 1 << 20, Ports: ports, Explicit: map[string]bool{"bin": true}}
|
|
l, err := net.Listen("tcp", loopback(ports.NVMe)) // stop each run before it starts children
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer l.Close()
|
|
if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "in use") {
|
|
t.Fatalf("setup: the fresh run should stop at the busy port: %d %v", code, err)
|
|
}
|
|
// The busy port refused before the dir was claimed: claim it as a real
|
|
// first run would, with the record.
|
|
if err := os.Mkdir(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n", Bin: bin}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r := miniConfig{Dir: dir, NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: ports, Reuse: true, Explicit: map[string]bool{}}
|
|
code, err := mini(context.Background(), r, io.Discard, io.Discard)
|
|
if err == nil || strings.Contains(err.Error(), "not found") || !strings.Contains(err.Error(), "in use") {
|
|
t.Fatalf("bare --reuse: %d %v; want the recorded binaries found (then the busy port)", code, err)
|
|
}
|
|
}
|
|
|
|
// shellWords splits a line as a POSIX shell does for words: blanks separate,
|
|
// '...' is literal, "..." keeps blanks (backslash escapes \\ \" \$ \`), and a
|
|
// backslash outside quotes escapes the next character.
|
|
func shellWords(line string) ([]string, error) {
|
|
var words []string
|
|
var w strings.Builder
|
|
in, quote := false, byte(0)
|
|
for i := 0; i < len(line); i++ {
|
|
ch := line[i]
|
|
switch {
|
|
case quote == '\'':
|
|
if ch == '\'' {
|
|
quote = 0
|
|
} else {
|
|
w.WriteByte(ch)
|
|
}
|
|
case quote == '"':
|
|
if ch == '"' {
|
|
quote = 0
|
|
} else if ch == '\\' && i+1 < len(line) && strings.IndexByte("\\\"$`", line[i+1]) >= 0 {
|
|
i++
|
|
w.WriteByte(line[i])
|
|
} else {
|
|
w.WriteByte(ch)
|
|
}
|
|
case ch == '\'' || ch == '"':
|
|
quote, in = ch, true
|
|
case ch == '\\' && i+1 < len(line):
|
|
i++
|
|
w.WriteByte(line[i])
|
|
in = true
|
|
case ch == ' ' || ch == '\t':
|
|
if in {
|
|
words = append(words, w.String())
|
|
w.Reset()
|
|
in = false
|
|
}
|
|
default:
|
|
w.WriteByte(ch)
|
|
in = true
|
|
}
|
|
}
|
|
if quote != 0 {
|
|
return nil, fmt.Errorf("unterminated %c quote", quote)
|
|
}
|
|
if in {
|
|
words = append(words, w.String())
|
|
}
|
|
return words, nil
|
|
}
|
|
|
|
func TestShQuoteRoundTrips(t *testing.T) {
|
|
for _, in := range []string{"plain", "/tmp/a b", "it's", `a"b`, "$HOME", "a\\b", "", "x;rm -rf y", "nqn.2026-05.io.seaweedfs:v1"} {
|
|
got, err := shellWords("cmd " + shQuote(in))
|
|
if err != nil || len(got) != 2 || got[1] != in {
|
|
t.Errorf("shQuote(%q) = %s: the shell reads %q (%v)", in, shQuote(in), got, err)
|
|
}
|
|
}
|
|
if shQuote("nqn.2026-05.io.seaweedfs:v1") != "nqn.2026-05.io.seaweedfs:v1" {
|
|
t.Error("a safe word was quoted")
|
|
}
|
|
}
|
|
|
|
// The printed resume line, run as printed (split as a shell splits it), on
|
|
// a dir with a space and a quote, reaches that dir's recorded run: it stops
|
|
// only at the lock this test holds, naming the dir. Control: the same line
|
|
// with the dir unquoted is not that command.
|
|
func TestMiniPrintedResumeRunsOnASpacedDir(t *testing.T) {
|
|
t.Setenv("PATH", t.TempDir())
|
|
bin := fakeBin(t)
|
|
dir := filepath.Join(t.TempDir(), "my run's dir")
|
|
if err := os.Mkdir(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
shift := -1
|
|
for s := 3000; s <= 10000 && shift < 0; s += 37 { // a shift whose walstore ports are free here
|
|
p, free := defaultMiniPorts.shifted(s), true
|
|
for _, port := range []int{p.Master, p.Data, p.Ctrl, p.Status, p.NVMe} {
|
|
l, err := net.Listen("tcp", loopback(port))
|
|
if err != nil {
|
|
free = false
|
|
break
|
|
}
|
|
l.Close()
|
|
}
|
|
if free {
|
|
shift = s
|
|
}
|
|
}
|
|
if shift < 0 {
|
|
t.Skip("no free shifted ports")
|
|
}
|
|
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, PortShift: shift, NQN: "n", Bin: bin}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
unlock, err := miniLock(dir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer unlock()
|
|
var out bytes.Buffer
|
|
miniAfterStop(&out, miniConfig{Dir: dir})
|
|
var line string
|
|
for _, l := range strings.Split(out.String(), "\n") {
|
|
if strings.HasPrefix(strings.TrimSpace(l), "sw-block mini ") {
|
|
line = strings.TrimSpace(l)
|
|
}
|
|
}
|
|
runLine := func(line string) (int, string) {
|
|
words, err := shellWords(line)
|
|
if err != nil {
|
|
return -1, err.Error()
|
|
}
|
|
if len(words) < 2 || words[0] != "sw-block" || words[1] != "mini" {
|
|
return -1, fmt.Sprintf("not a sw-block mini command: %q", words)
|
|
}
|
|
var errb bytes.Buffer
|
|
code := runMini(words[2:], io.Discard, &errb)
|
|
return code, errb.String()
|
|
}
|
|
code, e := runLine(line)
|
|
if code == 0 || !strings.Contains(e, dir+" is in use") {
|
|
t.Fatalf("the printed line %s: exit %d, %q; want it to reach %s (held here)", line, code, e, dir)
|
|
}
|
|
raw := "sw-block mini --dir " + dir + " --reuse"
|
|
if code, e := runLine(raw); strings.Contains(e, dir+" is in use") {
|
|
t.Fatalf("control: the unquoted line reached the dir too (exit %d)", code)
|
|
}
|
|
}
|