Files
seaweedfs/weed/shell/command_fs_du.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

275 lines
7.5 KiB
Go

package shell
import (
"context"
"flag"
"fmt"
"io"
"sort"
"strings"
"sync"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/filer/treewalk"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func init() {
Commands = append(Commands, &commandFsDu{})
}
type commandFsDu struct {
}
func (c *commandFsDu) Name() string {
return "fs.du"
}
func (c *commandFsDu) Help() string {
return `show disk usage
fs.du /dir
fs.du /dir/file_name
fs.du /dir/file_prefix
# also print the total of every directory down to 2 levels below /dir, like du -d 2
fs.du -depth=2 /dir
# print what the dir_usage worker job keeps instead of walking
fs.du -report -depth=2 /buckets/b
Flags go before the path. A directory is printed after the directories
below it, and the total of /dir comes last. If listing a directory fails,
what was listed of it before the failure still counts, and the command
then fails, saying that the totals are incomplete.
With -report nothing is walked. The dir_usage worker job keeps the totals
of each bucket, and of the directories holding at least 1% of it, and
fs.du prints those and how old they are. A smaller directory counts
toward the directory above it.
`
}
func (c *commandFsDu) HasTag(CommandTag) bool {
return false
}
func (c *commandFsDu) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
if handleHelpRequest(c, args, writer) {
return nil
}
duCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
depth := duCommand.Int("depth", 0, "also print the total of each directory down to this many levels below the given one")
report := duCommand.Bool("report", false, "print the totals the dir_usage worker job keeps instead of walking")
if err = duCommand.Parse(args); err != nil {
return err
}
if *depth < 0 {
return fmt.Errorf("-depth %d: must not be negative", *depth)
}
// flag parsing stops at the path, so a flag after it would be taken as a
// second path and the walk would silently start at the current directory
if duCommand.NArg() > 1 {
return fmt.Errorf("fs.du takes one path, with the flags before it: %s", strings.Join(duCommand.Args(), " "))
}
path, err := commandEnv.parseUrl(findInputDirectory(duCommand.Args()))
if err != nil {
return err
}
if *report {
return duReport(commandEnv, util.FullPath(path), *depth, writer)
}
if commandEnv.isDirectory(path) {
path = path + "/"
}
dir, name := util.FullPath(path).DirAndName()
totals := newDuTotals(*depth, name, writer)
walker := &treewalk.Walker{Client: commandEnv, Concurrency: duConcurrency, PageSize: duPageSize}
if err := walker.Walk(context.Background(), util.FullPath(dir), name, totals); err != nil {
return err
}
totals.printTotals(writer)
if name == "" {
fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s\n", totals.top.blocks, totals.top.bytes, dir)
}
return totals.err()
}
// duUsage is what fs.du adds up: the number of chunks and the logical size.
type duUsage struct {
blocks, bytes uint64
}
func (u *duUsage) add(other duUsage) {
u.blocks += other.blocks
u.bytes += other.bytes
}
func fileDuUsage(entry *filer_pb.Entry) duUsage {
return duUsage{blocks: uint64(len(entry.GetChunks())), bytes: filer.FileSize(entry)}
}
// duPageSize is how many entries fs.du takes from a listing before it walks
// the subdirectories among them.
var duPageSize uint32 = 1024
// duConcurrency is how many directories fs.du lists at the same time.
var duConcurrency = DefaultMaxParallelization
// duTotals adds up a walk. A directory's total is what its pages list plus
// the totals of its subdirectories, which are done before it is.
type duTotals struct {
maxDepth int
// with a prefix, each file it matches is printed
printFile func(dir util.FullPath, entry *filer_pb.Entry)
// with a prefix and no depth, nothing below a matched directory is walked
descend bool
mu sync.Mutex
// directories being walked: the files listed so far and the totals of the
// subdirectories that are done
running map[util.FullPath]duUsage
// directories 1 to maxDepth levels below the top
totals map[util.FullPath]duUsage
top duUsage
failures int
failure error
}
func newDuTotals(maxDepth int, prefix string, writer io.Writer) *duTotals {
d := &duTotals{
maxDepth: maxDepth,
descend: prefix == "" || maxDepth > 0,
running: make(map[util.FullPath]duUsage),
totals: make(map[util.FullPath]duUsage),
}
if prefix != "" {
d.printFile = func(dir util.FullPath, entry *filer_pb.Entry) {
usage := fileDuUsage(entry)
fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s/%s\n", usage.blocks, usage.bytes, dir, entry.Name)
}
}
return d
}
func (d *duTotals) Started(dir util.FullPath, depth int) {
d.mu.Lock()
defer d.mu.Unlock()
d.running[dir] = duUsage{}
}
func (d *duTotals) Listing(context.Context, util.FullPath) error { return nil }
func (d *duTotals) Listed(page *treewalk.Page) []string {
var files duUsage
var subDirs []string
for _, entry := range page.Entries {
if entry.IsDirectory {
subDirs = append(subDirs, entry.Name)
continue
}
files.add(fileDuUsage(entry))
// only the top directory is listed with the prefix
if page.Depth == 0 && d.printFile != nil {
d.printFile(page.Dir, entry)
}
}
d.mu.Lock()
usage := d.running[page.Dir]
usage.add(files)
d.running[page.Dir] = usage
d.mu.Unlock()
if page.Depth == 0 && !d.descend {
return nil
}
return subDirs
}
// Done adds a finished directory to its parent. If its listing failed, the
// pages before the failure still count and the failure is recorded; the top
// directory's failure is returned by the walk itself.
func (d *duTotals) Done(dir util.FullPath, depth int, err error) {
d.mu.Lock()
defer d.mu.Unlock()
total := d.running[dir]
delete(d.running, dir)
if depth == 0 {
d.top = total
return
}
if err != nil {
d.failures++
if d.failure == nil {
d.failure = fmt.Errorf("%s: %w", dir, err)
}
}
parentDir, _ := dir.DirAndName()
parent := util.FullPath(parentDir)
usage := d.running[parent]
usage.add(total)
d.running[parent] = usage
if depth <= d.maxDepth {
d.totals[dir] = total
}
}
func (d *duTotals) err() error {
d.mu.Lock()
defer d.mu.Unlock()
switch d.failures {
case 0:
return nil
case 1:
return fmt.Errorf("the totals are incomplete: %w", d.failure)
}
return fmt.Errorf("the totals are incomplete, %d directories could not be listed in full, the first: %w", d.failures, d.failure)
}
// printTotals prints the directory totals the way du does.
func (d *duTotals) printTotals(writer io.Writer) {
d.mu.Lock()
totals := make(map[util.FullPath]duUsage, len(d.totals))
for path, usage := range d.totals {
totals[path] = usage
}
d.mu.Unlock()
printDuOrder(writer, totals)
}
// printDuOrder prints totals the way du does: each directory after the
// directories below it, and siblings in name order.
func printDuOrder(writer io.Writer, totals map[util.FullPath]duUsage) {
type dirTotal struct {
path util.FullPath
parts []string
usage duUsage
}
dirs := make([]dirTotal, 0, len(totals))
for path, usage := range totals {
dirs = append(dirs, dirTotal{path: path, parts: strings.Split(string(path), "/"), usage: usage})
}
sort.Slice(dirs, func(i, j int) bool {
a, b := dirs[i].parts, dirs[j].parts
for k := 0; k < len(a) && k < len(b); k++ {
if a[k] != b[k] {
return a[k] < b[k]
}
}
// one holds the other: the one further down comes first
return len(a) > len(b)
})
for _, dir := range dirs {
fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s\n", dir.usage.blocks, dir.usage.bytes, dir.path)
}
}