//go:build linux package fuse_handover import ( "bufio" "fmt" "net/http" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "syscall" "testing" "time" "github.com/stretchr/testify/require" "github.com/seaweedfs/seaweedfs/test/testutil" ) // weedProc is a weed process of the test, with its output in a log file. type weedProc struct { name string cmd *exec.Cmd logPath string done chan struct{} err error // set before done is closed } func (p *weedProc) exited() (bool, error) { select { case <-p.done: return true, p.err default: return false, nil } } func (p *weedProc) log() string { b, _ := os.ReadFile(p.logPath) return string(b) } // waitLog waits for a line containing substr in the log and returns the last such line. func (p *weedProc) waitLog(substr string, timeout time.Duration) (string, error) { deadline := time.Now().Add(timeout) for { last := "" for _, line := range strings.Split(p.log(), "\n") { if strings.Contains(line, substr) { last = line } } if last != "" { return last, nil } if exited, err := p.exited(); exited { // It may have logged and exited between the read above and now. for _, line := range strings.Split(p.log(), "\n") { if strings.Contains(line, substr) { last = line } } if last != "" { return last, nil } return "", fmt.Errorf("%s exited (%v) before logging %q", p.name, err, substr) } if time.Now().After(deadline) { return "", fmt.Errorf("%s did not log %q within %v", p.name, substr, timeout) } time.Sleep(20 * time.Millisecond) } } func (p *weedProc) wait(timeout time.Duration) (error, bool) { select { case <-p.done: return p.err, true case <-time.After(timeout): return nil, false } } type cluster struct { t testing.TB weed string base string filer string // host:port.grpcPort, as -filer takes it filerURL string mini *weedProc mu sync.Mutex procs []*weedProc } func findWeed(t testing.TB) string { if p := os.Getenv("WEED_BINARY"); p != "" { return p } if p, err := exec.LookPath("weed"); err == nil { return p } t.Skip("weed binary not found: build one with `go build -o /path/weed ./weed` and set WEED_BINARY") return "" } func (c *cluster) start(name string, env []string, args ...string) *weedProc { logPath := filepath.Join(c.base, name+".log") lf, err := os.Create(logPath) require.NoError(c.t, err) cmd := exec.Command(c.weed, args...) cmd.Stdout, cmd.Stderr = lf, lf cmd.Env = append(os.Environ(), env...) require.NoError(c.t, cmd.Start()) p := &weedProc{name: name, cmd: cmd, logPath: logPath, done: make(chan struct{})} go func() { p.err = cmd.Wait() lf.Close() close(p.done) }() c.mu.Lock() c.procs = append(c.procs, p) c.mu.Unlock() return p } // startCluster starts weed mini, and arranges for everything the test starts // to be stopped, and every mount below the test directory to be unmounted. func startCluster(t *testing.T) *cluster { c := &cluster{t: t, weed: findWeed(t)} if _, err := os.Stat("/dev/fuse"); err != nil { t.Skip("no /dev/fuse") } var err error c.base, err = os.MkdirTemp("", "fuse_handover_") require.NoError(t, err) t.Cleanup(c.stop) ports, err := testutil.AllocatePorts(11) require.NoError(t, err) filerPort, filerGrpc := ports[0], ports[1] c.filer = fmt.Sprintf("127.0.0.1:%d.%d", filerPort, filerGrpc) c.filerURL = fmt.Sprintf("127.0.0.1:%d", filerPort) dataDir := filepath.Join(c.base, "data") require.NoError(t, os.MkdirAll(dataDir, 0o755)) c.mini = c.start("mini", nil, "-logtostderr=true", "mini", "-dir="+dataDir, "-ip=127.0.0.1", "-ip.bind=127.0.0.1", "-master.port="+strconv.Itoa(ports[2]), "-master.port.grpc="+strconv.Itoa(ports[3]), "-volume.port="+strconv.Itoa(ports[4]), "-volume.port.grpc="+strconv.Itoa(ports[5]), "-filer.port="+strconv.Itoa(filerPort), "-filer.port.grpc="+strconv.Itoa(filerGrpc), "-mq.broker.port="+strconv.Itoa(ports[6]), "-admin.port="+strconv.Itoa(ports[7]), "-admin.port.grpc="+strconv.Itoa(ports[8]), "-admin.port.legacy=0", "-debug.port="+strconv.Itoa(ports[9]), "-s3=false", "-webdav=false", "-admin.ui=false", "-vector=false", "-master.telemetry=false", ) require.NoError(t, c.waitHealthy(60*time.Second), "weed mini not ready:\n%s", c.mini.log()) return c } func (c *cluster) waitHealthy(timeout time.Duration) error { deadline := time.Now().Add(timeout) client := &http.Client{Timeout: time.Second} for time.Now().Before(deadline) { resp, err := client.Get("http://" + c.filerURL + "/healthz") if err == nil { resp.Body.Close() if resp.StatusCode == http.StatusOK { return nil } } if exited, err := c.mini.exited(); exited { return fmt.Errorf("mini exited: %v", err) } time.Sleep(100 * time.Millisecond) } return fmt.Errorf("filer not healthy within %v", timeout) } func (c *cluster) stop() { c.mu.Lock() procs := append([]*weedProc(nil), c.procs...) c.mu.Unlock() if c.t.Failed() { for _, p := range procs { c.t.Logf("---- %s log (tail) ----\n%s", p.name, tail(p.log(), 60)) } } // Mounts first, so unmounting does not wait for a filer that is gone. for i := len(procs) - 1; i >= 0; i-- { p := procs[i] if p.name == "mini" { continue } terminate(p) } for _, mp := range mountsUnder(c.base) { unmountLazily(mp) } if c.mini != nil { terminate(c.mini) } if c.t.Failed() { // /tmp is often memory: keep the logs, not the data. for _, d := range []string{"data", "cache", "mnt"} { os.RemoveAll(filepath.Join(c.base, d)) } c.t.Logf("logs kept in %s", c.base) return } os.RemoveAll(c.base) } // unmountLazily detaches a mount with whichever fusermount the host has: a // fuse3 host has fusermount3, and a fuse2 host, such as CentOS 7 or an Alpine // image with the fuse package, only fusermount. func unmountLazily(dir string) { for _, helper := range []string{"fusermount3", "fusermount"} { if exec.Command(helper, "-uz", dir).Run() == nil { return } } } func terminate(p *weedProc) { if exited, _ := p.exited(); exited { return } p.cmd.Process.Signal(syscall.SIGTERM) select { case <-p.done: case <-time.After(15 * time.Second): p.cmd.Process.Kill() <-p.done } } // withinTimeout runs f and returns its error, or an error once timeout has // passed: a call into a FUSE mount that stopped answering would block for // good. The goroutine of a call that timed out is left behind. func withinTimeout(timeout time.Duration, f func() error) error { done := make(chan error, 1) go func() { done <- f() }() select { case err := <-done: return err case <-time.After(timeout): return fmt.Errorf("no answer within %v", timeout) } } func tail(s string, lines int) string { all := strings.Split(strings.TrimRight(s, "\n"), "\n") if len(all) > lines { all = all[len(all)-lines:] } return strings.Join(all, "\n") } // mountInfo is a line of /proc/self/mountinfo. type mountInfo struct { id string dev string point string fstype string } func readMountInfo() []mountInfo { f, err := os.Open("/proc/self/mountinfo") if err != nil { return nil } defer f.Close() var out []mountInfo sc := bufio.NewScanner(f) for sc.Scan() { fields := strings.Fields(sc.Text()) if len(fields) < 10 { continue } sep := 0 for i, f := range fields { if f == "-" { sep = i break } } if sep == 0 || sep+1 >= len(fields) { continue } out = append(out, mountInfo{id: fields[0], dev: fields[2], point: fields[4], fstype: fields[sep+1]}) } return out } func mountAt(dir string) (mountInfo, bool) { for _, m := range readMountInfo() { if m.point == dir { return m, true } } return mountInfo{}, false } func mountsUnder(dir string) []string { var out []string for _, m := range readMountInfo() { if m.point == dir || strings.HasPrefix(m.point, dir+string(filepath.Separator)) { out = append(out, m.point) } } return out } func (c *cluster) mountArgs(dir, localSock, cacheDir string, extra ...string) []string { return append([]string{ "-logtostderr=true", "mount", "-filer=" + c.filer, "-dir=" + dir, "-filer.path=/", "-dirAutoCreate", "-allowOthers=false", "-localSocket=" + localSock, "-cacheDir=" + cacheDir, "-cacheCapacityMB=64", "-chunkSizeLimitMB=2", }, extra...) } // waitMounted waits until a filesystem is mounted at dir and answers. func waitMounted(p *weedProc, dir string, timeout time.Duration) error { deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { if m, ok := mountAt(dir); ok && strings.HasPrefix(m.fstype, "fuse") { // A mount that does not answer must not hold this loop up, nor // keep it past its deadline. probe := min(5*time.Second, time.Until(deadline)) if err := withinTimeout(probe, func() error { _, err := os.ReadDir(dir); return err }); err == nil { return nil } } if exited, err := p.exited(); exited { return fmt.Errorf("%s exited (%v):\n%s", p.name, err, tail(p.log(), 30)) } time.Sleep(50 * time.Millisecond) } return fmt.Errorf("%s: nothing mounted at %s within %v", p.name, dir, timeout) }