diff --git a/weed/mount/meta_cache/meta_cache.go b/weed/mount/meta_cache/meta_cache.go index 10f2e88b96..c889488c00 100644 --- a/weed/mount/meta_cache/meta_cache.go +++ b/weed/mount/meta_cache/meta_cache.go @@ -34,6 +34,7 @@ type MetaCache struct { invalidateFunc func(EntryInvalidation) onDirectoryUpdate func(dir util.FullPath) pinnedChildFn func(*filer.Entry) bool // a child a rebuild must not drop (local-only, not yet on the filer); nil disables + dropListingFn func(dir util.FullPath) // drops a directory's cached listing; see dropListingsOf. nil disables visitGroup singleflight.Group // deduplicates concurrent EnsureVisited calls for the same path applyCh chan metadataApplyRequest applyDone chan struct{} @@ -732,6 +733,49 @@ func (mc *MetaCache) SetPinnedChildFn(fn func(*filer.Entry) bool) { mc.pinnedChildFn = fn } +// SetDropListingFn installs how a directory's cached listing is dropped, so the +// directory is read from the filer again on its next use. See dropListingsOf. +func (mc *MetaCache) SetDropListingFn(fn func(dir util.FullPath)) { + mc.dropListingFn = fn +} + +// dropListingsOf answers an event the local store could not take, as when the +// cache disk is full: the cached listings the event changes no longer match +// the filer, so each one is dropped and read from the filer again, the way a +// local change whose apply failed drops its directory's listing. The event's +// kernel invalidations and directory notifications still go out, as for an +// event the store took. It runs in the apply loop, in the step that failed, so +// no later request is applied before the event's invalidations: a later +// create of the same name must not be moved by this event's rename. +func (mc *MetaCache) dropListingsOf(resp *filer_pb.SubscribeMetadataResponse, options MetadataResponseApplyOptions) { + if mc.dropListingFn != nil { + for _, dir := range listingsChangedBy(resp) { + mc.dropListingFn(dir) + } + } + // A directory being built is not notified: its build replays the event's + // part for it, which applyMetadataResponseNow kept, and invalidates its + // entries again. + mc.applyMetadataSideEffectsSkippingBuildingDirs(resp, options) +} + +// listingsChangedBy lists the directories whose cached listings an event +// changes: the parents it leaves and enters, and a directory it creates, moves +// or deletes. +func listingsChangedBy(resp *filer_pb.SubscribeMetadataResponse) []util.FullPath { + dirs := collectDirectoryNotifications(resp) + if old := resp.GetEventNotification().GetOldEntry(); old != nil && old.IsDirectory { + oldPath := util.NewFullPath(resp.Directory, old.Name) + for _, dir := range dirs { + if dir == oldPath { + return dirs + } + } + dirs = append(dirs, oldPath) + } + return dirs +} + // rebuildWipeBatchSize caps how many cached children one locked step of a // rebuild's wipe visits. Every metadata read in the mount takes mc's read lock, // and a pending writer blocks new readers, so a wipe that held the write lock @@ -1021,19 +1065,29 @@ func (mc *MetaCache) applyMetadataResponseNow(ctx context.Context, resp *filer_p immediateEvents, bufferedEvents := mc.routeMetadataResponse(resp) if len(bufferedEvents) == 0 { - return mc.applyMetadataResponseDirect(ctx, resp, options, false) + err := mc.applyMetadataResponseDirect(ctx, resp, options, false) + if err != nil { + mc.dropListingsOf(resp, options) + } + return err } + var immediateErr error for _, immediateEvent := range immediateEvents { - if err := mc.applyMetadataResponseDirect(ctx, immediateEvent, MetadataResponseApplyOptions{}, false); err != nil { - return err + if immediateErr = mc.applyMetadataResponseDirect(ctx, immediateEvent, MetadataResponseApplyOptions{}, false); immediateErr != nil { + break } } - // Apply side effects but skip directory notifications for dirs that are - // currently being built. Notifying a building dir can trigger - // markDirectoryReadThrough → DeleteFolderChildren, wiping entries that - // EnsureVisited already inserted, leaving an incomplete cache. - mc.applyMetadataSideEffectsSkippingBuildingDirs(resp, options) + if immediateErr == nil { + // Apply side effects but skip directory notifications for dirs that are + // currently being built. Notifying a building dir can trigger + // markDirectoryReadThrough → DeleteFolderChildren, wiping entries that + // EnsureVisited already inserted, leaving an incomplete cache. + mc.applyMetadataSideEffectsSkippingBuildingDirs(resp, options) + } + // A building directory's part is kept for its replay even when the part + // applied now failed: a build that published its listing without it would + // hide a file renamed into the directory. for buildDir, events := range bufferedEvents { state := mc.buildingDirs[buildDir] if state == nil { @@ -1047,7 +1101,10 @@ func (mc *MetaCache) applyMetadataResponseNow(ctx context.Context, resp *filer_p state.declinedRemovals[declined] = struct{}{} } } - return nil + if immediateErr != nil { + mc.dropListingsOf(resp, options) + } + return immediateErr } // vacateDuringWipe takes out of the store, at once, the paths that events diff --git a/weed/mount/meta_cache/meta_cache_apply_failure_test.go b/weed/mount/meta_cache/meta_cache_apply_failure_test.go new file mode 100644 index 0000000000..8bd3cc1029 --- /dev/null +++ b/weed/mount/meta_cache/meta_cache_apply_failure_test.go @@ -0,0 +1,301 @@ +package meta_cache + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +var errCacheDiskFull = errors.New("write /cache/meta/000001.log: no space left on device") + +// fullDiskStore refuses every write while full is set, the way the mount's +// leveldb store does once its cache disk has no space left. +type fullDiskStore struct { + filer.VirtualFilerStore + full atomic.Bool +} + +func (s *fullDiskStore) refuse() error { + if s.full.Load() { + return errCacheDiskFull + } + return nil +} + +func (s *fullDiskStore) InsertEntry(ctx context.Context, entry *filer.Entry) error { + if err := s.refuse(); err != nil { + return err + } + return s.VirtualFilerStore.InsertEntry(ctx, entry) +} + +func (s *fullDiskStore) UpdateEntry(ctx context.Context, entry *filer.Entry) error { + if err := s.refuse(); err != nil { + return err + } + return s.VirtualFilerStore.UpdateEntry(ctx, entry) +} + +func (s *fullDiskStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error { + if err := s.refuse(); err != nil { + return err + } + return s.VirtualFilerStore.DeleteEntry(ctx, fullpath) +} + +func (s *fullDiskStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error { + if err := s.refuse(); err != nil { + return err + } + return s.VirtualFilerStore.DeleteFolderChildren(ctx, fullpath) +} + +func (s *fullDiskStore) KvPut(ctx context.Context, key []byte, value []byte) error { + if err := s.refuse(); err != nil { + return err + } + return s.VirtualFilerStore.KvPut(ctx, key, value) +} + +func (s *fullDiskStore) KvDelete(ctx context.Context, key []byte) error { + if err := s.refuse(); err != nil { + return err + } + return s.VirtualFilerStore.KvDelete(ctx, key) +} + +// newFullDiskMetaCache is a meta cache over a store whose disk can be filled, +// and the listings dropped through SetDropListingFn. +func newFullDiskMetaCache(t *testing.T, cachedDirs ...util.FullPath) (*MetaCache, *fullDiskStore, func() []util.FullPath, *recordedPaths) { + t.Helper() + cached := map[util.FullPath]bool{} + for _, dir := range cachedDirs { + cached[dir] = true + } + mc, _, _, invalidations := newTestMetaCache(t, cached) + store := &fullDiskStore{VirtualFilerStore: mc.localStore} + mc.localStore = store + + var mu sync.Mutex + var dropped []util.FullPath + mc.SetDropListingFn(func(dir util.FullPath) { + mu.Lock() + defer mu.Unlock() + dropped = append(dropped, dir) + }) + return mc, store, func() []util.FullPath { + mu.Lock() + defer mu.Unlock() + return append([]util.FullPath(nil), dropped...) + }, invalidations +} + +func fileEntry(name string, mtime int64) *filer_pb.Entry { + return &filer_pb.Entry{ + Name: name, + Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: mtime, FileMode: 0100644, FileSize: 3}, + } +} + +func dirEntry(name string) *filer_pb.Entry { + return &filer_pb.Entry{ + Name: name, + IsDirectory: true, + Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 020000000755}, + } +} + +func sameDirs(got, want []util.FullPath) bool { + if len(got) != len(want) { + return false + } + seen := map[util.FullPath]int{} + for _, dir := range got { + seen[dir]++ + } + for _, dir := range want { + if seen[dir] == 0 { + return false + } + seen[dir]-- + } + return true +} + +// A peer creates a file in a directory this mount has cached while the cache +// disk is full. The event used to fail the subscription, which aborts the +// mount (FatalOnError). It now drops the directory's cached listing, so the +// directory is read from the filer again, and still tells the kernel. +func TestSubscribedEventTheStoreRefusesDropsTheListingItChanges(t *testing.T) { + mc, store, dropped, invalidations := newFullDiskMetaCache(t, "/", "/d") + defer mc.Shutdown() + store.full.Store(true) + + resp := &filer_pb.SubscribeMetadataResponse{ + Directory: "/d", + EventNotification: &filer_pb.EventNotification{NewEntry: fileEntry("b", 1)}, + TsNs: time.Now().UnixNano(), + } + if err := applySubscribedEvent(mc, resp); err != nil { + t.Fatalf("an event the store refused failed the subscription: %v", err) + } + + if got, want := dropped(), []util.FullPath{"/d"}; !sameDirs(got, want) { + t.Errorf("dropped listings %v, want %v", got, want) + } + mc.WaitForEntryInvalidations() + if countPath(invalidations.paths(), "/d/b") == 0 { + t.Errorf("no kernel invalidation for /d/b: %v", invalidations.paths()) + } +} + +// A directory moved while the disk is full: the parents it left and entered +// lose their listings, and so does the moved directory under both names, since +// its cached children were never moved. +func TestSubscribedDirectoryMoveTheStoreRefusesDropsEveryListingItChanges(t *testing.T) { + mc, store, dropped, _ := newFullDiskMetaCache(t, "/", "/d", "/e", "/d/sub") + defer mc.Shutdown() + store.full.Store(true) + + resp := &filer_pb.SubscribeMetadataResponse{ + Directory: "/d", + EventNotification: &filer_pb.EventNotification{ + OldEntry: dirEntry("sub"), + NewEntry: dirEntry("sub"), + NewParentPath: "/e", + }, + TsNs: time.Now().UnixNano(), + } + if err := applySubscribedEvent(mc, resp); err != nil { + t.Fatalf("an event the store refused failed the subscription: %v", err) + } + if got, want := dropped(), []util.FullPath{"/d", "/e", "/d/sub", "/e/sub"}; !sameDirs(got, want) { + t.Errorf("dropped listings %v, want %v", got, want) + } +} + +// An event the store takes drops nothing. +func TestSubscribedEventTheStoreTakesDropsNothing(t *testing.T) { + mc, _, dropped, _ := newFullDiskMetaCache(t, "/", "/d") + defer mc.Shutdown() + + resp := &filer_pb.SubscribeMetadataResponse{ + Directory: "/d", + EventNotification: &filer_pb.EventNotification{NewEntry: fileEntry("b", 1)}, + TsNs: time.Now().UnixNano(), + } + if err := applySubscribedEvent(mc, resp); err != nil { + t.Fatalf("apply: %v", err) + } + if got := dropped(); len(got) != 0 { + t.Errorf("dropped listings %v for an event the store took", got) + } + if entry, _, err := mc.FindEntry(context.Background(), "/d/b"); err != nil || entry == nil { + t.Errorf("/d/b not cached: %v", err) + } +} + +// A closed cache still ends the subscription instead of dropping listings. +func TestSubscribedEventOnAClosedCacheEndsTheSubscription(t *testing.T) { + mc, _, dropped, _ := newFullDiskMetaCache(t, "/", "/d") + mc.Shutdown() + + resp := &filer_pb.SubscribeMetadataResponse{ + Directory: "/d", + EventNotification: &filer_pb.EventNotification{NewEntry: fileEntry("b", 1)}, + TsNs: time.Now().UnixNano(), + } + if err := applySubscribedEvent(mc, resp); !errors.Is(err, pb.ErrStopFollowing) { + t.Fatalf("apply on a closed cache = %v, want ErrStopFollowing", err) + } + if got := dropped(); len(got) != 0 { + t.Errorf("dropped listings %v on a closed cache", got) + } +} + +// A file renamed into a directory whose listing is being built, while the +// disk is full: the part of the event that leaves the source is refused, and +// the part for the building directory must still reach its build. Otherwise +// the build publishes a listing taken before the rename, without the file, +// and the file stays hidden after the disk has room again. +func TestRenameIntoABuildingDirectoryIsReplayedAfterTheStoreRefusedIt(t *testing.T) { + mc, store, dropped, _ := newFullDiskMetaCache(t, "/", "/d") + defer mc.Shutdown() + ctx := context.Background() + + if err := mc.InsertEntry(ctx, &filer.Entry{ + FullPath: "/d/x", + Attr: filer.Attr{Mode: 0644, Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), FileSize: 3}, + }, 0); err != nil { + t.Fatalf("insert /d/x: %v", err) + } + if err := mc.BeginDirectoryBuild(ctx, "/e"); err != nil { + t.Fatalf("begin build of /e: %v", err) + } + + store.full.Store(true) + tsNs := time.Now().UnixNano() + resp := &filer_pb.SubscribeMetadataResponse{ + Directory: "/d", + EventNotification: &filer_pb.EventNotification{ + OldEntry: fileEntry("x", 1), + NewEntry: fileEntry("x", 2), + NewParentPath: "/e", + }, + TsNs: tsNs, + } + if err := applySubscribedEvent(mc, resp); err != nil { + t.Fatalf("an event the store refused failed the subscription: %v", err) + } + if got, want := dropped(), []util.FullPath{"/d", "/e"}; !sameDirs(got, want) { + t.Errorf("dropped listings %v, want %v", got, want) + } + + store.full.Store(false) + // The build's listing was taken before the rename. + if err := mc.CompleteDirectoryBuild(ctx, "/e", tsNs-1, nil); err != nil { + t.Fatalf("complete build of /e: %v", err) + } + if entry, _, err := mc.FindEntry(ctx, "/e/x"); err != nil || entry == nil { + t.Fatalf("/e/x is missing from the listing the build published: %v", err) + } +} + +// A refused event is handled in the apply step that refused it, before the +// apply returns and so before any request queued after it. Handled later, a +// peer's rename of /d/x to /e/x could be handled after this mount's own create +// of a new /d/x, and the rename's kernel invalidation, which moves the inode +// at /d/x to /e/x, would move the new file. +func TestRefusedEventIsHandledInTheApplyStepThatRefusedIt(t *testing.T) { + mc, store, dropped, invalidations := newFullDiskMetaCache(t, "/", "/d", "/e") + defer mc.Shutdown() + store.full.Store(true) + + resp := &filer_pb.SubscribeMetadataResponse{ + Directory: "/d", + EventNotification: &filer_pb.EventNotification{ + OldEntry: fileEntry("x", 1), + NewEntry: fileEntry("x", 1), + NewParentPath: "/e", + }, + TsNs: time.Now().UnixNano(), + } + if err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions); err == nil { + t.Fatal("the full store took the rename") + } + if got, want := dropped(), []util.FullPath{"/d", "/e"}; !sameDirs(got, want) { + t.Errorf("listings dropped by the apply: %v, want %v", got, want) + } + mc.WaitForEntryInvalidations() + if got := invalidations.paths(); countPath(got, "/d/x") == 0 || countPath(got, "/e/x") == 0 { + t.Errorf("kernel invalidations from the apply: %v, want /d/x and /e/x", got) + } +} diff --git a/weed/mount/meta_cache/meta_cache_subscribe.go b/weed/mount/meta_cache/meta_cache_subscribe.go index 6b891ed292..fa3bca7236 100644 --- a/weed/mount/meta_cache/meta_cache_subscribe.go +++ b/weed/mount/meta_cache/meta_cache_subscribe.go @@ -6,6 +6,8 @@ import ( "fmt" "io" "strings" + "sync/atomic" + "time" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/glog" @@ -47,6 +49,45 @@ func mergeProcessors(mainProcessor func(resp *filer_pb.SubscribeMetadataResponse } } +// 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 @@ -70,15 +111,7 @@ func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32 } } } - 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 + return applySubscribedEvent(mc, resp) } prefix := dir diff --git a/weed/mount/weedfs.go b/weed/mount/weedfs.go index a1c6f3b143..4f75809db2 100644 --- a/weed/mount/weedfs.go +++ b/weed/mount/weedfs.go @@ -362,6 +362,7 @@ func NewSeaweedFileSystem(option *Option) *WFS { return wfs.inodeToPath.IsChildrenCached(path) }, wfs.onEntryInvalidation, nil) wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry) + wfs.metaCache.SetDropListingFn(wfs.inodeToPath.InvalidateChildrenCache) grace.OnInterrupt(func() { // grace calls os.Exit(0) after all hooks, so WaitForAsyncFlush // after server.Serve() would never execute. Drain here first.