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.

721 lines
23 KiB

3 years ago
3 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
3 years ago
5 years ago
5 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package shell
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "github.com/seaweedfs/seaweedfs/weed/filer"
  10. "github.com/seaweedfs/seaweedfs/weed/operation"
  11. "github.com/seaweedfs/seaweedfs/weed/pb"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/idx"
  16. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  19. "github.com/seaweedfs/seaweedfs/weed/util"
  20. "io"
  21. "io/ioutil"
  22. "math"
  23. "net/http"
  24. "net/url"
  25. "os"
  26. "path"
  27. "path/filepath"
  28. "sync"
  29. "time"
  30. )
  31. func init() {
  32. Commands = append(Commands, &commandVolumeFsck{})
  33. }
  34. const (
  35. readbufferSize = 16
  36. verifyProbeBlobSize = 16
  37. )
  38. type commandVolumeFsck struct {
  39. env *CommandEnv
  40. writer io.Writer
  41. bucketsPath string
  42. collection *string
  43. volumeId *uint
  44. tempFolder string
  45. verbose *bool
  46. forcePurging *bool
  47. findMissingChunksInFiler *bool
  48. verifyNeedle *bool
  49. }
  50. func (c *commandVolumeFsck) Name() string {
  51. return "volume.fsck"
  52. }
  53. func (c *commandVolumeFsck) Help() string {
  54. return `check all volumes to find entries not used by the filer
  55. Important assumption!!!
  56. the system is all used by one filer.
  57. This command works this way:
  58. 1. collect all file ids from all volumes, as set A
  59. 2. collect all file ids from the filer, as set B
  60. 3. find out the set A subtract B
  61. If -findMissingChunksInFiler is enabled, this works
  62. in a reverse way:
  63. 1. collect all file ids from all volumes, as set A
  64. 2. collect all file ids from the filer, as set B
  65. 3. find out the set B subtract A
  66. `
  67. }
  68. func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  69. fsckCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  70. c.verbose = fsckCommand.Bool("v", false, "verbose mode")
  71. c.findMissingChunksInFiler = fsckCommand.Bool("findMissingChunksInFiler", false, "see \"help volume.fsck\"")
  72. c.collection = fsckCommand.String("collection", "", "the collection name")
  73. c.volumeId = fsckCommand.Uint("volumeId", 0, "the volume id")
  74. applyPurging := fsckCommand.Bool("reallyDeleteFromVolume", false, "<expert only!> after detection, delete missing data from volumes / delete missing file entries from filer. Currently this only works with default filerGroup.")
  75. c.forcePurging = fsckCommand.Bool("forcePurging", false, "delete missing data from volumes in one replica used together with applyPurging")
  76. purgeAbsent := fsckCommand.Bool("reallyDeleteFilerEntries", false, "<expert only!> delete missing file entries from filer if the corresponding volume is missing for any reason, please ensure all still existing/expected volumes are connected! used together with findMissingChunksInFiler")
  77. tempPath := fsckCommand.String("tempPath", path.Join(os.TempDir()), "path for temporary idx files")
  78. cutoffTimeAgo := fsckCommand.Duration("cutoffTimeAgo", 5*time.Minute, "only include entries on volume servers before this cutoff time to check orphan chunks")
  79. c.verifyNeedle = fsckCommand.Bool("verifyNeedles", false, "try get head needle blob from volume server")
  80. if err = fsckCommand.Parse(args); err != nil {
  81. return nil
  82. }
  83. if err = commandEnv.confirmIsLocked(args); err != nil {
  84. return
  85. }
  86. c.env = commandEnv
  87. c.writer = writer
  88. c.bucketsPath, err = readFilerBucketsPath(commandEnv)
  89. if err != nil {
  90. return fmt.Errorf("read filer buckets path: %v", err)
  91. }
  92. // create a temp folder
  93. c.tempFolder, err = os.MkdirTemp(*tempPath, "sw_fsck")
  94. if err != nil {
  95. return fmt.Errorf("failed to create temp folder: %v", err)
  96. }
  97. if *c.verbose {
  98. fmt.Fprintf(c.writer, "working directory: %s\n", c.tempFolder)
  99. }
  100. defer os.RemoveAll(c.tempFolder)
  101. // collect all volume id locations
  102. dataNodeVolumeIdToVInfo, err := c.collectVolumeIds()
  103. if err != nil {
  104. return fmt.Errorf("failed to collect all volume locations: %v", err)
  105. }
  106. if err != nil {
  107. return fmt.Errorf("read filer buckets path: %v", err)
  108. }
  109. collectMtime := time.Now().UnixNano()
  110. // collect each volume file ids
  111. for dataNodeId, volumeIdToVInfo := range dataNodeVolumeIdToVInfo {
  112. for volumeId, vinfo := range volumeIdToVInfo {
  113. if *c.volumeId > 0 && uint32(*c.volumeId) != volumeId {
  114. delete(volumeIdToVInfo, volumeId)
  115. continue
  116. }
  117. // or skip /topics/.system/log without collection name
  118. if (*c.collection != "" && vinfo.collection != *c.collection) || vinfo.collection == "" {
  119. delete(volumeIdToVInfo, volumeId)
  120. continue
  121. }
  122. if *c.volumeId > 0 && *c.collection == "" {
  123. *c.collection = vinfo.collection
  124. }
  125. cutoffFrom := time.Now().Add(-*cutoffTimeAgo).UnixNano()
  126. err = c.collectOneVolumeFileIds(dataNodeId, volumeId, vinfo, uint64(cutoffFrom))
  127. if err != nil {
  128. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, err)
  129. }
  130. }
  131. if *c.verbose {
  132. fmt.Fprintf(c.writer, "dn %+v filtred %d volumes and locations.\n", dataNodeId, len(dataNodeVolumeIdToVInfo[dataNodeId]))
  133. }
  134. }
  135. if *c.findMissingChunksInFiler {
  136. // collect all filer file ids and paths
  137. if err = c.collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo, *purgeAbsent, collectMtime); err != nil {
  138. return fmt.Errorf("collectFilerFileIdAndPaths: %v", err)
  139. }
  140. for dataNodeId, volumeIdToVInfo := range dataNodeVolumeIdToVInfo {
  141. // for each volume, check filer file ids
  142. if err = c.findFilerChunksMissingInVolumeServers(volumeIdToVInfo, dataNodeId, *applyPurging); err != nil {
  143. return fmt.Errorf("findFilerChunksMissingInVolumeServers: %v", err)
  144. }
  145. }
  146. } else {
  147. // collect all filer file ids
  148. if err = c.collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo, false, collectMtime); err != nil {
  149. return fmt.Errorf("failed to collect file ids from filer: %v", err)
  150. }
  151. // volume file ids subtract filer file ids
  152. if err = c.findExtraChunksInVolumeServers(dataNodeVolumeIdToVInfo, *applyPurging); err != nil {
  153. return fmt.Errorf("findExtraChunksInVolumeServers: %v", err)
  154. }
  155. }
  156. return nil
  157. }
  158. func (c *commandVolumeFsck) collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo map[string]map[uint32]VInfo, purgeAbsent bool, collectMtime int64) error {
  159. if *c.verbose {
  160. fmt.Fprintf(c.writer, "checking each file from filer path %s...\n", c.getCollectFilerFilePath())
  161. }
  162. files := make(map[uint32]*os.File)
  163. for _, volumeIdToServer := range dataNodeVolumeIdToVInfo {
  164. for vid := range volumeIdToServer {
  165. if _, ok := files[vid]; ok {
  166. continue
  167. }
  168. dst, openErr := os.OpenFile(getFilerFileIdFile(c.tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  169. if openErr != nil {
  170. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(c.tempFolder, vid), openErr)
  171. }
  172. files[vid] = dst
  173. }
  174. }
  175. defer func() {
  176. for _, f := range files {
  177. f.Close()
  178. }
  179. }()
  180. return doTraverseBfsAndSaving(c.env, nil, c.getCollectFilerFilePath(), false,
  181. func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  182. if *c.verbose && entry.Entry.IsDirectory {
  183. fmt.Fprintf(c.writer, "checking directory %s\n", util.NewFullPath(entry.Dir, entry.Entry.Name))
  184. }
  185. dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks, 0, math.MaxInt64)
  186. if resolveErr != nil {
  187. return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
  188. }
  189. dataChunks = append(dataChunks, manifestChunks...)
  190. for _, chunk := range dataChunks {
  191. if chunk.Mtime > collectMtime {
  192. continue
  193. }
  194. outputChan <- &Item{
  195. vid: chunk.Fid.VolumeId,
  196. fileKey: chunk.Fid.FileKey,
  197. cookie: chunk.Fid.Cookie,
  198. path: util.NewFullPath(entry.Dir, entry.Entry.Name),
  199. }
  200. }
  201. return nil
  202. },
  203. func(outputChan chan interface{}) {
  204. buffer := make([]byte, readbufferSize)
  205. for item := range outputChan {
  206. i := item.(*Item)
  207. if f, ok := files[i.vid]; ok {
  208. util.Uint64toBytes(buffer, i.fileKey)
  209. util.Uint32toBytes(buffer[8:], i.cookie)
  210. util.Uint32toBytes(buffer[12:], uint32(len(i.path)))
  211. f.Write(buffer)
  212. f.Write([]byte(i.path))
  213. } else if *c.findMissingChunksInFiler && *c.volumeId == 0 {
  214. fmt.Fprintf(c.writer, "%d,%x%08x %s volume not found\n", i.vid, i.fileKey, i.cookie, i.path)
  215. if purgeAbsent {
  216. fmt.Printf("deleting path %s after volume not found", i.path)
  217. c.httpDelete(i.path)
  218. }
  219. }
  220. }
  221. })
  222. }
  223. func (c *commandVolumeFsck) findFilerChunksMissingInVolumeServers(volumeIdToVInfo map[uint32]VInfo, dataNodeId string, applyPurging bool) error {
  224. for volumeId, vinfo := range volumeIdToVInfo {
  225. checkErr := c.oneVolumeFileIdsCheckOneVolume(dataNodeId, volumeId, applyPurging)
  226. if checkErr != nil {
  227. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  228. }
  229. }
  230. return nil
  231. }
  232. func (c *commandVolumeFsck) findExtraChunksInVolumeServers(dataNodeVolumeIdToVInfo map[string]map[uint32]VInfo, applyPurging bool) error {
  233. var totalInUseCount, totalOrphanChunkCount, totalOrphanDataSize uint64
  234. volumeIdOrphanFileIds := make(map[uint32]map[string]bool)
  235. isSeveralReplicas := make(map[uint32]bool)
  236. isEcVolumeReplicas := make(map[uint32]bool)
  237. isReadOnlyReplicas := make(map[uint32]bool)
  238. serverReplicas := make(map[uint32][]pb.ServerAddress)
  239. for dataNodeId, volumeIdToVInfo := range dataNodeVolumeIdToVInfo {
  240. for volumeId, vinfo := range volumeIdToVInfo {
  241. inUseCount, orphanFileIds, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(dataNodeId, volumeId, vinfo.collection)
  242. if checkErr != nil {
  243. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  244. }
  245. isSeveralReplicas[volumeId] = false
  246. if _, found := volumeIdOrphanFileIds[volumeId]; !found {
  247. volumeIdOrphanFileIds[volumeId] = make(map[string]bool)
  248. } else {
  249. isSeveralReplicas[volumeId] = true
  250. }
  251. for _, fid := range orphanFileIds {
  252. if isSeveralReplicas[volumeId] {
  253. if _, found := volumeIdOrphanFileIds[volumeId][fid]; !found {
  254. continue
  255. }
  256. }
  257. volumeIdOrphanFileIds[volumeId][fid] = isSeveralReplicas[volumeId]
  258. }
  259. totalInUseCount += inUseCount
  260. totalOrphanChunkCount += uint64(len(orphanFileIds))
  261. totalOrphanDataSize += orphanDataSize
  262. if *c.verbose {
  263. for _, fid := range orphanFileIds {
  264. fmt.Fprintf(c.writer, "%s:%s\n", vinfo.collection, fid)
  265. }
  266. }
  267. isEcVolumeReplicas[volumeId] = vinfo.isEcVolume
  268. if isReadOnly, found := isReadOnlyReplicas[volumeId]; !(found && isReadOnly) {
  269. isReadOnlyReplicas[volumeId] = vinfo.isReadOnly
  270. }
  271. serverReplicas[volumeId] = append(serverReplicas[volumeId], vinfo.server)
  272. }
  273. for volumeId, orphanReplicaFileIds := range volumeIdOrphanFileIds {
  274. if !(applyPurging && len(orphanReplicaFileIds) > 0) {
  275. continue
  276. }
  277. orphanFileIds := []string{}
  278. for fid, foundInAllReplicas := range orphanReplicaFileIds {
  279. if !isSeveralReplicas[volumeId] || *c.forcePurging || (isSeveralReplicas[volumeId] && foundInAllReplicas) {
  280. orphanFileIds = append(orphanFileIds, fid)
  281. }
  282. }
  283. if !(len(orphanFileIds) > 0) {
  284. continue
  285. }
  286. if *c.verbose {
  287. fmt.Fprintf(c.writer, "purging process for volume %d.\n", volumeId)
  288. }
  289. if isEcVolumeReplicas[volumeId] {
  290. fmt.Fprintf(c.writer, "skip purging for Erasure Coded volume %d.\n", volumeId)
  291. continue
  292. }
  293. for _, server := range serverReplicas[volumeId] {
  294. needleVID := needle.VolumeId(volumeId)
  295. if isReadOnlyReplicas[volumeId] {
  296. err := markVolumeWritable(c.env.option.GrpcDialOption, needleVID, server, true)
  297. if err != nil {
  298. return fmt.Errorf("mark volume %d read/write: %v", volumeId, err)
  299. }
  300. fmt.Fprintf(c.writer, "temporarily marked %d on server %v writable for forced purge\n", volumeId, server)
  301. defer markVolumeWritable(c.env.option.GrpcDialOption, needleVID, server, false)
  302. fmt.Fprintf(c.writer, "marked %d on server %v writable for forced purge\n", volumeId, server)
  303. }
  304. if *c.verbose {
  305. fmt.Fprintf(c.writer, "purging files from volume %d\n", volumeId)
  306. }
  307. if err := c.purgeFileIdsForOneVolume(volumeId, orphanFileIds); err != nil {
  308. return fmt.Errorf("purging volume %d: %v", volumeId, err)
  309. }
  310. }
  311. }
  312. }
  313. if !applyPurging {
  314. pct := float64(totalOrphanChunkCount*100) / (float64(totalOrphanChunkCount + totalInUseCount))
  315. fmt.Fprintf(c.writer, "\nTotal\t\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  316. totalOrphanChunkCount+totalInUseCount, totalOrphanChunkCount, pct, totalOrphanDataSize)
  317. fmt.Fprintf(c.writer, "This could be normal if multiple filers or no filers are used.\n")
  318. }
  319. if totalOrphanChunkCount == 0 {
  320. fmt.Fprintf(c.writer, "no orphan data\n")
  321. }
  322. return nil
  323. }
  324. func (c *commandVolumeFsck) collectOneVolumeFileIds(dataNodeId string, volumeId uint32, vinfo VInfo, cutoffFrom uint64) error {
  325. if *c.verbose {
  326. fmt.Fprintf(c.writer, "collecting volume %d file ids from %s ...\n", volumeId, vinfo.server)
  327. }
  328. return operation.WithVolumeServerClient(false, vinfo.server, c.env.option.GrpcDialOption,
  329. func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  330. ext := ".idx"
  331. if vinfo.isEcVolume {
  332. ext = ".ecx"
  333. }
  334. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  335. VolumeId: volumeId,
  336. Ext: ext,
  337. CompactionRevision: math.MaxUint32,
  338. StopOffset: math.MaxInt64,
  339. Collection: vinfo.collection,
  340. IsEcVolume: vinfo.isEcVolume,
  341. IgnoreSourceFileNotFound: false,
  342. })
  343. if err != nil {
  344. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  345. }
  346. var buf bytes.Buffer
  347. for {
  348. resp, err := copyFileClient.Recv()
  349. if errors.Is(err, io.EOF) {
  350. break
  351. }
  352. if err != nil {
  353. return err
  354. }
  355. buf.Write(resp.FileContent)
  356. }
  357. fileredBuf := filterDeletedNeedleFromIdx(buf.Bytes())
  358. if vinfo.isReadOnly == false {
  359. index, err := idx.FirstInvalidIndex(fileredBuf.Bytes(),
  360. func(key types.NeedleId, offset types.Offset, size types.Size) (bool, error) {
  361. resp, err := volumeServerClient.ReadNeedleMeta(context.Background(), &volume_server_pb.ReadNeedleMetaRequest{
  362. VolumeId: volumeId,
  363. NeedleId: uint64(key),
  364. Offset: offset.ToActualOffset(),
  365. Size: int32(size),
  366. })
  367. if err != nil {
  368. return false, fmt.Errorf("to read needle meta with id %d from volume %d with error %v", key, volumeId, err)
  369. }
  370. return resp.LastModified <= cutoffFrom, nil
  371. })
  372. if err != nil {
  373. fmt.Fprintf(c.writer, "Failed to search for last valid index on volume %d with error %v", volumeId, err)
  374. } else {
  375. fileredBuf.Truncate(index * types.NeedleMapEntrySize)
  376. }
  377. }
  378. idxFilename := getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)
  379. err = writeToFile(fileredBuf.Bytes(), idxFilename)
  380. if err != nil {
  381. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, vinfo.server, err)
  382. }
  383. return nil
  384. })
  385. }
  386. type Item struct {
  387. vid uint32
  388. fileKey uint64
  389. cookie uint32
  390. path util.FullPath
  391. }
  392. func (c *commandVolumeFsck) readFilerFileIdFile(volumeId uint32, fn func(needleId types.NeedleId, itemPath util.FullPath)) error {
  393. fp, err := os.Open(getFilerFileIdFile(c.tempFolder, volumeId))
  394. if err != nil {
  395. return err
  396. }
  397. defer fp.Close()
  398. br := bufio.NewReader(fp)
  399. buffer := make([]byte, readbufferSize)
  400. var readSize int
  401. var readErr error
  402. item := &Item{vid: volumeId}
  403. for {
  404. readSize, readErr = io.ReadFull(br, buffer)
  405. if errors.Is(readErr, io.EOF) {
  406. break
  407. }
  408. if readErr != nil {
  409. return readErr
  410. }
  411. if readSize != readbufferSize {
  412. return fmt.Errorf("readSize mismatch")
  413. }
  414. item.fileKey = util.BytesToUint64(buffer[:8])
  415. item.cookie = util.BytesToUint32(buffer[8:12])
  416. pathSize := util.BytesToUint32(buffer[12:16])
  417. pathBytes := make([]byte, int(pathSize))
  418. n, err := io.ReadFull(br, pathBytes)
  419. if err != nil {
  420. fmt.Fprintf(c.writer, "%d,%x%08x in unexpected error: %v\n", volumeId, item.fileKey, item.cookie, err)
  421. }
  422. if n != int(pathSize) {
  423. fmt.Fprintf(c.writer, "%d,%x%08x %d unexpected file name size %d\n", volumeId, item.fileKey, item.cookie, pathSize, n)
  424. }
  425. item.path = util.FullPath(pathBytes)
  426. needleId := types.NeedleId(item.fileKey)
  427. fn(needleId, item.path)
  428. }
  429. return nil
  430. }
  431. func (c *commandVolumeFsck) oneVolumeFileIdsCheckOneVolume(dataNodeId string, volumeId uint32, applyPurging bool) (err error) {
  432. if *c.verbose {
  433. fmt.Fprintf(c.writer, "find missing file chunks in dataNodeId %s volume %d ...\n", dataNodeId, volumeId)
  434. }
  435. db := needle_map.NewMemDb()
  436. defer db.Close()
  437. if err = db.LoadFromIdx(getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)); err != nil {
  438. return
  439. }
  440. if err = c.readFilerFileIdFile(volumeId, func(needleId types.NeedleId, itemPath util.FullPath) {
  441. if _, found := db.Get(needleId); !found {
  442. fmt.Fprintf(c.writer, "%s\n", itemPath)
  443. if applyPurging {
  444. c.httpDelete(itemPath)
  445. }
  446. }
  447. }); err != nil {
  448. return
  449. }
  450. return nil
  451. }
  452. func (c *commandVolumeFsck) httpDelete(path util.FullPath) {
  453. req, err := http.NewRequest(http.MethodDelete, "", nil)
  454. req.URL = &url.URL{
  455. Scheme: "http",
  456. Host: c.env.option.FilerAddress.ToHttpAddress(),
  457. Path: string(path),
  458. }
  459. if *c.verbose {
  460. fmt.Fprintf(c.writer, "full HTTP delete request to be sent: %v\n", req)
  461. }
  462. if err != nil {
  463. fmt.Fprintf(c.writer, "HTTP delete request error: %v\n", err)
  464. }
  465. client := &http.Client{}
  466. resp, err := client.Do(req)
  467. if err != nil {
  468. fmt.Fprintf(c.writer, "DELETE fetch error: %v\n", err)
  469. }
  470. defer resp.Body.Close()
  471. _, err = ioutil.ReadAll(resp.Body)
  472. if err != nil {
  473. fmt.Fprintf(c.writer, "DELETE response error: %v\n", err)
  474. }
  475. if *c.verbose {
  476. fmt.Fprintln(c.writer, "delete response Status : ", resp.Status)
  477. fmt.Fprintln(c.writer, "delete response Headers : ", resp.Header)
  478. }
  479. }
  480. func (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(dataNodeId string, volumeId uint32, collection string) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  481. db := needle_map.NewMemDb()
  482. defer db.Close()
  483. if err = db.LoadFromIdx(getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)); err != nil {
  484. err = fmt.Errorf("failed to LoadFromIdx %+v", err)
  485. return
  486. }
  487. voluemAddr := pb.NewServerAddressWithGrpcPort(dataNodeId, 0)
  488. if err = c.readFilerFileIdFile(volumeId, func(nId types.NeedleId, itemPath util.FullPath) {
  489. inUseCount++
  490. if *c.verifyNeedle {
  491. if v, ok := db.Get(nId); ok && v.Size.IsValid() {
  492. newSize := types.Size(verifyProbeBlobSize)
  493. if v.Size > newSize {
  494. v.Size = newSize
  495. }
  496. if _, err := readSourceNeedleBlob(c.env.option.GrpcDialOption, voluemAddr, volumeId, *v); err != nil {
  497. fmt.Fprintf(c.writer, "failed to read file %s NeedleBlob %+v: %+v", itemPath, nId, err)
  498. if *c.forcePurging {
  499. return
  500. }
  501. }
  502. }
  503. }
  504. if err = db.Delete(nId); err != nil && *c.verbose {
  505. fmt.Fprintf(c.writer, "failed to nm.delete %s(%+v): %+v", itemPath, nId, err)
  506. }
  507. }); err != nil {
  508. err = fmt.Errorf("failed to readFilerFileIdFile %+v", err)
  509. return
  510. }
  511. var orphanFileCount uint64
  512. if err = db.AscendingVisit(func(n needle_map.NeedleValue) error {
  513. if !n.Size.IsValid() {
  514. return nil
  515. }
  516. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s00000000", volumeId, n.Key.String()))
  517. orphanFileCount++
  518. orphanDataSize += uint64(n.Size)
  519. return nil
  520. }); err != nil {
  521. err = fmt.Errorf("failed to AscendingVisit %+v", err)
  522. return
  523. }
  524. if orphanFileCount > 0 {
  525. pct := float64(orphanFileCount*100) / (float64(orphanFileCount + inUseCount))
  526. fmt.Fprintf(c.writer, "dataNode:%s\tvolume:%d\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  527. dataNodeId, volumeId, orphanFileCount+inUseCount, orphanFileCount, pct, orphanDataSize)
  528. }
  529. return
  530. }
  531. type VInfo struct {
  532. server pb.ServerAddress
  533. collection string
  534. isEcVolume bool
  535. isReadOnly bool
  536. }
  537. func (c *commandVolumeFsck) collectVolumeIds() (volumeIdToServer map[string]map[uint32]VInfo, err error) {
  538. if *c.verbose {
  539. fmt.Fprintf(c.writer, "collecting volume id and locations from master ...\n")
  540. }
  541. volumeIdToServer = make(map[string]map[uint32]VInfo)
  542. // collect topology information
  543. topologyInfo, _, err := collectTopologyInfo(c.env, 0)
  544. if err != nil {
  545. return
  546. }
  547. eachDataNode(topologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {
  548. for _, diskInfo := range t.DiskInfos {
  549. dataNodeId := t.GetId()
  550. volumeIdToServer[dataNodeId] = make(map[uint32]VInfo)
  551. for _, vi := range diskInfo.VolumeInfos {
  552. volumeIdToServer[dataNodeId][vi.Id] = VInfo{
  553. server: pb.NewServerAddressFromDataNode(t),
  554. collection: vi.Collection,
  555. isEcVolume: false,
  556. isReadOnly: vi.ReadOnly,
  557. }
  558. }
  559. for _, ecShardInfo := range diskInfo.EcShardInfos {
  560. volumeIdToServer[dataNodeId][ecShardInfo.Id] = VInfo{
  561. server: pb.NewServerAddressFromDataNode(t),
  562. collection: ecShardInfo.Collection,
  563. isEcVolume: true,
  564. isReadOnly: true,
  565. }
  566. }
  567. if *c.verbose {
  568. fmt.Fprintf(c.writer, "dn %+v collected %d volumes and locations.\n", dataNodeId, len(volumeIdToServer[dataNodeId]))
  569. }
  570. }
  571. })
  572. return
  573. }
  574. func (c *commandVolumeFsck) purgeFileIdsForOneVolume(volumeId uint32, fileIds []string) (err error) {
  575. fmt.Fprintf(c.writer, "purging orphan data for volume %d...\n", volumeId)
  576. locations, found := c.env.MasterClient.GetLocations(volumeId)
  577. if !found {
  578. return fmt.Errorf("failed to find volume %d locations", volumeId)
  579. }
  580. resultChan := make(chan []*volume_server_pb.DeleteResult, len(locations))
  581. var wg sync.WaitGroup
  582. for _, location := range locations {
  583. wg.Add(1)
  584. go func(server pb.ServerAddress, fidList []string) {
  585. defer wg.Done()
  586. if deleteResults, deleteErr := operation.DeleteFilesAtOneVolumeServer(server, c.env.option.GrpcDialOption, fidList, false); deleteErr != nil {
  587. err = deleteErr
  588. } else if deleteResults != nil {
  589. resultChan <- deleteResults
  590. }
  591. }(location.ServerAddress(), fileIds)
  592. }
  593. wg.Wait()
  594. close(resultChan)
  595. for results := range resultChan {
  596. for _, result := range results {
  597. if result.Error != "" {
  598. fmt.Fprintf(c.writer, "purge error: %s\n", result.Error)
  599. }
  600. }
  601. }
  602. return
  603. }
  604. func (c *commandVolumeFsck) getCollectFilerFilePath() string {
  605. if *c.collection != "" {
  606. return fmt.Sprintf("%s/%s", c.bucketsPath, *c.collection)
  607. }
  608. return "/"
  609. }
  610. func getVolumeFileIdFile(tempFolder string, dataNodeid string, vid uint32) string {
  611. return filepath.Join(tempFolder, fmt.Sprintf("%s_%d.idx", dataNodeid, vid))
  612. }
  613. func getFilerFileIdFile(tempFolder string, vid uint32) string {
  614. return filepath.Join(tempFolder, fmt.Sprintf("%d.fid", vid))
  615. }
  616. func writeToFile(bytes []byte, fileName string) error {
  617. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  618. dst, err := os.OpenFile(fileName, flags, 0644)
  619. if err != nil {
  620. return nil
  621. }
  622. defer dst.Close()
  623. dst.Write(bytes)
  624. return nil
  625. }
  626. func filterDeletedNeedleFromIdx(arr []byte) bytes.Buffer {
  627. var filteredBuf bytes.Buffer
  628. for i := 0; i < len(arr); i += types.NeedleMapEntrySize {
  629. size := types.BytesToSize(arr[i+types.NeedleIdSize+types.OffsetSize : i+types.NeedleIdSize+types.OffsetSize+types.SizeSize])
  630. if size > 0 {
  631. filteredBuf.Write(arr[i : i+types.NeedleIdSize+types.OffsetSize+types.SizeSize])
  632. }
  633. }
  634. return filteredBuf
  635. }