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.

181 lines
5.2 KiB

2 years ago
2 years ago
  1. package command
  2. import (
  3. "fmt"
  4. "io/fs"
  5. "os"
  6. "path"
  7. "strconv"
  8. "strings"
  9. "github.com/seaweedfs/seaweedfs/weed/glog"
  10. "github.com/seaweedfs/seaweedfs/weed/storage"
  11. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  12. "github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
  13. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  14. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  15. "github.com/seaweedfs/seaweedfs/weed/util"
  16. )
  17. func init() {
  18. cmdFix.Run = runFix // break init cycle
  19. }
  20. var cmdFix = &Command{
  21. UsageLine: "fix [-volumeId=234] [-collection=bigData] /tmp",
  22. Short: "run weed tool fix on files or whole folders to recreate index file(s) if corrupted",
  23. Long: `Fix runs the SeaweedFS fix command on dat files or whole folders to re-create the index .idx file.
  24. You Need to stop the volume server when running this command.
  25. `,
  26. }
  27. var (
  28. fixVolumeCollection = cmdFix.Flag.String("collection", "", "an optional volume collection name, if specified only it will be processed")
  29. fixVolumeId = cmdFix.Flag.Int64("volumeId", 0, "an optional volume id, if not 0 (default) only it will be processed")
  30. fixIncludeDeleted = cmdFix.Flag.Bool("includeDeleted", true, "include deleted entries in the index file")
  31. fixIgnoreError = cmdFix.Flag.Bool("ignoreError", false, "an optional, if true will be processed despite errors")
  32. )
  33. type VolumeFileScanner4Fix struct {
  34. version needle.Version
  35. nm *needle_map.MemDb
  36. nmDeleted *needle_map.MemDb
  37. includeDeleted bool
  38. }
  39. func (scanner *VolumeFileScanner4Fix) VisitSuperBlock(superBlock super_block.SuperBlock) error {
  40. scanner.version = superBlock.Version
  41. return nil
  42. }
  43. func (scanner *VolumeFileScanner4Fix) ReadNeedleBody() bool {
  44. return false
  45. }
  46. func (scanner *VolumeFileScanner4Fix) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
  47. glog.V(2).Infof("key %v offset %d size %d disk_size %d compressed %v", n.Id, offset, n.Size, n.DiskSize(scanner.version), n.IsCompressed())
  48. if n.Size.IsValid() {
  49. if pe := scanner.nm.Set(n.Id, types.ToOffset(offset), n.Size); pe != nil {
  50. return fmt.Errorf("saved %d with error %v", n.Size, pe)
  51. }
  52. } else {
  53. if scanner.includeDeleted {
  54. if pe := scanner.nmDeleted.Set(n.Id, types.ToOffset(offset), types.TombstoneFileSize); pe != nil {
  55. return fmt.Errorf("saved deleted %d with error %v", n.Size, pe)
  56. }
  57. } else {
  58. glog.V(2).Infof("skipping deleted file ...")
  59. return scanner.nm.Delete(n.Id)
  60. }
  61. }
  62. return nil
  63. }
  64. func runFix(cmd *Command, args []string) bool {
  65. for _, arg := range args {
  66. basePath, f := path.Split(util.ResolvePath(arg))
  67. if util.FolderExists(arg) {
  68. basePath = arg
  69. f = ""
  70. }
  71. files := []fs.DirEntry{}
  72. if f == "" {
  73. fileInfo, err := os.ReadDir(basePath)
  74. if err != nil {
  75. fmt.Println(err)
  76. return false
  77. }
  78. files = fileInfo
  79. } else {
  80. fileInfo, err := os.Stat(arg)
  81. if err != nil {
  82. fmt.Println(err)
  83. return false
  84. }
  85. files = []fs.DirEntry{fs.FileInfoToDirEntry(fileInfo)}
  86. }
  87. for _, file := range files {
  88. if !strings.HasSuffix(file.Name(), ".dat") {
  89. continue
  90. }
  91. if *fixVolumeCollection != "" {
  92. if !strings.HasPrefix(file.Name(), *fixVolumeCollection+"_") {
  93. continue
  94. }
  95. }
  96. baseFileName := file.Name()[:len(file.Name())-4]
  97. collection, volumeIdStr := "", baseFileName
  98. if sepIndex := strings.LastIndex(baseFileName, "_"); sepIndex > 0 {
  99. collection = baseFileName[:sepIndex]
  100. volumeIdStr = baseFileName[sepIndex+1:]
  101. }
  102. volumeId, parseErr := strconv.ParseInt(volumeIdStr, 10, 64)
  103. if parseErr != nil {
  104. fmt.Printf("Failed to parse volume id from %s: %v\n", baseFileName, parseErr)
  105. return false
  106. }
  107. if *fixVolumeId != 0 && *fixVolumeId != volumeId {
  108. continue
  109. }
  110. doFixOneVolume(basePath, baseFileName, collection, volumeId, *fixIncludeDeleted)
  111. }
  112. }
  113. return true
  114. }
  115. func SaveToIdx(scaner *VolumeFileScanner4Fix, idxName string) (ret error) {
  116. idxFile, err := os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  117. if err != nil {
  118. return
  119. }
  120. defer func() {
  121. idxFile.Close()
  122. }()
  123. return scaner.nm.AscendingVisit(func(value needle_map.NeedleValue) error {
  124. _, err := idxFile.Write(value.ToBytes())
  125. if scaner.includeDeleted && err == nil {
  126. if deleted, ok := scaner.nmDeleted.Get(value.Key); ok {
  127. _, err = idxFile.Write(deleted.ToBytes())
  128. }
  129. }
  130. return err
  131. })
  132. }
  133. func doFixOneVolume(basepath string, baseFileName string, collection string, volumeId int64, fixIncludeDeleted bool) {
  134. indexFileName := path.Join(basepath, baseFileName+".idx")
  135. nm := needle_map.NewMemDb()
  136. nmDeleted := needle_map.NewMemDb()
  137. defer nm.Close()
  138. defer nmDeleted.Close()
  139. vid := needle.VolumeId(volumeId)
  140. scanner := &VolumeFileScanner4Fix{
  141. nm: nm,
  142. nmDeleted: nmDeleted,
  143. includeDeleted: fixIncludeDeleted,
  144. }
  145. if err := storage.ScanVolumeFile(basepath, collection, vid, storage.NeedleMapInMemory, scanner); err != nil {
  146. err := fmt.Errorf("scan .dat File: %v", err)
  147. if *fixIgnoreError {
  148. glog.Error(err)
  149. } else {
  150. glog.Fatal(err)
  151. }
  152. }
  153. if err := SaveToIdx(scanner, indexFileName); err != nil {
  154. err := fmt.Errorf("save to .idx File: %v", err)
  155. if *fixIgnoreError {
  156. glog.Error(err)
  157. } else {
  158. os.Remove(indexFileName)
  159. glog.Fatal(err)
  160. }
  161. }
  162. }