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.

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