Files
seaweedfs/weed/filer/treewalk/seed.go
T
2c48e8a014 worker: dir_usage keeps the sizes of buckets and their large directories (#13345)
* shell: fs.du walks with a shared treewalk.Walker

The walker fs.du used moves to a new package, filer/treewalk, so that the
dir_usage job proposed in #13257 walks the same way. fs.du adds up what
its visitor is told; what it prints and how it fails stay the same. A page
now also carries the snapshot the filer listed it at, and when it was
listed.

treewalktest serves a tree from memory and logs an event for each change,
for the tests of walks and of what follows.

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

* filer/treewalk: Seed adds up a walk and the events logged while it runs

Seed walks a directory tree while it follows the metadata log below it,
and reconciles the two, so that the result is the tree as of one log
position:

- an event at or before the snapshot of the page that lists its name
  shows in that page, and so does an event in a directory not listed yet;
- an event after the page's snapshot replaces what the page counted for
  the name, since the page may or may not show it;
- once a page is older than a margin, a minute by default since a rename
  logs its events after the move, an event changes the entry from its old
  to its new entry.

A directory missing from its parent's page counts from its events if it
was created after that page's snapshot, and not at all otherwise. This is
how the mount's metadata cache builds a directory from a listing and the
events around it, with a replace per name in place of the cache's
overwrite, which a running total cannot do.

Follow reads the events of a range of the log. The lookup of where the
log starts moves here from filer_ttl as LogStartTsNs.

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

* worker: dir_usage keeps the sizes of buckets and their large directories

A plugin worker job, off by default, that keeps what fs.du adds up of each
bucket and each top-level directory outside the buckets folder, and of
each directory in it holding at least 1% of its bytes, down to 10 levels.
Directories at one depth do not overlap, so a bucket has at most 1,000
such records, whatever the shape of its tree. They are one JSON file per
bucket under /etc/seaweedfs/dir_usage/<store signature>/.

The buckets without a record are seeded in one treewalk.Seed walk of the
buckets folder, and the top-level directories in one of /. After that,
each run replays the events since the last run, up to a minute before
now, applies each to the directories with a record above the entry,
writes the files that changed, and saves a cursor that meta_log_purge
keeps the log for. A record the log no longer reaches is seeded again,
and so is every record when no log is kept and the cursor is older than
the purge honors.

A tracked directory that moves keeps its record, which the events of the
entries it took along fill again. One deleted with totals left had
entries that went without events, as when a store drops a whole bucket,
and the rest comes off the directories above it. A bucket created since
the last run is seeded by the next.

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

* shell: fs.du -report prints what the dir_usage job keeps

fs.du -report [-depth=N] path prints the totals the dir_usage job keeps of
path and of the directories below it with a record, down to N levels, the
way fs.du prints a walk, and how old they are: as old as the job's cursor
for a record the last replay did not change. Nothing is walked. For / and
the buckets folder, the buckets and top-level directories add up.

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

* treewalk, dir_usage: wait for the filer's own position, stop waits on cancel

A subscription with an end stops once it has read everything the filer has
logged, without waiting for the end to come. So the seed's catch-up now
waits until the filer's listing snapshot reaches the seed's end, and a
replay ends at the snapshot the filer gives when it starts, both on the
filer's clock rather than this process's.

- A walk waiting for its pages to free names stops when its context ends.
- A seed reports the listing that failed, not the cancellation it caused.
- A walk canceled while the last page's subdirectories start fails.
- LogStartTsNs passes over a day a purge that stopped midway left empty.
- A bucket dropped while the buckets folder is seeded gets no record; the
  next run seeds it if it is made again.
- Detection keys a store's job by its signature, so no two runs share a
  store whichever filer each starts from.
- The buckets folder is taken without a trailing slash.
- fs.du -report names the buckets and top-level directories it leaves out
  for want of a record, and no longer says why a directory has no total of
  its own.
- treewalktest.Filer replays a quiet drop with what was below it, and can
  refuse a listing.

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

* treewalk: list a page again after a transient failure

A seed walks every bucket without a record in one walk, which on a large
store runs for hours. One page that failed because the filer restarted or a
connection dropped failed the whole walk, and the next run started it over.
A page that fails with a transient error is now asked for again, with
backoff, for up to a minute. Other failures still end the listing at once.

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

* dir_usage: keep the other seeded records when one fails to save

A save that failed after a seed returned at once, so the records of the
batch not saved yet were lost, and the top-level directories were not
seeded at all when it was the buckets' batch that failed. The next run
walked them all again, which on a large store takes hours. A failed save
is now reported and the run goes on; the next run seeds only that root.

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

* treewalk: measure how far the filer's clock runs ahead in a seed

A page's end is on this host's clock and the events it is compared to
are on the filer's, so a filer clock ahead by more than the margin
expired pages before the events they show arrived, and set the seed's
end before positions the filer had already logged. The seed now learns
a lower bound of the filer's lead from the page snapshots and the event
stamps, and adds it to page expiry and to the end.

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

* mini: expect the dir_usage handler among the default job types

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 11:05:56 -08:00

585 lines
16 KiB
Go

package treewalk
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// seedMargin is the Margin of a Seed that sets none.
const seedMargin = time.Minute
// maxFollowFailures is how often in a row the subscription of a seed can
// break before the seed fails.
const maxFollowFailures = 5
// seedMaxHeld bounds the names the pages of a seed keep. A walk that gets this
// far ahead of the events waits for them.
const seedMaxHeld = 1 << 20
// Seed adds up a directory tree from a walk of it and from the metadata events
// logged while the walk runs, so that the two together give the tree as of
// one log position, the one Run returns. Change is called for every listed
// entry and for every event that changes what the walk counted:
//
// - An event at or before the snapshot of the page that lists its name
// shows in that page and is left out, and so is an event in a directory
// the walk has not listed yet: the listing will show it.
// - An event after the page's snapshot replaces what the page counted for
// the name, since the page may or may not show it.
// - An event after the page stopped keeping its names, a margin after its
// listing ended, changes the entry from the event's old entry to its new
// one.
//
// A directory that is not in its parent's listing is counted from its events
// if it was created after that page's snapshot, and left out otherwise. This
// is how the mount's metadata cache builds a directory from a listing and the
// events around it, with the per-name replace standing in for the cache's
// overwrite, which a running total cannot do.
//
// A directory removed with one event for itself alone, as when a store drops
// a whole bucket, leaves what was listed below it counted: Change is told of
// the directory going, and the caller drops what it counted below it.
type Seed[V any] struct {
Client filer_pb.FilerClient
ClientName string
Concurrency int
PageSize uint32
// Value is what Change is told of an entry, and what a page keeps of
// each name it lists.
Value func(entry *filer_pb.Entry) V
// Change reports that name in dir went from from to to; nil is no entry.
// Change, Started and Done are called one at a time.
Change func(dir util.FullPath, name string, from, to *V)
// Started and Done, if set, are told when the listing of a directory
// starts, and when the directory and everything below it are listed.
Started func(dir util.FullPath, depth int)
Done func(dir util.FullPath, depth int)
// Skip, if set, reports whether dir is in a part of the tree to leave
// out. It is asked about each directory the walk would go into and each
// directory an event names.
Skip func(dir util.FullPath) bool
// Margin is how long after a change its event is logged at most; 0 is a
// minute. A rename logs the events of everything it moved once it is
// done, so a page can show a change whose event comes later, and a page
// keeps its names this long after its listing ended to recognize such
// events.
Margin time.Duration
maxHeld int // seedMaxHeld unless a test sets it
}
// seedPage is a listed page and, until it expires, what it counted per name.
type seedPage[V any] struct {
dir *seedDir[V]
after string
last string
final bool
snapshot int64
endNs int64
values map[string]*V // nil once the page expired
}
func (p *seedPage[V]) covers(name string) bool {
return name > p.after && (p.final || name <= p.last)
}
// seedDir is a directory the walk went into, kept while events about it can
// still need its pages: until it and everything below it are listed and its
// pages expired.
type seedDir[V any] struct {
path util.FullPath
parent *seedDir[V]
pages []*seedPage[V] // in name order
children map[string]*seedDir[V]
// gone are subdirectories missing from the listing that went away after
// it; what was below them was never counted, so their events are left out
gone map[string]bool
// held counts what keeps the directory: one until it is done, each page
// not expired and each child kept
held int
}
func (d *seedDir[V]) pageFor(name string) *seedPage[V] {
i := sort.Search(len(d.pages), func(i int) bool { return d.pages[i].after >= name })
if i == 0 {
return nil
}
if p := d.pages[i-1]; p.covers(name) {
return p
}
return nil
}
type seedRun[V any] struct {
seed *Seed[V]
root *seedDir[V]
margin int64
cancel context.CancelCauseFunc
mu sync.Mutex
cond *sync.Cond
dirs map[util.FullPath]*seedDir[V]
// pages in the order they were listed, which expire in about that order
expiring []*seedPage[V]
held int
maxHeld int
// the directories with a page request out, and when it was sent
inFlight map[util.FullPath]time.Time
// position is how far the events are applied; lastEvent the newest one
position int64
lastEvent int64
// untilNs, once the walk is done, is where the seed ends
untilNs int64
// ahead is how far the filer's clock is known to run ahead of this one:
// the filer cannot stamp a position later than its own now
ahead int64
failure error
}
// Run walks root and follows the events under it, and returns the log position
// the result is at: Change was told of every change under root up to it, and
// of none after it.
func (s *Seed[V]) Run(ctx context.Context, root util.FullPath) (int64, error) {
r := &seedRun[V]{
seed: s,
margin: int64(s.Margin),
dirs: make(map[util.FullPath]*seedDir[V]),
inFlight: make(map[util.FullPath]time.Time),
maxHeld: s.maxHeld,
}
if r.margin == 0 {
r.margin = int64(seedMargin)
}
if r.maxHeld == 0 {
r.maxHeld = seedMaxHeld
}
r.cond = sync.NewCond(&r.mu)
r.root = r.newDir(nil, root)
ctx, r.cancel = context.WithCancelCause(ctx)
defer r.cancel(nil)
stopWaking := context.AfterFunc(ctx, func() {
r.mu.Lock()
defer r.mu.Unlock()
r.fail(context.Cause(ctx))
r.cond.Broadcast()
})
defer stopWaking()
// Every page is complete through a position at least as late as this
// one, so the events after it are all the walk needs.
sinceNs, err := SnapshotTsNs(ctx, s.Client, root)
if err != nil {
return 0, err
}
if sinceNs == 0 {
// a filer that does not say: start a margin before the walk
sinceNs = time.Now().UnixNano() - r.margin
}
followCtx, stopFollowing := context.WithCancel(ctx)
defer stopFollowing()
followed := make(chan struct{})
go func() {
defer close(followed)
r.follow(followCtx, sinceNs)
}()
walker := &Walker{Client: s.Client, Concurrency: s.Concurrency, PageSize: s.PageSize}
err = walker.Walk(ctx, root, "", r)
// a failure below root cancels the walk, and root's listing then fails
// with the cancellation instead
if failure := r.err(); failure != nil {
err = failure
}
if err != nil {
stopFollowing()
<-followed
return 0, err
}
// The last page ended before now, so every page has expired by untilNs.
r.mu.Lock()
ahead := r.ahead
untilNs := time.Now().UnixNano() + ahead + r.margin
r.untilNs = untilNs
r.mu.Unlock()
select {
case <-time.After(time.Until(time.Unix(0, untilNs-ahead))):
case <-ctx.Done():
stopFollowing()
<-followed
return 0, context.Cause(ctx)
}
// A subscription that ends at untilNs stops once it has read all the
// filer logged, so the filer must have logged everything up to untilNs
// first, on its own clock.
if err := waitForSnapshot(ctx, s.Client, root, untilNs); err != nil {
stopFollowing()
<-followed
return 0, err
}
// The open subscription may not have delivered everything up to untilNs
// yet. One that ends there reads what is left.
stopFollowing()
<-followed
if err := r.err(); err != nil {
return 0, err
}
r.mu.Lock()
resumeNs := max(r.lastEvent, sinceNs)
r.mu.Unlock()
if err := subscribe(ctx, s.Client, s.ClientName, string(root), resumeNs, untilNs, r.receive); err != nil {
return 0, fmt.Errorf("follow %s: %w", root, err)
}
r.mu.Lock()
defer r.mu.Unlock()
if r.failure != nil {
return 0, r.failure
}
r.advance(untilNs)
if r.held != 0 || len(r.root.children) != 0 {
return 0, fmt.Errorf("seed %s: %d names and %d directories still kept at the end", root, r.held, len(r.root.children))
}
return untilNs, nil
}
// follow keeps a subscription open from sinceNs until ctx ends, and opens it
// again from the last event when it breaks. When it cannot, the seed fails.
func (r *seedRun[V]) follow(ctx context.Context, sinceNs int64) {
failures := 0
for {
r.mu.Lock()
from := max(r.lastEvent, sinceNs)
r.mu.Unlock()
err := subscribe(ctx, r.seed.Client, r.seed.ClientName, string(r.root.path), from, 0, r.receive)
if ctx.Err() != nil || r.err() != nil {
return
}
r.mu.Lock()
if r.lastEvent > from {
failures = 0
}
failures++
if failures > maxFollowFailures {
r.fail(fmt.Errorf("follow %s: %w", r.root.path, err))
r.mu.Unlock()
return
}
r.mu.Unlock()
glog.V(0).Infof("%s: follow %s again after: %v", r.seed.ClientName, r.root.path, err)
select {
case <-time.After(time.Duration(failures) * time.Second):
case <-ctx.Done():
return
}
}
}
func (r *seedRun[V]) newDir(parent *seedDir[V], path util.FullPath) *seedDir[V] {
d := &seedDir[V]{path: path, parent: parent, held: 1}
r.dirs[path] = d
if parent != nil {
if parent.children == nil {
parent.children = make(map[string]*seedDir[V])
}
parent.children[path.Name()] = d
parent.held++
}
return d
}
// release drops one hold on d, and forgets d once nothing holds it.
func (r *seedRun[V]) release(d *seedDir[V]) {
for d != nil {
d.held--
if d.held > 0 || d.parent == nil {
return
}
delete(d.parent.children, d.path.Name())
delete(r.dirs, d.path)
d = d.parent
}
}
func (r *seedRun[V]) err() error {
r.mu.Lock()
defer r.mu.Unlock()
return r.failure
}
func (r *seedRun[V]) fail(err error) {
if r.failure == nil {
r.failure = err
r.cancel(err)
}
}
func (r *seedRun[V]) value(entry *filer_pb.Entry) *V {
if entry == nil {
return nil
}
v := r.seed.Value(entry)
return &v
}
func (r *seedRun[V]) Started(dir util.FullPath, depth int) {
r.mu.Lock()
defer r.mu.Unlock()
if r.seed.Started != nil {
r.seed.Started(dir, depth)
}
}
// Listing holds the walk back while the pages keep too many names, and
// records the request, so that no event is applied before the page it may
// show in is known.
func (r *seedRun[V]) Listing(ctx context.Context, dir util.FullPath) error {
stopWaking := context.AfterFunc(ctx, func() {
r.mu.Lock()
defer r.mu.Unlock()
r.cond.Broadcast()
})
defer stopWaking()
r.mu.Lock()
defer r.mu.Unlock()
for r.held >= r.maxHeld && r.failure == nil && ctx.Err() == nil {
r.cond.Wait()
}
if r.failure != nil {
return r.failure
}
if err := ctx.Err(); err != nil {
return err
}
r.inFlight[dir] = time.Now()
return nil
}
func (r *seedRun[V]) Listed(page *Page) []string {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.inFlight, page.Dir)
defer r.cond.Broadcast()
d := r.dirs[page.Dir]
if d == nil || r.failure != nil {
return nil
}
p := &seedPage[V]{
dir: d,
after: page.After,
final: page.Last,
snapshot: page.Snapshot,
endNs: page.End.UnixNano(),
values: make(map[string]*V, len(page.Entries)),
}
r.noteFilerClock(page.Snapshot, page.End)
var subDirs []string
for _, entry := range page.Entries {
p.last = entry.Name
v := r.value(entry)
p.values[entry.Name] = v
r.seed.Change(page.Dir, entry.Name, nil, v)
if entry.IsDirectory {
child := page.Dir.Child(entry.Name)
if r.seed.Skip == nil || !r.seed.Skip(child) {
r.newDir(d, child)
subDirs = append(subDirs, entry.Name)
}
}
}
d.pages = append(d.pages, p)
d.held++
r.held += len(p.values)
r.expiring = append(r.expiring, p)
return subDirs
}
func (r *seedRun[V]) Done(dir util.FullPath, depth int, err error) {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.inFlight, dir)
defer r.cond.Broadcast()
// a directory removed since its parent was listed has nothing to count
if err != nil && (depth == 0 || !errors.Is(err, filer_pb.ErrNotFound)) {
r.fail(fmt.Errorf("list %s: %w", dir, err))
}
if r.failure != nil {
return
}
if r.seed.Done != nil {
r.seed.Done(dir, depth)
}
if d := r.dirs[dir]; d != nil {
r.release(d)
}
}
// receive applies one response of the subscription. An event waits for the
// pages that were being listed when it arrived, since it may show in them.
func (r *seedRun[V]) receive(event *filer_pb.SubscribeMetadataResponse) error {
arrived := time.Now()
r.mu.Lock()
defer r.mu.Unlock()
for r.failure == nil && r.listingSince(arrived) {
r.cond.Wait()
}
if r.failure != nil {
return r.failure
}
r.noteFilerClock(event.TsNs, arrived)
if r.untilNs != 0 && event.TsNs > r.untilNs {
return nil
}
if event.EventNotification == nil {
// a heartbeat: no event older than a margin before it is still coming
if event.TsNs > 0 {
r.advance(event.TsNs - r.margin)
}
return nil
}
if event.TsNs <= r.lastEvent {
return nil
}
r.lastEvent = event.TsNs
r.advance(event.TsNs)
r.apply(event)
return nil
}
func (r *seedRun[V]) listingSince(t time.Time) bool {
for _, sent := range r.inFlight {
if !sent.After(t) {
return true
}
}
return false
}
// noteFilerClock learns from a position the filer had reached by local time
// at how far its clock runs ahead. It stops learning once the seed's end is
// set, so that every page expires by then.
func (r *seedRun[V]) noteFilerClock(tsNs int64, at time.Time) {
if tsNs > 0 && r.untilNs == 0 {
r.ahead = max(r.ahead, tsNs-at.UnixNano())
}
}
// advance expires the pages whose listing ended more than a margin before
// position: the events from there on are after anything the pages show.
func (r *seedRun[V]) advance(position int64) {
if position <= r.position {
return
}
r.position = position
expired := 0
for _, p := range r.expiring {
if p.endNs+r.ahead+r.margin >= position {
break
}
r.held -= len(p.values)
p.values = nil
r.release(p.dir)
expired++
}
if expired > 0 {
r.expiring = r.expiring[expired:]
r.cond.Broadcast()
}
}
func (r *seedRun[V]) apply(event *filer_pb.SubscribeMetadataResponse) {
n := event.EventNotification
oldDir := util.FullPath(event.Directory)
newDir := util.FullPath(filer_pb.MetadataEventTargetDirectory(event))
if n.OldEntry != nil && n.NewEntry != nil && oldDir == newDir && n.OldEntry.Name == n.NewEntry.Name {
r.applySide(oldDir, n.OldEntry.Name, event.TsNs, n.OldEntry, n.NewEntry)
return
}
if n.OldEntry != nil {
r.applySide(oldDir, n.OldEntry.Name, event.TsNs, n.OldEntry, nil)
}
if n.NewEntry != nil {
r.applySide(newDir, n.NewEntry.Name, event.TsNs, nil, n.NewEntry)
}
}
// applySide applies what an event did to one name: from and to are the entry
// before and after, nil where there was none.
func (r *seedRun[V]) applySide(dir util.FullPath, name string, tsNs int64, from, to *filer_pb.Entry) {
if dir != r.root.path && !dir.IsUnder(r.root.path) {
return
}
if r.seed.Skip != nil && r.seed.Skip(dir) {
return
}
d := r.root
for _, part := range relativeParts(r.root.path, dir) {
p := d.pageFor(part)
if p == nil || d.gone[part] {
// not listed yet, so the listing will show it; or below a
// directory that was never counted
return
}
if child := d.children[part]; child != nil {
d = child
continue
}
if _, listed := p.values[part]; p.values == nil || listed {
// the directory was walked and is no longer kept, or was created
// after its page: its entries change by the event
r.seed.Change(dir, name, r.value(from), r.value(to))
return
}
// missing from the walk and not created since: never counted
return
}
p := d.pageFor(name)
if p == nil || tsNs <= p.snapshot {
return
}
toValue := r.value(to)
if p.values == nil {
r.seed.Change(dir, name, r.value(from), toValue)
} else {
counted, listed := p.values[name]
if !listed {
r.held++
}
p.values[name] = toValue
r.seed.Change(dir, name, counted, toValue)
if to == nil && from != nil && from.IsDirectory && counted == nil && d.children[name] == nil {
if d.gone == nil {
d.gone = make(map[string]bool)
}
d.gone[name] = true
}
}
if to != nil && to.IsDirectory {
delete(d.gone, name)
}
}
// relativeParts are the names from root down to dir, which is root or below it.
func relativeParts(root, dir util.FullPath) []string {
if dir == root {
return nil
}
rest := string(dir)
if root != "/" {
rest = rest[len(root):]
}
return util.FullPath(rest).Split()
}