You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

185 lines
4.6 KiB

5 years ago
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "os"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/golang/protobuf/proto"
  12. "github.com/chrislusf/seaweedfs/weed/filer2"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "github.com/chrislusf/seaweedfs/weed/util"
  15. )
  16. func init() {
  17. Commands = append(Commands, &commandFsMetaSave{})
  18. }
  19. type commandFsMetaSave struct {
  20. }
  21. func (c *commandFsMetaSave) Name() string {
  22. return "fs.meta.save"
  23. }
  24. func (c *commandFsMetaSave) Help() string {
  25. return `save all directory and file meta data to a local file for metadata backup.
  26. fs.meta.save / # save from the root
  27. fs.meta.save -v -o t.meta / # save from the root, output to t.meta file.
  28. fs.meta.save /path/to/save # save from the directory /path/to/save
  29. fs.meta.save . # save from current directory
  30. fs.meta.save # save from current directory
  31. The meta data will be saved into a local <filer_host>-<port>-<time>.meta file.
  32. These meta data can be later loaded by fs.meta.load command,
  33. This assumes there are no deletions, so this is different from taking a snapshot.
  34. `
  35. }
  36. func (c *commandFsMetaSave) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  37. fsMetaSaveCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  38. verbose := fsMetaSaveCommand.Bool("v", false, "print out each processed files")
  39. outputFileName := fsMetaSaveCommand.String("o", "", "output the meta data to this file")
  40. if err = fsMetaSaveCommand.Parse(args); err != nil {
  41. return nil
  42. }
  43. filerServer, filerPort, path, parseErr := commandEnv.parseUrl(findInputDirectory(fsMetaSaveCommand.Args()))
  44. if parseErr != nil {
  45. return parseErr
  46. }
  47. ctx := context.Background()
  48. t := time.Now()
  49. fileName := *outputFileName
  50. if fileName == "" {
  51. fileName = fmt.Sprintf("%s-%d-%4d%02d%02d-%02d%02d%02d.meta",
  52. filerServer, filerPort, t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
  53. }
  54. dst, openErr := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  55. if openErr != nil {
  56. return fmt.Errorf("failed to create file %s: %v", fileName, openErr)
  57. }
  58. defer dst.Close()
  59. var wg sync.WaitGroup
  60. wg.Add(1)
  61. outputChan := make(chan []byte, 1024)
  62. go func() {
  63. sizeBuf := make([]byte, 4)
  64. for b := range outputChan {
  65. util.Uint32toBytes(sizeBuf, uint32(len(b)))
  66. dst.Write(sizeBuf)
  67. dst.Write(b)
  68. }
  69. wg.Done()
  70. }()
  71. var dirCount, fileCount uint64
  72. err = doTraverseBFS(ctx, writer, commandEnv.getFilerClient(filerServer, filerPort), filer2.FullPath(path), func(parentPath filer2.FullPath, entry *filer_pb.Entry) {
  73. protoMessage := &filer_pb.FullEntry{
  74. Dir: string(parentPath),
  75. Entry: entry,
  76. }
  77. bytes, err := proto.Marshal(protoMessage)
  78. if err != nil {
  79. fmt.Fprintf(writer, "marshall error: %v\n", err)
  80. return
  81. }
  82. outputChan <- bytes
  83. if entry.IsDirectory {
  84. atomic.AddUint64(&dirCount, 1)
  85. } else {
  86. atomic.AddUint64(&fileCount, 1)
  87. }
  88. if *verbose {
  89. println(parentPath.Child(entry.Name))
  90. }
  91. })
  92. close(outputChan)
  93. wg.Wait()
  94. if err == nil {
  95. fmt.Fprintf(writer, "total %d directories, %d files\n", dirCount, fileCount)
  96. fmt.Fprintf(writer, "meta data for http://%s:%d%s is saved to %s\n", filerServer, filerPort, path, fileName)
  97. }
  98. return err
  99. }
  100. func doTraverseBFS(ctx context.Context, writer io.Writer, filerClient filer2.FilerClient,
  101. parentPath filer2.FullPath, fn func(parentPath filer2.FullPath, entry *filer_pb.Entry)) (err error) {
  102. K := 5
  103. var jobQueueWg sync.WaitGroup
  104. queue := util.NewQueue()
  105. jobQueueWg.Add(1)
  106. queue.Enqueue(parentPath)
  107. var isTerminating bool
  108. for i := 0; i < K; i++ {
  109. go func() {
  110. for {
  111. if isTerminating {
  112. break
  113. }
  114. t := queue.Dequeue()
  115. if t == nil {
  116. time.Sleep(329 * time.Millisecond)
  117. continue
  118. }
  119. dir := t.(filer2.FullPath)
  120. processErr := processOneDirectory(ctx, writer, filerClient, dir, queue, &jobQueueWg, fn)
  121. if processErr != nil {
  122. err = processErr
  123. }
  124. jobQueueWg.Done()
  125. }
  126. }()
  127. }
  128. jobQueueWg.Wait()
  129. isTerminating = true
  130. return
  131. }
  132. func processOneDirectory(ctx context.Context, writer io.Writer, filerClient filer2.FilerClient,
  133. parentPath filer2.FullPath, queue *util.Queue, jobQueueWg *sync.WaitGroup,
  134. fn func(parentPath filer2.FullPath, entry *filer_pb.Entry)) (err error) {
  135. return filer2.ReadDirAllEntries(ctx, filerClient, parentPath, "", func(entry *filer_pb.Entry, isLast bool) {
  136. fn(parentPath, entry)
  137. if entry.IsDirectory {
  138. subDir := fmt.Sprintf("%s/%s", parentPath, entry.Name)
  139. if parentPath == "/" {
  140. subDir = "/" + entry.Name
  141. }
  142. jobQueueWg.Add(1)
  143. queue.Enqueue(filer2.FullPath(subDir))
  144. }
  145. })
  146. }