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.

717 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. 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. fileredBuf := filterDeletedNeedleFromIdx(buf.Bytes())
  354. if vinfo.isReadOnly == false {
  355. index, err := idx.FirstInvalidIndex(fileredBuf.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.LastModified <= 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. fileredBuf.Truncate(index * types.NeedleMapEntrySize)
  372. }
  373. }
  374. idxFilename := getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)
  375. err = writeToFile(fileredBuf.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, collection string) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  477. db := needle_map.NewMemDb()
  478. defer db.Close()
  479. if err = db.LoadFromIdx(getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)); err != nil {
  480. err = fmt.Errorf("failed to LoadFromIdx %+v", err)
  481. return
  482. }
  483. volumeAddr := pb.NewServerAddressWithGrpcPort(dataNodeId, 0)
  484. if err = c.readFilerFileIdFile(volumeId, func(nId types.NeedleId, itemPath util.FullPath) {
  485. inUseCount++
  486. if *c.verifyNeedle {
  487. if v, ok := db.Get(nId); ok && v.Size.IsValid() {
  488. newSize := types.Size(verifyProbeBlobSize)
  489. if v.Size > newSize {
  490. v.Size = newSize
  491. }
  492. if _, err := readSourceNeedleBlob(c.env.option.GrpcDialOption, volumeAddr, volumeId, *v); err != nil {
  493. fmt.Fprintf(c.writer, "failed to read file %s NeedleBlob %+v: %+v", itemPath, nId, err)
  494. if *c.forcePurging {
  495. return
  496. }
  497. }
  498. }
  499. }
  500. if err = db.Delete(nId); err != nil && *c.verbose {
  501. fmt.Fprintf(c.writer, "failed to nm.delete %s(%+v): %+v", itemPath, nId, err)
  502. }
  503. }); err != nil {
  504. err = fmt.Errorf("failed to readFilerFileIdFile %+v", err)
  505. return
  506. }
  507. var orphanFileCount uint64
  508. if err = db.AscendingVisit(func(n needle_map.NeedleValue) error {
  509. if !n.Size.IsValid() {
  510. return nil
  511. }
  512. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s00000000", volumeId, n.Key.String()))
  513. orphanFileCount++
  514. orphanDataSize += uint64(n.Size)
  515. return nil
  516. }); err != nil {
  517. err = fmt.Errorf("failed to AscendingVisit %+v", err)
  518. return
  519. }
  520. if orphanFileCount > 0 {
  521. pct := float64(orphanFileCount*100) / (float64(orphanFileCount + inUseCount))
  522. fmt.Fprintf(c.writer, "dataNode:%s\tvolume:%d\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  523. dataNodeId, volumeId, orphanFileCount+inUseCount, orphanFileCount, pct, orphanDataSize)
  524. }
  525. return
  526. }
  527. type VInfo struct {
  528. server pb.ServerAddress
  529. collection string
  530. isEcVolume bool
  531. isReadOnly bool
  532. }
  533. func (c *commandVolumeFsck) collectVolumeIds() (volumeIdToServer map[string]map[uint32]VInfo, err error) {
  534. if *c.verbose {
  535. fmt.Fprintf(c.writer, "collecting volume id and locations from master ...\n")
  536. }
  537. volumeIdToServer = make(map[string]map[uint32]VInfo)
  538. // collect topology information
  539. topologyInfo, _, err := collectTopologyInfo(c.env, 0)
  540. if err != nil {
  541. return
  542. }
  543. eachDataNode(topologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {
  544. for _, diskInfo := range t.DiskInfos {
  545. dataNodeId := t.GetId()
  546. volumeIdToServer[dataNodeId] = make(map[uint32]VInfo)
  547. for _, vi := range diskInfo.VolumeInfos {
  548. volumeIdToServer[dataNodeId][vi.Id] = VInfo{
  549. server: pb.NewServerAddressFromDataNode(t),
  550. collection: vi.Collection,
  551. isEcVolume: false,
  552. isReadOnly: vi.ReadOnly,
  553. }
  554. }
  555. for _, ecShardInfo := range diskInfo.EcShardInfos {
  556. volumeIdToServer[dataNodeId][ecShardInfo.Id] = VInfo{
  557. server: pb.NewServerAddressFromDataNode(t),
  558. collection: ecShardInfo.Collection,
  559. isEcVolume: true,
  560. isReadOnly: true,
  561. }
  562. }
  563. if *c.verbose {
  564. fmt.Fprintf(c.writer, "dn %+v collected %d volumes and locations.\n", dataNodeId, len(volumeIdToServer[dataNodeId]))
  565. }
  566. }
  567. })
  568. return
  569. }
  570. func (c *commandVolumeFsck) purgeFileIdsForOneVolume(volumeId uint32, fileIds []string) (err error) {
  571. fmt.Fprintf(c.writer, "purging orphan data for volume %d...\n", volumeId)
  572. locations, found := c.env.MasterClient.GetLocations(volumeId)
  573. if !found {
  574. return fmt.Errorf("failed to find volume %d locations", volumeId)
  575. }
  576. resultChan := make(chan []*volume_server_pb.DeleteResult, len(locations))
  577. var wg sync.WaitGroup
  578. for _, location := range locations {
  579. wg.Add(1)
  580. go func(server pb.ServerAddress, fidList []string) {
  581. defer wg.Done()
  582. if deleteResults, deleteErr := operation.DeleteFilesAtOneVolumeServer(server, c.env.option.GrpcDialOption, fidList, false); deleteErr != nil {
  583. err = deleteErr
  584. } else if deleteResults != nil {
  585. resultChan <- deleteResults
  586. }
  587. }(location.ServerAddress(), fileIds)
  588. }
  589. wg.Wait()
  590. close(resultChan)
  591. for results := range resultChan {
  592. for _, result := range results {
  593. if result.Error != "" {
  594. fmt.Fprintf(c.writer, "purge error: %s\n", result.Error)
  595. }
  596. }
  597. }
  598. return
  599. }
  600. func (c *commandVolumeFsck) getCollectFilerFilePath() string {
  601. if *c.collection != "" {
  602. return fmt.Sprintf("%s/%s", c.bucketsPath, *c.collection)
  603. }
  604. return "/"
  605. }
  606. func getVolumeFileIdFile(tempFolder string, dataNodeid string, vid uint32) string {
  607. return filepath.Join(tempFolder, fmt.Sprintf("%s_%d.idx", dataNodeid, vid))
  608. }
  609. func getFilerFileIdFile(tempFolder string, vid uint32) string {
  610. return filepath.Join(tempFolder, fmt.Sprintf("%d.fid", vid))
  611. }
  612. func writeToFile(bytes []byte, fileName string) error {
  613. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  614. dst, err := os.OpenFile(fileName, flags, 0644)
  615. if err != nil {
  616. return nil
  617. }
  618. defer dst.Close()
  619. dst.Write(bytes)
  620. return nil
  621. }
  622. func filterDeletedNeedleFromIdx(arr []byte) bytes.Buffer {
  623. var filteredBuf bytes.Buffer
  624. for i := 0; i < len(arr); i += types.NeedleMapEntrySize {
  625. size := types.BytesToSize(arr[i+types.NeedleIdSize+types.OffsetSize : i+types.NeedleIdSize+types.OffsetSize+types.SizeSize])
  626. if size > 0 {
  627. filteredBuf.Write(arr[i : i+types.NeedleIdSize+types.OffsetSize+types.SizeSize])
  628. }
  629. }
  630. return filteredBuf
  631. }