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) } }