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.

280 lines
9.5 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/chrislusf/seaweedfs/weed/operation"
  8. "github.com/chrislusf/seaweedfs/weed/pb"
  9. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  10. "github.com/chrislusf/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. if err = commandEnv.confirmIsLocked(args); err != nil {
  45. return
  46. }
  47. c.env = commandEnv
  48. // collect topology information
  49. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  50. if err != nil {
  51. return err
  52. }
  53. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  54. // pick 1 pairs of volume replica
  55. fileCount := func(replica *VolumeReplica) uint64 {
  56. return replica.info.FileCount - replica.info.DeleteCount
  57. }
  58. for _, replicas := range volumeReplicas {
  59. if *volumeId > 0 && replicas[0].info.Id != uint32(*volumeId) {
  60. continue
  61. }
  62. slices.SortFunc(replicas, func(a, b *VolumeReplica) bool {
  63. return fileCount(a) > fileCount(b)
  64. })
  65. for len(replicas) >= 2 {
  66. a, b := replicas[0], replicas[1]
  67. if !*slowMode {
  68. if fileCount(a) == fileCount(b) {
  69. replicas = replicas[1:]
  70. continue
  71. }
  72. }
  73. if a.info.ReadOnly || b.info.ReadOnly {
  74. fmt.Fprintf(writer, "skipping readonly volume %d on %s and %s\n", a.info.Id, a.location.dataNode.Id, b.location.dataNode.Id)
  75. replicas = replicas[1:]
  76. continue
  77. }
  78. if err := c.syncTwoReplicas(a, b, *applyChanges, *nonRepairThreshold, *verbose, writer); err != nil {
  79. fmt.Fprintf(writer, "sync volume %d on %s and %s: %v\n", a.info.Id, a.location.dataNode.Id, b.location.dataNode.Id, err)
  80. }
  81. replicas = replicas[1:]
  82. }
  83. }
  84. return nil
  85. }
  86. func (c *commandVolumeCheckDisk) syncTwoReplicas(a *VolumeReplica, b *VolumeReplica, applyChanges bool, nonRepairThreshold float64, verbose bool, writer io.Writer) (err error) {
  87. aHasChanges, bHasChanges := true, true
  88. for aHasChanges || bHasChanges {
  89. if aHasChanges, bHasChanges, err = c.checkBoth(a, b, applyChanges, nonRepairThreshold, verbose, writer); err != nil {
  90. return err
  91. }
  92. }
  93. return nil
  94. }
  95. func (c *commandVolumeCheckDisk) checkBoth(a *VolumeReplica, b *VolumeReplica, applyChanges bool, nonRepairThreshold float64, verbose bool, writer io.Writer) (aHasChanges bool, bHasChanges bool, err error) {
  96. aDB, bDB := needle_map.NewMemDb(), needle_map.NewMemDb()
  97. defer func() {
  98. aDB.Close()
  99. bDB.Close()
  100. }()
  101. // read index db
  102. if err = c.readIndexDatabase(aDB, a.info.Collection, a.info.Id, pb.NewServerAddressFromDataNode(a.location.dataNode), verbose, writer); err != nil {
  103. return true, true, fmt.Errorf("readIndexDatabase %s volume %d: %v", a.location.dataNode, a.info.Id, err)
  104. }
  105. if err := c.readIndexDatabase(bDB, b.info.Collection, b.info.Id, pb.NewServerAddressFromDataNode(b.location.dataNode), verbose, writer); err != nil {
  106. return true, true, fmt.Errorf("readIndexDatabase %s volume %d: %v", b.location.dataNode, b.info.Id, err)
  107. }
  108. // find and make up the differences
  109. if aHasChanges, err = c.doVolumeCheckDisk(bDB, aDB, b, a, verbose, writer, applyChanges, nonRepairThreshold); err != nil {
  110. return true, true, fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", b.location.dataNode, a.location.dataNode, b.info.Id, err)
  111. }
  112. if bHasChanges, err = c.doVolumeCheckDisk(aDB, bDB, a, b, verbose, writer, applyChanges, nonRepairThreshold); err != nil {
  113. return true, true, fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", a.location.dataNode, b.location.dataNode, a.info.Id, err)
  114. }
  115. return
  116. }
  117. 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) {
  118. // find missing keys
  119. // hash join, can be more efficient
  120. var missingNeedles []needle_map.NeedleValue
  121. var counter int
  122. minuend.AscendingVisit(func(value needle_map.NeedleValue) error {
  123. counter++
  124. if _, found := subtrahend.Get(value.Key); !found {
  125. missingNeedles = append(missingNeedles, value)
  126. }
  127. return nil
  128. })
  129. 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))
  130. if counter == 0 || len(missingNeedles) == 0 {
  131. return false, nil
  132. }
  133. missingNeedlesFraction := float64(len(missingNeedles)) / float64(counter)
  134. if missingNeedlesFraction > nonRepairThreshold {
  135. return false, fmt.Errorf(
  136. "failed to start repair volume %d, percentage of missing keys is greater than the threshold: %.2f > %.2f",
  137. source.info.Id, missingNeedlesFraction, nonRepairThreshold)
  138. }
  139. for _, needleValue := range missingNeedles {
  140. needleBlob, err := c.readSourceNeedleBlob(pb.NewServerAddressFromDataNode(source.location.dataNode), source.info.Id, needleValue)
  141. if err != nil {
  142. return hasChanges, err
  143. }
  144. if !applyChanges {
  145. continue
  146. }
  147. if verbose {
  148. fmt.Fprintf(writer, "read %d,%x %s => %s \n", source.info.Id, needleValue.Key, source.location.dataNode.Id, target.location.dataNode.Id)
  149. }
  150. hasChanges = true
  151. if err = c.writeNeedleBlobToTarget(pb.NewServerAddressFromDataNode(target.location.dataNode), source.info.Id, needleValue, needleBlob); err != nil {
  152. return hasChanges, err
  153. }
  154. }
  155. return
  156. }
  157. func (c *commandVolumeCheckDisk) readSourceNeedleBlob(sourceVolumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue) (needleBlob []byte, err error) {
  158. err = operation.WithVolumeServerClient(false, sourceVolumeServer, c.env.option.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  159. resp, err := client.ReadNeedleBlob(context.Background(), &volume_server_pb.ReadNeedleBlobRequest{
  160. VolumeId: volumeId,
  161. NeedleId: uint64(needleValue.Key),
  162. Offset: needleValue.Offset.ToActualOffset(),
  163. Size: int32(needleValue.Size),
  164. })
  165. if err != nil {
  166. return err
  167. }
  168. needleBlob = resp.NeedleBlob
  169. return nil
  170. })
  171. return
  172. }
  173. func (c *commandVolumeCheckDisk) writeNeedleBlobToTarget(targetVolumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue, needleBlob []byte) error {
  174. return operation.WithVolumeServerClient(false, targetVolumeServer, c.env.option.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  175. _, err := client.WriteNeedleBlob(context.Background(), &volume_server_pb.WriteNeedleBlobRequest{
  176. VolumeId: volumeId,
  177. NeedleId: uint64(needleValue.Key),
  178. Size: int32(needleValue.Size),
  179. NeedleBlob: needleBlob,
  180. })
  181. return err
  182. })
  183. }
  184. func (c *commandVolumeCheckDisk) readIndexDatabase(db *needle_map.MemDb, collection string, volumeId uint32, volumeServer pb.ServerAddress, verbose bool, writer io.Writer) error {
  185. var buf bytes.Buffer
  186. if err := c.copyVolumeIndexFile(collection, volumeId, volumeServer, &buf, verbose, writer); err != nil {
  187. return err
  188. }
  189. if verbose {
  190. fmt.Fprintf(writer, "load collection %s volume %d index size %d from %s ...\n", collection, volumeId, buf.Len(), volumeServer)
  191. }
  192. return db.LoadFromReaderAt(bytes.NewReader(buf.Bytes()))
  193. }
  194. func (c *commandVolumeCheckDisk) copyVolumeIndexFile(collection string, volumeId uint32, volumeServer pb.ServerAddress, buf *bytes.Buffer, verbose bool, writer io.Writer) error {
  195. return operation.WithVolumeServerClient(true, volumeServer, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  196. ext := ".idx"
  197. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  198. VolumeId: volumeId,
  199. Ext: ".idx",
  200. CompactionRevision: math.MaxUint32,
  201. StopOffset: math.MaxInt64,
  202. Collection: collection,
  203. IsEcVolume: false,
  204. IgnoreSourceFileNotFound: false,
  205. })
  206. if err != nil {
  207. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  208. }
  209. err = writeToBuffer(copyFileClient, buf)
  210. if err != nil {
  211. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, volumeServer, err)
  212. }
  213. return nil
  214. })
  215. }
  216. func writeToBuffer(client volume_server_pb.VolumeServer_CopyFileClient, buf *bytes.Buffer) error {
  217. for {
  218. resp, receiveErr := client.Recv()
  219. if receiveErr == io.EOF {
  220. break
  221. }
  222. if receiveErr != nil {
  223. return fmt.Errorf("receiving: %v", receiveErr)
  224. }
  225. buf.Write(resp.FileContent)
  226. }
  227. return nil
  228. }