Files
seaweedfs/weed/mount/meta_cache/meta_cache_subscribe.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

204 lines
7.8 KiB
Go

package meta_cache
import (
"context"
"errors"
"fmt"
"io"
"strings"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
type MetadataFollower struct {
PathPrefixToWatch string
ProcessEventFn func(resp *filer_pb.SubscribeMetadataResponse) error
}
func mergeProcessors(mainProcessor func(resp *filer_pb.SubscribeMetadataResponse) error, followers ...*MetadataFollower) func(resp *filer_pb.SubscribeMetadataResponse) error {
return func(resp *filer_pb.SubscribeMetadataResponse) error {
// build the full path
entry := resp.EventNotification.NewEntry
if entry == nil {
entry = resp.EventNotification.OldEntry
}
if entry != nil {
dir := resp.Directory
if resp.EventNotification.NewParentPath != "" {
dir = resp.EventNotification.NewParentPath
}
fp := util.NewFullPath(dir, entry.Name)
for _, follower := range followers {
if strings.HasPrefix(string(fp), follower.PathPrefixToWatch) {
if err := follower.ProcessEventFn(resp); err != nil {
return err
}
}
}
}
return mainProcessor(resp)
}
}
// SubscriptionCredentials resolves the bearer of one subscription attempt. It
// is called before each attempt with a context that ends with the attempt, and
// returns the attempt's token source and a channel that, once closed, ends the
// attempt so the next one resubscribes from the checkpoint with a newer token.
type SubscriptionCredentials func(ctx context.Context) (security.FilerTokenSource, <-chan struct{}, error)
// applySubscribedEvent applies one event of the filer's metadata log to the
// cache. It fails only to end the subscription, when the cache is closed.
func applySubscribedEvent(mc *MetaCache, resp *filer_pb.SubscribeMetadataResponse) error {
err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions)
if err == nil {
return nil
}
if errors.Is(err, ErrClosed) {
// The cache is gone: no event can be applied to it and no retry
// helps. Report it as the end of the subscription rather than as a
// failed event, which under the mount's FatalOnError would abort a
// process that is only unmounting.
return fmt.Errorf("%w: %w", pb.ErrStopFollowing, err)
}
// The local store did not take the event: its disk is full or failing.
// Failing the event aborts the mount under FatalOnError, and every file
// open on it, for good. An event replayed from the persisted log is
// returned to the follow loop instead, which resubscribes from it and
// fails on it again, so no later event reaches the cache. The apply
// already dropped the listings the event changes (dropListingsOf): the
// next lookup reads the filer, and the next listing rebuilds them once the
// cache can hold them. So the follow goes on.
if n := failedApplies.Add(1); n == 1 || time.Since(time.Unix(0, lastFailedApplyLog.Load())) >= failedApplyLogInterval {
lastFailedApplyLog.Store(time.Now().UnixNano())
glog.Warningf("metadata cache did not take an event (%d so far), reading the directories it changes from the filer: %s: %v",
n, filer_pb.MetadataEventTargetFullPath(resp), err)
}
return nil
}
// failedApplies counts the events the cache did not take; a warning goes out
// for the first and then at most once per failedApplyLogInterval, since a
// full disk fails every event.
var (
failedApplies atomic.Int64
lastFailedApplyLog atomic.Int64
failedApplyLogInterval = time.Minute
)
// SubscribeMetaEvents keeps the meta cache current by following the filer's
// metadata log until ctx is cancelled, the cache is closed, the stream ends
// cleanly, or the process exits. Cancelling ctx is how a mount quiesces the
// follow before closing the cache it writes into. credentials, when set,
// authorizes each attempt; a resubscribe it asks for resumes at once from the
// checkpoint and is not a gap, so onRetry is not called for it. Nil keeps the
// client's own credentials.
func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32, client filer_pb.FilerClient, lookupFn wdclient.LookupFileIdFunctionType, dir string, lastTsNs int64, skipSelfEvents bool, credentials SubscriptionCredentials, onRetry func(lastTsNs int64, err error), followers ...*MetadataFollower) error {
if ctx == nil {
ctx = context.Background()
}
var prefixes []string
for _, follower := range followers {
prefixes = append(prefixes, follower.PathPrefixToWatch)
}
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
if skipSelfEvents && resp.EventNotification != nil {
for _, sig := range resp.EventNotification.Signatures {
if sig == selfSignature {
glog.V(4).Infof("skip self-originated event %s", resp.Directory)
mc.NoteSubscribedTsNs(resp.TsNs)
return nil
}
}
}
if err := applySubscribedEvent(mc, resp); err != nil {
return err
}
mc.NoteSubscribedTsNs(resp.TsNs)
return nil
}
prefix := dir
if !strings.HasSuffix(prefix, "/") {
prefix = prefix + "/"
}
// Replaying the persisted log chunks here keeps the cost off the filer's heap.
// The caller's lookup says where to read them from, so a mount that cannot
// reach volume servers directly still replays through its filer.
metadataFollowOption := &pb.MetadataFollowOption{
ClientName: "mount",
ClientId: selfSignature,
ClientEpoch: 1,
SelfSignature: selfSignature,
PathPrefix: prefix,
AdditionalPathPrefixes: prefixes,
DirectoriesToWatch: nil,
StartTsNs: lastTsNs,
StopTsNs: 0,
EventErrorType: pb.FatalOnError,
ParentContext: ctx,
}
// A nil lookup asks for decoded events instead: a keyless mount cannot
// read raw metadata-log chunks with its entry-scoped volume tokens.
if lookupFn != nil {
metadataFollowOption.LogFileReaderFn = func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
return filer.NewChunkStreamReaderFromLookup(context.Background(), lookupFn, chunks), nil
}
}
follow := func() error {
attemptCtx, cancel := context.WithCancel(ctx)
defer cancel()
if credentials != nil {
source, refresh, err := credentials(attemptCtx)
if err != nil {
return fmt.Errorf("subscription credentials: %w", err)
}
metadataFollowOption.FilerTokenSource = source
metadataFollowOption.Resubscribe = refresh
}
return pb.WithFilerClientFollowMetadata(client, metadataFollowOption, mergeProcessors(processEventFn, followers...))
}
util.RetryUntil("followMetaUpdates", func() error {
for {
if err := ctx.Err(); err != nil {
return fmt.Errorf("%w: %w", pb.ErrStopFollowing, err)
}
metadataFollowOption.ClientEpoch++
err := follow()
if credentials == nil || !errors.Is(err, pb.ErrResubscribe) {
return err
}
glog.V(1).Infof("follow metadata updates: resubscribing with a replaced filer token from %v", time.Unix(0, metadataFollowOption.StartTsNs))
}
}, func(err error) bool {
// A cancelled context is the common case here, and it does not arrive
// wrapped: the stream's own gRPC Canceled status surfaces bare. Without
// this the stop is logged as a gap, the retry callback wipes every cached
// listing on that assumption, and the loop sleeps before its own check
// ends it — so a clean unmount would read as a metadata failure.
if ctx.Err() != nil || errors.Is(err, ErrClosed) || errors.Is(err, pb.ErrStopFollowing) {
glog.V(0).Infof("follow metadata updates stopped: %v", err)
return false
}
if onRetry != nil {
onRetry(metadataFollowOption.StartTsNs, err)
}
glog.Errorf("follow metadata updates: %v", err)
return true
})
return nil
}