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.

325 lines
12 KiB

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