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.

733 lines
24 KiB

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