mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* 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>
144 lines
4.6 KiB
Go
144 lines
4.6 KiB
Go
package mount
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
// FlushForHandover publishes everything a handover would otherwise refuse to
|
|
// carry: every open handle with dirty pages, dirty metadata (a deferred create
|
|
// is published here: its only copy in the meta cache is a placeholder that
|
|
// does not cross) or a deferred close flush is flushed the way fsync flushes
|
|
// it, and the closed files still draining in the background and the creates
|
|
// still being sent are waited for. It adds no flush logic: each handle goes
|
|
// through doFlush with allowAsync false. ctx bounds the wait; on expiry the
|
|
// work already started carries on in the background, nothing is lost, and the
|
|
// error says so.
|
|
//
|
|
// It is safe while requests are served, like an fsync of every open file from
|
|
// another thread: run it once then, so the bulk of the uploads is not part of
|
|
// the pause, and again after the FUSE server stopped reading requests, for
|
|
// what became dirty in between. ExportHandoverState still refuses whatever is
|
|
// left (a failed flush leaves its handle dirty, and a file closed during the
|
|
// first run may still drain in the background).
|
|
func (wfs *WFS) FlushForHandover(ctx context.Context) error {
|
|
done := make(chan error, 1)
|
|
go func() { done <- wfs.flushForHandover(ctx) }()
|
|
select {
|
|
case err := <-done:
|
|
return err
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("flush before handover: %w", ctx.Err())
|
|
}
|
|
}
|
|
|
|
func (wfs *WFS) flushForHandover(ctx context.Context) error {
|
|
// Closed files draining in the background first: their handle is still in
|
|
// the map, and a new flush of it would race the drain.
|
|
wfs.pendingAsyncFlushMu.Lock()
|
|
drains := make([]chan struct{}, 0, len(wfs.pendingAsyncFlush))
|
|
for _, done := range wfs.pendingAsyncFlush {
|
|
drains = append(drains, done)
|
|
}
|
|
wfs.pendingAsyncFlushMu.Unlock()
|
|
for _, done := range drains {
|
|
select {
|
|
case <-done:
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
|
|
// Requests are still served during the first run, so each handle's state
|
|
// is read under the lock its writers hold. The map's lock is only held to
|
|
// list the handles: a handle's flush lock is never taken under it.
|
|
type openHandle struct {
|
|
fh *FileHandle
|
|
// deferred is asyncFlushPending, read under the map's lock as RELEASE
|
|
// reads it. A close sets it with no lock, so a flag missed here waits
|
|
// for the run after the FUSE server stopped; the export refuses the
|
|
// handle until then.
|
|
deferred bool
|
|
}
|
|
wfs.fhMap.RLock()
|
|
handles := make([]openHandle, 0, len(wfs.fhMap.inode2fh))
|
|
for _, fh := range wfs.fhMap.inode2fh {
|
|
handles = append(handles, openHandle{fh, fh.asyncFlushPending})
|
|
}
|
|
wfs.fhMap.RUnlock()
|
|
|
|
var (
|
|
mu sync.Mutex
|
|
errs []error
|
|
wg sync.WaitGroup
|
|
)
|
|
concurrency := wfs.option.ConcurrentWriters
|
|
if concurrency <= 0 {
|
|
concurrency = 16
|
|
}
|
|
sem := make(chan struct{}, concurrency)
|
|
for _, h := range handles {
|
|
if ctx.Err() != nil {
|
|
break
|
|
}
|
|
wg.Add(1)
|
|
sem <- struct{}{}
|
|
go func(h openHandle) {
|
|
defer wg.Done()
|
|
defer func() { <-sem }()
|
|
if !h.deferred && !wfs.hasUnflushedState(h.fh) {
|
|
return
|
|
}
|
|
// Closed since it was listed: its release, or the background
|
|
// drain waited for above on the next run, deals with it.
|
|
if !wfs.fhMap.isOpen(h.fh) {
|
|
return
|
|
}
|
|
if status := wfs.doFlush(context.Background(), h.fh, unknownCallerId, unknownCallerId, false, metadataFlushTimeout); !status.Ok() {
|
|
mu.Lock()
|
|
errs = append(errs, fmt.Errorf("flush %s: status %v", h.fh.FullPath(), status))
|
|
mu.Unlock()
|
|
}
|
|
}(h)
|
|
}
|
|
wg.Wait()
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Creates sent in the background have no handle to wait on.
|
|
for wfs.asyncCreates.Load() > 0 {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-time.After(10 * time.Millisecond):
|
|
}
|
|
}
|
|
if len(errs) > 0 {
|
|
glog.Warningf("flush before handover: %d handles failed to flush", len(errs))
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// hasUnflushedState reports whether fh has anything a flush would publish. It
|
|
// waits for the handle's flush lock: writes, truncates and flushes change this
|
|
// state under it.
|
|
func (wfs *WFS) hasUnflushedState(fh *FileHandle) bool {
|
|
lock := wfs.fhLockTable.AcquireLock("FlushForHandover", fh.fh, util.SharedLock)
|
|
defer wfs.fhLockTable.ReleaseLock(fh.fh, lock)
|
|
return fh.dirtyMetadata || fh.dirtyContent || fh.dirtyPages.HasPendingUploads()
|
|
}
|
|
|
|
// isOpen reports whether fh is still the handle of its inode with an open left.
|
|
func (i *FileHandleToInode) isOpen(fh *FileHandle) bool {
|
|
i.RLock()
|
|
defer i.RUnlock()
|
|
return i.inode2fh[fh.inode] == fh && fh.counter > 0
|
|
}
|