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