Files
seaweedfs/weed/shell/command_fs_du.go
T
76aa922d06 shell: let fs.du print subdirectory totals and list directories in parallel (#13212)
* shell: let fs.du print subdirectory totals and list directories in parallel

fs.du prints one total and walks the tree one directory at a time. Finding
where the data of a large bucket sits takes one fs.du per directory, each a
full walk, and every listing waits on the filer and its store in turn.

-depth N also prints the total of each directory down to N levels below the
given one, like du -d N. Directories come in du's order: each one after the
directories below it, siblings by name, and the given directory's total
last, as before. One walk now gives the whole breakdown.

-concurrency N lists up to N directories at a time. A subdirectory gets a
goroutine of its own while the limit allows one and is walked in place
otherwise, so memory grows with depth and concurrency, not with the number
of directories. filer_pb.TraverseBfs is not used because it remembers every
directory it visits and queues whole levels: on a tree of 200k directories
it held 49 MB more live heap than this walk at the same speed, and weed
shell often runs in a small container. A directory's listing is complete
before its subdirectories are walked, so no listing stream stays open while
a subtree is walked.

A directory that cannot be listed used to drop out of the totals silently.
It is still left out, but the command now fails at the end with the number
of such directories and the first of them. fs.du took its last argument as
the path, or the current directory when that argument started with a dash,
so "fs.du /dir -depth=1" would have walked the current directory. Flags now
go before the path, and anything else is an error. With a prefix
(fs.du /dir/name_prefix) and no -depth, the directories the prefix matches
are no longer walked, because nothing below them is printed.

The defaults, -depth=0 and -concurrency=1, print what fs.du printed before.

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

* shell: fs.du walks a page of subdirectories before listing the next one

fs.du collected the names of all subdirectories of a directory before it
walked any of them, so a directory with millions of subdirectories held
millions of names. It now lists 1024 entries at a time and walks the
subdirectories of a page before it asks for the next page. A directory
holds at most one page of names, and still no listing stream stays open
while its subdirectories are walked. On one directory with 200k
subdirectories the walk holds 0.5 MB of live heap with -concurrency=1 and
2.5 MB with -concurrency=5.

When a page of a listing fails, the pages before it still count and the
failed page is dropped. The help and the error said that such a directory
was left out of the totals; they now say that the totals are incomplete.
When the given directory itself cannot be listed, fs.du cancels the walks
under way and waits for them before it returns the error.

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

* shell: fs.du tests refuse a listing the way a failing filer store does

An Unavailable without details makes pb close the shared connection, so the
listings running beside the refused one failed with "the client connection
is closing" and the error named another directory (6 of 30 runs with -race).
A store error reaches the client as Unknown and leaves the connection up.

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

* shell: fs.du lists directories in parallel without a -concurrency flag

The walk prints the same totals in the same order at any concurrency, so
there is nothing for a user to choose: list up to DefaultMaxParallelization
directories at a time, like the other shell commands that fan out.

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-01 11:01:37 -08:00

330 lines
9.1 KiB
Go

package shell
import (
"context"
"flag"
"fmt"
"io"
"sort"
"strings"
"sync"
"github.com/seaweedfs/seaweedfs/weed/filer"
"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
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.
`
}
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")
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 commandEnv.isDirectory(path) {
path = path + "/"
}
dir, name := util.FullPath(path).DirAndName()
walker := newDuWalker(commandEnv, *depth, duConcurrency)
total, err := walker.walkTop(context.Background(), util.FullPath(dir), name, writer)
if err != nil {
return err
}
walker.printTotals(writer)
if name == "" {
fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s\n", total.blocks, total.bytes, dir)
}
return walker.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
// duWalker adds up directory trees depth first, listing up to concurrency
// directories at a time. A subdirectory gets a goroutine of its own while the
// concurrency allows one and is walked in place otherwise. Each directory is
// listed a page at a time, and a page's subdirectories are walked before the
// next page is listed, so memory grows with the depth of the tree and the
// concurrency, not with the number or the width of its directories.
type duWalker struct {
filerClient filer_pb.FilerClient
maxDepth int
// one slot per goroutine walking beside the caller's
slots chan struct{}
mu sync.Mutex
// directories 1 to maxDepth levels below the top
totals map[util.FullPath]duUsage
failures int
failure error
}
func newDuWalker(filerClient filer_pb.FilerClient, maxDepth, concurrency int) *duWalker {
return &duWalker{
filerClient: filerClient,
maxDepth: maxDepth,
slots: make(chan struct{}, concurrency-1),
totals: make(map[util.FullPath]duUsage),
}
}
// duChildren adds up the subdirectories of one directory as they finish.
type duChildren struct {
wg sync.WaitGroup
mu sync.Mutex
total duUsage
}
func (c *duChildren) add(usage duUsage) {
c.mu.Lock()
c.total.add(usage)
c.mu.Unlock()
}
// wait returns the sum once the subdirectories walked by goroutines are done.
func (c *duChildren) wait() duUsage {
c.wg.Wait()
c.mu.Lock()
defer c.mu.Unlock()
return c.total
}
// walkTop adds up dir, or with a prefix only the entries of dir whose names
// start with it. Each file a prefix matches is printed on a line of its own.
func (w *duWalker) walkTop(ctx context.Context, dir util.FullPath, prefix string, writer io.Writer) (total duUsage, err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var printFile func(entry *filer_pb.Entry)
if prefix != "" {
printFile = func(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)
}
}
// with a prefix and no depth, nothing below a matched directory is printed
descend := prefix == "" || w.maxDepth > 0
var children duChildren
err = w.list(ctx, dir, prefix, printFile, func(files duUsage, subDirs []string) {
total.add(files)
if descend {
w.walkSubDirs(ctx, &children, dir, subDirs, 1)
}
})
if err != nil {
// nothing is printed after this, so stop the walks under way
cancel()
children.wait()
return total, err
}
total.add(children.wait())
return total, nil
}
// walk adds up everything below dir, which is depth levels below the top. If
// a page of its listing fails, the pages before it still count and the
// failure is recorded.
func (w *duWalker) walk(ctx context.Context, dir util.FullPath, depth int) (total duUsage) {
var children duChildren
err := w.list(ctx, dir, "", nil, func(files duUsage, subDirs []string) {
total.add(files)
w.walkSubDirs(ctx, &children, dir, subDirs, depth+1)
})
if err != nil {
w.fail(fmt.Errorf("%s: %w", dir, err))
}
total.add(children.wait())
if depth <= w.maxDepth {
w.mu.Lock()
w.totals[dir] = total
w.mu.Unlock()
}
return total
}
// list lists dir, or with a prefix only the entries starting with it, a page
// at a time. Once a page's stream is done, eachPage gets the page's file usage
// and subdirectory names, so no listing stays open while subdirectories are
// walked. A page that fails is dropped and its error returned.
func (w *duWalker) list(ctx context.Context, dir util.FullPath, prefix string, eachFile func(entry *filer_pb.Entry), eachPage func(files duUsage, subDirs []string)) error {
startFrom := ""
for {
var files duUsage
var subDirs []string
var count uint32
lastName := startFrom
err := filer_pb.List(ctx, w.filerClient, string(dir), prefix, func(entry *filer_pb.Entry, isLast bool) error {
count++
lastName = entry.Name
if entry.IsDirectory {
subDirs = append(subDirs, entry.Name)
return nil
}
files.add(fileDuUsage(entry))
if eachFile != nil {
eachFile(entry)
}
return nil
}, startFrom, false, duPageSize)
if err != nil {
return err
}
eachPage(files, subDirs)
if count < duPageSize {
return nil
}
// a store that does not move past the cursor would page forever
if lastName == startFrom {
return fmt.Errorf("list %s: pagination stuck at %q", dir, startFrom)
}
startFrom = lastName
}
}
// walkSubDirs walks the named subdirectories of parent, which are depth levels
// below the top, each in a goroutine of its own while a slot is free and in
// place otherwise, and adds their totals to children.
func (w *duWalker) walkSubDirs(ctx context.Context, children *duChildren, parent util.FullPath, names []string, depth int) {
for _, name := range names {
if ctx.Err() != nil {
return
}
child := parent.Child(name)
select {
case w.slots <- struct{}{}:
children.wg.Add(1)
go func() {
defer children.wg.Done()
usage := w.walk(ctx, child, depth)
<-w.slots
children.add(usage)
}()
default:
children.add(w.walk(ctx, child, depth))
}
}
}
func (w *duWalker) fail(err error) {
w.mu.Lock()
defer w.mu.Unlock()
w.failures++
if w.failure == nil {
w.failure = err
}
}
func (w *duWalker) err() error {
w.mu.Lock()
defer w.mu.Unlock()
switch w.failures {
case 0:
return nil
case 1:
return fmt.Errorf("the totals are incomplete: %w", w.failure)
}
return fmt.Errorf("the totals are incomplete, %d directories could not be listed in full, the first: %w", w.failures, w.failure)
}
// printTotals prints the directory totals the way du does: each directory
// after the directories below it, and siblings in name order.
func (w *duWalker) printTotals(writer io.Writer) {
type dirTotal struct {
path util.FullPath
parts []string
usage duUsage
}
w.mu.Lock()
dirs := make([]dirTotal, 0, len(w.totals))
for path, usage := range w.totals {
dirs = append(dirs, dirTotal{path: path, parts: strings.Split(string(path), "/"), usage: usage})
}
w.mu.Unlock()
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 _, d := range dirs {
fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s\n", d.usage.blocks, d.usage.bytes, d.path)
}
}