Files
seaweedfs/weed/worker/tasks/dir_usage/run.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

511 lines
15 KiB
Go

package dir_usage
import (
"context"
"fmt"
"math"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer/dirusage"
"github.com/seaweedfs/seaweedfs/weed/filer/treewalk"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/meta_log_purge"
)
const (
clientName = "dir_usage"
// seedConcurrency and seedPageSize are fs.du's
seedConcurrency = 10
seedPageSize = 1024
)
// logMargin is the seeds' Margin, how long after a change its event is
// logged at most. Tests shorten it.
var logMargin = time.Minute
type runStats struct {
events int64
written int64
removed int64
seeded int64
failed []string
}
// run brings the records of the store behind client up to a margin before
// now: it replays the events since the records' positions, and seeds the
// buckets and top-level directories without a record from a walk.
func run(ctx context.Context, client filer_pb.FilerClient, now time.Time, stats *runStats, progress func(string)) error {
var roots dirusage.Roots
var signature int32
var logStart int64
err := client.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
var err error
if roots, signature, err = dirusage.RootsOf(ctx, c); err != nil {
return err
}
logStart, err = treewalk.LogStartTsNs(ctx, c)
return err
})
if err != nil {
return err
}
store := &dirusage.Store{Client: client, Signature: signature, Roots: roots}
records, cursorTsNs, err := store.LoadAll(ctx)
if err != nil {
return err
}
if logStart == 0 && now.Sub(time.Unix(0, cursorTsNs)) > meta_log_purge.CursorStaleAfter {
// No log is kept. The purge keeps the log from a cursor saved since,
// so no event was logged after it; from a stale one, some may be gone.
logStart = now.UnixNano()
}
for root, record := range records {
// the replay that saved the cursor took this record to it
record.TsNs = max(record.TsNs, cursorTsNs)
// the events it needs are gone: seed it again
if record.TsNs < logStart {
if err := store.Delete(ctx, root); err != nil {
return err
}
delete(records, root)
stats.removed++
}
}
// The replay ends where the filer says it has logged every event, on its
// own clock: a subscription with an end stops once it read all the filer
// logged. The cursor never goes back.
untilNs, err := treewalk.SnapshotTsNs(ctx, client, "/")
if err != nil {
return err
}
if untilNs == 0 {
untilNs = now.Add(-logMargin).UnixNano()
}
untilNs = max(untilNs, cursorTsNs)
if len(records) > 0 {
progress(fmt.Sprintf("replaying the events of %d records", len(records)))
t := newTracker(roots, records)
sinceNs := int64(math.MaxInt64)
for _, record := range records {
sinceNs = min(sinceNs, record.TsNs)
}
_, err := treewalk.Follow(ctx, client, clientName, "/", sinceNs, untilNs, t.apply)
stats.events += t.events
if err != nil {
return fmt.Errorf("replay: %w", err)
}
for root := range t.removed {
if err := store.Delete(ctx, root); err != nil {
return err
}
stats.removed++
}
for root := range t.changed {
record := t.records[root]
record.TsNs = untilNs
if err := store.Save(ctx, record); err != nil {
return err
}
stats.written++
}
records = t.records
}
// Every record is at untilNs now. Saved after the records, so a run
// that stops in between replays again what it did not save.
if err := store.SaveCursor(ctx, untilNs); err != nil {
return err
}
current, err := roots.List(ctx, client)
if err != nil {
return err
}
for root := range records {
if !current[root] {
// gone without an event the replay saw
if err := store.Delete(ctx, root); err != nil {
return err
}
stats.removed++
}
}
// The buckets without a record are seeded in one walk of the buckets
// folder, and the top-level directories in one of /, so that a run waits
// the margin at the end of a walk at most twice.
buckets, tops := make(map[util.FullPath]bool), make(map[util.FullPath]bool)
for root := range current {
switch {
case records[root] != nil:
case root.IsUnder(roots.Buckets):
buckets[root] = true
default:
tops[root] = true
}
}
for _, batch := range []struct {
container util.FullPath
roots map[util.FullPath]bool
}{{roots.Buckets, buckets}, {"/", tops}} {
if len(batch.roots) == 0 {
continue
}
progress(fmt.Sprintf("seeding %d directories in %s", len(batch.roots), batch.container))
seeded, err := seedRoots(ctx, client, roots, batch.container, batch.roots)
if err != nil {
if ctx.Err() != nil {
return err
}
// the next run tries again
stats.failed = append(stats.failed, fmt.Sprintf("seed %s: %v", batch.container, err))
continue
}
for _, record := range seeded {
if err := store.Save(ctx, record); err != nil {
if ctx.Err() != nil {
return err
}
// the next run seeds this one again, not the whole batch
stats.failed = append(stats.failed, err.Error())
continue
}
stats.seeded++
}
}
if len(stats.failed) > 0 {
return fmt.Errorf("%s", strings.Join(stats.failed, "; "))
}
return nil
}
// tracker applies metadata events to the records.
type tracker struct {
roots dirusage.Roots
records map[util.FullPath]*dirusage.Record
changed map[util.FullPath]bool
removed map[util.FullPath]bool
events int64
}
func newTracker(roots dirusage.Roots, records map[util.FullPath]*dirusage.Record) *tracker {
return &tracker{
roots: roots,
records: records,
changed: make(map[util.FullPath]bool),
removed: make(map[util.FullPath]bool),
}
}
func (t *tracker) apply(event *filer_pb.SubscribeMetadataResponse) error {
t.events++
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 {
t.side(oldDir.Child(n.OldEntry.Name), event.TsNs, n.OldEntry, n.NewEntry, false)
return nil
}
// a moved directory keeps its record, and so do the ones below it
var carried []string
if n.OldEntry != nil && n.NewEntry != nil && n.OldEntry.IsDirectory && n.NewEntry.IsDirectory {
carried = t.trackedBelow(oldDir.Child(n.OldEntry.Name), event.TsNs)
}
if n.OldEntry != nil {
t.side(oldDir.Child(n.OldEntry.Name), event.TsNs, n.OldEntry, nil, n.NewEntry != nil)
}
if n.NewEntry != nil {
t.side(newDir.Child(n.NewEntry.Name), event.TsNs, nil, n.NewEntry, false)
}
if len(carried) > 0 {
t.track(newDir.Child(n.NewEntry.Name), event.TsNs, carried)
}
return nil
}
// recordOf is the record that counts an entry at path, and the path of the
// entry's directory relative to the record's root; nil for an entry inside a
// part of the tree left out, or outside every bucket and top-level directory,
// and for an event the record already counted.
func (t *tracker) recordOf(path util.FullPath, tsNs int64) (*dirusage.Record, string) {
dir, _ := path.DirAndName()
parent := util.FullPath(dir)
if dirusage.Skipped(parent) {
return nil, ""
}
root, ok := t.roots.RootOf(parent)
if !ok {
return nil, ""
}
record := t.records[root]
if record == nil || tsNs <= record.TsNs {
return nil, ""
}
return record, dirusage.Relative(root, parent)
}
// side applies what an event did at path: from and to are the entry before
// and after, nil where there was none. moved is set when from went elsewhere.
func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry, moved bool) {
if t.roots.IsRoot(path) {
t.rootChanged(path, tsNs, to)
return
}
record, rel := t.recordOf(path, tsNs)
if record == nil {
return
}
delta := dirusage.EntryUsage(to)
delta.Sub(dirusage.EntryUsage(from))
addUp(record, rel, delta)
if from != nil && from.IsDirectory && (to == nil || !to.IsDirectory) {
dropTracked(record, joinRelative(rel, path.Name()), rel, moved && to == nil)
}
t.changed[util.FullPath(record.Root)] = true
}
// trackedBelow are the directories at or below path with a record, relative
// to path.
func (t *tracker) trackedBelow(path util.FullPath, tsNs int64) []string {
if t.roots.IsRoot(path) {
return nil
}
record, parentRel := t.recordOf(path, tsNs)
if record == nil {
return nil
}
rel := joinRelative(parentRel, path.Name())
var below []string
for tracked := range record.Dirs {
if tracked == rel {
below = append(below, "")
} else if strings.HasPrefix(tracked, rel+"/") {
below = append(below, tracked[len(rel)+1:])
}
}
return below
}
// track gives the directories a move carried to path an empty record each,
// as deep as records go; the events of the entries the move took along fill
// them.
func (t *tracker) track(path util.FullPath, tsNs int64, carried []string) {
if t.roots.IsRoot(path) {
return
}
record, parentRel := t.recordOf(path, tsNs)
if record == nil {
return
}
rel := joinRelative(parentRel, path.Name())
for _, below := range carried {
tracked := joinRelative(rel, below)
if _, found := record.Dirs[tracked]; !found && depthOf(tracked) <= dirusage.MaxDepth {
record.Dirs[tracked] = dirusage.Usage{}
}
}
t.changed[util.FullPath(record.Root)] = true
}
// rootChanged drops the record of a bucket or top-level directory that went
// away or moved. One created or moved in is seeded by the run.
func (t *tracker) rootChanged(root util.FullPath, tsNs int64, to *filer_pb.Entry) {
record := t.records[root]
if record == nil || tsNs <= record.TsNs || to != nil {
return
}
delete(t.records, root)
delete(t.changed, root)
t.removed[root] = true
}
// addUp adds delta to the directory at rel and to each directory above it
// that has a record of its own.
func addUp(record *dirusage.Record, rel string, delta dirusage.Usage) {
for {
if usage, tracked := record.Dirs[rel]; tracked {
usage.Add(delta)
record.Dirs[rel] = usage
}
if rel == "" {
return
}
rel = parentRelative(rel)
}
}
// dropTracked drops the record of a removed directory and of what was below
// it. A directory deleted with totals left had entries that went without
// events, as when a store drops a whole bucket: the rest comes off the
// directories above it. A moved directory's entries each log their own move.
func dropTracked(record *dirusage.Record, rel, parentRel string, moved bool) {
usage, tracked := record.Dirs[rel]
if !tracked {
return
}
if !moved && !usage.IsZero() {
var rest dirusage.Usage
rest.Sub(usage)
addUp(record, parentRel, rest)
}
delete(record.Dirs, rel)
for below := range record.Dirs {
if strings.HasPrefix(below, rel+"/") {
delete(record.Dirs, below)
}
}
}
func parentRelative(rel string) string {
if i := strings.LastIndex(rel, "/"); i >= 0 {
return rel[:i]
}
return ""
}
func joinRelative(rel, name string) string {
switch {
case rel == "":
return name
case name == "":
return rel
}
return rel + "/" + name
}
// depthOf is how many levels below its root the directory at rel is.
func depthOf(rel string) int {
if rel == "" {
return 0
}
return strings.Count(rel, "/") + 1
}
// seeding adds up a walk of the buckets folder or of / into the totals of
// the roots in it: of each directory being walked, kept once it is done while
// it holds its share of what the walk counted of its root so far. A directory
// holding its share of the whole root holds it of any part.
type seeding struct {
roots dirusage.Roots
totals map[util.FullPath]map[string]*dirusage.Usage // by root, then by path relative to it
}
// seedRoots walks container, the buckets folder or /, into the roots in it
// that toSeed holds, and returns their records.
func seedRoots(ctx context.Context, client filer_pb.FilerClient, roots dirusage.Roots, container util.FullPath, toSeed map[util.FullPath]bool) (map[util.FullPath]*dirusage.Record, error) {
s := &seeding{roots: roots, totals: make(map[util.FullPath]map[string]*dirusage.Usage)}
seed := &treewalk.Seed[dirusage.Usage]{
Client: client,
ClientName: clientName,
Concurrency: seedConcurrency,
PageSize: seedPageSize,
Value: dirusage.EntryUsage,
Change: s.change,
Started: s.started,
Done: s.done,
Skip: func(dir util.FullPath) bool {
if dirusage.Skipped(dir) {
return true
}
root, ok := roots.RootOf(dir)
if !ok {
// the buckets folder, when walking /
return dir != container
}
return !toSeed[root]
},
Margin: logMargin,
}
atNs, err := seed.Run(ctx, container)
if err != nil {
return nil, err
}
return s.records(atNs), nil
}
// of is the totals of the root dir is in, and dir relative to it; nil for
// the container.
func (s *seeding) of(dir util.FullPath) (root util.FullPath, totals map[string]*dirusage.Usage, rel string) {
root, ok := s.roots.RootOf(dir)
if !ok {
return "", nil, ""
}
return root, s.totals[root], dirusage.Relative(root, dir)
}
func (s *seeding) started(dir util.FullPath, depth int) {
root, totals, rel := s.of(dir)
switch {
case root == "":
case rel == "":
s.totals[root] = map[string]*dirusage.Usage{"": {}}
case totals != nil && depthOf(rel) <= dirusage.MaxDepth:
totals[rel] = &dirusage.Usage{}
}
}
// change adds what changed in dir to each directory being walked or kept
// above it. An entry of the container is a root: one that goes away during
// the walk gets no record, since a store that drops a whole bucket logs no
// event for what was in it; the next run seeds it if it comes back.
func (s *seeding) change(dir util.FullPath, name string, from, to *dirusage.Usage) {
if path := dir.Child(name); s.roots.IsRoot(path) {
if to == nil {
delete(s.totals, path)
}
return
}
_, totals, rel := s.of(dir)
if totals == nil {
return
}
var delta dirusage.Usage
if to != nil {
delta.Add(*to)
}
if from != nil {
delta.Sub(*from)
}
for {
if usage := totals[rel]; usage != nil {
usage.Add(delta)
}
if rel == "" {
return
}
rel = parentRelative(rel)
}
}
func (s *seeding) done(dir util.FullPath, depth int) {
_, totals, rel := s.of(dir)
if totals == nil || rel == "" {
return
}
if usage := totals[rel]; usage != nil && !holdsShare(*usage, *totals[""]) {
delete(totals, rel)
}
}
func (s *seeding) records(atNs int64) map[util.FullPath]*dirusage.Record {
records := make(map[util.FullPath]*dirusage.Record, len(s.totals))
for root, totals := range s.totals {
rootUsage := *totals[""]
dirs := map[string]dirusage.Usage{"": rootUsage}
for rel, usage := range totals {
if rel != "" && holdsShare(*usage, rootUsage) {
dirs[rel] = *usage
}
}
records[root] = &dirusage.Record{Version: dirusage.Version, Root: string(root), TsNs: atNs, SeededNs: atNs, Dirs: dirs}
}
return records
}
// holdsShare reports whether a directory with usage holds its share of a
// bucket with total.
func holdsShare(usage, total dirusage.Usage) bool {
return usage.Bytes > 0 && usage.Bytes >= (total.Bytes*dirusage.MinSharePercent+99)/100
}