//go:build linux package mount import ( "context" "errors" "fmt" "net" "os" "path/filepath" "slices" "strings" "sync" "sync/atomic" "syscall" "testing" "time" "github.com/seaweedfs/go-fuse/v2/fuse" "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" "github.com/seaweedfs/seaweedfs/weed/pb" ) // fakeFuse stands in for the FUSE server on the old side. type fakeFuse struct { mu sync.Mutex calls []string blockStop bool stopErr error shutdownErr error panicOnDev bool } func (f *fakeFuse) record(c string) { f.mu.Lock() f.calls = append(f.calls, c) f.mu.Unlock() } func (f *fakeFuse) Calls() []string { f.mu.Lock() defer f.mu.Unlock() return slices.Clone(f.calls) } func (f *fakeFuse) Stop(ctx context.Context) error { f.record("Stop") if f.blockStop { <-ctx.Done() return ctx.Err() } return f.stopErr } func (f *fakeFuse) Start() error { f.record("Start"); return nil } func (f *fakeFuse) Shutdown(ctx context.Context) error { f.record("Shutdown") return f.shutdownErr } func (f *fakeFuse) Dev() (*fuse.Dev, error) { f.record("Dev") if f.panicOnDev { panic("boom") } fd, err := syscall.Open("/dev/null", syscall.O_RDWR|syscall.O_CLOEXEC, 0) if err != nil { return nil, err } in := &fuse.InitIn{Major: 7, Minor: 31} out := &fuse.InitOut{Major: 7, Minor: 31, MaxWrite: 1 << 20} return fuse.NewDev(fd, in, out), nil } const testMountDir = "/mnt/handover-test" type handoverRig struct { t *testing.T src *WFS fake *fakeFuse svc *HandoverService path string paused atomic.Int32 resumed atomic.Int32 flushes atomic.Int32 // flushFail makes the n-th flush fail (1-based), 0 never. flushFail atomic.Int32 } func newHandoverRig(t *testing.T, opts HandoverOptions) *handoverRig { t.Helper() r := &handoverRig{t: t, src: newHandoverWFS(t), fake: &fakeFuse{}} now := time.Now().Unix() it := r.src.inodeToPath it.Lookup("/a", now, true, false, 0, true) file := it.Lookup("/a/f1", now, false, false, 0, true) r.src.fhMap.AcquireFileHandle(r.src, file, testEntry("f1", file), 111, 5, false) r.src.metaCache.NoteSubscribedTsNs(98765) // A running subscription, as far as pause and resume can tell. r.src.metaFollower = &meta_cache.MetadataFollower{} r.src.metaFollowCancel = func() { r.paused.Add(1) } r.src.resumeFollowHook = func(start time.Time, f *meta_cache.MetadataFollower) { r.resumed.Add(1) if start.UnixNano() != 98765 || f != r.src.metaFollower { t.Errorf("subscription resumed from %d with follower %p, want 98765 and the kept one", start.UnixNano(), f) } } // A short path: a unix socket path is limited to about 100 bytes, and // t.TempDir carries the test name. sockDir, err := os.MkdirTemp("", "ho") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(sockDir) }) r.path = filepath.Join(sockDir, "h.sock") ln, err := ListenHandover(r.path, false) if err != nil { t.Fatal(err) } if opts.MountDir == "" { opts.MountDir = testMountDir } r.svc = r.src.NewHandoverService(r.fake, ln, opts) r.svc.flush = func(ctx context.Context) error { n := r.flushes.Add(1) if n == r.flushFail.Load() { return errors.New("injected flush failure") } return nil } go r.svc.Serve() t.Cleanup(r.svc.Close) return r } func (r *handoverRig) takeover(dir string) (*WFS, *Takeover, error) { dst := newHandoverWFS(r.t) tk, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: dir, OfferTimeout: 10 * time.Second}) return dst, tk, err } // waitIdle waits until the service finished the conversation it was in. func (r *handoverRig) waitIdle() { r.t.Helper() deadline := time.Now().Add(10 * time.Second) for r.svc.busy.Load() && !r.svc.Committed() { if time.Now().After(deadline) { r.t.Fatal("the handover did not end") } time.Sleep(5 * time.Millisecond) } } // requireRolledBack checks what every rollback must leave: the server // serving, the subscription running, the writers released, nothing committed. func (r *handoverRig) requireRolledBack(wantCalls ...string) { r.t.Helper() r.waitIdle() if got := r.fake.Calls(); !slices.Equal(got, wantCalls) { r.t.Fatalf("server calls %v, want %v", got, wantCalls) } if r.svc.Committed() { r.t.Fatal("committed after a rollback") } if r.src.BackgroundQuiesced() { r.t.Fatal("background writers are still quiesced") } // The subscription starts again in the background. deadline := time.Now().Add(10 * time.Second) for r.paused.Load() != r.resumed.Load() { if time.Now().After(deadline) { r.t.Fatalf("subscription paused %d times, resumed %d", r.paused.Load(), r.resumed.Load()) } time.Sleep(5 * time.Millisecond) } select { case <-r.svc.Done(): r.t.Fatal("done after a rollback") default: } } func requireRefused(t *testing.T, err error, contains string) { t.Helper() var refused *HandoverRefusedError if !errors.As(err, &refused) { t.Fatalf("error %v, want a refusal", err) } if !strings.Contains(refused.Reason, contains) { t.Fatalf("refused with %q, want %q in it", refused.Reason, contains) } } func TestHandoverSucceeds(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst, tk, err := r.takeover(testMountDir) if err != nil { t.Fatal(err) } defer tk.Close() // The state arrived. if tk.StateBytes == 0 { t.Error("no state bytes counted") } if got, _ := dst.inodeToPath.GetInode("/a/f1"); got == 0 { t.Error("the inode of /a/f1 did not cross") } if dst.handoverMetaTsNs != 98765 { t.Errorf("subscription position %d did not cross", dst.handoverMetaTsNs) } // The connection arrived with its negotiation. dev := tk.Dev() defer dev.Close() if _, out := dev.Init(); out.Major != 7 || out.MaxWrite != 1<<20 { t.Errorf("negotiation %+v", out) } var st syscall.Stat_t if err := syscall.Fstat(dev.Fd(), &st); err != nil { t.Errorf("the received fd is not usable: %v", err) } // Nothing is final before ready, and nothing is closed before go. if slices.Contains(r.fake.Calls(), "Shutdown") || r.svc.Committed() { t.Fatal("old side committed before ready") } if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Dev"}) { t.Fatalf("calls before ready %v", got) } if err := tk.Ready(); err != nil { t.Fatal(err) } if err := tk.WaitGo(10 * time.Second); err != nil { t.Fatal(err) } select { case <-r.svc.Done(): case <-time.After(10 * time.Second): t.Fatal("old side did not finish") } if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Dev", "Shutdown"}) { t.Fatalf("calls %v", got) } if !r.svc.Committed() { t.Fatal("not marked as committed: its exit would unlink the successor's sockets") } if !r.src.BackgroundQuiesced() || r.paused.Load() != 1 || r.resumed.Load() != 0 { t.Fatalf("writers quiesced %v, subscription paused %d resumed %d", r.src.BackgroundQuiesced(), r.paused.Load(), r.resumed.Load()) } if got := r.flushes.Load(); got != 2 { t.Fatalf("%d flushes, want one before and one after the stop", got) } // The listener went away with the handover: a second attempt finds nothing. if _, _, err := r.takeover(testMountDir); err == nil { t.Fatal("a handover was offered after the mount was handed over") } } func TestHandoverRefusals(t *testing.T) { t.Run("wrong mount dir", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) _, _, err := r.takeover("/mnt/somewhere-else") requireRefused(t, err, "serves "+testMountDir) r.requireRolledBack() }) t.Run("peer uid", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{AllowPeerUID: func(uint32) bool { return false }}) _, _, err := r.takeover(testMountDir) requireRefused(t, err, "not allowed") r.requireRolledBack() }) t.Run("running mount of another uid", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst := newHandoverWFS(t) _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir, AllowPeerUID: func(uint32) bool { return false }}) if err == nil || !strings.Contains(err.Error(), "runs as uid") { t.Fatalf("error %v", err) } r.requireRolledBack() }) t.Run("blocked lock request", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.src.routedLockWaiters.Add(1) _, _, err := r.takeover(testMountDir) requireRefused(t, err, "1 lock requests are blocked") r.requireRolledBack() if n := r.flushes.Load(); n != 0 { t.Fatalf("%d flushes before the refusal, want none", n) } r.src.routedLockWaiters.Add(-1) // A waiter in the local table counts as well. r.src.posixLocks.mu.Lock() r.src.posixLocks.inodes[77] = &inodeLocks{waiters: []*lockWaiter{{}}} r.src.posixLocks.mu.Unlock() _, _, err = r.takeover(testMountDir) requireRefused(t, err, "1 lock requests are blocked") r.requireRolledBack() }) t.Run("peer uid default allows ours", func(t *testing.T) { o := HandoverOptions{} o.withDefaults() if !o.AllowPeerUID(uint32(syscall.Getuid())) || !o.AllowPeerUID(0) || o.AllowPeerUID(uint32(syscall.Getuid())+12345) { t.Fatal("default uid policy") } }) t.Run("first flush fails", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.flushFail.Store(1) _, _, err := r.takeover(testMountDir) requireRefused(t, err, "flush before handover") r.requireRolledBack() }) t.Run("stop times out", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{StopTimeout: 200 * time.Millisecond}) r.fake.blockStop = true _, _, err := r.takeover(testMountDir) requireRefused(t, err, "drain requests") r.requireRolledBack("Stop", "Start") // The mount keeps serving and a later handover goes through. r.fake.blockStop = false _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatalf("handover after a rollback: %v", err) } tk.Close() }) t.Run("final flush fails", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.flushFail.Store(2) _, _, err := r.takeover(testMountDir) requireRefused(t, err, "final flush") r.requireRolledBack("Stop", "Start") }) t.Run("export refuses", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.src.asyncCreates.Add(1) // a create still being sent: the state cannot be carried _, _, err := r.takeover(testMountDir) requireRefused(t, err, "cannot be handed over") r.requireRolledBack("Stop", "Dev", "Start") if r.paused.Load() != 1 { t.Fatalf("subscription paused %d times", r.paused.Load()) } }) t.Run("panic", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.fake.panicOnDev = true _, _, err := r.takeover(testMountDir) requireRefused(t, err, "panic") r.requireRolledBack("Stop", "Dev", "Start") }) t.Run("peer aborts instead of ready", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatal(err) } tk.Abort("test") r.requireRolledBack("Stop", "Dev", "Start") }) t.Run("peer vanishes before ready", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatal(err) } tk.Close() r.requireRolledBack("Stop", "Dev", "Start") }) t.Run("peer never answers", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{ReadyTimeout: 300 * time.Millisecond}) _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatal(err) } defer tk.Close() r.requireRolledBack("Stop", "Dev", "Start") if err := tk.WaitGo(2 * time.Second); err == nil { t.Fatal("go after a timeout") } }) t.Run("go cannot be written", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.svc.sendGo = func(net.Conn) error { return errors.New("broken pipe") } _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatal(err) } defer tk.Close() if err := tk.Ready(); err != nil { t.Fatal(err) } r.requireRolledBack("Stop", "Dev", "Start") if err := tk.WaitGo(2 * time.Second); err == nil { t.Fatal("go received although it was not sent") } }) t.Run("one at a time", func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatal(err) } _, _, err = r.takeover(testMountDir) requireRefused(t, err, "in progress") tk.Abort("done") r.requireRolledBack("Stop", "Dev", "Start") }) } // A frame the peer would refuse is not sent. func TestWriteControlRefusesOversizedFrame(t *testing.T) { var sent strings.Builder err := writeControl(&sent, &controlMsg{Type: ctlAbort, Reason: strings.Repeat("x", maxControlFrame)}) if err == nil || sent.Len() != 0 { t.Fatalf("error %v with %d bytes sent, want an error and nothing sent", err, sent.Len()) } } // A hello that is not one is refused, and so is a peer of another protocol. func TestHandoverBadHello(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) c, err := net.Dial("unix", r.path) if err != nil { t.Fatal(err) } defer c.Close() if err := writeControl(c, &controlMsg{Type: ctlHello, Version: 99, MountDir: testMountDir}); err != nil { t.Fatal(err) } kind, length, fd, err := readHeader(c.(*net.UnixConn)) if err != nil || kind != headerRefused || fd >= 0 { t.Fatalf("header %d %d fd %d err %v", kind, length, fd, err) } reason, _ := readPayload(c, length) if !strings.Contains(string(reason), "unsupported hello") { t.Fatalf("reason %q", reason) } r.requireRolledBack() } func TestTakeoverNothingListens(t *testing.T) { dst := newHandoverWFS(t) _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: filepath.Join(os.TempDir(), fmt.Sprintf("none-%d.sock", os.Getpid())), MountDir: testMountDir}) if err == nil || !strings.Contains(err.Error(), "nothing answers") { t.Fatalf("error %v", err) } } // The options the state depends on are compared in the hello: a successor // that differs is refused before the running mount flushes or pauses. func TestHandoverOptionsMismatchRefusedBeforePause(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst := newHandoverWFS(t) dst.option.WritebackCache = false // the source runs with writeback on _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir}) requireRefused(t, err, "-writebackCache is true here and false in the new process") r.requireRolledBack() if n := r.flushes.Load(); n != 0 { t.Fatalf("%d flushes before the mismatch was refused, want none", n) } } // Without default_permissions the kernel leaves the permission checks to the // mount: a successor that counts on the kernel would make none. func TestHandoverDefaultPermissionsMismatchRefusedBeforePause(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst := newHandoverWFS(t) dst.option.KernelDefaultPermissions = !r.src.option.KernelDefaultPermissions _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir}) requireRefused(t, err, "default_permissions") r.requireRolledBack() if n := r.flushes.Load(); n != 0 { t.Fatalf("%d flushes before the mismatch was refused, want none", n) } } // The kernel's mount options are fixed in the mount: a successor started with // others, -readOnly or -o noexec say, would run with the old ones without // knowing. func TestHandoverKernelMountOptionsMismatchRefused(t *testing.T) { for _, c := range []struct { name, reason string set func(*WFS) }{ {"ro", "the mount flags (-readOnly and -o) are nodev,nosuid here and nodev,nosuid,ro in the new process", func(w *WFS) { w.option.KernelMountFlags = []string{"nodev", "nosuid", "ro"} }}, {"noexec", "are nodev,nosuid here and nodev,noexec,nosuid in the new process", func(w *WFS) { w.option.KernelMountFlags = []string{"nodev", "noexec", "nosuid"} }}, {"allow_other", "allow_other (", func(w *WFS) { w.option.KernelAllowOther = true }}, {"default_permissions", "default_permissions (", func(w *WFS) { w.option.KernelDefaultPermissions = !w.option.KernelDefaultPermissions }}, } { t.Run(c.name, func(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst := newHandoverWFS(t) c.set(dst) _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir}) requireRefused(t, err, c.reason) r.requireRolledBack() }) } } // A successor started against other filers would send the reads and writes of // the open files it gets to those: refused before anything pauses. func TestHandoverOtherFilersRefusedBeforePause(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst := newHandoverWFS(t) dst.option.FilerAddresses = []pb.ServerAddress{"10.9.9.9:8888"} _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir}) requireRefused(t, err, "the filers are") r.requireRolledBack() if n := r.flushes.Load(); n != 0 { t.Fatalf("%d flushes before the mismatch was refused, want none", n) } } // A successor that names a filer of the running mount, however it writes the // address and whatever other filers it lists, serves the same filer store: // the handover goes through. func TestHandoverFilerInCommonAccepted(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) dst := newHandoverWFS(t) // The running mount names its filer with the gRPC port, 127.0.0.1:1.1. dst.option.FilerAddresses = []pb.ServerAddress{"10.9.9.9:8888", "127.0.0.1:1"} tk, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir, OfferTimeout: 10 * time.Second}) if err != nil { t.Fatal(err) } defer tk.Close() defer tk.Dev().Close() if err := tk.Ready(); err != nil { t.Fatal(err) } if err := tk.WaitGo(10 * time.Second); err != nil { t.Fatal(err) } select { case <-r.svc.Done(): case <-time.After(10 * time.Second): t.Fatal("old side did not finish") } if !r.svc.Committed() { t.Fatal("the handover did not commit") } } // A subscription that does not end in time fails the handover. The rollback // lets the mount serve again at once, starts the subscription again only once // the old one has ended, and a handover in between is refused before anything // pauses. func TestHandoverRollbackDoesNotWaitForAStuckSubscription(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) r.src.metaFollowWg.Add(1) // a subscription that does not end released := false defer func() { if !released { r.src.metaFollowWg.Done() } }() _, _, err := r.takeover(testMountDir) requireRefused(t, err, "did not stop") r.waitIdle() if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Start"}) { t.Fatalf("server calls %v, want it stopped and started again", got) } if n := r.resumed.Load(); n != 0 { t.Fatalf("the subscription started again %d times before the old one ended", n) } _, _, err = r.takeover(testMountDir) requireRefused(t, err, "still starting again") if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Start"}) { t.Fatalf("server calls %v: a refused handover paused the mount", got) } released = true r.src.metaFollowWg.Done() r.requireRolledBack("Stop", "Start") } // A successor that cannot import the state makes the old side roll back, the // nfs export writer that the export stopped included. func TestHandoverImportFailureRollsBack(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) kv := &fakeKv{values: map[string][]byte{}} r.src.exportedHandles = newExportedHandlesForTest(kv, 1, 0) dst := newHandoverWFS(t) dst.exportedHandles = newExportedHandlesForTest(kv, 2, 0) // A successor that holds state already refuses to import. dst.inodeToPath.Lookup("/already", time.Now().Unix(), false, false, 0, true) _, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir}) if err == nil || !strings.Contains(err.Error(), "fresh mount") { t.Fatalf("error %v", err) } r.requireRolledBack("Stop", "Dev", "Start") h := r.src.exportedHandles h.mu.Lock() stopped := h.handedOver h.mu.Unlock() if stopped { t.Fatal("the nfs export writer is still stopped after the rollback") } } // A new mount probes for a running one before it decides to take the mount // over. The probe is no handover: nothing pauses, and a handover right after // it is not turned away as one in progress. func TestHandoverProbe(t *testing.T) { r := newHandoverRig(t, HandoverOptions{}) if !HandoverAnswers(r.path) { t.Fatal("the running mount does not answer a probe") } if HandoverAnswers(r.path + ".none") { t.Fatal("a socket nobody listens on answers") } _, tk, err := r.takeover(testMountDir) if err != nil { t.Fatalf("handover right after a probe: %v", err) } tk.Close() r.requireRolledBack("Stop", "Dev", "Start") if n := r.flushes.Load(); n != 2 { t.Fatalf("%d flushes, want the 2 of the one handover", n) } }