Files
seaweedfs/weed/mount/meta_cache/meta_cache_subscribe.go
T
Yip LeoandClaude Opus 5.5 ecd0493906 mount: keep following the metadata log when the cache refuses an event (#13141)
* mount: keep following the metadata log when the cache refuses an event

The mount applies each event of the filer's metadata log to its local
metadata cache, a leveldb store under -cacheDir. Once that disk is full
every write to the store fails, and an event the cache refuses goes one
of two ways:

- An event the stream delivers fails the follow, which the mount runs
  with FatalOnError: glog.Fatalf ends the process, every file open on
  the mount goes with it, and the mount does not come back when the disk
  has room again.
- An event replayed from the persisted log is returned to the follow
  loop, which resubscribes from it and fails on it again: the mount
  stays up, but no later event reaches its cache, so its listings stop
  changing.

A local change whose apply fails (create, mkdir, unlink, rmdir) drops
its directory's cached listing with InvalidateChildrenCache and goes on.
An event from the log now does the same: the cached listings it
changes, the parents it leaves and enters and a directory it creates,
moves or deletes, are dropped, so the next lookup reads the filer and
the next listing rebuilds them, and the event's kernel invalidations
still go out. The follow goes on. A warning reports the first such
event and then at most one a minute.

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

* mount: handle a refused event in the apply step that refused it

Review of the previous commit found two gaps.

A rename into a directory whose listing is being built applies the part
leaving the source at once and keeps the part entering the building
directory for the build to replay. When the part applied at once was
refused, the other part was not kept, and the build published its
listing without the renamed file. It is now kept whatever happens to
the part applied at once.

The listings a refused event changes were dropped, and its kernel
invalidations sent, by the follow's event function after the apply
returned. By then the apply loop could have taken a later request, such
as this mount's own create of the name a rename left, and the rename's
invalidation would then move the new file. The apply step that fails
now does both before it returns, as it sends the side effects of an
event the store takes, and on the apply loop, which owns buildingDirs
and is the only one to feed the invalidate worker. A local change whose
apply fails gets the same; its caller still drops its directory's
listing as before.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:42:25 -08:00

170 lines
6.4 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/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)
}
}
// 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.
func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32, client filer_pb.FilerClient, lookupFn wdclient.LookupFileIdFunctionType, dir string, lastTsNs int64, skipSelfEvents bool, 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)
return nil
}
}
}
return applySubscribedEvent(mc, resp)
}
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
}
}
util.RetryUntil("followMetaUpdates", func() error {
if err := ctx.Err(); err != nil {
return fmt.Errorf("%w: %w", pb.ErrStopFollowing, err)
}
metadataFollowOption.ClientEpoch++
return pb.WithFilerClientFollowMetadata(client, metadataFollowOption, mergeProcessors(processEventFn, followers...))
}, 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
}