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.

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