diff --git a/weed/mount/meta_cache/meta_cache.go b/weed/mount/meta_cache/meta_cache.go index e044a5c576..10f2e88b96 100644 --- a/weed/mount/meta_cache/meta_cache.go +++ b/weed/mount/meta_cache/meta_cache.go @@ -70,7 +70,10 @@ type MetaCache struct { invalidateWorker *util.AsyncBatchWorker[EntryInvalidation] } -var errMetaCacheClosed = errors.New("metadata cache is shut down") +// ErrClosed reports that the metadata cache is shut down, so no event can be +// applied to it any more. Consumers distinguish it from a storage failure: +// retrying an event against a closed cache cannot succeed. +var ErrClosed = errors.New("metadata cache is shut down") type MetadataResponseApplyOptions struct { NotifyDirectories bool @@ -923,7 +926,7 @@ func (mc *MetaCache) enqueueApplyRequest(req metadataApplyRequest) error { mc.applyStateMu.Lock() if mc.applyClosed { mc.applyStateMu.Unlock() - return errMetaCacheClosed + return ErrClosed } // Release the mutex before the potentially-blocking channel send so that // Shutdown can still acquire it to set applyClosed when the channel is full. @@ -932,7 +935,7 @@ func (mc *MetaCache) enqueueApplyRequest(req metadataApplyRequest) error { case mc.applyCh <- req: return nil case <-mc.applyDone: - return errMetaCacheClosed + return ErrClosed } } @@ -955,7 +958,7 @@ func (mc *MetaCache) drainApplyCh() { for { select { case req := <-mc.applyCh: - req.done <- errMetaCacheClosed + req.done <- ErrClosed close(req.done) default: return diff --git a/weed/mount/meta_cache/meta_cache_subscribe.go b/weed/mount/meta_cache/meta_cache_subscribe.go index 1331b80a1e..6b891ed292 100644 --- a/weed/mount/meta_cache/meta_cache_subscribe.go +++ b/weed/mount/meta_cache/meta_cache_subscribe.go @@ -2,6 +2,8 @@ package meta_cache import ( "context" + "errors" + "fmt" "io" "strings" @@ -45,7 +47,14 @@ func mergeProcessors(mainProcessor func(resp *filer_pb.SubscribeMetadataResponse } } -func SubscribeMetaEvents(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 { +// 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 { @@ -61,7 +70,15 @@ func SubscribeMetaEvents(mc *MetaCache, selfSignature int32, client filer_pb.Fil } } } - return mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions) + err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions) + 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) + } + return err } prefix := dir @@ -83,6 +100,7 @@ func SubscribeMetaEvents(mc *MetaCache, selfSignature int32, client filer_pb.Fil 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. @@ -92,9 +110,21 @@ func SubscribeMetaEvents(mc *MetaCache, selfSignature int32, client filer_pb.Fil } } 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) } diff --git a/weed/mount/weedfs.go b/weed/mount/weedfs.go index 8009b911dd..157dae3404 100644 --- a/weed/mount/weedfs.go +++ b/weed/mount/weedfs.go @@ -221,6 +221,14 @@ type WFS struct { // Must be waited on before unmount cleanup to prevent data loss. asyncFlushWg sync.WaitGroup + // metaFollowWg tracks the metadata subscription goroutine and + // metaFollowCancel ends it. Unmount closes the meta cache the follow writes + // into, so it has to be joined first: an event that lands after the cache + // is closed is the mount aborting on its own way out. + metaFollowMu sync.Mutex + metaFollowCancel context.CancelFunc + metaFollowWg sync.WaitGroup + // entryChanged is notified of every applied metadata event, for a front // end that has to push invalidations to its own client. entryChangeMu sync.RWMutex @@ -372,6 +380,8 @@ func NewSeaweedFileSystem(option *Option) *WFS { asyncDrained = false } } + // End the metadata follow before closing the cache it writes into. + wfs.stopMetadataFollow() wfs.metaCache.Shutdown() if asyncDrained { os.RemoveAll(option.getUniqueCacheDirForWrite()) @@ -520,15 +530,7 @@ func (wfs *WFS) StartBackgroundTasks() error { } startTime := time.Now() - go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, func(lastTsNs int64, err error) { - glog.Warningf("meta events follow retry from %v: %v", time.Unix(0, lastTsNs), err) - // A subscription gap may have dropped events, so distrust every cached - // listing. Reset the flags first (safe — it never deletes entries), then - // wipe the root's stale children through the apply loop so the delete - // cannot strand a concurrent rebuild cached-but-empty. - wfs.inodeToPath.InvalidateAllChildrenCache() - wfs.purgeDirectoryCache(util.FullPath(wfs.option.FilerMountRootPath)) - }, follower) + wfs.followMetadataUpdates(startTime, follower) go wfs.loopCheckQuota() go wfs.loopFlushDirtyMetadata() go wfs.loopEvictIdleDirCache() @@ -540,6 +542,63 @@ func (wfs *WFS) StartBackgroundTasks() error { return nil } +// followMetadataUpdates starts the subscription that keeps the meta cache +// current, tracked so unmount can end it. See stopMetadataFollow. +func (wfs *WFS) followMetadataUpdates(startTime time.Time, follower *meta_cache.MetadataFollower) { + ctx, cancel := context.WithCancel(context.Background()) + + // Publish the handle and bump the counter under one lock: stopMetadataFollow + // waits only on the counter it read, so an Add that lands after its Wait + // would let the join report success with the follow still running. + wfs.metaFollowMu.Lock() + wfs.metaFollowCancel = cancel + wfs.metaFollowWg.Add(1) + wfs.metaFollowMu.Unlock() + + go func() { + defer wfs.metaFollowWg.Done() + meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, func(lastTsNs int64, err error) { + glog.Warningf("meta events follow retry from %v: %v", time.Unix(0, lastTsNs), err) + // A subscription gap may have dropped events, so distrust every cached + // listing. Reset the flags first (safe — it never deletes entries), then + // wipe the root's stale children through the apply loop so the delete + // cannot strand a concurrent rebuild cached-but-empty. + wfs.inodeToPath.InvalidateAllChildrenCache() + wfs.purgeDirectoryCache(util.FullPath(wfs.option.FilerMountRootPath)) + }, follower) + }() +} + +// metadataFollowStopWait bounds the unmount wait for the metadata follow to +// unwind. A subscriber stuck in a read against an unreachable filer must not +// hold up an unmount; the closed-cache path covers the event it misses. +const metadataFollowStopWait = 5 * time.Second + +// stopMetadataFollow ends the metadata subscription and waits for its +// goroutine, so nothing is left writing into the meta cache when it closes. +// Safe to call more than once and before the follow ever started. +func (wfs *WFS) stopMetadataFollow() { + wfs.metaFollowMu.Lock() + cancel := wfs.metaFollowCancel + wfs.metaFollowCancel = nil + wfs.metaFollowMu.Unlock() + if cancel == nil { + return + } + cancel() + + stopped := make(chan struct{}) + go func() { + wfs.metaFollowWg.Wait() + close(stopped) + }() + select { + case <-stopped: + case <-time.After(metadataFollowStopWait): + glog.Warningf("metadata subscriber did not stop within %v", metadataFollowStopWait) + } +} + func (wfs *WFS) String() string { return "seaweedfs" } @@ -1333,6 +1392,9 @@ func (wfs *WFS) getCurrentFiler() pb.ServerAddress { } func (wfs *WFS) ClearCacheDir() { + // End the metadata follow before closing the cache it writes into, so an + // event still in flight cannot land on a closed store. + wfs.stopMetadataFollow() wfs.metaCache.Shutdown() os.RemoveAll(wfs.option.getUniqueCacheDirForWrite()) os.RemoveAll(wfs.option.getUniqueCacheDirForRead()) diff --git a/weed/mount/weedfs_meta_subscribe_shutdown_test.go b/weed/mount/weedfs_meta_subscribe_shutdown_test.go new file mode 100644 index 0000000000..e13c8ea602 --- /dev/null +++ b/weed/mount/weedfs_meta_subscribe_shutdown_test.go @@ -0,0 +1,367 @@ +package mount + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// subscriberChildEnv marks the child process that reproduces the mount +// aborting, so the parent can read its exit code. +const subscriberChildEnv = "SEAWEEDFS_MOUNT_SUBSCRIBER_CHILD" + +// eventFilerServer serves one metadata subscriber and hands it events when the +// test asks, so an event can be delivered at a chosen moment — after the +// metadata cache closed, which is what unmount does to the subscriber. +type eventFilerServer struct { + filer_pb.UnimplementedSeaweedFilerServer + + subscribed chan struct{} + once sync.Once + + mu sync.Mutex + events []*filer_pb.SubscribeMetadataResponse + wake chan struct{} +} + +func (s *eventFilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error { + s.once.Do(func() { close(s.subscribed) }) + for { + s.mu.Lock() + pending := s.events + s.events = nil + s.mu.Unlock() + for _, event := range pending { + if err := stream.Send(event); err != nil { + return err + } + } + select { + case <-s.wake: + case <-stream.Context().Done(): + return stream.Context().Err() + case <-time.After(50 * time.Millisecond): + } + } +} + +// push queues an event for the subscriber and wakes its send loop. +func (s *eventFilerServer) push(event *filer_pb.SubscribeMetadataResponse) { + s.mu.Lock() + s.events = append(s.events, event) + s.mu.Unlock() + select { + case s.wake <- struct{}{}: + default: + } +} + +// newMetaSubscriberMount is the smallest WFS that can follow metadata: a real +// meta cache over a temp dir, and a filer that only answers subscriptions. +func newMetaSubscriberMount(t *testing.T) (*WFS, *eventFilerServer) { + t.Helper() + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + grpcAddr := listener.Addr().(*net.TCPAddr) + testServer := &eventFilerServer{ + subscribed: make(chan struct{}), + wake: make(chan struct{}, 1), + } + server := pb.NewGrpcServer() + filer_pb.RegisterSeaweedFilerServer(server, testServer) + go server.Serve(listener) + t.Cleanup(server.Stop) + + uidGidMapper, err := meta_cache.NewUidGidMapper("", "") + if err != nil { + t.Fatalf("create uid/gid mapper: %v", err) + } + + root := util.FullPath("/") + wfs := &WFS{ + signature: 1, + inodeToPath: NewInodeToPath(root, 0), + fhMap: NewFileHandleToInode(), + fhLockTable: util.NewLockTable[FileHandleId](), + hardLinkLockTable: util.NewLockTable[string](), + option: &Option{ + ChunkSizeLimit: 1024, + ConcurrentReaders: 1, + // filerProxy: LookupFn needs no cached volume client, which this + // minimal WFS does not have. + VolumeServerAccess: "filerProxy", + FilerMountRootPath: "/", + CacheDirForRead: filepath.Join(t.TempDir(), "read"), + CacheDirForWrite: filepath.Join(t.TempDir(), "write"), + FilerAddresses: []pb.ServerAddress{ + pb.NewServerAddress("127.0.0.1", grpcAddr.Port, grpcAddr.Port), + }, + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }, + } + wfs.option.setupUniqueCacheDirectory() + wfs.metaCache = meta_cache.NewMetaCache( + filepath.Join(t.TempDir(), "meta"), + uidGidMapper, + root, + false, + func(path util.FullPath) { wfs.inodeToPath.MarkChildrenCached(path) }, + func(path util.FullPath) bool { return wfs.inodeToPath.IsChildrenCached(path) }, + func(meta_cache.EntryInvalidation) {}, + nil, + ) + return wfs, testServer +} + +func createdEvent(name string) *filer_pb.SubscribeMetadataResponse { + return &filer_pb.SubscribeMetadataResponse{ + Directory: "/dir", + TsNs: time.Now().UnixNano(), + EventNotification: &filer_pb.EventNotification{ + NewEntry: &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileSize: 7}}, + }, + } +} + +// TestMountMetaSubscriberEndsWhenMetaCacheCloses reproduces issue #5289: a +// metadata event that arrives after the metadata cache was closed reached +// glog.Fatalf, so the mount aborted with a goroutine dump instead of exiting +// cleanly. glog.Fatalf cannot be intercepted from another package (glog's +// logExitFunc is unexported), so the child runs in its own process and the +// parent reads the exit code: 255 is glog's fatal exit. +func TestMountMetaSubscriberEndsWhenMetaCacheCloses(t *testing.T) { + if os.Getenv(subscriberChildEnv) == "1" { + runMetaSubscriberAfterClose(t) + return + } + + cmd := exec.Command(os.Args[0], + "-test.run=TestMountMetaSubscriberEndsWhenMetaCacheCloses$", + "-test.timeout=120s", + "-test.v", + ) + cmd.Env = append(os.Environ(), subscriberChildEnv+"=1") + out, err := cmd.CombinedOutput() + if err == nil { + return + } + if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 255 { + t.Fatalf("the mount aborted instead of stopping: a metadata event after"+ + " metaCache.Shutdown() reached glog.Fatalf (exit 255).\n%s", headLines(string(out), 40)) + } + t.Fatalf("child test failed: %v\n%s", err, headLines(string(out), 40)) +} + +func runMetaSubscriberAfterClose(t *testing.T) { + wfs, filer := newMetaSubscriberMount(t) + + stopped := make(chan struct{}) + go func() { + defer close(stopped) + // nil lookupFn: the filer streams decoded events, so the apply path is + // reached without any volume server. + meta_cache.SubscribeMetaEvents(context.Background(), wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false, nil) + }() + + select { + case <-filer.subscribed: + case <-time.After(15 * time.Second): + t.Fatal("the mount never subscribed to the filer") + } + + // What unmount does today: close the cache while the subscriber runs. + wfs.metaCache.Shutdown() + filer.push(createdEvent("file")) + + select { + case <-stopped: + case <-time.After(20 * time.Second): + t.Fatal("the metadata subscriber neither stopped nor ended after the cache closed") + } +} + +// TestMountStopsMetadataSubscriberOnUnmount checks the other half of the fix: +// unmount has to end the goroutine that writes into the cache it is about to +// close, instead of only surviving the events that land after it. Runs in a +// child process so a glog.Fatalf in the mount shows up as exit 255. +func TestMountStopsMetadataSubscriberOnUnmount(t *testing.T) { + if os.Getenv(subscriberChildEnv) == "1" { + runStopSubscriberOnUnmount(t) + return + } + + cmd := exec.Command(os.Args[0], + "-test.run=TestMountStopsMetadataSubscriberOnUnmount$", + "-test.timeout=120s", + "-test.v", + ) + cmd.Env = append(os.Environ(), subscriberChildEnv+"=1") + out, err := cmd.CombinedOutput() + if err != nil { + if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 255 { + t.Fatalf("the mount aborted during unmount instead of stopping the subscriber (exit 255).\n%s", + headLines(string(out), 40)) + } + t.Fatalf("child test failed: %v\n%s", err, headLines(string(out), 40)) + } +} + +func runStopSubscriberOnUnmount(t *testing.T) { + wfs, filer := newMetaSubscriberMount(t) + // The real mount always hands the follow a filer.conf follower + // (subscribeFilerConfEvents returns nil only on its error path, which ends + // StartBackgroundTasks). Watch a path this test never writes to. + wfs.followMetadataUpdates(time.Now(), &meta_cache.MetadataFollower{ + PathPrefixToWatch: "/etc/seaweedfs/filer.conf", + ProcessEventFn: func(*filer_pb.SubscribeMetadataResponse) error { return nil }, + }) + + select { + case <-filer.subscribed: + case <-time.After(15 * time.Second): + t.Fatal("the mount never subscribed to the filer") + } + + wfs.stopMetadataFollow() + + if stack := metadataSubscriberStack(); stack != "" { + t.Fatalf("the metadata subscriber is still running after stopMetadataFollow:\n%s", headLines(stack, 20)) + } + + // What the unmount does next. With the follow joined there is no reader + // left, so this event cannot reach the apply path at all. + wfs.metaCache.Shutdown() + filer.push(createdEvent("late")) + time.Sleep(500 * time.Millisecond) +} + +// metadataSubscriberStack returns any running goroutine still inside the +// metadata follow, or empty text when there is none. +func metadataSubscriberStack() string { + buf := make([]byte, 1<<16) + n := runtime.Stack(buf, true) + var current []string + for _, block := range strings.Split(string(buf[:n]), "\n\n") { + if strings.Contains(block, "meta_cache.SubscribeMetaEvents") { + current = append(current, block) + } + } + return strings.Join(current, "\n\n") +} + +func headLines(s string, n int) string { + lines := strings.Split(s, "\n") + if len(lines) <= n { + return strings.Join(lines, "\n") + } + return fmt.Sprintf("%s\n... (%d more lines)", strings.Join(lines[:n], "\n"), len(lines)-n) +} + +// TestMountMetaFollowCancelIsAStop not a failure: cancelling the follow context +// must end the subscription without going through the retry path. onRetry wipes +// every cached listing on the assumption that events were missed, so treating a +// deliberate stop as a gap would throw away the whole cache on each unmount. +func TestMountMetaFollowCancelIsAStop(t *testing.T) { + wfs, filer := newMetaSubscriberMount(t) + + ctx, cancel := context.WithCancel(context.Background()) + stopped := make(chan error, 1) + var retries atomic.Int32 + go func() { + stopped <- meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false, + func(int64, error) { retries.Add(1) }) + }() + + select { + case <-filer.subscribed: + case <-time.After(15 * time.Second): + t.Fatal("the mount never subscribed to the filer") + } + + cancel() + + select { + case err := <-stopped: + if err != nil && !errors.Is(err, pb.ErrStopFollowing) && !errors.Is(err, context.Canceled) { + t.Fatalf("the follow ended with an unexpected error: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("cancelling the follow context did not end the subscription") + } + + if got := retries.Load(); got != 0 { + t.Fatalf("a cancelled follow went through the retry path %d times; a cancel is a stop, not a gap", got) + } +} + +// TestMountClearCacheDirStopsTheFollowFirst drives the production unmount entry +// point, so the ordering it guards cannot rot: if stopMetadataFollow is dropped +// from ClearCacheDir (or moved after metaCache.Shutdown), the follow is still +// running when the cache closes and the late event aborts the mount again. +func TestMountClearCacheDirStopsTheFollowFirst(t *testing.T) { + if os.Getenv(subscriberChildEnv) == "1" { + runClearCacheDirOrdering(t) + return + } + + cmd := exec.Command(os.Args[0], + "-test.run=TestMountClearCacheDirStopsTheFollowFirst$", + "-test.timeout=120s", + "-test.v", + ) + cmd.Env = append(os.Environ(), subscriberChildEnv+"=1") + out, err := cmd.CombinedOutput() + if err == nil && !strings.Contains(string(out), "--- PASS: TestMountClearCacheDirStopsTheFollowFirst") { + t.Fatalf("the child ran no test, so its exit code proved nothing:\n%s", headLines(string(out), 30)) + } + if err != nil { + if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 255 { + t.Fatalf("the mount aborted during ClearCacheDir instead of stopping the follow first (exit 255).\n%s", + headLines(string(out), 40)) + } + t.Fatalf("child test failed: %v\n%s", err, headLines(string(out), 40)) + } +} + +func runClearCacheDirOrdering(t *testing.T) { + wfs, filer := newMetaSubscriberMount(t) + wfs.followMetadataUpdates(time.Now(), &meta_cache.MetadataFollower{ + PathPrefixToWatch: "/etc/seaweedfs/filer.conf", + ProcessEventFn: func(*filer_pb.SubscribeMetadataResponse) error { return nil }, + }) + + select { + case <-filer.subscribed: + case <-time.After(15 * time.Second): + t.Fatal("the mount never subscribed to the filer") + } + + wfs.ClearCacheDir() + filer.push(createdEvent("late")) + time.Sleep(500 * time.Millisecond) + + if stack := metadataSubscriberStack(); stack != "" { + t.Fatalf("ClearCacheDir left the metadata subscriber running against a closed cache:\n%s", headLines(stack, 20)) + } +} diff --git a/weed/mount/weedfs_meta_subscribe_test.go b/weed/mount/weedfs_meta_subscribe_test.go index c3cc7975db..fca8d84a3a 100644 --- a/weed/mount/weedfs_meta_subscribe_test.go +++ b/weed/mount/weedfs_meta_subscribe_test.go @@ -189,7 +189,7 @@ func testMountMetadataReplayAuthorization(t *testing.T, access string, readAuth followed := make(chan struct{}) go func() { defer close(followed) - meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, 0, false, nil) + meta_cache.SubscribeMetaEvents(context.Background(), wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, 0, false, nil) }() select { diff --git a/weed/pb/filer_pb_tail.go b/weed/pb/filer_pb_tail.go index c84ee36498..42cb5dde32 100644 --- a/weed/pb/filer_pb_tail.go +++ b/weed/pb/filer_pb_tail.go @@ -59,6 +59,11 @@ type MetadataFollowOption struct { // durably processed watermark while StartTsNs keeps tracking positions the // stream has merely seen. GetResumeTsNs func() int64 + // ParentContext bounds the subscription itself. Cancelling it ends the + // stream, so a consumer that is shutting down can quiesce the follow + // before closing what the events are applied to. Nil follows the stream's + // own lifetime, which is the subscription call alone. + ParentContext context.Context // Resubscribe, when closed, drops the stream with ErrResubscribe so the // caller's reconnect loop resubscribes from GetResumeTsNs and replays the // events still pinning the processed watermark. Target-side job failures @@ -71,6 +76,15 @@ type MetadataFollowOption struct { // stream to drop so the reconnect replays what the resume watermark pins. var ErrResubscribe = errors.New("resubscribe to replay events behind the failed offset") +// ErrStopFollowing ends a metadata follow because the consumer reported a +// condition that no later event on this stream can get past — a metadata cache +// that has been closed, for one. Unlike the errors that reach the event error +// modes, it is not a failure of one event but the end of the subscription, so +// it leaves the stream instead of being logged per event. It also keeps a +// consumer's FatalOnError from firing on its own shutdown: the mount exiting is +// not a fatal condition. +var ErrStopFollowing = errors.New("stop following metadata") + type ProcessMetadataFunc func(resp *filer_pb.SubscribeMetadataResponse) error func FollowMetadata(filerAddress ServerAddress, grpcDialOption grpc.DialOption, option *MetadataFollowOption, processEventFn ProcessMetadataFunc) error { @@ -94,7 +108,11 @@ func WithFilerClientFollowMetadata(filerClient filer_pb.FilerClient, option *Met func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn ProcessMetadataFunc) func(client filer_pb.SeaweedFilerClient) error { return func(client filer_pb.SeaweedFilerClient) error { - ctx, cancel := context.WithCancel(context.Background()) + parent := option.ParentContext + if parent == nil { + parent = context.Background() + } + ctx, cancel := context.WithCancel(parent) defer cancel() sinceNs := option.StartTsNs if option.GetResumeTsNs != nil { @@ -178,7 +196,7 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc // MaxUnsyncedEvents marker (empty one). Both route to OnIdleHeartbeat, // else the marker pins sync_offset to the stale processed watermark and a // nil heartbeat folded into a batch nil-derefs in the sync job path. - handleOneEvent := func(resp *filer_pb.SubscribeMetadataResponse) { + handleOneEvent := func(resp *filer_pb.SubscribeMetadataResponse) error { if resp.EventNotification == nil || filer_pb.IsEmpty(resp) { if resp.TsNs > 0 && option.OnIdleHeartbeat != nil { option.OnIdleHeartbeat(resp.TsNs) @@ -190,25 +208,35 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc if resp.EventNotification != nil && resp.TsNs > 0 { if option.GetResumeTsNs != nil { if err := processEventFn(resp); err != nil { + if errors.Is(err, ErrStopFollowing) { + return err + } handleErr(resp, err) } } else { option.StartTsNs = resp.TsNs } } - return + return nil } if err := processEventFn(resp); err != nil { + // A consumer that reported the end of the subscription is not a + // failed event: the error modes would log it per event, and + // FatalOnError would abort a process that is only shutting down. + if errors.Is(err, ErrStopFollowing) { + return err + } handleErr(resp, err) // RetryForeverOnError only returns once the event was handled; // other modes leave it failed and the cursor stays behind it. if option.EventErrorType != RetryForeverOnError { - return + return nil } } if option.GetResumeTsNs == nil { option.StartTsNs = resp.TsNs } + return nil } var pendingRefs []*filer_pb.LogFileChunkRef @@ -288,9 +316,13 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc // The server folds a backlog into one response: the first event lives in // the top-level fields, the rest in resp.Events. Either slot can hold a // freshness signal, so both go through the same handler. - handleOneEvent(resp) + if err := handleOneEvent(resp); err != nil { + return err + } for _, batchedEvent := range resp.Events { - handleOneEvent(batchedEvent) + if err := handleOneEvent(batchedEvent); err != nil { + return err + } } } } diff --git a/weed/pb/filer_pb_tail_test.go b/weed/pb/filer_pb_tail_test.go index 1fb62bce84..4fc2e84162 100644 --- a/weed/pb/filer_pb_tail_test.go +++ b/weed/pb/filer_pb_tail_test.go @@ -604,3 +604,75 @@ func TestChunkReplayCheckpointSurvivesReconnect(t *testing.T) { t.Fatalf("expected subscribes at 100 then 101, got %v", sinceNs) } } + +// A consumer reporting ErrStopFollowing is ending the subscription, not failing +// one event: the follow must return it instead of routing it through the per +// event error modes, and must leave the cursor behind the event it did not +// apply so a later subscriber replays from there. +func TestStopFollowingEndsStreamAndKeepsCursor(t *testing.T) { + const firstTs = int64(100) + const secondTs = int64(200) + + option := &MetadataFollowOption{ + ClientName: "syncFrom_A_To_B", + StartTsNs: firstTs, + EventErrorType: DontLogError, + } + stream := &fakeSubscribeStream{ + responses: []*filer_pb.SubscribeMetadataResponse{ + {Directory: "/watched", TsNs: secondTs, EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{Name: "stop"}}}, + {Directory: "/watched", TsNs: secondTs + 1, EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{Name: "next"}}}, + }, + } + + var seen int + fn := makeSubscribeMetadataFunc(option, func(resp *filer_pb.SubscribeMetadataResponse) error { + seen++ + if seen == 1 { + return fmt.Errorf("%w: metadata cache is shut down", ErrStopFollowing) + } + t.Error("the stream kept delivering events after the consumer asked to stop") + return nil + }) + + err := fn(&fakeFilerClient{stream: stream}) + if !errors.Is(err, ErrStopFollowing) { + t.Fatalf("expected the follow to end with ErrStopFollowing, got %v", err) + } + if seen != 1 { + t.Fatalf("events processed = %d, want 1", seen) + } + if option.StartTsNs != firstTs { + t.Fatalf("StartTsNs advanced to %d past the stopped event, want it to stay at %d", option.StartTsNs, firstTs) + } +} + +// Cancelling the caller's context must end the stream, so a consumer can +// quiesce the follow before closing what the events are applied to. +func TestParentContextCancelEndsStream(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + option := &MetadataFollowOption{ + ClientName: "syncFrom_A_To_B", + EventErrorType: DontLogError, + ParentContext: ctx, + } + fn := makeSubscribeMetadataFunc(option, func(resp *filer_pb.SubscribeMetadataResponse) error { + return nil + }) + + done := make(chan error, 1) + go func() { + done <- fn(&blockingFilerClient{}) + }() + + cancel() + + select { + case err := <-done: + if err == nil { + t.Fatal("the follow ended cleanly after its parent context was cancelled; it must report the failure") + } + case <-time.After(5 * time.Second): + t.Fatal("cancelling ParentContext did not end the subscription") + } +}