mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* go.mod: take seaweedfs/go-fuse from #5 until it is released The handover builds on the server API of seaweedfs/go-fuse#5: Server.Stop, Start and Shutdown, Server.Dev and NewServerFromDev. Until that pull request is merged and tagged, go-fuse is replaced by its branch; the replace goes with the release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: quiesce the background writers, pause and resume the metadata subscription, and give a takeover its own cache directories The periodic metadata flush, the proactive chunk flush and the idle directory eviction check a gate before each tick, so a handover can stop them and wait for the work they run. PauseMetadataFollow and ResumeMetadataFollow end the subscription and start it again from the position of the last event it handled, with the filer.conf follower it had. A successor keeps the subscription's client id (the signature crosses), so it subscribes at an epoch above its predecessor's: the filer then replaces the old subscription instead of refusing the new one as a duplicate and making it wait for a retry. A process that takes a mount over (Option.Takeover) uses <id>.t<pid> for its read and swap directories, as the predecessor still uses <id>. A normal start removes the stale <id>.t* siblings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: the handover protocol, old side and new side A running mount listens on a unix socket (0600; the peer's uid is checked with SO_PEERCRED on both ends, ours or root). A successor connects, says hello, receives the FUSE fd with the INIT negotiation and the exported state, answers ready, and is told go. The hello carries the mount directory, the filer path and the options the state depends on (writeback cache, routed locks, nfs export): the running mount refuses a mismatch, a blocked lock request and a peer chunk server before it flushes or pauses. A connection closed before its hello is a probe (HandoverAnswers), logged at V(1). Until go the old side rolls back at every step (pre-flush, quiesce, stop, final flush, pause of the subscription, export, ready) and keeps serving: the subscription restarts from its position, the background writers and the nfs export writer resume, the server reads again. After go it closes its server without unmounting and marks itself committed, so its exit leaves the mount and the successor's sockets alone. The fd is carried by a fixed-size header written with one sendmsg and read with one recvmsg; control messages are length-prefixed JSON, and the state stream and the go frame are read through one bufio.Reader. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: a new mount on a live mount directory takes it over A weed mount started on a directory that is mounted already, whose weed mount answers on the handover socket, takes that mount over instead of replacing it: open files, locks and working directories inside it carry on. - Every Linux mount listens on a socket next to its local gRPC socket, <localSocket without .sock>.handover.sock, /tmp/seaweedfs-mount-<hash>.handover.sock by default; a deployment that keeps the local socket where the next mount process can reach it gets the same for this one. Not with -peer.enable, whose listen port has a single owner, nor with -filer.tokenFile, as read tokens and chunk proofs do not cross. - Those mounts read /dev/fuse in the stoppable way. - A new mount takes over when its directory is in the mount table and a process answers on the socket. When none answers (none runs, it crashed, it is an older weed), the mount proceeds as before. - A takeover skips the pre-mount unmount and the mount point check, binds the local gRPC socket and the handover socket only after the old process said go, and uses cache directories of its own. One that does not go through exits non-zero and leaves the running mount serving; to mount anew, stop that weed mount or unmount first, as for a busy mount today. - After go, a socket the new process cannot bind is logged, not fatal: the mount goes on without mount.configure or without a next handover, rather than going down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: end-to-end handover test test/fuse_handover starts a real weed mini and weed mount processes with the same arguments, and lets each new one take the live mount over, twice in a row and once more after a refusal. An appending writer, a streaming reader, an mmap, an unlinked temp file, an unclosed new file, a directory walk and a listing in progress, a held flock and POSIX lock, a process working inside the mount and a renamed open file run through it. It checks that the mount was never unmounted (mount id and st_dev), that the old processes exit 0, that a takeover refused because a SETLKW is blocked, or because the options differ, leaves the mount serving without a pause, and prints the pause. With HANDOVER_SCALE_FILES=<n> a second test creates n files, takes the mount over, and logs the pause and the size of the state. On a 2-vCPU VM: 10k files 18 ms and 360 KB, 100k files 134 ms and 2.9 MB, 300k files 410 ms and 7.1 MB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: answer the first review of the handover The checks before anything pauses: - The hello carries the filer addresses, sorted, and -defaultPermissions: the running mount refuses a successor of other filers (its open files and inode table name entries and chunks of this filer) or of another default_permissions (without it the kernel leaves the permission checks to the mount, and a successor that counts on the kernel would make none). - A successor finds the live mount for a relative -dir and for a path with a space: the mount table is read with the absolute path, and its octal escapes (\040 ...) are undone, which checkMountPointAvailable gets too. The local socket keeps its name. Rollback and commitment: - A rolled back handover starts the FUSE server first. A subscription that did not end in time may wait for a request to be served, and the rollback waited for it before the server read again. The subscription now starts again in the background once the old one has ended; until then a new handover is refused before anything pauses. - A successor reads the filer configuration (PrepareBackgroundTasks) before it connects, since a failure there after go would end the process with nobody serving the mount, and it does not create the mount root, which the running mount serves. - A reconnecting subscription publishes its epoch, so that a later one with the same client id starts above it instead of being refused as a duplicate. - A takeover's cache directories are <id>.t<pid>-<random>: two processes that each run as pid 1 of a container sharing the cache base got the same directory. Tests: - The protocol tests run on Linux only, as the protocol does; those of the background gate and of the cache directories run everywhere. - The end-to-end harness bounds the probes that go into the mount, waits until the SETLKW helper sleeps in FUSE before it asks for a takeover, counts only complete reader passes, closes the retained files on failure, rechecks a log after its process exited, and cleans up only mounts below its own directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: read the filer configuration again after a takeover A successor reads the filer configuration before it connects, so that nothing that can fail is left for after go. A change that the predecessor applied in between does not come again with the subscription, which starts where the predecessor stopped, and the successor kept the configuration it had read. It now reads it once more when it starts its background tasks; on failure the one read before stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: build the moved handover tests where their helpers are handover_quiesce_test.go uses newHandoverWFS, which is defined in a test file built everywhere but on Windows; it gets the same constraint. The mount readiness probe of the end-to-end test is also capped at the remaining deadline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: renew the routed lock leases before the background tasks wait on the filer A successor with -dlm holds the routed locks its predecessor took, and the filer drops their leases 15 s after the last renewal. StartBackgroundTasks began renewing only after it had read the filer configuration again, a filer call that can take longer than that. The renewal now starts first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: compare -readOnly and -allowOthers in the hello, and drop a filer configuration that is gone - -readOnly and -allowOthers are kernel mount options, fixed when the mount was made: a successor started with others would run with the old ones without knowing. The hello carries them and the running mount refuses a mismatch before anything pauses. - The filer configuration read again after a takeover clears the one read before when the file is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: close the held lock files of the handover workload on failure The flock and POSIX lock files are opened before the takeovers and closed in finish(); an assertion that fails in between left them open. They get a cleanup right after they open, like the other retained files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: compare the kernel's mount options as -o sets them too, and retry the filer configuration read after a takeover - allow_other, ro and default_permissions can come from -o as well as from their flags. The hello compared the flags only, so a successor started with -allowOthers=false could take over a mount made with -o allow_other. The mount now records the kernel's options from both (KernelReadOnly, KernelAllowOther, KernelDefaultPermissions), and the hello compares those. - The read of the filer configuration after a takeover is tried three times before the subscription starts, which can wait: it starts where the predecessor stopped. Only if all fail does the configuration read before the takeover stay until its next change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: drop the WEED_MOUNT_HANDOVER_STOP_TIMEOUT test hook The drain bound stays at its 10 s default; the end-to-end tests wait well over that for a refusal, so they do not need a setting of their own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: close a descriptor that comes with a refused handover Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: take a mount over when the new process shares a filer with it The hello required the sorted -filer list to match exactly, so a successor started after filers were added to the cluster or taken out of it was refused, and the old mount kept serving. A filer serves one filer store: one filer in common means the store that the open files, the inode table and the chunks belong to. Compare the filers as host:port, as ServerAddress.Equals does, so that an address written with its gRPC port counts as the same filer, and refuse only lists with no filer in common. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci: run the FUSE mount handover end-to-end tests test/fuse_handover starts a real weed mini and weed mount processes and lets each new mount take the live one over; no workflow ran it, so only the unit tests guarded the handover in CI. The job follows the FUSE DLM one: it repairs the fusermount3 setuid bit, builds weed and runs the tests with WEED_BINARY. The tests mount as the runner user without allow_other, so fuse.conf is left alone. A failed run uploads the weed logs, which the harness keeps in /tmp/fuse_handover_*. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: compare the kernel's mount flags in the hello, resolved in order The hello compared ro as "-readOnly or -o ro", and no other mount flag. -readOnly puts ro before the -o options, and both fusermount3 and go-fuse's direct mount apply the options in order, so -readOnly with -o rw mounts read-write while the hello said ro. A successor started with -o noexec, nosuid or nodev also got the old mount's flags without knowing. Resolve the generic flags from the option list go-fuse mounts with, in order, from nosuid and nodev as both mount paths start, and refuse a successor whose flags differ before anything pauses. relatime is left out: the kernel uses it unless noatime or strictatime is set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: do not send a handover control frame the peer would refuse writeControl sized its buffer from the encoded message without a bound, while readControl refuses a frame over maxControlFrame. Refuse the larger frame before allocating, as the reading side does (CodeQL go/allocation-size-overflow). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: unmount the handover e2e mounts with fusermount when fusermount3 is missing The harness detached leftover mounts with fusermount3 only. A fuse2 host, such as CentOS 7 or an Alpine image with the fuse package, has only fusermount, so the last step of TestHandoverEndToEnd failed there after every handover had passed. Try fusermount3, then fusermount. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * go.mod: use go-fuse v2.9.6 instead of the branch of seaweedfs/go-fuse#5 seaweedfs/go-fuse#5 is merged and tagged v2.9.6, whose tree is the one this pull request was tested with (1eec9a8). Drop the replace with the fork and require the release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: whitebear009 <whitebear009@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
1146 lines
43 KiB
Go
1146 lines
43 KiB
Go
//go:build !windows
|
|
|
|
package mount
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"hash/crc32"
|
|
"io"
|
|
"reflect"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/go-fuse/v2/fuse"
|
|
"google.golang.org/protobuf/encoding/protowire"
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/filer/posixlock"
|
|
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
// newHandoverWFS builds a WFS without FUSE that has every table a handover
|
|
// touches, in writeback mode so the per-inode refusal flags are bound.
|
|
func newHandoverWFS(t *testing.T) *WFS {
|
|
t.Helper()
|
|
wfs := newInvalidateTestWFS(t)
|
|
wfs.option.WritebackCache = true
|
|
wfs.option.FilerMountRootPath = "/"
|
|
wfs.option.KernelMountFlags = []string{"nodev", "nosuid"}
|
|
wfs.dhMap = NewDirectoryHandleToInode()
|
|
wfs.posixLocks = NewPosixLockTable()
|
|
wfs.posixHint = newPosixLockHint()
|
|
wfs.posixOwn = posixlock.NewManager()
|
|
wfs.pendingAsyncFlush = make(map[uint64]chan struct{})
|
|
wfs.atimeMap = make(map[uint64]time.Time)
|
|
wfs.dirMtimeMap = make(map[uint64]time.Time)
|
|
wfs.inodeToPath.RetainForgotten(8)
|
|
return wfs
|
|
}
|
|
|
|
func exportToBytes(t *testing.T, wfs *WFS) []byte {
|
|
t.Helper()
|
|
var buf bytes.Buffer
|
|
if err := wfs.ExportHandoverState(&buf); err != nil {
|
|
t.Fatalf("export: %v", err)
|
|
}
|
|
return buf.Bytes()
|
|
}
|
|
|
|
func testEntry(name string, inode uint64) *filer_pb.Entry {
|
|
return &filer_pb.Entry{
|
|
Name: name,
|
|
Attributes: &filer_pb.FuseAttributes{
|
|
FileMode: 0o644, FileSize: 10, Inode: inode, Mtime: 5, Uid: 1000, Gid: 1000,
|
|
},
|
|
Chunks: []*filer_pb.FileChunk{
|
|
{FileId: "3,0102", Offset: 0, Size: 5},
|
|
{FileId: "3,0203", Offset: 5, Size: 5, IsChunkManifest: true},
|
|
},
|
|
Extended: map[string][]byte{"k": []byte("v")},
|
|
}
|
|
}
|
|
|
|
// handoverFixture is the state the round trip carries.
|
|
type handoverFixture struct {
|
|
dir, file, linked, removed, forgotten, unlinked uint64
|
|
openA, openB FileHandleId
|
|
dirHandle DirectoryHandleId
|
|
}
|
|
|
|
func populateForHandover(t *testing.T, wfs *WFS) handoverFixture {
|
|
t.Helper()
|
|
var fx handoverFixture
|
|
now := time.Now().Unix()
|
|
it := wfs.inodeToPath
|
|
|
|
fx.dir = it.Lookup("/a", now, true, false, 0, true)
|
|
it.SetSubdirCount("/a", 3)
|
|
fx.file = it.Lookup("/a/f1", now, false, false, 0, true)
|
|
it.Lookup("/a/f1", now, false, false, 0, true) // nlookup 2
|
|
// A hard link: the same inode under a second name.
|
|
if got := it.Lookup("/a/f1.link", now, false, true, fx.file, true); got != fx.file {
|
|
t.Fatalf("hard link inode %d, want %d", got, fx.file)
|
|
}
|
|
fx.removed = it.Lookup("/a/gone", now, false, false, 0, true)
|
|
it.RemovePath("/a/gone", nil) // the kernel still holds it, with no name
|
|
fx.forgotten = it.Lookup("/a/g", now, false, false, 0, true)
|
|
it.Forget(fx.forgotten, 1, nil, nil)
|
|
fx.unlinked = it.Lookup("/a/tmp", now, false, false, 0, true)
|
|
|
|
// A file opened twice, the second open O_APPEND, with state that changes
|
|
// what later operations do.
|
|
fhA, openA, _, _ := wfs.fhMap.AcquireFileHandle(wfs, fx.file, testEntry("f1", fx.file), 111, 5, false)
|
|
fhA.RememberPath("/a/f1")
|
|
_, openB, _, _ := wfs.fhMap.AcquireFileHandle(wfs, fx.file, nil, 0, 0, true)
|
|
fx.openA, fx.openB = openA, openB
|
|
fhA.contentType = "text/x-test"
|
|
fhA.isRenamed = true
|
|
fhA.nameTaken = true
|
|
fhA.linkRefresh = []byte("link-id")
|
|
fhA.deleteEpoch = 3
|
|
fhA.noteTruncate(7)
|
|
|
|
// An unlinked file still open: dirty for good, its entry only in the handle.
|
|
fhU, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, fx.unlinked, testEntry("tmp", fx.unlinked), 222, 6, false)
|
|
fhU.RememberPath("/a/tmp")
|
|
fhU.isDeleted, fhU.deleteEpoch = true, 1
|
|
fhU.dirtyMetadata, fhU.dirtyContent = true, true
|
|
fhU.pendingAppend, fhU.pendingAppendOffset = true, 9
|
|
state, _ := wfs.writebackContentErrors.Load(fx.unlinked)
|
|
state.(*atomic.Bool).Store(true)
|
|
|
|
// A directory handle mid-listing.
|
|
var dh *DirectoryHandle
|
|
fx.dirHandle, dh = wfs.AcquireDirectoryHandle()
|
|
dh.entryStreamOffset = 12
|
|
dh.lastListedName = "x2"
|
|
dh.snapshotTsNs = 4444
|
|
dh.isFinished = true
|
|
for i := 0; i < 3; i++ {
|
|
name := fmt.Sprintf("x%d", i)
|
|
dh.entryStream = append(dh.entryStream, &filer.Entry{
|
|
FullPath: util.FullPath("/a").Child(name),
|
|
Attr: filer.Attr{Mode: 0o644, Inode: uint64(100 + i), FileSize: uint64(i), Mtime: time.Unix(5, 0), Crtime: time.Unix(4, 0)},
|
|
})
|
|
}
|
|
|
|
// Locks.
|
|
if s := wfs.posixLocks.SetLk(fx.file, lockRange{Start: 0, End: 99, Typ: f_WRLCK, Owner: 9, Pid: 3}); s != fuse.OK {
|
|
t.Fatalf("SetLk: %v", s)
|
|
}
|
|
if s := wfs.posixLocks.SetLk(fx.file, lockRange{Start: 0, End: ^uint64(0), Typ: f_RDLCK, Owner: 11, Pid: 4, IsFlock: true}); s != fuse.OK {
|
|
t.Fatalf("flock: %v", s)
|
|
}
|
|
wfs.fhLocks.add(uint64(openA), 9)
|
|
wfs.fhLocks.add(uint64(openB), 12)
|
|
wfs.posixHint.add(fx.file, 9)
|
|
wfs.posixSid = 777
|
|
wfs.signature = 4242
|
|
wfs.posixOwn.Track("s3.fuse.lock:/a/f1", posixlock.Range{Start: 5, End: 8, Type: 1, Sid: 777, Owner: 9, Pid: 3})
|
|
|
|
// Overlays.
|
|
wfs.setAtime(fx.file, time.Unix(1700000000, 123))
|
|
wfs.setDirMtime(fx.dir, time.Unix(1700000001, 456))
|
|
wfs.rememberRemovedDir(fx.removed, &filer_pb.Entry{Name: "rd", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0o755}})
|
|
wfs.metaCache.NoteSubscribedTsNs(98765)
|
|
return fx
|
|
}
|
|
|
|
func sortedPaths(ps []util.FullPath) []string {
|
|
out := make([]string, len(ps))
|
|
for i, p := range ps {
|
|
out[i] = string(p)
|
|
}
|
|
slices.Sort(out)
|
|
return out
|
|
}
|
|
|
|
func requireSameInodeTables(t *testing.T, src, dst *InodeToPath) {
|
|
t.Helper()
|
|
src.RLock()
|
|
defer src.RUnlock()
|
|
dst.RLock()
|
|
defer dst.RUnlock()
|
|
if len(src.inode2path) != len(dst.inode2path) {
|
|
t.Fatalf("inode2path: %d entries, want %d", len(dst.inode2path), len(src.inode2path))
|
|
}
|
|
for inode, want := range src.inode2path {
|
|
got := dst.inode2path[inode]
|
|
if got == nil {
|
|
t.Fatalf("inode %d missing", inode)
|
|
}
|
|
if got.nlookup != want.nlookup || !slices.Equal(sortedPaths(got.appendPaths(nil)), sortedPaths(want.appendPaths(nil))) || got.path != want.path {
|
|
t.Fatalf("inode %d: got %+v, want %+v", inode, got, want)
|
|
}
|
|
}
|
|
if !reflect.DeepEqual(src.path2inode, dst.path2inode) {
|
|
t.Fatalf("path2inode differs:\n got %v\nwant %v", dst.path2inode, src.path2inode)
|
|
}
|
|
if len(src.dirStates) != len(dst.dirStates) {
|
|
t.Fatalf("dirStates: %d, want %d", len(dst.dirStates), len(src.dirStates))
|
|
}
|
|
for inode, want := range src.dirStates {
|
|
got := dst.dirStates[inode]
|
|
if got == nil || got.path != want.path || got.subdirCount != want.subdirCount {
|
|
t.Fatalf("dirState %d: got %+v, want %+v", inode, got, want)
|
|
}
|
|
if got.isChildrenCached {
|
|
t.Fatalf("dirState %d: children-cached flag crossed", inode)
|
|
}
|
|
}
|
|
if len(src.dirPaths) != len(dst.dirPaths) {
|
|
t.Fatalf("dirPaths: %d, want %d", len(dst.dirPaths), len(src.dirPaths))
|
|
}
|
|
if !slices.Equal(src.forgotten.Keys(), dst.forgotten.Keys()) {
|
|
t.Fatalf("forgotten: %v, want %v", dst.forgotten.Keys(), src.forgotten.Keys())
|
|
}
|
|
for _, inode := range src.forgotten.Keys() {
|
|
a, _ := src.forgotten.Peek(inode)
|
|
b, _ := dst.forgotten.Peek(inode)
|
|
if a != b || dst.forgottenInodes[b] != inode {
|
|
t.Fatalf("forgotten %d: %q, want %q", inode, b, a)
|
|
}
|
|
}
|
|
}
|
|
|
|
func requireSameFileHandles(t *testing.T, src, dst *WFS) {
|
|
t.Helper()
|
|
if len(src.fhMap.inode2fh) != len(dst.fhMap.inode2fh) || !reflect.DeepEqual(src.fhMap.fh2inode, dst.fhMap.fh2inode) {
|
|
t.Fatalf("handle maps differ: %v / %v", dst.fhMap.fh2inode, src.fhMap.fh2inode)
|
|
}
|
|
for inode, want := range src.fhMap.inode2fh {
|
|
got := dst.fhMap.inode2fh[inode]
|
|
if got == nil {
|
|
t.Fatalf("handle of inode %d missing", inode)
|
|
}
|
|
if got.fh != want.fh || got.counter != want.counter || !reflect.DeepEqual(got.fhs, want.fhs) {
|
|
t.Fatalf("inode %d ids: got %d/%d/%v want %d/%d/%v", inode, got.fh, got.counter, got.fhs, want.fh, want.counter, want.fhs)
|
|
}
|
|
if !proto.Equal(got.entry.Entry, want.entry.Entry) || !proto.Equal(got.baseEntry.Load(), want.baseEntry.Load()) {
|
|
t.Fatalf("inode %d: entry or base differs", inode)
|
|
}
|
|
if got.entryVersionTsNs.Load() != want.entryVersionTsNs.Load() || got.entryVersionSignature.Load() != want.entryVersionSignature.Load() {
|
|
t.Fatalf("inode %d: entry version differs", inode)
|
|
}
|
|
if got.savedDir != want.savedDir || got.savedName != want.savedName || got.contentType != want.contentType ||
|
|
got.isDeleted != want.isDeleted || got.deleteEpoch != want.deleteEpoch || got.isRenamed != want.isRenamed ||
|
|
got.nameTaken != want.nameTaken || !bytes.Equal(got.linkRefresh, want.linkRefresh) ||
|
|
got.dirtyMetadata != want.dirtyMetadata || got.dirtyContent != want.dirtyContent ||
|
|
got.pendingAppend != want.pendingAppend || got.pendingAppendOffset != want.pendingAppendOffset {
|
|
t.Fatalf("inode %d: flags differ:\n got %+v\nwant %+v", inode, got, want)
|
|
}
|
|
gm, wm := got.sinceBase.Load(), want.sinceBase.Load()
|
|
if (gm == nil) != (wm == nil) || gm != nil && (gm.truncatedTo != wm.truncatedTo || gm.rewrote != wm.rewrote || gm.base != got.baseEntry.Load()) {
|
|
t.Fatalf("inode %d: base mark %+v, want %+v", inode, gm, wm)
|
|
}
|
|
if (got.writebackContentError == nil) || got.writebackContentError.Load() != want.writebackContentError.Load() {
|
|
t.Fatalf("inode %d: writeback refusal flag differs", inode)
|
|
}
|
|
// Chunks with a manifest are resolved lazily, never at import.
|
|
hasManifest := false
|
|
for _, c := range want.entry.Entry.Chunks {
|
|
hasManifest = hasManifest || c.IsChunkManifest
|
|
}
|
|
if got.chunkViewStale.Load() != hasManifest {
|
|
t.Fatalf("inode %d: chunkViewStale %v, manifest %v", inode, got.chunkViewStale.Load(), hasManifest)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHandoverRoundTrip(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
fx := populateForHandover(t, src)
|
|
data := exportToBytes(t, src)
|
|
|
|
dst := newHandoverWFS(t)
|
|
dst.signature, dst.posixSid = 1, 1
|
|
if err := dst.ImportHandoverState(bytes.NewReader(data)); err != nil {
|
|
t.Fatalf("import: %v", err)
|
|
}
|
|
|
|
requireSameInodeTables(t, src.inodeToPath, dst.inodeToPath)
|
|
if dst.inodeToPath.dirStateOf("/a") == nil || dst.inodeToPath.GetSubdirCount("/a") != 3 {
|
|
t.Fatal("directory state of /a not restored")
|
|
}
|
|
if paths := dst.inodeToPath.GetAllPaths(fx.file); !slices.Equal(sortedPaths(paths), []string{"/a/f1", "/a/f1.link"}) {
|
|
t.Fatalf("hard link paths: %v", paths)
|
|
}
|
|
if _, status := dst.inodeToPath.GetPath(fx.removed); status == fuse.OK {
|
|
t.Fatal("the removed inode got a path")
|
|
}
|
|
requireSameFileHandles(t, src, dst)
|
|
|
|
// Directory handle: the window the kernel is inside.
|
|
srcDh, dstDh := src.dhMap.dir2inode[fx.dirHandle], dst.dhMap.dir2inode[fx.dirHandle]
|
|
if dstDh == nil || dstDh.entryStreamOffset != 12 || dstDh.lastListedName != "x2" || dstDh.snapshotTsNs != 4444 || !dstDh.isFinished || len(dstDh.entryStream) != 3 {
|
|
t.Fatalf("directory handle: %+v", dstDh)
|
|
}
|
|
for i, e := range srcDh.entryStream {
|
|
g := dstDh.entryStream[i]
|
|
if g.FullPath != e.FullPath || g.Inode != e.Inode || g.FileSize != e.FileSize || g.Mode != e.Mode || !g.Mtime.Equal(e.Mtime) {
|
|
t.Fatalf("stream entry %d: %+v, want %+v", i, g, e)
|
|
}
|
|
}
|
|
|
|
// Locks.
|
|
il := dst.posixLocks.inodes[fx.file]
|
|
if il == nil || len(il.locks) != 2 || len(il.waiters) != 0 {
|
|
t.Fatalf("lock table: %+v", il)
|
|
}
|
|
if !reflect.DeepEqual(il.locks, src.posixLocks.inodes[fx.file].locks) {
|
|
t.Fatalf("locks %v, want %v", il.locks, src.posixLocks.inodes[fx.file].locks)
|
|
}
|
|
if st := dst.posixLocks.SetLk(fx.file, lockRange{Start: 10, End: 20, Typ: f_WRLCK, Owner: 99}); st != fuse.EAGAIN {
|
|
t.Fatalf("a conflicting lock got %v, want EAGAIN", st)
|
|
}
|
|
if !reflect.DeepEqual(dst.fhLocks.m, src.fhLocks.m) || !reflect.DeepEqual(dst.posixHint.m, src.posixHint.m) {
|
|
t.Fatalf("lock owners: %v %v", dst.fhLocks.m, dst.posixHint.m)
|
|
}
|
|
if !reflect.DeepEqual(dst.posixOwn.Snapshot(), src.posixOwn.Snapshot()) {
|
|
t.Fatalf("routed lock mirror: %v", dst.posixOwn.Snapshot())
|
|
}
|
|
|
|
// Identities.
|
|
if dst.signature != 4242 || dst.posixSid != 777 {
|
|
t.Fatalf("signature %d, session %d", dst.signature, dst.posixSid)
|
|
}
|
|
if dst.handoverMetaTsNs != 98765 {
|
|
t.Fatalf("subscription position %d, want 98765", dst.handoverMetaTsNs)
|
|
}
|
|
|
|
// Overlays.
|
|
if at := dst.atimeMap[fx.file]; !at.Equal(time.Unix(1700000000, 123)) {
|
|
t.Fatalf("atime %v", at)
|
|
}
|
|
if mt := dst.dirMtimeMap[fx.dir]; !mt.Equal(time.Unix(1700000001, 456)) {
|
|
t.Fatalf("dir mtime %v", mt)
|
|
}
|
|
if rd := dst.removedDirEntry(fx.removed); rd == nil || rd.Name != "rd" {
|
|
t.Fatalf("removed dir entry %v", rd)
|
|
}
|
|
state, ok := dst.writebackContentErrors.Load(fx.unlinked)
|
|
if !ok || !state.(*atomic.Bool).Load() {
|
|
t.Fatal("writeback refusal flag lost")
|
|
}
|
|
|
|
// Restored handles behave like live ones.
|
|
fh := dst.GetHandle(fx.openB)
|
|
if fh == nil || fh.inode != fx.file {
|
|
t.Fatalf("GetHandle after import: %v", fh)
|
|
}
|
|
if !dst.fhMap.isAppendHandle(fx.openB) || dst.fhMap.isAppendHandle(fx.openA) {
|
|
t.Fatal("append mode of the opens lost")
|
|
}
|
|
if _, err := fh.dirtyPages.AddPage(0, []byte("hello"), true, time.Now().UnixNano()); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
if !fh.dirtyPages.HasPendingUploads() {
|
|
t.Fatal("a write on a restored handle is not buffered")
|
|
}
|
|
fh.dirtyPages.Destroy()
|
|
dst.ReleaseHandle(fx.openA)
|
|
dst.ReleaseHandle(fx.openB)
|
|
if _, found := dst.fhMap.FindFileHandle(fx.file); found {
|
|
t.Fatal("handle survived its last release")
|
|
}
|
|
}
|
|
|
|
// An export is repeatable: what was imported exports to the same state.
|
|
func TestHandoverReexport(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
populateForHandover(t, src)
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(exportToBytes(t, src))); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// The unlinked handle was dirty and stays so; the open handle's pending
|
|
// state is empty, so the second export must succeed too.
|
|
third := newHandoverWFS(t)
|
|
if err := third.ImportHandoverState(bytes.NewReader(exportToBytes(t, dst))); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
requireSameInodeTables(t, src.inodeToPath, third.inodeToPath)
|
|
requireSameFileHandles(t, src, third)
|
|
// dst never started its subscription: it passes on the position it got.
|
|
if third.handoverMetaTsNs != 98765 {
|
|
t.Fatalf("subscription position after a second handover %d, want 98765", third.handoverMetaTsNs)
|
|
}
|
|
}
|
|
|
|
func TestHandoverExportRefusals(t *testing.T) {
|
|
now := time.Now().Unix()
|
|
open := func(wfs *WFS, path util.FullPath) *FileHandle {
|
|
inode := wfs.inodeToPath.Lookup(path, now, false, false, 0, true)
|
|
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, testEntry(path.Name(), inode), 1, 1, false)
|
|
fh.RememberPath(path)
|
|
return fh
|
|
}
|
|
cases := []struct {
|
|
name string
|
|
arm func(t *testing.T, wfs *WFS) (undo func())
|
|
want string
|
|
}{
|
|
{"dirty pages", func(t *testing.T, wfs *WFS) func() {
|
|
fh := open(wfs, "/dirty")
|
|
if _, err := fh.dirtyPages.AddPage(0, []byte("data"), true, time.Now().UnixNano()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return func() { fh.dirtyPages.Destroy() }
|
|
}, "dirty pages or uploads"},
|
|
{"dirty metadata", func(t *testing.T, wfs *WFS) func() {
|
|
open(wfs, "/meta").dirtyMetadata = true
|
|
return func() {}
|
|
}, "unflushed changes"},
|
|
{"unpublished create", func(t *testing.T, wfs *WFS) func() {
|
|
fh := open(wfs, "/created")
|
|
fh.dirtyMetadata = true
|
|
fh.baseEntry.Store(nil)
|
|
return func() {}
|
|
}, "unpublished create"},
|
|
{"deferred close flush", func(t *testing.T, wfs *WFS) func() {
|
|
open(wfs, "/closed").asyncFlushPending = true
|
|
return func() {}
|
|
}, "close flush still deferred"},
|
|
{"operation in flight", func(t *testing.T, wfs *WFS) func() {
|
|
fh := open(wfs, "/busy")
|
|
lock := wfs.fhLockTable.AcquireLock("test", fh.fh, util.ExclusiveLock)
|
|
return func() { wfs.fhLockTable.ReleaseLock(fh.fh, lock) }
|
|
}, "an operation on it is in flight"},
|
|
{"failed flush left state", func(t *testing.T, wfs *WFS) func() {
|
|
open(wfs, "/failed").noteFailedFlush(&chunkFold{}, []*filer_pb.FileChunk{{FileId: "9,1"}})
|
|
return func() {}
|
|
}, "failed flush left state"},
|
|
{"blocked lock waiter", func(t *testing.T, wfs *WFS) func() {
|
|
inode := wfs.inodeToPath.Lookup("/locked", now, false, false, 0, true)
|
|
wfs.posixLocks.SetLk(inode, lockRange{Start: 0, End: 9, Typ: f_WRLCK, Owner: 1})
|
|
cancel := make(chan struct{})
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
wfs.posixLocks.SetLkw(inode, lockRange{Start: 0, End: 9, Typ: f_WRLCK, Owner: 2}, cancel)
|
|
}()
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
il := wfs.posixLocks.getInodeLocks(inode)
|
|
il.mu.Lock()
|
|
waiting := len(il.waiters)
|
|
il.mu.Unlock()
|
|
if waiting > 0 {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("waiter never blocked")
|
|
}
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
return func() { close(cancel); <-done }
|
|
}, "lock waiters still blocked"},
|
|
{"routed lock waiter", func(t *testing.T, wfs *WFS) func() {
|
|
wfs.routedLockWaiters.Add(1)
|
|
return func() { wfs.routedLockWaiters.Add(-1) }
|
|
}, "routed lock requests still waiting"},
|
|
{"background close flush", func(t *testing.T, wfs *WFS) func() {
|
|
wfs.pendingAsyncFlush[5] = make(chan struct{})
|
|
return func() { delete(wfs.pendingAsyncFlush, 5) }
|
|
}, "still flush in the background"},
|
|
{"background create", func(t *testing.T, wfs *WFS) func() {
|
|
wfs.asyncCreates.Add(1)
|
|
return func() { wfs.asyncCreates.Add(-1) }
|
|
}, "still being sent"},
|
|
{"filer token", func(t *testing.T, wfs *WFS) func() {
|
|
wfs.chunkProofs = newChunkProofs(chunkProofLimit)
|
|
return func() { wfs.chunkProofs = nil }
|
|
}, "filer token"},
|
|
{"directory read in flight", func(t *testing.T, wfs *WFS) func() {
|
|
_, dh := wfs.AcquireDirectoryHandle()
|
|
dh.Lock()
|
|
return dh.Unlock
|
|
}, "a read is in flight"},
|
|
{"metadata subscription running", func(t *testing.T, wfs *WFS) func() {
|
|
wfs.metaFollowers.Add(1)
|
|
return func() { wfs.metaFollowers.Add(-1) }
|
|
}, "metadata subscription is still running"},
|
|
{"metadata event not yet applied", func(t *testing.T, wfs *WFS) func() {
|
|
wait := handoverEventSettleWait
|
|
handoverEventSettleWait = 20 * time.Millisecond
|
|
t.Cleanup(func() { handoverEventSettleWait = wait })
|
|
return holdEntryInvalidations(t, wfs, updateEventFor("file", 1, 1000))
|
|
}, "still being applied"},
|
|
{"nfs export record being written", func(t *testing.T, wfs *WFS) func() {
|
|
wait := handoverEventSettleWait
|
|
handoverEventSettleWait = 20 * time.Millisecond
|
|
t.Cleanup(func() { handoverEventSettleWait = wait })
|
|
kv := &fakeKv{values: map[string][]byte{}}
|
|
entered, let := make(chan struct{}), make(chan struct{})
|
|
wfs.exportedHandles = newExportedHandles(1, func(key, value []byte) error {
|
|
close(entered)
|
|
<-let
|
|
return kv.put(key, value)
|
|
}, kv.get, kv.lock)
|
|
wfs.exportedHandles.AcquireHandle(5, "/a")
|
|
select {
|
|
case <-entered:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("the record write never reached the filer")
|
|
}
|
|
return func() { close(let) }
|
|
}, "still being written to the filer"},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
wfs := newHandoverWFS(t)
|
|
defer tc.arm(t, wfs)()
|
|
var buf bytes.Buffer
|
|
err := wfs.ExportHandoverState(&buf)
|
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
|
t.Fatalf("export error %v, want one naming %q", err, tc.want)
|
|
}
|
|
if buf.Len() != 0 {
|
|
t.Fatalf("a refused export wrote %d bytes", buf.Len())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A refused export leaves the mount serving, and its nfs export writer with it.
|
|
func TestHandoverRefusedExportResumesNfsExportWriter(t *testing.T) {
|
|
kv := &fakeKv{values: map[string][]byte{}}
|
|
wfs := newHandoverWFS(t)
|
|
wfs.exportedHandles = newExportedHandlesForTest(kv, 1, time.Minute)
|
|
wfs.asyncCreates.Add(1)
|
|
if err := wfs.ExportHandoverState(io.Discard); err == nil {
|
|
t.Fatal("export went through with a create still being sent")
|
|
}
|
|
wfs.asyncCreates.Add(-1)
|
|
wfs.exportedHandles.AcquireHandle(5, "/after")
|
|
kv.waitFor(t, 5, "/after")
|
|
}
|
|
|
|
// holdEntryInvalidations applies events as the metadata subscription does and
|
|
// returns with the invalidation worker held at the first of them, as a busy
|
|
// handle lock or a slow kernel notification holds it. release lets it go on;
|
|
// the test's cleanup calls it too, before the meta cache is shut down.
|
|
func holdEntryInvalidations(t *testing.T, wfs *WFS, events ...*filer_pb.SubscribeMetadataResponse) (release func()) {
|
|
t.Helper()
|
|
reached, gate := make(chan struct{}), make(chan struct{})
|
|
var once, releaseOnce sync.Once
|
|
release = func() { releaseOnce.Do(func() { close(gate) }) }
|
|
t.Cleanup(release)
|
|
wfs.SetEntryChangeListener(func(meta_cache.EntryInvalidation) {
|
|
once.Do(func() { close(reached) })
|
|
<-gate
|
|
})
|
|
for _, event := range events {
|
|
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), event, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
|
t.Fatalf("apply event: %v", err)
|
|
}
|
|
// The subscription moves its position on once the event is applied.
|
|
wfs.metaCache.NoteSubscribedTsNs(event.TsNs)
|
|
}
|
|
select {
|
|
case <-reached:
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("the invalidation worker never got the event")
|
|
}
|
|
return release
|
|
}
|
|
|
|
// The subscription's position moves on when an event is in the meta cache,
|
|
// while what the event does to an open handle or to the inode table is still
|
|
// queued. An export in between would hand the successor the position without
|
|
// the change, and it would never see the event again.
|
|
func TestHandoverExportWaitsForEventsToReachTheState(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
now := time.Now().Unix()
|
|
opened := src.inodeToPath.Lookup("/dir/file", now, false, false, 0, true)
|
|
fh, _, _, _ := src.fhMap.AcquireFileHandle(src, opened, &filer_pb.Entry{
|
|
Name: "file",
|
|
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
|
}, 0, 0)
|
|
fh.RememberPath("/dir/file")
|
|
moved := src.inodeToPath.Lookup("/dir/old", now, false, false, 0, true)
|
|
|
|
// Another mount writes the open file and renames the other one.
|
|
rename := &filer_pb.SubscribeMetadataResponse{
|
|
Directory: "/dir",
|
|
TsNs: 6000,
|
|
EventNotification: &filer_pb.EventNotification{
|
|
OldEntry: &filer_pb.Entry{Name: "old"},
|
|
NewEntry: &filer_pb.Entry{Name: "new", Attributes: &filer_pb.FuseAttributes{FileSize: 1}},
|
|
NewParentPath: "/dir",
|
|
},
|
|
}
|
|
release := holdEntryInvalidations(t, src, updateEventFor("file", 4096, 5000), rename)
|
|
|
|
// The events are let through only once the export waits for them, so the
|
|
// test cannot pass by an export that starts after they have landed.
|
|
waiting := make(chan struct{})
|
|
var waitingOnce sync.Once
|
|
settleStarted := handoverEventSettleStarted
|
|
handoverEventSettleStarted = func() { waitingOnce.Do(func() { close(waiting) }) }
|
|
t.Cleanup(func() { handoverEventSettleStarted = settleStarted })
|
|
|
|
exported := make(chan []byte, 1)
|
|
go func() {
|
|
var buf bytes.Buffer
|
|
if err := src.ExportHandoverState(&buf); err != nil {
|
|
t.Errorf("export: %v", err)
|
|
}
|
|
exported <- buf.Bytes()
|
|
}()
|
|
select {
|
|
case <-waiting:
|
|
case <-exported:
|
|
t.Fatal("exported while events were still on their way to the open file and the inode table")
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("the export never started waiting for the events")
|
|
}
|
|
select {
|
|
case <-exported:
|
|
t.Fatal("exported while events were still on their way to the open file and the inode table")
|
|
case <-time.After(100 * time.Millisecond):
|
|
}
|
|
release()
|
|
data := <-exported
|
|
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(data)); err != nil {
|
|
t.Fatalf("import: %v", err)
|
|
}
|
|
if dst.handoverMetaTsNs != 6000 {
|
|
t.Fatalf("subscription position %d, want that of the last event, 6000", dst.handoverMetaTsNs)
|
|
}
|
|
got := dst.fhMap.inode2fh[opened]
|
|
if got == nil || got.GetEntry().GetEntry().Attributes.FileSize != 4096 {
|
|
t.Fatalf("the open file crossed without the event at or below the position: %+v", got)
|
|
}
|
|
if path, status := dst.inodeToPath.GetPath(moved); status != fuse.OK || path != "/dir/new" {
|
|
t.Fatalf("the renamed inode crossed at %q (%v), want /dir/new", path, status)
|
|
}
|
|
}
|
|
|
|
// The unlinked file's handle is dirty for good; it must not block the export.
|
|
func TestHandoverExportCarriesUnlinkedDirtyHandle(t *testing.T) {
|
|
wfs := newHandoverWFS(t)
|
|
inode := wfs.inodeToPath.Lookup("/u", time.Now().Unix(), false, false, 0, true)
|
|
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, testEntry("u", inode), 1, 1, false)
|
|
fh.isDeleted, fh.dirtyMetadata = true, true
|
|
exportToBytes(t, wfs)
|
|
}
|
|
|
|
func TestHandoverImportRefusals(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
populateForHandover(t, src)
|
|
good := exportToBytes(t, src)
|
|
|
|
t.Run("truncated", func(t *testing.T) {
|
|
for _, cut := range []int{0, 5, 11, 40, len(good) / 2, len(good) - 1} {
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(good[:cut])); err == nil {
|
|
t.Fatalf("a stream cut at %d of %d bytes was accepted", cut, len(good))
|
|
}
|
|
if dst.inodeToPath.HasPath("/a") || len(dst.fhMap.inode2fh) != 0 {
|
|
t.Fatalf("a refused import changed the WFS (cut %d)", cut)
|
|
}
|
|
}
|
|
})
|
|
t.Run("corrupt", func(t *testing.T) {
|
|
bad := bytes.Clone(good)
|
|
bad[len(bad)/2] ^= 0xff
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(bad)); err == nil {
|
|
t.Fatal("a corrupt stream was accepted")
|
|
}
|
|
if dst.inodeToPath.HasPath("/a") {
|
|
t.Fatal("a refused import changed the WFS")
|
|
}
|
|
})
|
|
t.Run("version", func(t *testing.T) {
|
|
bad := bytes.Clone(good)
|
|
binary.BigEndian.PutUint32(bad[len(handoverMagic):], handoverFormatVersion+1)
|
|
if err := newHandoverWFS(t).ImportHandoverState(bytes.NewReader(bad)); err == nil || !strings.Contains(err.Error(), "version") {
|
|
t.Fatalf("got %v", err)
|
|
}
|
|
})
|
|
t.Run("mount root", func(t *testing.T) {
|
|
dst := newHandoverWFS(t)
|
|
dst.option.FilerMountRootPath = "/other"
|
|
if err := dst.ImportHandoverState(bytes.NewReader(good)); err == nil || !strings.Contains(err.Error(), "mount root") {
|
|
t.Fatalf("got %v", err)
|
|
}
|
|
})
|
|
t.Run("cache mode", func(t *testing.T) {
|
|
dst := newHandoverWFS(t)
|
|
dst.option.WritebackCache = false
|
|
if err := dst.ImportHandoverState(bytes.NewReader(good)); err == nil || !strings.Contains(err.Error(), "writebackCache") {
|
|
t.Fatalf("got %v", err)
|
|
}
|
|
})
|
|
// A lock held in the exporter's own table would exclude no one in a mount
|
|
// that asks the filer, and the other way round.
|
|
t.Run("lock mode", func(t *testing.T) {
|
|
mount := func(routed bool) *WFS {
|
|
wfs := newHandoverWFS(t)
|
|
wfs.option.WritebackCache = false
|
|
if routed {
|
|
wfs.lockClient = cluster.NewLockClient(wfs.option.GrpcDialOption, wfs.option.FilerAddresses[0])
|
|
}
|
|
return wfs
|
|
}
|
|
for _, routed := range []bool{false, true} {
|
|
src := mount(routed)
|
|
src.posixLocks.SetLk(7, lockRange{Start: 0, End: 9, Typ: f_WRLCK, Owner: 1})
|
|
src.posixOwn.Track("key", posixlock.Range{Start: 0, End: 9, Type: 1, Sid: src.posixSid, Owner: 1})
|
|
state := exportToBytes(t, src)
|
|
|
|
other := mount(!routed)
|
|
err := other.ImportHandoverState(bytes.NewReader(state))
|
|
if err == nil || !strings.Contains(err.Error(), "-dlm") {
|
|
t.Fatalf("from routed=%v to routed=%v: got %v", routed, !routed, err)
|
|
}
|
|
if len(other.posixLocks.inodes) != 0 || len(other.posixOwn.Snapshot()) != 0 || other.inodeToPath.HasPath("/a") {
|
|
t.Fatalf("from routed=%v: a refused import changed the WFS", routed)
|
|
}
|
|
if err := mount(routed).ImportHandoverState(bytes.NewReader(state)); err != nil {
|
|
t.Fatalf("from routed=%v to the same mode: %v", routed, err)
|
|
}
|
|
}
|
|
})
|
|
t.Run("used WFS", func(t *testing.T) {
|
|
dst := newHandoverWFS(t)
|
|
dst.inodeToPath.Lookup("/already", time.Now().Unix(), false, false, 0, true)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(good)); err == nil || !strings.Contains(err.Error(), "fresh") {
|
|
t.Fatalf("got %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A newer build may add fields and frame bodies; this one skips them.
|
|
func TestHandoverImportSkipsUnknownFields(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
buf.WriteString(handoverMagic)
|
|
binary.Write(&buf, binary.BigEndian, handoverFormatVersion)
|
|
e := &handoverEncoder{w: &buf, crc: crc32.NewIEEE()}
|
|
unknownField := protowire.AppendString(protowire.AppendTag(nil, 999, protowire.BytesType), "from the future")
|
|
|
|
identity := &hpb.HandoverFrame{Body: &hpb.HandoverFrame_Identity{Identity: &hpb.Identity{MountRoot: "/", Writeback: true, Signature: 9}}}
|
|
identity.ProtoReflect().SetUnknown(unknownField)
|
|
root := &hpb.Inode{Inode: 1, Nlookup: 1, Path: "/", IsDir: true}
|
|
rootFrame := &hpb.HandoverFrame{Body: &hpb.HandoverFrame_Inode{Inode: root}}
|
|
root.ProtoReflect().SetUnknown(unknownField)
|
|
futureBody := &hpb.HandoverFrame{} // a body this build has no field for
|
|
futureBody.ProtoReflect().SetUnknown(protowire.AppendString(protowire.AppendTag(nil, 77, protowire.BytesType), "new section"))
|
|
for _, f := range []*hpb.HandoverFrame{identity, futureBody, rootFrame} {
|
|
if err := e.write(f); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
end := &hpb.HandoverFrame{Body: &hpb.HandoverFrame_End{End: &hpb.End{Crc32: e.crc.Sum32(), Frames: e.frames}}}
|
|
if err := e.write(end); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(&buf); err != nil {
|
|
t.Fatalf("import: %v", err)
|
|
}
|
|
if dst.signature != 9 {
|
|
t.Fatalf("signature %d", dst.signature)
|
|
}
|
|
}
|
|
|
|
// Every field of the structures a handover touches has a place in the
|
|
// classification written next to its type. Adding a field fails here until it
|
|
// is classified in the code comment and in handover_*.go.
|
|
func TestHandoverClassifiesEveryHandleField(t *testing.T) {
|
|
classified := map[string]map[string]string{
|
|
"FileHandle": {
|
|
"fh": "crosses", "counter": "crosses", "fhs": "crosses", "entry": "crosses", "entryLock": "rebuilt",
|
|
"entryChunkGroup": "rebuilt", "inode": "crosses", "wfs": "rebuilt", "pendingAppend": "crosses",
|
|
"pendingAppendOffset": "crosses", "writebackContentError": "rebuilt", "dirtyMetadata": "crosses",
|
|
"dirtyContent": "crosses", "dirtyPages": "empty", "reader": "rebuilt", "contentType": "crosses",
|
|
"asyncFlushPending": "empty", "asyncFlushUid": "empty", "asyncFlushGid": "empty", "savedDir": "crosses",
|
|
"savedName": "crosses", "isDeleted": "crosses", "deleteEpoch": "crosses", "isRenamed": "crosses",
|
|
"nameTaken": "crosses", "linkRefresh": "crosses", "pageWrites": "rebuilt", "entryVersionTsNs": "crosses",
|
|
"entryVersionSignature": "crosses", "baseEntry": "crosses", "sinceBase": "crosses",
|
|
"chunkViewStale": "rebuilt", "dlmLock": "empty", "remoteInstallMu": "rebuilt", "mirrorFile": "rebuilt",
|
|
},
|
|
"InodeToPath": {
|
|
"RWMutex": "rebuilt", "nextInodeId": "unused", "forgotten": "crosses", "forgottenInodes": "crosses",
|
|
"cacheMetaTtlSec": "config", "inode2path": "crosses", "path2inode": "rebuilt", "dirStates": "crosses",
|
|
"dirPaths": "rebuilt", "wasCachedDirs": "dropped", "wasCachedOrder": "dropped", "wasCachedGen": "dropped",
|
|
},
|
|
"InodeEntry": {"path": "crosses", "nlookup": "crosses", "extraPaths": "crosses"},
|
|
"dirState": {
|
|
"path": "crosses", "isChildrenCached": "dropped", "readDirDirect": "dropped", "cachedExpiresTime": "dropped",
|
|
"lastAccess": "dropped", "lastRefresh": "dropped", "lastRebuildAttempt": "dropped",
|
|
"lastSectionAttempts": "dropped", "subdirCount": "crosses",
|
|
},
|
|
"DirectoryHandle": {
|
|
"Mutex": "rebuilt", "isFinished": "crosses", "entryStream": "crosses", "entryStreamOffset": "crosses",
|
|
"lastListedName": "crosses", "snapshotTsNs": "crosses",
|
|
},
|
|
"inodeLocks": {"mu": "rebuilt", "locks": "crosses", "waiters": "empty", "wakeRefs": "empty", "dead": "rebuilt"},
|
|
"lockRange": {"Start": "crosses", "End": "crosses", "Typ": "crosses", "Owner": "crosses", "Pid": "crosses", "IsFlock": "crosses"},
|
|
}
|
|
types := map[string]reflect.Type{
|
|
"FileHandle": reflect.TypeOf(FileHandle{}), "InodeToPath": reflect.TypeOf(InodeToPath{}),
|
|
"InodeEntry": reflect.TypeOf(InodeEntry{}), "dirState": reflect.TypeOf(dirState{}),
|
|
"DirectoryHandle": reflect.TypeOf(DirectoryHandle{}), "inodeLocks": reflect.TypeOf(inodeLocks{}),
|
|
"lockRange": reflect.TypeOf(lockRange{}),
|
|
}
|
|
for name, typ := range types {
|
|
seen := map[string]bool{}
|
|
for i := 0; i < typ.NumField(); i++ {
|
|
f := typ.Field(i).Name
|
|
seen[f] = true
|
|
if _, ok := classified[name][f]; !ok {
|
|
t.Errorf("%s.%s is not classified for a handover: decide whether it crosses, is rebuilt or must be empty, and say so next to the type", name, f)
|
|
}
|
|
}
|
|
for f := range classified[name] {
|
|
if !seen[f] {
|
|
t.Errorf("%s.%s is classified but no longer exists", name, f)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// A listing in progress, with the kernel's offset in the middle of a batch,
|
|
// continues after a handover with no entry skipped or repeated.
|
|
func TestHandoverContinuesListingInProgress(t *testing.T) {
|
|
dir := util.FullPath("/big")
|
|
var names []string
|
|
for i := 0; i < 2600; i++ {
|
|
names = append(names, fmt.Sprintf("f%05d", i))
|
|
}
|
|
src := newPagingWFS(t, dir, names, 0)
|
|
prepare := func(wfs *WFS) { // what the handover test needs on top of the paging fixture
|
|
wfs.dhMap = NewDirectoryHandleToInode()
|
|
wfs.posixLocks = NewPosixLockTable()
|
|
wfs.posixHint = newPosixLockHint()
|
|
wfs.posixOwn = posixlock.NewManager()
|
|
wfs.pendingAsyncFlush = make(map[uint64]chan struct{})
|
|
wfs.atimeMap = make(map[uint64]time.Time)
|
|
wfs.dirMtimeMap = make(map[uint64]time.Time)
|
|
}
|
|
prepare(src)
|
|
dirInode, _ := src.inodeToPath.GetInode(dir)
|
|
dhid, _ := src.AcquireDirectoryHandle()
|
|
|
|
var got []string
|
|
offset := uint64(0)
|
|
readRounds := func(wfs *WFS, rounds, perRound int) {
|
|
t.Helper()
|
|
for r := 0; r < rounds; r++ {
|
|
sink := &pagingSink{limit: perRound}
|
|
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
|
|
InHeader: fuse.InHeader{NodeId: dirInode}, Fh: uint64(dhid), Offset: offset,
|
|
}, sink, false)
|
|
if status != fuse.OK {
|
|
t.Fatalf("readdir at %d: %v", offset, status)
|
|
}
|
|
for _, n := range sink.names {
|
|
if n != "." && n != ".." {
|
|
got = append(got, n)
|
|
}
|
|
}
|
|
if sink.lastOff != 0 {
|
|
offset = sink.lastOff
|
|
}
|
|
}
|
|
}
|
|
// 5 rounds of 130 entries: well inside the first batch of 1000.
|
|
readRounds(src, 5, 130)
|
|
if len(got) != 648 || offset == 0 {
|
|
t.Fatalf("setup: read %d entries, offset %d", len(got), offset)
|
|
}
|
|
|
|
data := exportToBytes(t, src)
|
|
dst := newPagingWFS(t, dir, names, 0)
|
|
prepare(dst)
|
|
dst.inodeToPath = NewInodeToPath("/", 0) // a fresh process holds no inodes
|
|
if err := dst.ImportHandoverState(bytes.NewReader(data)); err != nil {
|
|
t.Fatalf("import: %v", err)
|
|
}
|
|
// The new process has the listing cached by now, as a first listing
|
|
// would have loaded it from the filer.
|
|
dst.inodeToPath.MarkChildrenCached("/")
|
|
dst.inodeToPath.MarkChildrenCached(dir)
|
|
|
|
if dh := dst.dhMap.dir2inode[dhid]; dh == nil || len(dh.entryStream) == 0 || dh.entryStreamOffset <= directoryStreamBaseOffset {
|
|
t.Fatalf("the handle's window did not cross: %+v", dh)
|
|
}
|
|
|
|
// The rest, across the end of the window and the next batches.
|
|
for len(got) < len(names) {
|
|
before := len(got)
|
|
readRounds(dst, 1, 130)
|
|
if len(got) == before {
|
|
break
|
|
}
|
|
}
|
|
if !slices.Equal(got, names) {
|
|
for i := range got {
|
|
if i >= len(names) || got[i] != names[i] {
|
|
t.Fatalf("listing diverges at %d: got %q, want %q (got %d names, want %d)", i, got[i], names[len(names)-1], len(got), len(names))
|
|
}
|
|
}
|
|
t.Fatalf("got %d names, want %d", len(got), len(names))
|
|
}
|
|
}
|
|
|
|
// A mount that hands over before its subscription saw an event still passes a
|
|
// position on: where it started. Its successor would otherwise subscribe from
|
|
// its own start time and miss what happened in between.
|
|
func TestHandoverCarriesTheSubscriptionStart(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
before := time.Now().UnixNano()
|
|
started := src.metadataFollowStart().UnixNano()
|
|
if started < before {
|
|
t.Fatalf("subscription start %d is before now %d", started, before)
|
|
}
|
|
if got := src.metaCache.SubscribedTsNs(); got != started {
|
|
t.Fatalf("position %d before the first event, want the start %d", got, started)
|
|
}
|
|
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(exportToBytes(t, src))); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := dst.metadataFollowStart().UnixNano(); got != started {
|
|
t.Fatalf("the successor subscribes from %d, want the predecessor's start %d", got, started)
|
|
}
|
|
|
|
// An event moves the position on, and it never moves back.
|
|
src.metaCache.NoteSubscribedTsNs(started + 1000)
|
|
src.metaCache.NoteSubscribedTsNs(started + 10)
|
|
if got := src.metaCache.SubscribedTsNs(); got != started+1000 {
|
|
t.Fatalf("position %d, want %d", got, started+1000)
|
|
}
|
|
}
|
|
|
|
// The import leaves a caller's buffered reader right behind the state, so the
|
|
// rest of a conversation on the same connection is not swallowed.
|
|
func TestHandoverImportStopsAtTheEndFrame(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
populateForHandover(t, src)
|
|
const next = "the next message"
|
|
stream := append(exportToBytes(t, src), next...)
|
|
|
|
// Smaller than the import's own buffer: bufio would wrap it, not reuse it.
|
|
br := bufio.NewReaderSize(bytes.NewReader(stream), 4096)
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(br); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rest, err := io.ReadAll(br)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if string(rest) != next {
|
|
t.Fatalf("after the state the reader holds %q, want %q", rest, next)
|
|
}
|
|
}
|
|
|
|
// Each open of a file has its own fh id over one shared handle, whose own id is
|
|
// that of the first open and stays so after that open is closed: it keys the
|
|
// handle's lock. A handle crosses with whichever of its opens are left.
|
|
func TestHandoverCarriesPartlyClosedHandle(t *testing.T) {
|
|
for _, closeFirst := range []bool{true, false} {
|
|
name := "second open closed"
|
|
if closeFirst {
|
|
name = "first open closed"
|
|
}
|
|
t.Run(name, func(t *testing.T) {
|
|
src := newHandoverWFS(t)
|
|
inode := src.inodeToPath.Lookup("/f", time.Now().Unix(), false, false, 0, true)
|
|
fh, first, _, _ := src.fhMap.AcquireFileHandle(src, inode, testEntry("f", inode), 111, 5, false)
|
|
fh.RememberPath("/f")
|
|
_, second, _, _ := src.fhMap.AcquireFileHandle(src, inode, nil, 0, 0, true)
|
|
closed, left := second, first
|
|
if closeFirst {
|
|
closed, left = first, second
|
|
}
|
|
src.ReleaseHandle(closed)
|
|
if fh.fh != first || fh.counter != 1 || len(fh.fhs) != 1 {
|
|
t.Fatalf("after the release: fh %d (first open %d), counter %d, opens %v", fh.fh, first, fh.counter, fh.fhs)
|
|
}
|
|
|
|
dst := newHandoverWFS(t)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(exportToBytes(t, src))); err != nil {
|
|
t.Fatalf("import: %v", err)
|
|
}
|
|
requireSameFileHandles(t, src, dst)
|
|
if got := dst.GetHandle(left); got == nil || got.inode != inode || got.fh != first {
|
|
t.Fatalf("the open that is left resolves to %+v", got)
|
|
}
|
|
if got := dst.GetHandle(closed); got != nil {
|
|
t.Fatalf("the closed open resolves to inode %d", got.inode)
|
|
}
|
|
// The handle's lock is keyed by its own id on both sides.
|
|
lock := dst.fhLockTable.AcquireLock("test", first, util.ExclusiveLock)
|
|
dst.fhLockTable.ReleaseLock(first, lock)
|
|
dst.ReleaseHandle(left)
|
|
if _, found := dst.fhMap.FindFileHandle(inode); found {
|
|
t.Fatal("handle survived its last release")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// With -nfsExport the mount registers the path of every open file on the filer,
|
|
// through one background writer. What that writer has not written crosses as
|
|
// dirty, so the successor writes it: a record it has queued, one whose write is
|
|
// in flight or waits for its retry (both are lost with the process), and the
|
|
// removal of a closed file's record, which has neither a path nor an open count
|
|
// left to be found by.
|
|
func TestHandoverCarriesUnwrittenNfsExportRecords(t *testing.T) {
|
|
const stays, renamed, failing, closed, closing = 11, 12, 13, 14, 15
|
|
kv := &fakeKv{values: map[string][]byte{}}
|
|
|
|
// The exporter's writer: it fails every write of one inode, and can be
|
|
// held in the write of another until the successor has written it again,
|
|
// as when the write is slow to reach the filer. Once the test is over it
|
|
// writes what it has left and goes idle.
|
|
var failed atomic.Int32
|
|
var heldOnce, heldDoneOnce sync.Once
|
|
hold, held, over := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
|
let, heldDone := make(chan struct{}), make(chan struct{})
|
|
t.Cleanup(func() { close(over) })
|
|
src := newHandoverWFS(t)
|
|
src.exportedHandles = newExportedHandles(1, kv.put, kv.get, func(inode uint64) (func(), error) {
|
|
select {
|
|
case <-over:
|
|
return func() {}, nil
|
|
default:
|
|
}
|
|
select {
|
|
case <-hold:
|
|
if inode == renamed {
|
|
heldOnce.Do(func() { close(held) })
|
|
select {
|
|
case <-let:
|
|
case <-over:
|
|
}
|
|
return func() { heldDoneOnce.Do(func() { close(heldDone) }) }, nil
|
|
}
|
|
default:
|
|
}
|
|
if inode == failing {
|
|
failed.Add(1)
|
|
return nil, errors.New("no lock server")
|
|
}
|
|
return func() {}, nil
|
|
})
|
|
h := src.exportedHandles
|
|
h.delay = time.Millisecond
|
|
|
|
h.AcquireHandle(stays, "/stays")
|
|
h.AcquireHandle(renamed, "/old")
|
|
h.AcquireHandle(closed, "/closed")
|
|
h.AcquireHandle(closing, "/closing")
|
|
for inode, path := range map[uint64]util.FullPath{stays: "/stays", renamed: "/old", closed: "/closed", closing: "/closing"} {
|
|
kv.waitFor(t, inode, path)
|
|
}
|
|
h.AcquireHandle(failing, "/failing") // its write fails, and waits a second for the retry
|
|
waitUntil := func(what string, done func() bool) {
|
|
t.Helper()
|
|
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) {
|
|
h.mu.Lock()
|
|
ok := done()
|
|
h.mu.Unlock()
|
|
if ok {
|
|
return
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("never happened: %s", what)
|
|
}
|
|
}
|
|
}
|
|
waitUntil("the failed write", func() bool { return failed.Load() > 0 && len(h.dirty) == 0 })
|
|
|
|
close(hold)
|
|
h.RememberPath(renamed, "/new") // the writer takes it and stays in its write
|
|
select {
|
|
case <-held:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("the writer never took the write of the renamed file")
|
|
}
|
|
h.ReleaseHandle(closed) // the timer fires: no path, no open, queued behind the held writer
|
|
waitUntil("the removal timer of the closed file", func() bool {
|
|
_, recorded := h.paths[closed]
|
|
_, queued := h.dirty[closed]
|
|
return !recorded && queued
|
|
})
|
|
h.mu.Lock()
|
|
h.delay = time.Minute
|
|
h.mu.Unlock()
|
|
h.ReleaseHandle(closing) // closed, its removal timer still pending
|
|
|
|
state := exportToBytes(t, src)
|
|
|
|
// The successor runs in a new pod, whose hostname gives it another owner:
|
|
// it takes the exporter's, and finds on the filer what the exporter last
|
|
// wrote.
|
|
dst := newHandoverWFS(t)
|
|
dst.exportedHandles = newExportedHandlesForTest(kv, 2, 20*time.Millisecond)
|
|
if err := dst.ImportHandoverState(bytes.NewReader(state)); err != nil {
|
|
t.Fatalf("import: %v", err)
|
|
}
|
|
kv.waitFor(t, renamed, "/new") // the write that was in flight
|
|
kv.waitFor(t, failing, "/failing") // the write that waited for its retry
|
|
kv.waitFor(t, closed, "") // the queued removal
|
|
kv.waitFor(t, closing, "") // the removal whose timer started again
|
|
kv.waitFor(t, stays, "/stays") // untouched
|
|
d := dst.exportedHandles
|
|
d.mu.Lock()
|
|
if d.paths[stays] != "/stays" || d.opens[stays] != 1 || d.paths[renamed] != "/new" || d.opens[failing] != 1 {
|
|
t.Fatalf("records of the open files: paths %v, opens %v", d.paths, d.opens)
|
|
}
|
|
if _, recorded := d.paths[closed]; recorded || d.opens[closed] != 0 || d.opens[closing] != 0 {
|
|
t.Fatalf("records of the closed files: paths %v, opens %v", d.paths, d.opens)
|
|
}
|
|
d.mu.Unlock()
|
|
|
|
// The successor renames the file again. The exporter's write still in
|
|
// flight must not take the record back once it gets through.
|
|
d.RememberPath(renamed, "/newest")
|
|
kv.waitFor(t, renamed, "/newest")
|
|
close(let)
|
|
select {
|
|
case <-heldDone:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("the exporter's held write never finished")
|
|
}
|
|
h.mu.Lock()
|
|
h.delay = time.Millisecond
|
|
h.mu.Unlock()
|
|
h.ReleaseHandle(stays) // its removal timer fires in the exporter
|
|
waitUntil("the removal timer of the stays record", func() bool {
|
|
_, recorded := h.paths[stays]
|
|
return !recorded && len(h.wake) == 0
|
|
})
|
|
h.wake <- struct{}{} // the writer takes it only once done with the removal's wake
|
|
waitUntil("the stopped writer to leave the removal queued", func() bool {
|
|
_, queued := h.dirty[stays]
|
|
return queued && len(h.wake) == 0
|
|
})
|
|
kv.waitFor(t, renamed, "/newest")
|
|
kv.waitFor(t, stays, "/stays")
|
|
}
|