command_fs_du.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package shell
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "github.com/seaweedfs/seaweedfs/weed/filer"
  7. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  8. "github.com/seaweedfs/seaweedfs/weed/util"
  9. )
  10. func init() {
  11. Commands = append(Commands, &commandFsDu{})
  12. }
  13. type commandFsDu struct {
  14. }
  15. func (c *commandFsDu) Name() string {
  16. return "fs.du"
  17. }
  18. func (c *commandFsDu) Help() string {
  19. return `show disk usage
  20. fs.du /dir
  21. fs.du /dir/file_name
  22. fs.du /dir/file_prefix
  23. `
  24. }
  25. func (c *commandFsDu) HasTag(CommandTag) bool {
  26. return false
  27. }
  28. func (c *commandFsDu) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  29. path, err := commandEnv.parseUrl(findInputDirectory(args))
  30. if err != nil {
  31. return err
  32. }
  33. if commandEnv.isDirectory(path) {
  34. path = path + "/"
  35. }
  36. var blockCount, byteCount uint64
  37. dir, name := util.FullPath(path).DirAndName()
  38. blockCount, byteCount, err = duTraverseDirectory(writer, commandEnv, dir, name)
  39. if name == "" && err == nil {
  40. fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s\n", blockCount, byteCount, dir)
  41. }
  42. return
  43. }
  44. func duTraverseDirectory(writer io.Writer, filerClient filer_pb.FilerClient, dir, name string) (blockCount, byteCount uint64, err error) {
  45. err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(dir), name, func(entry *filer_pb.Entry, isLast bool) error {
  46. var fileBlockCount, fileByteCount uint64
  47. if entry.IsDirectory {
  48. subDir := fmt.Sprintf("%s/%s", dir, entry.Name)
  49. if dir == "/" {
  50. subDir = "/" + entry.Name
  51. }
  52. numBlock, numByte, err := duTraverseDirectory(writer, filerClient, subDir, "")
  53. if err == nil {
  54. blockCount += numBlock
  55. byteCount += numByte
  56. }
  57. } else {
  58. fileBlockCount = uint64(len(entry.GetChunks()))
  59. fileByteCount = filer.FileSize(entry)
  60. blockCount += fileBlockCount
  61. byteCount += fileByteCount
  62. }
  63. if name != "" && !entry.IsDirectory {
  64. fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s/%s\n", fileBlockCount, fileByteCount, dir, entry.Name)
  65. }
  66. return nil
  67. })
  68. return
  69. }