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. "google.golang.org/grpc"
  13. "io"
  14. "math"
  15. )
  16. func init() {
  17. Commands = append(Commands, &commandVolumeCheckDisk{})
  18. }
  19. type commandVolumeCheckDisk struct {
  20. env *CommandEnv
  21. }
  22. func (c *commandVolumeCheckDisk) Name() string {
  23. return "volume.check.disk"
  24. }
  25. func (c *commandVolumeCheckDisk) Help() string {
  26. return `check all replicated volumes to find and fix inconsistencies. It is optional and resource intensive.
  27. How it works:
  28. find all volumes that are replicated
  29. for each volume id, if there are more than 2 replicas, find one pair with the largest 2 in file count.
  30. for the pair volume A and B
  31. append entries in A and not in B to B
  32. append entries in B and not in A to A
  33. `
  34. }
  35. func (c *commandVolumeCheckDisk) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  36. fsckCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  37. slowMode := fsckCommand.Bool("slow", false, "slow mode checks all replicas even file counts are the same")
  38. verbose := fsckCommand.Bool("v", false, "verbose mode")
  39. volumeId := fsckCommand.Uint("volumeId", 0, "the volume id")
  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. infoAboutSimulationMode(writer, *applyChanges, "-force")
  46. if err = commandEnv.confirmIsLocked(args); err != nil {
  47. return
  48. }
  49. c.env = commandEnv
  50. // collect topology information
  51. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  52. if err != nil {
  53. return err
  54. }
  55. volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo)
  56. // pick 1 pairs of volume replica
  57. fileCount := func(replica *VolumeReplica) uint64 {
  58. return replica.info.FileCount - replica.info.DeleteCount
  59. }
  60. for _, replicas := range volumeReplicas {
  61. if *volumeId > 0 && replicas[0].info.Id != uint32(*volumeId) {
  62. continue
  63. }
  64. slices.SortFunc(replicas, func(a, b *VolumeReplica) bool {
  65. return fileCount(a) > fileCount(b)
  66. })
  67. for len(replicas) >= 2 {
  68. a, b := replicas[0], replicas[1]
  69. if !*slowMode {
  70. if fileCount(a) == fileCount(b) {
  71. replicas = replicas[1:]
  72. continue
  73. }
  74. }
  75. if a.info.ReadOnly || b.info.ReadOnly {
  76. fmt.Fprintf(writer, "skipping readonly volume %d on %s and %s\n", a.info.Id, a.location.dataNode.Id, b.location.dataNode.Id)
  77. replicas = replicas[1:]
  78. continue
  79. }
  80. if err := c.syncTwoReplicas(a, b, *applyChanges, *nonRepairThreshold, *verbose, writer); err != nil {
  81. fmt.Fprintf(writer, "sync volume %d on %s and %s: %v\n", a.info.Id, a.location.dataNode.Id, b.location.dataNode.Id, err)
  82. }
  83. replicas = replicas[1:]
  84. }
  85. }
  86. return nil
  87. }
  88. func (c *commandVolumeCheckDisk) syncTwoReplicas(a *VolumeReplica, b *VolumeReplica, applyChanges bool, nonRepairThreshold float64, verbose bool, writer io.Writer) (err error) {
  89. aHasChanges, bHasChanges := true, true
  90. for aHasChanges || bHasChanges {
  91. if aHasChanges, bHasChanges, err = c.checkBoth(a, b, applyChanges, nonRepairThreshold, verbose, writer); err != nil {
  92. return err
  93. }
  94. }
  95. return nil
  96. }
  97. func (c *commandVolumeCheckDisk) checkBoth(a *VolumeReplica, b *VolumeReplica, applyChanges bool, nonRepairThreshold float64, verbose bool, writer io.Writer) (aHasChanges bool, bHasChanges bool, err error) {
  98. aDB, bDB := needle_map.NewMemDb(), needle_map.NewMemDb()
  99. defer func() {
  100. aDB.Close()
  101. bDB.Close()
  102. }()
  103. // read index db
  104. if err = c.readIndexDatabase(aDB, a.info.Collection, a.info.Id, pb.NewServerAddressFromDataNode(a.location.dataNode), verbose, writer); err != nil {
  105. return true, true, fmt.Errorf("readIndexDatabase %s volume %d: %v", a.location.dataNode, a.info.Id, err)
  106. }
  107. if err := c.readIndexDatabase(bDB, b.info.Collection, b.info.Id, pb.NewServerAddressFromDataNode(b.location.dataNode), verbose, writer); err != nil {
  108. return true, true, fmt.Errorf("readIndexDatabase %s volume %d: %v", b.location.dataNode, b.info.Id, err)
  109. }
  110. // find and make up the differences
  111. if aHasChanges, err = c.doVolumeCheckDisk(bDB, aDB, b, a, verbose, writer, applyChanges, nonRepairThreshold); err != nil {
  112. return true, true, fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", b.location.dataNode.Id, a.location.dataNode.Id, b.info.Id, err)
  113. }
  114. if bHasChanges, err = c.doVolumeCheckDisk(aDB, bDB, a, b, verbose, writer, applyChanges, nonRepairThreshold); err != nil {
  115. return true, true, fmt.Errorf("doVolumeCheckDisk source:%s target:%s volume %d: %v", a.location.dataNode.Id, b.location.dataNode.Id, a.info.Id, err)
  116. }
  117. return
  118. }
  119. 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) {
  120. // find missing keys
  121. // hash join, can be more efficient
  122. var missingNeedles []needle_map.NeedleValue
  123. var counter int
  124. minuend.AscendingVisit(func(value needle_map.NeedleValue) error {
  125. counter++
  126. if _, found := subtrahend.Get(value.Key); !found {
  127. missingNeedles = append(missingNeedles, value)
  128. }
  129. return nil
  130. })
  131. 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))
  132. if counter == 0 || len(missingNeedles) == 0 {
  133. return false, nil
  134. }
  135. missingNeedlesFraction := float64(len(missingNeedles)) / float64(counter)
  136. if missingNeedlesFraction > nonRepairThreshold {
  137. return false, fmt.Errorf(
  138. "failed to start repair volume %d, percentage of missing keys is greater than the threshold: %.2f > %.2f",
  139. source.info.Id, missingNeedlesFraction, nonRepairThreshold)
  140. }
  141. for _, needleValue := range missingNeedles {
  142. needleBlob, err := readSourceNeedleBlob(c.env.option.GrpcDialOption, pb.NewServerAddressFromDataNode(source.location.dataNode), source.info.Id, needleValue)
  143. if err != nil {
  144. return hasChanges, err
  145. }
  146. if !applyChanges {
  147. continue
  148. }
  149. if verbose {
  150. fmt.Fprintf(writer, "read %d,%x %s => %s \n", source.info.Id, needleValue.Key, source.location.dataNode.Id, target.location.dataNode.Id)
  151. }
  152. hasChanges = true
  153. if err = c.writeNeedleBlobToTarget(pb.NewServerAddressFromDataNode(target.location.dataNode), source.info.Id, needleValue, needleBlob); err != nil {
  154. return hasChanges, err
  155. }
  156. }
  157. return
  158. }
  159. func readSourceNeedleBlob(grpcDialOption grpc.DialOption, sourceVolumeServer pb.ServerAddress, volumeId uint32, needleValue needle_map.NeedleValue) (needleBlob []byte, err error) {
  160. err = operation.WithVolumeServerClient(false, sourceVolumeServer, grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  161. resp, err := client.ReadNeedleBlob(context.Background(), &volume_server_pb.ReadNeedleBlobRequest{
  162. VolumeId: volumeId,
  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. }