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
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. 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. if *c.collection != "" && vinfo.collection != *c.collection {
  118. delete(volumeIdToVInfo, volumeId)
  119. continue
  120. }
  121. cutoffFrom := time.Now().Add(-*cutoffTimeAgo).UnixNano()
  122. err = c.collectOneVolumeFileIds(dataNodeId, volumeId, vinfo, uint64(cutoffFrom))
  123. if err != nil {
  124. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, err)
  125. }
  126. }
  127. if *c.verbose {
  128. fmt.Fprintf(c.writer, "dn %+v filtred %d volumes and locations.\n", dataNodeId, len(dataNodeVolumeIdToVInfo[dataNodeId]))
  129. }
  130. }
  131. if *c.findMissingChunksInFiler {
  132. // collect all filer file ids and paths
  133. if err = c.collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo, *purgeAbsent, collectMtime); err != nil {
  134. return fmt.Errorf("collectFilerFileIdAndPaths: %v", err)
  135. }
  136. for dataNodeId, volumeIdToVInfo := range dataNodeVolumeIdToVInfo {
  137. // for each volume, check filer file ids
  138. if err = c.findFilerChunksMissingInVolumeServers(volumeIdToVInfo, dataNodeId, *applyPurging); err != nil {
  139. return fmt.Errorf("findFilerChunksMissingInVolumeServers: %v", err)
  140. }
  141. }
  142. } else {
  143. // collect all filer file ids
  144. if err = c.collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo, false, collectMtime); err != nil {
  145. return fmt.Errorf("failed to collect file ids from filer: %v", err)
  146. }
  147. // volume file ids subtract filer file ids
  148. if err = c.findExtraChunksInVolumeServers(dataNodeVolumeIdToVInfo, *applyPurging); err != nil {
  149. return fmt.Errorf("findExtraChunksInVolumeServers: %v", err)
  150. }
  151. }
  152. return nil
  153. }
  154. func (c *commandVolumeFsck) collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo map[string]map[uint32]VInfo, purgeAbsent bool, collectMtime int64) error {
  155. if *c.verbose {
  156. fmt.Fprintf(c.writer, "checking each file from filer path %s...\n", c.getCollectFilerFilePath())
  157. }
  158. files := make(map[uint32]*os.File)
  159. for _, volumeIdToServer := range dataNodeVolumeIdToVInfo {
  160. for vid := range volumeIdToServer {
  161. if _, ok := files[vid]; ok {
  162. continue
  163. }
  164. dst, openErr := os.OpenFile(getFilerFileIdFile(c.tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  165. if openErr != nil {
  166. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(c.tempFolder, vid), openErr)
  167. }
  168. files[vid] = dst
  169. }
  170. }
  171. defer func() {
  172. for _, f := range files {
  173. f.Close()
  174. }
  175. }()
  176. return doTraverseBfsAndSaving(c.env, nil, c.getCollectFilerFilePath(), false,
  177. func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  178. if *c.verbose && entry.Entry.IsDirectory {
  179. fmt.Fprintf(c.writer, "checking directory %s\n", util.NewFullPath(entry.Dir, entry.Entry.Name))
  180. }
  181. dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks, 0, math.MaxInt64)
  182. if resolveErr != nil {
  183. return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
  184. }
  185. dataChunks = append(dataChunks, manifestChunks...)
  186. for _, chunk := range dataChunks {
  187. if chunk.Mtime > collectMtime {
  188. continue
  189. }
  190. outputChan <- &Item{
  191. vid: chunk.Fid.VolumeId,
  192. fileKey: chunk.Fid.FileKey,
  193. cookie: chunk.Fid.Cookie,
  194. path: util.NewFullPath(entry.Dir, entry.Entry.Name),
  195. }
  196. }
  197. return nil
  198. },
  199. func(outputChan chan interface{}) {
  200. buffer := make([]byte, readbufferSize)
  201. for item := range outputChan {
  202. i := item.(*Item)
  203. if f, ok := files[i.vid]; ok {
  204. util.Uint64toBytes(buffer, i.fileKey)
  205. util.Uint32toBytes(buffer[8:], i.cookie)
  206. util.Uint32toBytes(buffer[12:], uint32(len(i.path)))
  207. f.Write(buffer)
  208. f.Write([]byte(i.path))
  209. } else if *c.findMissingChunksInFiler && *c.volumeId == 0 {
  210. fmt.Fprintf(c.writer, "%d,%x%08x %s volume not found\n", i.vid, i.fileKey, i.cookie, i.path)
  211. if purgeAbsent {
  212. fmt.Printf("deleting path %s after volume not found", i.path)
  213. c.httpDelete(i.path)
  214. }
  215. }
  216. }
  217. })
  218. }
  219. func (c *commandVolumeFsck) findFilerChunksMissingInVolumeServers(volumeIdToVInfo map[uint32]VInfo, dataNodeId string, applyPurging bool) error {
  220. for volumeId, vinfo := range volumeIdToVInfo {
  221. checkErr := c.oneVolumeFileIdsCheckOneVolume(dataNodeId, volumeId, applyPurging)
  222. if checkErr != nil {
  223. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  224. }
  225. }
  226. return nil
  227. }
  228. func (c *commandVolumeFsck) findExtraChunksInVolumeServers(dataNodeVolumeIdToVInfo map[string]map[uint32]VInfo, applyPurging bool) error {
  229. var totalInUseCount, totalOrphanChunkCount, totalOrphanDataSize uint64
  230. volumeIdOrphanFileIds := make(map[uint32]map[string]bool)
  231. isSeveralReplicas := make(map[uint32]bool)
  232. isEcVolumeReplicas := make(map[uint32]bool)
  233. isReadOnlyReplicas := make(map[uint32]bool)
  234. serverReplicas := make(map[uint32][]pb.ServerAddress)
  235. for dataNodeId, volumeIdToVInfo := range dataNodeVolumeIdToVInfo {
  236. for volumeId, vinfo := range volumeIdToVInfo {
  237. inUseCount, orphanFileIds, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(dataNodeId, volumeId, vinfo.collection)
  238. if checkErr != nil {
  239. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  240. }
  241. isSeveralReplicas[volumeId] = false
  242. if _, found := volumeIdOrphanFileIds[volumeId]; !found {
  243. volumeIdOrphanFileIds[volumeId] = make(map[string]bool)
  244. } else {
  245. isSeveralReplicas[volumeId] = true
  246. }
  247. for _, fid := range orphanFileIds {
  248. if isSeveralReplicas[volumeId] {
  249. if _, found := volumeIdOrphanFileIds[volumeId][fid]; !found {
  250. continue
  251. }
  252. }
  253. volumeIdOrphanFileIds[volumeId][fid] = isSeveralReplicas[volumeId]
  254. }
  255. totalInUseCount += inUseCount
  256. totalOrphanChunkCount += uint64(len(orphanFileIds))
  257. totalOrphanDataSize += orphanDataSize
  258. if *c.verbose {
  259. for _, fid := range orphanFileIds {
  260. fmt.Fprintf(c.writer, "%s:%s\n", vinfo.collection, fid)
  261. }
  262. }
  263. isEcVolumeReplicas[volumeId] = vinfo.isEcVolume
  264. if isReadOnly, found := isReadOnlyReplicas[volumeId]; !(found && isReadOnly) {
  265. isReadOnlyReplicas[volumeId] = vinfo.isReadOnly
  266. }
  267. serverReplicas[volumeId] = append(serverReplicas[volumeId], vinfo.server)
  268. }
  269. for volumeId, orphanReplicaFileIds := range volumeIdOrphanFileIds {
  270. if !(applyPurging && len(orphanReplicaFileIds) > 0) {
  271. continue
  272. }
  273. orphanFileIds := []string{}
  274. for fid, foundInAllReplicas := range orphanReplicaFileIds {
  275. if !isSeveralReplicas[volumeId] || *c.forcePurging || (isSeveralReplicas[volumeId] && foundInAllReplicas) {
  276. orphanFileIds = append(orphanFileIds, fid)
  277. }
  278. }
  279. if !(len(orphanFileIds) > 0) {
  280. continue
  281. }
  282. if *c.verbose {
  283. fmt.Fprintf(c.writer, "purging process for volume %d.\n", volumeId)
  284. }
  285. if isEcVolumeReplicas[volumeId] {
  286. fmt.Fprintf(c.writer, "skip purging for Erasure Coded volume %d.\n", volumeId)
  287. continue
  288. }
  289. for _, server := range serverReplicas[volumeId] {
  290. needleVID := needle.VolumeId(volumeId)
  291. if isReadOnlyReplicas[volumeId] {
  292. err := markVolumeWritable(c.env.option.GrpcDialOption, needleVID, server, true)
  293. if err != nil {
  294. return fmt.Errorf("mark volume %d read/write: %v", volumeId, err)
  295. }
  296. fmt.Fprintf(c.writer, "temporarily marked %d on server %v writable for forced purge\n", volumeId, server)
  297. defer markVolumeWritable(c.env.option.GrpcDialOption, needleVID, server, false)
  298. fmt.Fprintf(c.writer, "marked %d on server %v writable for forced purge\n", volumeId, server)
  299. }
  300. if *c.verbose {
  301. fmt.Fprintf(c.writer, "purging files from volume %d\n", volumeId)
  302. }
  303. if err := c.purgeFileIdsForOneVolume(volumeId, orphanFileIds); err != nil {
  304. return fmt.Errorf("purging volume %d: %v", volumeId, err)
  305. }
  306. }
  307. }
  308. }
  309. if !applyPurging {
  310. pct := float64(totalOrphanChunkCount*100) / (float64(totalOrphanChunkCount + totalInUseCount))
  311. fmt.Fprintf(c.writer, "\nTotal\t\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  312. totalOrphanChunkCount+totalInUseCount, totalOrphanChunkCount, pct, totalOrphanDataSize)
  313. fmt.Fprintf(c.writer, "This could be normal if multiple filers or no filers are used.\n")
  314. }
  315. if totalOrphanChunkCount == 0 {
  316. fmt.Fprintf(c.writer, "no orphan data\n")
  317. }
  318. return nil
  319. }
  320. func (c *commandVolumeFsck) collectOneVolumeFileIds(dataNodeId string, volumeId uint32, vinfo VInfo, cutoffFrom uint64) error {
  321. if *c.verbose {
  322. fmt.Fprintf(c.writer, "collecting volume %d file ids from %s ...\n", volumeId, vinfo.server)
  323. }
  324. return operation.WithVolumeServerClient(false, vinfo.server, c.env.option.GrpcDialOption,
  325. func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  326. ext := ".idx"
  327. if vinfo.isEcVolume {
  328. ext = ".ecx"
  329. }
  330. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  331. VolumeId: volumeId,
  332. Ext: ext,
  333. CompactionRevision: math.MaxUint32,
  334. StopOffset: math.MaxInt64,
  335. Collection: vinfo.collection,
  336. IsEcVolume: vinfo.isEcVolume,
  337. IgnoreSourceFileNotFound: false,
  338. })
  339. if err != nil {
  340. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  341. }
  342. var buf bytes.Buffer
  343. for {
  344. resp, err := copyFileClient.Recv()
  345. if errors.Is(err, io.EOF) {
  346. break
  347. }
  348. if err != nil {
  349. return err
  350. }
  351. buf.Write(resp.FileContent)
  352. }
  353. if vinfo.isReadOnly == false {
  354. index, err := idx.FirstInvalidIndex(buf.Bytes(),
  355. func(key types.NeedleId, offset types.Offset, size types.Size) (bool, error) {
  356. resp, err := volumeServerClient.ReadNeedleMeta(context.Background(), &volume_server_pb.ReadNeedleMetaRequest{
  357. VolumeId: volumeId,
  358. NeedleId: uint64(key),
  359. Offset: offset.ToActualOffset(),
  360. Size: int32(size),
  361. })
  362. if err != nil {
  363. return false, fmt.Errorf("to read needle meta with id %d from volume %d with error %v", key, volumeId, err)
  364. }
  365. return resp.AppendAtNs <= cutoffFrom, nil
  366. })
  367. if err != nil {
  368. fmt.Fprintf(c.writer, "Failed to search for last valid index on volume %d with error %v", volumeId, err)
  369. } else {
  370. buf.Truncate(index * types.NeedleMapEntrySize)
  371. }
  372. }
  373. idxFilename := getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)
  374. err = writeToFile(buf.Bytes(), idxFilename)
  375. if err != nil {
  376. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, vinfo.server, err)
  377. }
  378. return nil
  379. })
  380. }
  381. type Item struct {
  382. vid uint32
  383. fileKey uint64
  384. cookie uint32
  385. path util.FullPath
  386. }
  387. func (c *commandVolumeFsck) readFilerFileIdFile(volumeId uint32, fn func(needleId types.NeedleId, itemPath util.FullPath)) error {
  388. fp, err := os.Open(getFilerFileIdFile(c.tempFolder, volumeId))
  389. if err != nil {
  390. return err
  391. }
  392. defer fp.Close()
  393. br := bufio.NewReader(fp)
  394. buffer := make([]byte, readbufferSize)
  395. var readSize int
  396. var readErr error
  397. item := &Item{vid: volumeId}
  398. for {
  399. readSize, readErr = io.ReadFull(br, buffer)
  400. if errors.Is(readErr, io.EOF) {
  401. break
  402. }
  403. if readErr != nil {
  404. return readErr
  405. }
  406. if readSize != readbufferSize {
  407. return fmt.Errorf("readSize mismatch")
  408. }
  409. item.fileKey = util.BytesToUint64(buffer[:8])
  410. item.cookie = util.BytesToUint32(buffer[8:12])
  411. pathSize := util.BytesToUint32(buffer[12:16])
  412. pathBytes := make([]byte, int(pathSize))
  413. n, err := io.ReadFull(br, pathBytes)
  414. if err != nil {
  415. fmt.Fprintf(c.writer, "%d,%x%08x in unexpected error: %v\n", volumeId, item.fileKey, item.cookie, err)
  416. }
  417. if n != int(pathSize) {
  418. fmt.Fprintf(c.writer, "%d,%x%08x %d unexpected file name size %d\n", volumeId, item.fileKey, item.cookie, pathSize, n)
  419. }
  420. item.path = util.FullPath(pathBytes)
  421. needleId := types.NeedleId(item.fileKey)
  422. fn(needleId, item.path)
  423. }
  424. return nil
  425. }
  426. func (c *commandVolumeFsck) oneVolumeFileIdsCheckOneVolume(dataNodeId string, volumeId uint32, applyPurging bool) (err error) {
  427. if *c.verbose {
  428. fmt.Fprintf(c.writer, "find missing file chunks in dataNodeId %s volume %d ...\n", dataNodeId, volumeId)
  429. }
  430. db := needle_map.NewMemDb()
  431. defer db.Close()
  432. if err = db.LoadFromIdx(getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)); err != nil {
  433. return
  434. }
  435. if err = c.readFilerFileIdFile(volumeId, func(needleId types.NeedleId, itemPath util.FullPath) {
  436. if _, found := db.Get(needleId); !found {
  437. fmt.Fprintf(c.writer, "%s\n", itemPath)
  438. if applyPurging {
  439. c.httpDelete(itemPath)
  440. }
  441. }
  442. }); err != nil {
  443. return
  444. }
  445. return nil
  446. }
  447. func (c *commandVolumeFsck) httpDelete(path util.FullPath) {
  448. req, err := http.NewRequest(http.MethodDelete, "", nil)
  449. req.URL = &url.URL{
  450. Scheme: "http",
  451. Host: c.env.option.FilerAddress.ToHttpAddress(),
  452. Path: string(path),
  453. }
  454. if *c.verbose {
  455. fmt.Fprintf(c.writer, "full HTTP delete request to be sent: %v\n", req)
  456. }
  457. if err != nil {
  458. fmt.Fprintf(c.writer, "HTTP delete request error: %v\n", err)
  459. }
  460. client := &http.Client{}
  461. resp, err := client.Do(req)
  462. if err != nil {
  463. fmt.Fprintf(c.writer, "DELETE fetch error: %v\n", err)
  464. }
  465. defer resp.Body.Close()
  466. _, err = ioutil.ReadAll(resp.Body)
  467. if err != nil {
  468. fmt.Fprintf(c.writer, "DELETE response error: %v\n", err)
  469. }
  470. if *c.verbose {
  471. fmt.Fprintln(c.writer, "delete response Status : ", resp.Status)
  472. fmt.Fprintln(c.writer, "delete response Headers : ", resp.Header)
  473. }
  474. }
  475. func (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(dataNodeId string, volumeId uint32, collection string) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  476. db := needle_map.NewMemDb()
  477. defer db.Close()
  478. if err = db.LoadFromIdx(getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)); err != nil {
  479. err = fmt.Errorf("failed to LoadFromIdx %+v", err)
  480. return
  481. }
  482. volumeAddr := pb.NewServerAddressWithGrpcPort(dataNodeId, 0)
  483. if err = c.readFilerFileIdFile(volumeId, func(nId types.NeedleId, itemPath util.FullPath) {
  484. inUseCount++
  485. if *c.verifyNeedle {
  486. if v, ok := db.Get(nId); ok && v.Size.IsValid() {
  487. newSize := types.Size(verifyProbeBlobSize)
  488. if v.Size > newSize {
  489. v.Size = newSize
  490. }
  491. if _, err := readSourceNeedleBlob(c.env.option.GrpcDialOption, volumeAddr, volumeId, *v); err != nil {
  492. fmt.Fprintf(c.writer, "failed to read file %s NeedleBlob %+v: %+v", itemPath, nId, err)
  493. if *c.forcePurging {
  494. return
  495. }
  496. }
  497. }
  498. }
  499. if err = db.Delete(nId); err != nil && *c.verbose {
  500. fmt.Fprintf(c.writer, "failed to nm.delete %s(%+v): %+v", itemPath, nId, err)
  501. }
  502. }); err != nil {
  503. err = fmt.Errorf("failed to readFilerFileIdFile %+v", err)
  504. return
  505. }
  506. var orphanFileCount uint64
  507. if err = db.AscendingVisit(func(n needle_map.NeedleValue) error {
  508. if !n.Size.IsValid() {
  509. return nil
  510. }
  511. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s00000000", volumeId, n.Key.String()))
  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. }