Files
seaweedfs/weed/mount/handover_handles.go
T
a4269d6b51 mount: export and import the in-memory state of a mount for a handover (#13370)
* pb: add mount_handover.proto, the state a mount hands to its successor

Messages for the in-memory state a new `weed mount` process needs to take
over a live FUSE connection. The stream is a small header followed by
length-delimited HandoverFrame messages, one record per frame, so a table of
millions of inodes is neither encoded nor decoded as a whole. Protobuf keeps
the state readable across builds: fields are only added, and a reader ignores
fields and frame bodies it does not know, so a newer build imports what an
older one exported. File entries reuse filer_pb.Entry.

Generated with protoc 33.4 and protoc-gen-go 1.36.6, as mount.pb.go is.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: export and import the in-memory state of a mount for a handover

ExportHandoverState / ImportHandoverState carry what a new weed mount process
needs to serve the kernel's existing node and handle ids: the inode table
(paths, hard-link names, lookup counts, which inodes are directories), open
file handles under their fh ids with entry, base entry, entry version and the
flags that change later operations, directory handles with the window of
entries the kernel is inside, held POSIX/flock locks and the routed (-dlm)
session id with its mirror, the mount signature, the sticky per-inode write
errors, atime/dir-mtime overlays, removed-directory entries, the -nfsExport
records, and the metadata subscription position. Nothing is carried that
cannot be: the export is refused, naming every cause, for dirty pages,
uploads or deferred flushes, an unpublished create, a handle busy under its
lock, a blocked lock waiter (never answered with EINTR, which the kernel
turns into a restart only for a caller with a signal pending), a background
create, or a filer token. The handle of an unlinked file crosses dirty, as its
entry exists only there.

Encoding: protobuf (weed/pb/mount_handover.proto), one length-delimited frame
per record behind a header with a format version, ending in a frame with the
CRC-32. Frames stream, so a million-inode table is neither encoded nor decoded
as a whole, and the importer builds the final maps directly. Import verifies
the checksum before it changes anything, refuses another mount root, cache
mode or a WFS that already holds state, and makes no filer call: a manifest
chunk is resolved lazily on the first read, as after a failed resolution. A
caller's *bufio.Reader is used as it is and left right behind the state, so
more can follow on the same connection.

Every structure documents next to its type what crosses, what is rebuilt and
what must be empty; a test fails when a field is added without a place in it.

Three hooks in existing code, none of which changes behaviour:

- MetaCache.SubscribedTsNs is the log position of the last subscribed event
  handled, applied or skipped as the mount's own. The subscription's start is
  its first position, so a mount that hands over before its first event still
  passes one on. WFS.handoverMetaTsNs, which only an import sets, is where
  StartBackgroundTasks starts the subscription instead of at the start time.
- WFS.asyncCreates and WFS.routedLockWaiters count the writeback Mknod create
  goroutines and the SETLKW calls polling a routed lock. Neither has a handle
  or a table entry to inspect, and a handover must not drop either.

No caller yet: the handover itself follows.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: flush everything a handover would refuse to carry

FlushForHandover flushes every open handle that has dirty pages, dirty
metadata (this publishes deferred creates, whose only copy is a placeholder in
the meta cache that does not cross) or a deferred close flush, through doFlush
as fsync does, and waits for the closed files draining in the background and
the creates still being sent, all bounded by a context. No new flush logic.
It is safe while requests are served, like an fsync of every open file from
another thread, which keeps the bulk of the uploads out of the pause.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: measure the handover of a million-inode table

Skipped with -short. Logs encode and decode time and bytes for 1M inodes:
1.3 s to export, 1.6 s to import and 39 MB on a 2-vCPU VM.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: hand over a file whose first open was closed

Each open of a file has its own fh id over one shared handle. The handle's
own id is that of the first open, and stays so when that open is closed: it
keys the handle's lock. The import required it to be among the live opens,
so a file opened twice and then closed through its first descriptor was
exported, and refused by the successor before anything was installed.

The import now only requires the handle ids to be distinct, as the lock
table does. Tested for both close orders.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: export the subscription position only with its events applied

The metadata subscription moves its position on as soon as an event is in
the meta cache. What the event does to the inode table and to the open
handles, a rename by another mount or a newer entry, is queued for the
invalidation worker and happens later. An export in between carried the
position of the event without its change, and the successor, resuming
behind the event, never applied it: an open file kept its old entry and a
renamed inode its old path.

The export now refuses while the subscription runs, since it would keep
feeding the worker, and waits for the worker to be through what it holds
before it takes the handle locks, which the worker needs. The wait is
bounded at 5 s and ends in a refusal: the worker can sit in a kernel
notification that needs a request served, which nobody does while the FUSE
server is stopped.

Hooks: WFS.metaFollowers counts the subscription goroutines, and
MetaCache.WaitForEntryInvalidationsWithin is the bounded drain.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: an imported subscription position survives another handover

The import kept the position for StartBackgroundTasks only, and the export
reads the meta cache's, which stayed zero until the subscription started. A
mount that handed over again before that passed on no position, and its
successor would have followed from its own start time, missing the events
in between. The import now also records the position in the meta cache.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: refuse a handover between different lock modes

The advisory locks an application holds are either in the mount's own
table or, with -dlm and no writeback cache, on the filer, and each mode
only asks its own place. The import installed whatever it was given: a
successor started with -dlm kept the predecessor's local locks in a table
it no longer consults, so a second lock on the same range was granted; one
started without it kept routed locks whose leases nothing renews.

The mode now crosses in the identity (Identity.routed_locks) and the import
refuses another one before it changes anything, as for the cache mode.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: read a handle's dirty state under its lock in the handover flush

FlushForHandover runs once while requests are served, and looked for the
handles to flush by reading their dirty flags and page state under the
handle map's lock only. Writes, truncates and flushes change those under
the handle's flush lock, so the read raced with them.

Each handle is now examined under its own flush lock, in the worker that
flushes it, with the map's lock held only to list the handles: a handle's
lock is never taken under the map's. A handle closed since it was listed
is left to its release or to the background drain. asyncFlushPending is
still read under the map's lock, as RELEASE reads it.

The new test runs the flush next to writers and to opens and closes; with
the handle lock taken out again the race detector reports the read.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: hand over the nfs export records not yet written to the filer

With -nfsExport one background writer keeps the filer's record of every
open file. The export listed the inodes that have a path or an open count
and marked those still queued for the writer. Two kinds of pending work
were missing:

- a record to remove. When the removal timer of a closed file fires, the
  inode has no path and no open left, only its place in the writer's
  queue, so it was not listed and the registration stayed on the filer;
- a write the writer had taken from its queue: in flight, or failed and
  waiting a second for its retry. It is lost with the process, and the
  record crossed as clean.

The writer now counts what it has taken and not finished
(exportedHandles.unwritten), and the export lists queued and unfinished
inodes too and marks both dirty. Writes in flight are not waited for: the
successor writes the record again under the same owner, with the same
result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: keep followMetadataUpdates' doc comment on its function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: hand over the owner of the nfs export registrations

The owner is a hash of the hostname and mount directory, so a successor in
a replaced pod has another one: the records it rewrites or removes would sit
next to the exporter's instead of replacing them. The importer takes the
exporter's owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: bound the wait for the held nfs record write in the handover test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: stop the nfs export writer once a handover export starts

The successor registers under the exporter's owner, so a record write of
the exporter landing after one of the successor's took the record back,
and a removal timer firing in the exporter dropped the successor's entry.
The export now stops the writer before it captures the records: a write
not yet at its put drops it and stays dirty, a put already sent is waited
for (the export refuses if it does not return in time), and the writer
starts again when the export fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: let the drain test's events through only once the export waits

TestHandoverExportWaitsForEventsToReachTheState released the held
invalidations 100 ms after it started the export goroutine. A goroutine
that started later found the events applied already, and the test passed
without testing the wait.

The export now calls a test hook, handoverEventSettleStarted, when it
starts that wait, with the subscription's position already taken. The
test lets the events through only after the hook, and after checking that
the export did not finish while they were held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: wait for the exporter's removal timer instead of a fixed sleep

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: confirm the stopped writer took the removal's wake in the handover test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: whitebear009 <whitebear009@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 23:43:41 -08:00

364 lines
14 KiB
Go

package mount
import (
"fmt"
"slices"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// How a FileHandle crosses a handover. Every field is one of: crosses
// (exported, restored as is), rebuilt (derived again on import), or empty
// (must hold nothing at export; the export is refused otherwise, and the
// importer starts it empty). TestHandoverClassifiesEveryHandleField fails when
// a field is added without a line here.
//
// fh, fhs, counter crosses: fhs are the ids the kernel holds, one per open, and counter
// their number. fh is the id of the first open and keys the handle's
// lock for as long as the handle lives, also once that open is closed.
// inode crosses.
// entry crosses (filer_pb.Entry); the chunk group over it is rebuilt without
// any RPC, a manifest chunk is resolved lazily (chunkViewStale).
// baseEntry crosses: the filer state last acknowledged, merges judge events by it.
// entryVersionTsNs/Signature crosses: events at or below it must not roll the entry back.
// savedDir, savedName crosses: the path of a handle whose inode was forgotten.
// isDeleted, deleteEpoch, cross: they change what a later flush, rename or unlink does.
// isRenamed, nameTaken,
// linkRefresh
// contentType crosses: the mime the next flush stamps.
// sinceBase crosses its scalars (truncatedTo, rewrote) when it still marks the
// current base; empty of failed-flush folds and sent chunks.
// dirtyMetadata, dirtyContent, pendingAppend, pendingAppendOffset
// cross, but only an unlinked file's handle may carry them set: its
// flushes are skipped, so it stays dirty for good and its entry, with
// the chunk list its uploads built, exists only in the handle.
// dirtyPages empty: unflushed data cannot be carried; a new page writer is built.
// asyncFlushPending/Uid/Gid empty: a deferred close flush has to finish first.
// dlmLock empty: a lease held by a live renewal goroutine of this process.
// entryChunkGroup, chunkViewStale, reader
// rebuilt: read state.
// writebackContentError rebuilt: bound to the per-inode flag in wfs.writebackContentErrors,
// which crosses on its own (set flags only).
// wfs, entryLock, remoteInstallMu, pageWrites, mirrorFile
// rebuilt: process-local; pageWrites only compares against itself.
// handoverBlocker returns why fh cannot cross, or "". The caller holds fh's
// lock.
func (fh *FileHandle) handoverBlocker() string {
name := fh.FullPath()
switch {
case fh.counter <= 0 || fh.asyncFlushPending:
return fmt.Sprintf("%s: close flush still deferred", name)
case fh.dlmLock != nil:
return fmt.Sprintf("%s: holds a distributed lock", name)
case fh.dirtyPages.HasPendingUploads():
return fmt.Sprintf("%s: dirty pages or uploads in flight", name)
case fh.isDeleted:
// Never published again; its dirty flags cross as they are.
case fh.unpublishedCreate():
return fmt.Sprintf("%s: unpublished create", name)
case fh.dirtyMetadata || fh.dirtyContent || fh.pendingAppend:
return fmt.Sprintf("%s: unflushed changes", name)
}
if m := fh.sinceBase.Load(); m != nil && m.base == fh.baseEntry.Load() {
if len(m.folds) > 0 || m.sent.size() > 0 {
return fmt.Sprintf("%s: a failed flush left state over its base", name)
}
}
return ""
}
func (s *sentChunks) size() int {
if s == nil {
return 0
}
s.Lock()
defer s.Unlock()
return len(s.ids)
}
// lockHandlesForHandover takes every open handle's flush lock without waiting
// and checks each can cross. A lock that is held means an operation on the
// handle is in flight (a delete, a rename, a flush, a write). The locks stay
// held until release, so the handles cannot change while they are exported.
func (wfs *WFS) lockHandlesForHandover() (handles []*FileHandle, release func(), blockers handoverBlockers) {
wfs.fhMap.RLock()
handles = make([]*FileHandle, 0, len(wfs.fhMap.inode2fh))
for _, fh := range wfs.fhMap.inode2fh {
handles = append(handles, fh)
}
openIds := 0
for _, fh := range handles {
openIds += len(fh.fhs)
for id := range fh.fhs {
if wfs.fhMap.fh2inode[id] != fh.inode {
blockers.add("file handle %d of inode %d is not registered", id, fh.inode)
}
}
}
if openIds != len(wfs.fhMap.fh2inode) {
blockers.add("%d registered file handle ids, %d open", len(wfs.fhMap.fh2inode), openIds)
}
wfs.fhMap.RUnlock()
slices.SortFunc(handles, func(a, b *FileHandle) int { return compareU64(uint64(a.fh), uint64(b.fh)) })
type held struct {
fh FileHandleId
lock *util.ActiveLock
}
var locks []held
release = func() {
for _, h := range locks {
wfs.fhLockTable.ReleaseLock(h.fh, h.lock)
}
}
for _, fh := range handles {
lock, ok := wfs.fhLockTable.TryAcquireLock("handover", fh.fh, util.ExclusiveLock)
if !ok {
blockers.add("%s: busy, an operation on it is in flight", fh.FullPath())
continue
}
locks = append(locks, held{fh.fh, lock})
if why := fh.handoverBlocker(); why != "" {
blockers.add("%s", why)
}
}
return handles, release, blockers
}
func compareU64(a, b uint64) int {
switch {
case a < b:
return -1
case a > b:
return 1
}
return 0
}
func (wfs *WFS) exportFileHandles(e *handoverEncoder, handles []*FileHandle) error {
for _, fh := range handles {
rec := &hpb.FileHandle{
Fh: uint64(fh.fh),
Inode: fh.inode,
Counter: fh.counter,
VersionTsNs: fh.entryVersionTsNs.Load(),
VersionSignature: fh.entryVersionSignature.Load(),
SavedDir: fh.savedDir,
SavedName: fh.savedName,
IsDeleted: fh.isDeleted,
DeleteEpoch: fh.deleteEpoch,
IsRenamed: fh.isRenamed,
NameTaken: fh.nameTaken,
LinkRefresh: fh.linkRefresh,
ContentType: fh.contentType,
DirtyMetadata: fh.dirtyMetadata,
DirtyContent: fh.dirtyContent,
PendingAppend: fh.pendingAppend,
PendingAppendOffset: fh.pendingAppendOffset,
}
for id, appendMode := range fh.fhs {
rec.Opens = append(rec.Opens, &hpb.OpenFh{Fh: uint64(id), Append: appendMode})
}
slices.SortFunc(rec.Opens, func(a, b *hpb.OpenFh) int { return compareU64(a.Fh, b.Fh) })
fh.entry.RLock()
if fh.entry.Entry != nil {
// The frame is marshalled below, still under the lock.
rec.Entry = fh.entry.Entry
}
base := fh.baseEntry.Load()
rec.Base = base
if m := fh.sinceBase.Load(); m != nil && m.base == base {
rec.Mark = &hpb.BaseMark{TruncatedTo: m.truncatedTo, Rewrote: m.rewrote}
}
err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_FileHandle{FileHandle: rec}})
fh.entry.RUnlock()
if err != nil {
return fmt.Errorf("export file handle %d (%s): %w", fh.fh, fh.FullPath(), err)
}
}
return nil
}
// captureDirHandles copies the directory handles, with the window of entries
// each holds: the kernel's next READDIR continues inside it, and a handle
// rebuilt empty would list again from the start and skip by position (the
// fallback for a handle the process has never seen, not a faithful resume).
// lastListedName is how far the store listing reached, ahead of what the
// kernel has consumed, so it only makes sense together with the entries.
func (wfs *WFS) captureDirHandles() (records []*hpb.DirHandle, blockers handoverBlockers) {
wfs.dhMap.Lock()
defer wfs.dhMap.Unlock()
for id, dh := range wfs.dhMap.dir2inode {
if !dh.TryLock() {
blockers.add("directory handle %d: a read is in flight", id)
continue
}
rec := &hpb.DirHandle{
Fh: uint64(id),
EntryStreamOffset: dh.entryStreamOffset,
IsFinished: dh.isFinished,
LastListedName: dh.lastListedName,
SnapshotTsNs: dh.snapshotTsNs,
}
for _, entry := range dh.entryStream {
dir, _ := entry.FullPath.DirAndName()
rec.Entries = append(rec.Entries, &hpb.StreamEntry{Dir: dir, Entry: entry.ToProtoEntry()})
}
dh.Unlock()
records = append(records, rec)
}
return records, blockers
}
func restoreDirHandles(records []*hpb.DirHandle) map[DirectoryHandleId]*DirectoryHandle {
handles := make(map[DirectoryHandleId]*DirectoryHandle, len(records))
for _, rec := range records {
dh := &DirectoryHandle{
isFinished: rec.IsFinished,
entryStreamOffset: rec.EntryStreamOffset,
lastListedName: rec.LastListedName,
snapshotTsNs: rec.SnapshotTsNs,
}
for _, se := range rec.Entries {
dh.entryStream = append(dh.entryStream, filer.FromPbEntry(se.Dir, se.Entry))
}
handles[DirectoryHandleId(rec.Fh)] = dh
}
return handles
}
// exportContentErrors lists the inodes whose writeback refusal flag is set: it
// outlives the handle, until the kernel forgets the inode.
func (wfs *WFS) exportContentErrors() []*hpb.ContentError {
var records []*hpb.ContentError
wfs.writebackContentErrors.Range(func(key, value any) bool {
if value.(*atomic.Bool).Load() {
records = append(records, &hpb.ContentError{Inode: key.(uint64)})
}
return true
})
return records
}
// checkHandoverHandles refuses records that would leave the handle maps
// inconsistent, before any state is replaced.
func checkHandoverHandles(imp *handoverImport) error {
byInode := make(map[uint64]bool, len(imp.fileHandles))
lockKeys := make(map[uint64]bool, len(imp.fileHandles))
ids := make(map[uint64]bool)
for _, rec := range imp.fileHandles {
if byInode[rec.Inode] {
return fmt.Errorf("two file handles for inode %d", rec.Inode)
}
byInode[rec.Inode] = true
// The handle's own id need not be among its opens: it is the first
// open's, which may have been closed while later ones stay.
if lockKeys[rec.Fh] {
return fmt.Errorf("two file handles with the id %d", rec.Fh)
}
lockKeys[rec.Fh] = true
if len(rec.Opens) == 0 || int64(len(rec.Opens)) != rec.Counter {
return fmt.Errorf("file handle %d of inode %d: %d opens, counter %d", rec.Fh, rec.Inode, len(rec.Opens), rec.Counter)
}
for _, o := range rec.Opens {
if ids[o.Fh] {
return fmt.Errorf("file handle id %d appears twice", o.Fh)
}
ids[o.Fh] = true
}
}
return nil
}
func (wfs *WFS) importContentErrors(records []*hpb.ContentError) {
if !wfs.option.WritebackCache {
return
}
for _, rec := range records {
state, _ := wfs.writebackContentErrors.LoadOrStore(rec.Inode, new(atomic.Bool))
state.(*atomic.Bool).Store(true)
}
}
// installFileHandles builds the handles of the records and enters them in the
// maps. Their entries are bound to the inode table, which must be installed.
func (wfs *WFS) installFileHandles(records []*hpb.FileHandle) {
restored := make([]*FileHandle, 0, len(records))
for _, rec := range records {
restored = append(restored, wfs.restoreFileHandle(rec))
}
wfs.fhMap.Lock()
defer wfs.fhMap.Unlock()
for _, fh := range restored {
wfs.fhMap.inode2fh[fh.inode] = fh
for id := range fh.fhs {
wfs.fhMap.fh2inode[id] = fh.inode
}
}
}
// restoreFileHandle builds the handle a record describes, as AcquireFileHandle
// built it at open. It is not yet in the maps, and makes no RPC.
func (wfs *WFS) restoreFileHandle(rec *hpb.FileHandle) *FileHandle {
fh := newFileHandle(wfs, FileHandleId(rec.Fh), rec.Inode, nil)
fh.counter = rec.Counter
fh.fhs = make(map[FileHandleId]bool, len(rec.Opens))
for _, o := range rec.Opens {
fh.fhs[FileHandleId(o.Fh)] = o.Append
}
fh.savedDir, fh.savedName = rec.SavedDir, rec.SavedName
fh.isDeleted, fh.deleteEpoch = rec.IsDeleted, rec.DeleteEpoch
fh.isRenamed, fh.nameTaken = rec.IsRenamed, rec.NameTaken
fh.linkRefresh = rec.LinkRefresh
fh.contentType = rec.ContentType
fh.dirtyMetadata, fh.dirtyContent = rec.DirtyMetadata, rec.DirtyContent
fh.pendingAppend, fh.pendingAppendOffset = rec.PendingAppend, rec.PendingAppendOffset
fh.entryVersionTsNs.Store(rec.VersionTsNs)
fh.entryVersionSignature.Store(rec.VersionSignature)
if wfs.option.WritebackCache {
wfs.inodeToPath.RLock()
state, found := wfs.writebackContentErrors.Load(rec.Inode)
if !found {
state, _ = wfs.writebackContentErrors.LoadOrStore(rec.Inode, new(atomic.Bool))
}
wfs.inodeToPath.RUnlock()
fh.writebackContentError = state.(*atomic.Bool)
}
if rec.Base != nil {
fh.baseEntry.Store(rec.Base)
}
if rec.Mark != nil {
fh.sinceBase.Store(&baseMark{base: rec.Base, truncatedTo: rec.Mark.TruncatedTo, rewrote: rec.Mark.Rewrote})
}
if rec.Entry != nil {
if rec.Entry.Attributes == nil {
rec.Entry.Attributes = &filer_pb.FuseAttributes{}
}
fh.restoreEntry(rec.Entry)
}
return fh
}
// restoreEntry installs an entry and the read view over it without a remote
// call. A manifest chunk is resolved from a volume server, so a handle that
// has one starts with the view of its plain chunks and marked stale: its first
// read or lseek resolves the rest (refreshChunkView), as after a failed
// resolution.
func (fh *FileHandle) restoreEntry(entry *filer_pb.Entry) {
fh.wfs.readAuth.Track(fh.FullPath(), entry.Chunks)
plain := make([]*filer_pb.FileChunk, 0, len(entry.Chunks))
for _, c := range entry.Chunks {
if !c.IsChunkManifest {
plain = append(plain, c)
}
}
fh.entryChunkGroup, _ = filer.NewChunkGroup(fh.wfs.LookupFn(), fh.wfs.chunkCache, plain, fh.wfs.option.ConcurrentReaders, fh.wfs.CacheInvalidator(), fh.wfs.manifestCache, fh.wfs.readerCacheBudget)
fh.chunkViewStale.Store(len(plain) != len(entry.Chunks))
fh.entry.SetEntry(entry)
}