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.

257 lines
7.8 KiB

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