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.

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