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) 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 } } 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 }