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.

281 lines
9.6 KiB

3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
  1. package shell
  2. import (
  3. "bytes"
  4. "context"
  5. "flag"
  6. "fmt"
  7. "github.com/seaweedfs/seaweedfs/weed/operation"
  8. "github.com/seaweedfs/seaweedfs/weed/pb"
  9. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  10. "github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
  11. "golang.org/x/exp/slices"
  12. "io"
  13. "math"
  14. )
  15. func init() {
  16. Commands = append(Commands, &commandVolumeCheckDisk{})
  17. }
  18. type commandVolumeCheckDisk struct {
  19. env *CommandEnv
  20. }
  21. func (c *commandVolumeCheckDisk) Name() string {
  22. return "volume.check.disk"
  23. }
  24. func (c *commandVolumeCheckDisk) Help() string {
  25. return `check all replicated volumes to find and fix inconsistencies. It is optional and resource intensive.
  26. How it works:
  27. find all volumes that are replicated
  28. for each volume id, if there are more than 2 replicas, find one pair with the largest 2 in file count.
  29. for the pair volume A and B
  30. append entries in A and not in B to B
  31. append entries in B and not in A to A
  32. `
  33. }
  34. func (c *commandVolumeCheckDisk) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  35. fsckCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  36. slowMode := fsckCommand.Bool("slow", false, "slow mode checks all replicas even file counts are the same")
  37. verbose := fsckCommand.Bool("v", false, "verbose mode")
  38. volumeId := fsckCommand.Uint("volumeId", 0, "the volume id")
  39. applyChanges := fsckCommand.Bool("force", false, "apply the fix")
  40. nonRepairThreshold := fsckCommand.Float64("nonRepairThreshold", 0.3, "repair when missing keys is not more than this limit")
  41. if err = fsckCommand.Parse(args); err != nil {
  42. return nil
  43. }
  44. infoAboutSimulationMode(writer, *applyChanges, "-force")
  45. if err = commandEnv.confirmIsLocked(args); err != nil {
  46. return
  47. }
  48. c.env = commandEnv
  49. // collect topology information
  50. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  51. if err != nil {
  52. return err
  53. }
  54. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  55. // pick 1 pairs of volume replica
  56. fileCount := func(replica *VolumeReplica) uint64 {
  57. return replica.info.FileCount - replica.info.DeleteCount
  58. }
  59. for _, replicas := range volumeReplicas {
  60. if *volumeId > 0 && replicas[0].info.Id != uint32(*volumeId) {
  61. continue
  62. }
  63. slices.SortFunc(replicas, func(a, b *VolumeReplica) bool {
  64. return fileCount(a) > fileCount(b)
  65. })
  66. for len(replicas) >= 2 {
  67. a, b := replicas[0], replicas[1]
  68. if !*slowMode {
  69. if fileCount(a) == fileCount(b) {
  70. replicas = replicas[1:]
  71. continue
  72. }
  73. }
  74. if a.info.ReadOnly || b.info.ReadOnly {
  75. fmt.Fprintf(writer, "skipping readonly volume %d on %s and %s\n", a.info.Id, a.location.dataNode.Id, b.location.dataNode.Id)
  76. replicas = replicas[1:]
  77. continue
  78. }
  79. if err := c.syncTwoReplicas(a, b, *applyChanges, *nonRepairThreshold, *verbose, writer); err != nil {
  80. fmt.Fprintf(writer, "sync volume %d on %s and %s: %v\n", a.info.Id, a.location.dataNode.Id, b.location.dataNode.Id, err)
  81. }
  82. replicas = replicas[1:]
  83. }
  84. }
  85. return nil
  86. }
  87. func (c *commandVolumeCheckDisk) syncTwoReplicas(a *VolumeReplica, b *VolumeReplica, applyChanges bool, nonRepairThreshold float64, verbose bool, writer io.Writer) (err error) {
  88. aHasChanges, bHasChanges := true, true
  89. for aHasChanges || bHasChanges {
  90. if aHasChanges, bHasChanges, err = c.checkBoth(a, b, applyChanges, nonRepairThreshold, verbose, writer); err != nil {
  91. return err
  92. }
  93. }
  94. return nil
  95. }
  96. func (c *commandVolumeCheckDisk) checkBoth(a *VolumeReplica, b *VolumeReplica, applyChanges bool, nonRepairThreshold float64, verbose bool, writer io.Writer) (aHasChanges bool, bHasChanges bool, err error) {
  97. aDB, bDB := needle_map.NewMemDb(), needle_map.NewMemDb()
  98. defer func() {
  99. aDB.Close()
  100. bDB.Close()
  101. }()
  102. // read index db
  103. if err = c.readIndexDatabase(aDB, a.info.Collection, a.info.Id, pb.NewServerAddressFromDataNode(a.location.dataNode), verbose, writer); err != nil {
  104. return true, true, fmt.Errorf("readIndexDatabase %s volume %d: %v", a.location.dataNode, a.info.Id, err)
  105. }
  106. if err := c.readIndexDatabase(bDB, b.info.Collection, b.info.Id, pb.NewServerAddressFromDataNode(b.location.dataNode), verbose, writer); err != nil {
  107. return true, true, fmt.Errorf("readIndexDatabase %s volume %d: %v", b.location.dataNode, b.info.Id, err)
  108. }
  109. // find and make up the differences
  110. if aHasChanges, err = c.doVolumeCheckDisk(bDB, aDB, b, a, verbose, writer, applyChanges, nonRepairThreshold); err != nil {
  111. return true, true, fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", b.location.dataNode, a.location.dataNode, b.info.Id, err)
  112. }
  113. if bHasChanges, err = c.doVolumeCheckDisk(aDB, bDB, a, b, verbose, writer, applyChanges, nonRepairThreshold); err != nil {
  114. return true, true, fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", a.location.dataNode, b.location.dataNode, a.info.Id, err)
  115. }
  116. return
  117. }
  118. func (c *commandVolumeCheckDisk) doVolumeCheckDisk(minuend, subtrahend *needle_map.MemDb, source, target *VolumeReplica, verbose bool, writer io.Writer, applyChanges bool, nonRepairThreshold float64) (hasChanges bool, err error) {
  119. // find missing keys
  120. // hash join, can be more efficient
  121. var missingNeedles []needle_map.NeedleValue
  122. var counter int
  123. minuend.AscendingVisit(func(value needle_map.NeedleValue) error {
  124. counter++
  125. if _, found := subtrahend.Get(value.Key); !found {
  126. missingNeedles = append(missingNeedles, value)
  127. }
  128. return nil
  129. })
  130. fmt.Fprintf(writer, "volume %d %s has %d entries, %s missed %d entries\n", source.info.Id, source.location.dataNode.Id, counter, target.location.dataNode.Id, len(missingNeedles))
  131. if counter == 0 || len(missingNeedles) == 0 {
  132. return false, nil
  133. }
  134. missingNeedlesFraction := float64(len(missingNeedles)) / float64(counter)
  135. if missingNeedlesFraction > nonRepairThreshold {
  136. return false, fmt.Errorf(
  137. "failed to start repair volume %d, percentage of missing keys is greater than the threshold: %.2f > %.2f",
  138. source.info.Id, missingNeedlesFraction, nonRepairThreshold)
  139. }
  140. for _, needleValue := range missingNeedles {
  141. needleBlob, err := c.readSourceNeedleBlob(pb.NewServerAddressFromDataNode(source.location.dataNode), source.info.Id, needleValue)
  142. if err != nil {
  143. return hasChanges, err
  144. }
  145. if !applyChanges {
  146. continue
  147. }
  148. if verbose {
  149. fmt.Fprintf(writer, "read %d,%x %s => %s \n", source.info.Id, needleValue.Key, source.location.dataNode.Id, target.location.dataNode.Id)
  150. }
  151. hasChanges = true
  152. if err = c.writeNeedleBlobToTarget(pb.NewServerAddressFromDataNode(target.location.dataNode), source.info.Id, needleValue, needleBlob); err != nil {
  153. return hasChanges, err
  154. }
  155. }
  156. return
  157. }
  158. func (c *commandVolumeCheckDisk) readSourceNeedleBlob(sourceVolumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue) (needleBlob []byte, err error) {
  159. err = operation.WithVolumeServerClient(false, sourceVolumeServer, c.env.option.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  160. resp, err := client.ReadNeedleBlob(context.Background(), &volume_server_pb.ReadNeedleBlobRequest{
  161. VolumeId: volumeId,
  162. NeedleId: uint64(needleValue.Key),
  163. Offset: needleValue.Offset.ToActualOffset(),
  164. Size: int32(needleValue.Size),
  165. })
  166. if err != nil {
  167. return err
  168. }
  169. needleBlob = resp.NeedleBlob
  170. return nil
  171. })
  172. return
  173. }
  174. func (c *commandVolumeCheckDisk) writeNeedleBlobToTarget(targetVolumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue, needleBlob []byte) error {
  175. return operation.WithVolumeServerClient(false, targetVolumeServer, c.env.option.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  176. _, err := client.WriteNeedleBlob(context.Background(), &volume_server_pb.WriteNeedleBlobRequest{
  177. VolumeId: volumeId,
  178. NeedleId: uint64(needleValue.Key),
  179. Size: int32(needleValue.Size),
  180. NeedleBlob: needleBlob,
  181. })
  182. return err
  183. })
  184. }
  185. func (c *commandVolumeCheckDisk) readIndexDatabase(db *needle_map.MemDb, collection string, volumeId uint32, volumeServer pb.ServerAddress, verbose bool, writer io.Writer) error {
  186. var buf bytes.Buffer
  187. if err := c.copyVolumeIndexFile(collection, volumeId, volumeServer, &buf, verbose, writer); err != nil {
  188. return err
  189. }
  190. if verbose {
  191. fmt.Fprintf(writer, "load collection %s volume %d index size %d from %s ...\n", collection, volumeId, buf.Len(), volumeServer)
  192. }
  193. return db.LoadFromReaderAt(bytes.NewReader(buf.Bytes()))
  194. }
  195. func (c *commandVolumeCheckDisk) copyVolumeIndexFile(collection string, volumeId uint32, volumeServer pb.ServerAddress, buf *bytes.Buffer, verbose bool, writer io.Writer) error {
  196. return operation.WithVolumeServerClient(true, volumeServer, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  197. ext := ".idx"
  198. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  199. VolumeId: volumeId,
  200. Ext: ".idx",
  201. CompactionRevision: math.MaxUint32,
  202. StopOffset: math.MaxInt64,
  203. Collection: collection,
  204. IsEcVolume: false,
  205. IgnoreSourceFileNotFound: false,
  206. })
  207. if err != nil {
  208. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  209. }
  210. err = writeToBuffer(copyFileClient, buf)
  211. if err != nil {
  212. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, volumeServer, err)
  213. }
  214. return nil
  215. })
  216. }
  217. func writeToBuffer(client volume_server_pb.VolumeServer_CopyFileClient, buf *bytes.Buffer) error {
  218. for {
  219. resp, receiveErr := client.Recv()
  220. if receiveErr == io.EOF {
  221. break
  222. }
  223. if receiveErr != nil {
  224. return fmt.Errorf("receiving: %v", receiveErr)
  225. }
  226. buf.Write(resp.FileContent)
  227. }
  228. return nil
  229. }