command_fs_du.go 1.9 KB

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