Files
seaweedfs/seaweed-block/internal/weedtest/cluster.go
T
Ping QiuandClaude Opus 5.5 a5686e7fa7 Sync seaweed-block v1.1.1 into seaweed-block/ (#13411)
Brings seaweed-block main (v1.1.1 plus the docs and a test fix after it)
into seaweed-block/ as one commit. Only files under seaweed-block/ change,
and the subtree equals seaweed-block main exactly. The module's full
history stays in the seaweed-block repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:04:53 -08:00

230 lines
6.9 KiB
Go

package weedtest
import (
"fmt"
"math/rand"
"net"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
// Starts is how many times a cluster that does not start (a server exits or
// never listens, or the cluster is never ready) is started again on fresh
// ports. A port pair is checked free and then released before weed binds
// it; another process on the host (a concurrent job on a shared runner) can
// take it in between. Each server's pair is picked just before that server
// starts, which keeps that window short.
var Starts = 3
// PickPair picks a server's port pair (role "master", "volume", "filer");
// a test replaces it to make a start collide with another process.
var PickPair = func(t testing.TB, used map[int]bool, role string) int {
t.Helper()
p, ok := FreeWeedPair(host, used)
if !ok {
t.Fatal("no free port pair")
}
return p
}
const host = "127.0.0.1"
// Options shape a cluster: the master's volume size limit (MB), the volume
// server's volume count (-max), the contents of a security.toml in the
// cluster's directory ("" for none), and Ready, which reports whether the
// started cluster serves (nil: its filer's gRPC port listens).
type Options struct {
SizeMB, Max int
Security string
Ready func(filerGRPC string) error
}
// Cluster is one started weed cluster.
type Cluster struct {
Master, FilerHTTP, FilerGRPC string
Dir string // this start's directory (server logs: <role>.log)
Starts []string // the directory of every start, the discarded ones first
procs []*proc
}
type proc struct {
role string
log *os.File
cmd *exec.Cmd
done chan struct{}
err error // the exit status, set before done closes
discarded bool // its start was discarded and its log already reported
}
// Start starts a cluster from the weed binary in dir, starting again on
// fresh ports (Starts times in all) while a start fails; the last failure
// fails t. The servers are stopped when t ends.
func Start(t testing.TB, weed, dir string, o Options) *Cluster {
t.Helper()
var starts []string
for attempt := 1; ; attempt++ {
at := dir
if attempt > 1 {
at = filepath.Join(dir, fmt.Sprintf("start-%d", attempt))
}
starts = append(starts, at)
c, err := startOnce(t, weed, at, o)
c.Starts = starts
if err == nil {
return c
}
if attempt >= Starts {
t.Fatalf("weed start %d of %d failed: %v", attempt, Starts, err)
}
t.Logf("weed start %d of %d failed, starting again on fresh ports: %v", attempt, Starts, err)
c.discard(t)
}
}
func startOnce(t testing.TB, weed, dir string, o Options) (*Cluster, error) {
t.Helper()
c := &Cluster{Dir: dir}
for _, d := range []string{"m", "v", "f"} {
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
t.Fatal(err)
}
}
if o.Security != "" {
if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(o.Security), 0o600); err != nil {
t.Fatal(err)
}
}
used := map[int]bool{}
mp := PickPair(t, used, "master")
c.Master = fmt.Sprintf("%s:%d", host, mp)
m := c.start(t, weed, "master", "master", "-ip="+host, fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.SizeMB), "-defaultReplication=000")
if err := c.listening(m, c.Master, 20*time.Second); err != nil {
return c, err
}
vp := PickPair(t, used, "volume")
c.start(t, weed, "volume", "volume", "-ip="+host, fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.Master, fmt.Sprintf("-max=%d", o.Max))
fp := PickPair(t, used, "filer")
c.FilerHTTP = fmt.Sprintf("%s:%d", host, fp)
c.FilerGRPC = fmt.Sprintf("%s:%d", host, fp+10000)
// Its own filer group: another cluster's filer that reaches this master
// (a port pair picked alike) is not counted by this cluster's census.
f := c.start(t, weed, "filer", "filer", "-ip="+host, fmt.Sprintf("-port=%d", fp), "-master="+c.Master, "-defaultStoreDir="+filepath.Join(dir, "f"), fmt.Sprintf("-filerGroup=swt%016x", rand.Uint64()))
if err := c.listening(f, c.FilerGRPC, 30*time.Second); err != nil {
return c, err
}
if o.Ready != nil {
deadline := time.Now().Add(60 * time.Second)
for {
err := o.Ready(c.FilerGRPC)
if err == nil {
break
}
if e := c.exited(); e != nil {
return c, fmt.Errorf("%w; not ready: %v", e, err)
}
if time.Now().After(deadline) {
return c, fmt.Errorf("the cluster was not ready within 60s: %w", err)
}
time.Sleep(500 * time.Millisecond)
}
}
// A server that could not bind its port has exited by now, even when
// another process answered on that port.
return c, c.exited()
}
// start launches one server of this start; it is stopped when t ends.
func (c *Cluster) start(t testing.TB, weed, role string, args ...string) *proc {
t.Helper()
logf, err := os.Create(filepath.Join(c.Dir, role+".log"))
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(weed, args...)
cmd.Stdout, cmd.Stderr, cmd.Dir = logf, logf, c.Dir
if err := cmd.Start(); err != nil {
t.Fatalf("start weed %s: %v", role, err)
}
p := &proc{role: role, log: logf, cmd: cmd, done: make(chan struct{})}
go func() {
p.err = cmd.Wait()
close(p.done)
}()
c.procs = append(c.procs, p)
t.Cleanup(func() {
if !p.stop() {
t.Errorf("weed %s did not exit after kill", role)
}
p.log.Close()
if t.Failed() && !p.discarded {
t.Logf("---- %s log tail (%s) ----\n%s", role, c.Dir, p.tail())
}
})
return p
}
// listening waits until addr accepts a connection while p runs.
func (c *Cluster) listening(p *proc, addr string, d time.Duration) error {
deadline := time.Now().Add(d)
for time.Now().Before(deadline) {
select {
case <-p.done:
return fmt.Errorf("weed %s exited (%v) before %s listened", p.role, p.err, addr)
default:
}
if conn, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil {
conn.Close()
return nil
}
time.Sleep(100 * time.Millisecond)
}
return fmt.Errorf("weed %s: %s not listening after %v", p.role, addr, d)
}
// exited reports a server of this start that has already exited.
func (c *Cluster) exited() error {
for _, p := range c.procs {
select {
case <-p.done:
return fmt.Errorf("weed %s exited (%v)", p.role, p.err)
default:
}
}
return nil
}
// discard stops a start that failed and logs each server's log tail.
func (c *Cluster) discard(t testing.TB) {
t.Helper()
for _, p := range c.procs {
if !p.stop() {
t.Errorf("weed %s did not exit after kill", p.role)
}
p.discarded = true
t.Logf("---- discarded start: %s log tail (%s) ----\n%s", p.role, c.Dir, p.tail())
}
}
// stop kills the server and waits for its exit; false when it did not exit
// within 5 s.
func (p *proc) stop() bool {
_ = p.cmd.Process.Kill()
select {
case <-p.done:
return true
case <-time.After(5 * time.Second):
return false
}
}
func (p *proc) tail() []byte {
b, _ := os.ReadFile(p.log.Name())
if len(b) > 4000 {
b = b[len(b)-4000:]
}
return b
}