Files
seaweedfs/weed/mount/meta_cache/meta_cache_init.go
T
Yip LeoandClaude Opus 5.5 82a435c468 mount: list a directory from the filer when the cache disk cannot hold it (#13204)
* mount: list a directory from the filer when the cache disk cannot hold it

A listing builds the directory into the mount's local metadata cache, a
leveldb store under -cacheDir, and serves it from there. Once that disk is
full the build fails at its first write, and the listing failed with it:
readdir returned EIO for every directory the mount had not cached, and for
one whose cached listing a refused event had just dropped (#13141). Files
could still be opened, read and written; only listing them broke.

A build the store refuses now reports a LocalStoreError, and the listing
reads the directory through from the filer, the way it already does for a
directory too large to cache. Builds then wait out a 10s backoff instead of
re-listing a directory from the filer only to fail at its first insert
again; once the disk has room the next build caches the directory. While
the store refuses, at most 4 listings per mount read through at once, so a
burst of them reaches the filer spread out rather than all together.

The hand-over from a walk served from the cache to one read through from
the filer resumed at the request's offset, so the entries the cached walk
had just put in the same reply were sent again and the client listed them
twice. A directory found too large partway through a walk took that path
rarely; a full cache disk takes it on every request. The direct walk now
resumes past the entries already in the reply.

Lookups needed no change: in a directory the cache does not hold, a lookup
already asks the filer for the one entry.

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

* mount: list unflushed creates and every page when reading a directory through

Listings read through from the filer are now the common path on a full
cache disk. This fixes three gaps in them:

- A file created on this mount is not on the filer until its first flush.
  Until then the local store holds a placeholder for it, which a rebuild
  keeps. A cached listing showed such a file; a listing read through from
  the filer left it out. The read-through now merges in, page by page and
  in name order, the children the local store keeps for a rebuild
  (MetaCache.LocalOnlyChildren, which asks the same pinnedChildFn as the
  rebuild's wipe). Each page takes the ones after its start and up to its
  last name; the last page takes every one past its start. A name the
  filer also has by now is listed once. Directories too large to cache
  read through the same way, so they get the fix as well.
- The filer applies the page limit before the loader leaves out the root's
  hidden system entries (etc, topics). A full page that held one came back
  short, and the listing ended there. The end of the directory is now read
  from the number of entries the filer sent. If a failover reruns a page,
  the loader starts its entries and that count over.
- A walk served from the cache also hands over to the filer when
  refreshing a stale section would list too many entries
  (ErrRefreshRangeTooLarge). That hand-over still resumed at the request's
  offset, so it sent again the entries already in the reply. It now
  resumes where the cached walk reached, like the other hand-over.

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

* mount: keep the rest of a read-through page on the directory handle

A page listed from the filer went onto the directory handle only up to the
entry the reply had no room for. The next request listed the filer again
from there and merged the unflushed creates again, so with small replies
each filer page was listed, and the local store scanned, once per reply.
Now the whole page goes onto the handle, and later requests take what is
left from it, as they do from the cache. The unflushed creates are also
looked up without decoding chunk lists.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:57:29 -08:00

323 lines
11 KiB
Go

package meta_cache
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/sync/errgroup"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// DirectoryTooLargeError reports a directory the mount refuses to cache
// locally. Its listings read through to the filer instead.
type DirectoryTooLargeError struct {
Path util.FullPath
}
func (e *DirectoryTooLargeError) Error() string {
return fmt.Sprintf("directory %s is too large to cache locally", e.Path)
}
// LocalStoreError reports a directory build the local store refused: a write
// to the cache disk failed, typically because the disk is full. The directory
// reads through to the filer, the way an oversized one does, until the store
// takes writes again.
type LocalStoreError struct {
Path util.FullPath
Err error
}
func (e *LocalStoreError) Error() string {
return fmt.Sprintf("local store cannot cache directory %s: %v", e.Path, e.Err)
}
func (e *LocalStoreError) Unwrap() error {
return e.Err
}
// storeRefusalBackoff is how long directories read through after the store
// refused a build before a build is tried again. A build on a full disk lists
// the directory from the filer only to fail at its first write.
var storeRefusalBackoff = 10 * time.Second
var errStoreRefusing = errors.New("it refused a write moments ago")
// noteStoreRefusal starts the backoff after a build the store refused. It logs
// once per backoff, not once per listing.
func (mc *MetaCache) noteStoreRefusal(path util.FullPath, err error) {
now := time.Now()
if previous := mc.storeRefusedUntil.Swap(now.Add(storeRefusalBackoff).UnixNano()); previous <= now.UnixNano() {
glog.Warningf("local store cannot cache %s, listing directories from the filer for %v: %v", path, storeRefusalBackoff, err)
}
}
// storeRefusal is errStoreRefusing while the backoff after a refused build
// lasts, nil otherwise.
func (mc *MetaCache) storeRefusal() error {
if time.Now().UnixNano() < mc.storeRefusedUntil.Load() {
return errStoreRefusing
}
return nil
}
// maxCacheableEntries is the directory size above which a build gives up, or 0
// to cache everything.
func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClient, dirPath util.FullPath, maxCacheableEntries int) error {
// Collect all uncached paths from target directory up to root
var uncachedPaths []util.FullPath
currentPath := dirPath
for {
// If this path is cached, all ancestors are also cached
if mc.isCachedFn(currentPath) {
break
}
if mc.isOversized(currentPath) {
// The directory itself reads through; an ancestor is stepped over,
// or it would wedge every listing beneath it forever.
if currentPath == dirPath {
return &DirectoryTooLargeError{Path: currentPath}
}
} else {
uncachedPaths = append(uncachedPaths, currentPath)
}
// Continue to parent directory
if currentPath != mc.root {
parent, _ := currentPath.DirAndName()
currentPath = util.FullPath(parent)
} else {
break
}
}
if len(uncachedPaths) == 0 {
return nil
}
// A build the store refused moments ago would be refused again.
if err := mc.storeRefusal(); err != nil {
return &LocalStoreError{Path: dirPath, Err: err}
}
// Fetch all uncached directories in parallel with context for cancellation
// If one fetch fails, cancel the others to avoid unnecessary work
g, ctx := errgroup.WithContext(ctx)
for _, p := range uncachedPaths {
path := p // capture for closure
g.Go(func() error {
err := doEnsureVisited(ctx, mc, client, path, maxCacheableEntries)
// A build discarded by a distrust lists the directory again.
for attempt := 1; errors.Is(err, ErrDirectoryBuildDiscarded) && attempt < maxDiscardedBuildRetries; attempt++ {
err = doEnsureVisited(ctx, mc, client, path, maxCacheableEntries)
}
var tooLarge *DirectoryTooLargeError
if errors.As(err, &tooLarge) && path != dirPath {
// An ancestor found oversized just reads through; failing the
// group here would cancel the builds of its cacheable
// descendants, and the caller would treat the refusal as the
// listed directory's own.
return nil
}
return err
})
}
return g.Wait()
}
// batchInsertSize is the number of entries to accumulate before flushing to LevelDB.
// 100 provides a balance between memory usage (~100 Entry pointers) and write efficiency
// (fewer disk syncs). Larger values reduce I/O overhead but increase memory and latency.
const batchInsertSize = 100
// maxDiscardedBuildRetries bounds how often one visit lists a directory whose
// build a distrust discarded.
const maxDiscardedBuildRetries = 3
const (
emptyRebuildConfirmations = 2
emptyRebuildConfirmDelay = 50 * time.Millisecond
)
func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClient, path util.FullPath, maxCacheableEntries int) error {
// The shared build must not run on the requester's context. A FUSE request
// that returns — or that the kernel interrupts — cancels that context, and
// every other requester waiting on the same build would inherit the
// cancellation. weed/mount/weedfs_dir_read.go only reports EINTR when the
// *local* context is done, so such a waiter falls through to fuse.EIO and
// the kernel hands EIO to readdirent: kubelet's applyFSGroup fails and the
// volume never mounts.
//
// Build on a context that keeps the request's values but not its
// cancellation. Waiters still abandon on their own context below, so a
// canceled request stops waiting immediately.
buildCtx := context.WithoutCancel(ctx)
// Use singleflight to deduplicate concurrent requests for the same path.
// DoChan so a canceled request stops waiting even when another request
// owns the in-flight build.
resultCh := mc.visitGroup.DoChan(string(path), func() (interface{}, error) {
// Check for cancellation before starting
if buildCtx.Err() != nil {
return nil, buildCtx.Err()
}
// Double-check if already cached (another goroutine may have completed)
if mc.isCachedFn(path) {
return nil, nil
}
glog.V(4).Infof("ReadDirAllEntries %s ...", path)
// Use context.Background() for build lifecycle calls so that
// errgroup cancellation of ctx doesn't cause enqueueAndWait to
// return early, which would trigger cleanupBuild while the
// operation is still queued.
if err := mc.BeginDirectoryBuild(context.Background(), path); err != nil {
return nil, fmt.Errorf("begin build %s: %w", path, err)
}
cleanupDone := false
cleanupBuild := func(reason string) {
if cleanupDone {
return
}
cleanupDone = true
if deleteErr := mc.deleteFolderChildrenForRebuild(context.Background(), path); deleteErr != nil {
glog.V(2).Infof("clear %s build %s: %v", reason, path, deleteErr)
}
if abortErr := mc.AbortDirectoryBuild(context.Background(), path); abortErr != nil {
glog.V(2).Infof("abort %s build %s: %v", reason, path, abortErr)
}
}
defer func() {
if !cleanupDone && buildCtx.Err() != nil {
cleanupBuild("canceled")
}
}()
// reloadFromFiler wipes the cached children and reloads them from the filer.
reloadFromFiler := func() (entryCount int, snapshotTsNs int64, sections sectionBoundsCollector, err error) {
err = util.Retry("ReadDirAllEntries", func() error {
entryCount = 0
sections = sectionBoundsCollector{}
var batch []*filer.Entry // reset on retry, allow GC of previous entries
if err := mc.deleteFolderChildrenForRebuild(buildCtx, path); err != nil {
return &LocalStoreError{Path: path, Err: fmt.Errorf("clear existing entries: %w", err)}
}
var listErr error
snapshotTsNs, listErr = filer_pb.ReadDirAllEntriesWithSnapshot(buildCtx, client, path, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
entry := filer.FromPbEntry(string(path), pbEntry)
if !mc.includeSystemEntries && IsHiddenSystemEntry(string(path), entry.Name()) {
return nil
}
if maxCacheableEntries > 0 && entryCount >= maxCacheableEntries {
return &DirectoryTooLargeError{Path: path}
}
sections.note(entry.Name())
batch = append(batch, entry)
entryCount++
// flush by size, not isLast: hidden entries can return early
if len(batch) >= batchInsertSize {
if err := mc.doBatchInsertEntries(buildCtx, batch); err != nil {
return &LocalStoreError{Path: path, Err: fmt.Errorf("batch insert: %w", err)}
}
batch = make([]*filer.Entry, 0, batchInsertSize)
}
return nil
})
if listErr != nil {
return listErr
}
if len(batch) > 0 {
if err := mc.doBatchInsertEntries(buildCtx, batch); err != nil {
return &LocalStoreError{Path: path, Err: fmt.Errorf("batch insert remaining: %w", err)}
}
}
return nil
})
return entryCount, snapshotTsNs, sections, err
}
// noteIfRefused starts the store backoff when a build failed on the
// store rather than on the filer.
noteIfRefused := func(err error) {
var refused *LocalStoreError
if errors.As(err, &refused) {
mc.noteStoreRefusal(path, refused.Err)
}
}
entryCount, snapshotTsNs, sections, fetchErr := reloadFromFiler()
if fetchErr != nil {
noteIfRefused(fetchErr)
var tooLarge *DirectoryTooLargeError
if errors.As(fetchErr, &tooLarge) {
// Remember the refusal so the next visit fails fast instead of
// streaming up to the limit again to rediscover it.
mc.markOversized(path)
glog.V(0).Infof("directory %s exceeds %d entries, reading it through instead of caching", path, maxCacheableEntries)
cleanupBuild("oversized")
return nil, fetchErr
}
cleanupBuild("failed")
return nil, fmt.Errorf("list %s: %w", path, fetchErr)
}
// A transient empty listing would strand a populated directory cached over
// an empty store; re-read to confirm before trusting it. First re-read is
// immediate (a clean-EOF stream glitch clears at once), later ones space out.
// On cancellation the deferred cleanup aborts the build.
for attempt := 0; entryCount == 0 && attempt < emptyRebuildConfirmations; attempt++ {
if buildCtx.Err() != nil {
return nil, buildCtx.Err()
}
if attempt > 0 {
select {
case <-time.After(emptyRebuildConfirmDelay):
case <-buildCtx.Done():
return nil, buildCtx.Err()
}
}
if entryCount, snapshotTsNs, sections, fetchErr = reloadFromFiler(); fetchErr != nil {
noteIfRefused(fetchErr)
cleanupBuild("failed")
return nil, fmt.Errorf("confirm empty list %s: %w", path, fetchErr)
}
if entryCount > 0 {
glog.Warningf("rebuild of %s saw a transient empty listing, recovered %d entries on confirmation", path, entryCount)
}
}
if err := mc.CompleteDirectoryBuild(context.Background(), path, snapshotTsNs, sections.bounds); err != nil {
cleanupBuild("unreplayed")
if !errors.Is(err, ErrClosed) && !errors.Is(err, ErrDirectoryBuildDiscarded) {
// Otherwise completing fails only on writing the events
// buffered during the listing to the store.
err = &LocalStoreError{Path: path, Err: fmt.Errorf("replay buffered events: %w", err)}
noteIfRefused(err)
}
return nil, fmt.Errorf("complete build for %s: %w", path, err)
}
cleanupDone = true // Prevent deferred cleanup after successful publish
return nil, nil
})
select {
case result := <-resultCh:
return result.Err
case <-ctx.Done():
return ctx.Err()
}
}
func IsHiddenSystemEntry(dir, name string) bool {
return dir == "/" && (name == "topics" || name == "etc")
}