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.

720 lines
23 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. if vinfo.isReadOnly == false {
  350. index, err := idx.FirstInvalidIndex(buf.Bytes(), func(key types.NeedleId, offset types.Offset, size types.Size) (bool, error) {
  351. resp, err := volumeServerClient.ReadNeedleMeta(context.Background(), &volume_server_pb.ReadNeedleMetaRequest{
  352. VolumeId: volumeId,
  353. NeedleId: uint64(key),
  354. Offset: offset.ToActualOffset(),
  355. Size: int32(size),
  356. })
  357. if err != nil {
  358. return false, fmt.Errorf("to read needle meta with id %d from volume %d with error %v", key, volumeId, err)
  359. }
  360. return resp.LastModified <= cutoffFrom, nil
  361. })
  362. if err != nil {
  363. fmt.Fprintf(writer, "Failed to search for last vilad index on volume %d with error %v", volumeId, err)
  364. }
  365. buf.Truncate(index * types.NeedleMapEntrySize)
  366. }
  367. idxFilename := getVolumeFileIdFile(tempFolder, dataNodeId, volumeId)
  368. err = writeToFile(buf.Bytes(), idxFilename)
  369. if err != nil {
  370. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, vinfo.server, err)
  371. }
  372. return nil
  373. })
  374. }
  375. func (c *commandVolumeFsck) collectFilerFileIds(dataNodeVolumeIdToVInfo map[string]map[uint32]VInfo, tempFolder string, writer io.Writer, verbose bool) error {
  376. if verbose {
  377. fmt.Fprintf(writer, "collecting file ids from filer ...\n")
  378. }
  379. files := make(map[uint32]*os.File)
  380. for _, volumeIdToServer := range dataNodeVolumeIdToVInfo {
  381. for vid := range volumeIdToServer {
  382. dst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  383. if openErr != nil {
  384. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(tempFolder, vid), openErr)
  385. }
  386. files[vid] = dst
  387. }
  388. }
  389. defer func() {
  390. for _, f := range files {
  391. f.Close()
  392. }
  393. }()
  394. type Item struct {
  395. vid uint32
  396. fileKey uint64
  397. }
  398. return doTraverseBfsAndSaving(c.env, nil, "/", false, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  399. dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks, 0, math.MaxInt64)
  400. if resolveErr != nil {
  401. if verbose {
  402. fmt.Fprintf(writer, "resolving manifest chunks in %s: %v\n", util.NewFullPath(entry.Dir, entry.Entry.Name), resolveErr)
  403. }
  404. return nil
  405. }
  406. dataChunks = append(dataChunks, manifestChunks...)
  407. for _, chunk := range dataChunks {
  408. outputChan <- &Item{
  409. vid: chunk.Fid.VolumeId,
  410. fileKey: chunk.Fid.FileKey,
  411. }
  412. }
  413. return nil
  414. }, func(outputChan chan interface{}) {
  415. buffer := make([]byte, 8)
  416. for item := range outputChan {
  417. i := item.(*Item)
  418. util.Uint64toBytes(buffer, i.fileKey)
  419. files[i.vid].Write(buffer)
  420. }
  421. })
  422. }
  423. func (c *commandVolumeFsck) oneVolumeFileIdsCheckOneVolume(tempFolder string, dataNodeId string, volumeId uint32, writer io.Writer, verbose bool, applyPurging bool) (err error) {
  424. if verbose {
  425. fmt.Fprintf(writer, "find missing file chunks in dataNodeId %s volume %d ...\n", dataNodeId, volumeId)
  426. }
  427. db := needle_map.NewMemDb()
  428. defer db.Close()
  429. if err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, dataNodeId, volumeId)); err != nil {
  430. return
  431. }
  432. file := getFilerFileIdFile(tempFolder, volumeId)
  433. fp, err := os.Open(file)
  434. if err != nil {
  435. return
  436. }
  437. defer fp.Close()
  438. type Item struct {
  439. fileKey uint64
  440. cookie uint32
  441. path util.FullPath
  442. }
  443. br := bufio.NewReader(fp)
  444. buffer := make([]byte, 16)
  445. item := &Item{}
  446. var readSize int
  447. for {
  448. readSize, err = io.ReadFull(br, buffer)
  449. if err != nil || readSize != 16 {
  450. break
  451. }
  452. item.fileKey = util.BytesToUint64(buffer[:8])
  453. item.cookie = util.BytesToUint32(buffer[8:12])
  454. pathSize := util.BytesToUint32(buffer[12:16])
  455. pathBytes := make([]byte, int(pathSize))
  456. n, err := io.ReadFull(br, pathBytes)
  457. if err != nil {
  458. fmt.Fprintf(writer, "%d,%x%08x in unexpected error: %v\n", volumeId, item.fileKey, item.cookie, err)
  459. }
  460. if n != int(pathSize) {
  461. fmt.Fprintf(writer, "%d,%x%08x %d unexpected file name size %d\n", volumeId, item.fileKey, item.cookie, pathSize, n)
  462. }
  463. item.path = util.FullPath(string(pathBytes))
  464. needleId := types.NeedleId(item.fileKey)
  465. if _, found := db.Get(needleId); !found {
  466. fmt.Fprintf(writer, "%s\n", item.path)
  467. if applyPurging {
  468. // defining the URL this way automatically escapes complex path names
  469. c.httpDelete(item.path, verbose)
  470. }
  471. }
  472. }
  473. return nil
  474. }
  475. func (c *commandVolumeFsck) httpDelete(path util.FullPath, verbose bool) {
  476. req, err := http.NewRequest(http.MethodDelete, "", nil)
  477. req.URL = &url.URL{
  478. Scheme: "http",
  479. Host: c.env.option.FilerAddress.ToHttpAddress(),
  480. Path: string(path),
  481. }
  482. if verbose {
  483. fmt.Printf("full HTTP delete request to be sent: %v\n", req)
  484. }
  485. if err != nil {
  486. fmt.Errorf("HTTP delete request error: %v\n", err)
  487. }
  488. client := &http.Client{}
  489. resp, err := client.Do(req)
  490. if err != nil {
  491. fmt.Errorf("DELETE fetch error: %v\n", err)
  492. }
  493. defer resp.Body.Close()
  494. _, err = ioutil.ReadAll(resp.Body)
  495. if err != nil {
  496. fmt.Errorf("DELETE response error: %v\n", err)
  497. }
  498. if verbose {
  499. fmt.Println("delete response Status : ", resp.Status)
  500. fmt.Println("delete response Headers : ", resp.Header)
  501. }
  502. }
  503. func (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(tempFolder string, dataNodeId string, volumeId uint32, writer io.Writer, verbose bool) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  504. db := needle_map.NewMemDb()
  505. defer db.Close()
  506. if err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, dataNodeId, volumeId)); err != nil {
  507. return
  508. }
  509. filerFileIdsData, err := os.ReadFile(getFilerFileIdFile(tempFolder, volumeId))
  510. if err != nil {
  511. return
  512. }
  513. dataLen := len(filerFileIdsData)
  514. if dataLen%8 != 0 {
  515. return 0, nil, 0, fmt.Errorf("filer data is corrupted")
  516. }
  517. for i := 0; i < len(filerFileIdsData); i += 8 {
  518. fileKey := util.BytesToUint64(filerFileIdsData[i : i+8])
  519. db.Delete(types.NeedleId(fileKey))
  520. inUseCount++
  521. }
  522. var orphanFileCount uint64
  523. db.AscendingVisit(func(n needle_map.NeedleValue) error {
  524. // fmt.Printf("%d,%x\n", volumeId, n.Key)
  525. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s00000000", volumeId, n.Key.String()))
  526. orphanFileCount++
  527. orphanDataSize += uint64(n.Size)
  528. return nil
  529. })
  530. if orphanFileCount > 0 {
  531. pct := float64(orphanFileCount*100) / (float64(orphanFileCount + inUseCount))
  532. fmt.Fprintf(writer, "dataNode:%s\tvolume:%d\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  533. dataNodeId, volumeId, orphanFileCount+inUseCount, orphanFileCount, pct, orphanDataSize)
  534. }
  535. return
  536. }
  537. type VInfo struct {
  538. server pb.ServerAddress
  539. collection string
  540. isEcVolume bool
  541. isReadOnly bool
  542. }
  543. func (c *commandVolumeFsck) collectVolumeIds(commandEnv *CommandEnv, verbose bool, writer io.Writer) (volumeIdToServer map[string]map[uint32]VInfo, err error) {
  544. if verbose {
  545. fmt.Fprintf(writer, "collecting volume id and locations from master ...\n")
  546. }
  547. volumeIdToServer = make(map[string]map[uint32]VInfo)
  548. // collect topology information
  549. topologyInfo, _, err := collectTopologyInfo(commandEnv, 0)
  550. if err != nil {
  551. return
  552. }
  553. eachDataNode(topologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {
  554. for _, diskInfo := range t.DiskInfos {
  555. dataNodeId := t.GetId()
  556. volumeIdToServer[dataNodeId] = make(map[uint32]VInfo)
  557. for _, vi := range diskInfo.VolumeInfos {
  558. volumeIdToServer[dataNodeId][vi.Id] = VInfo{
  559. server: pb.NewServerAddressFromDataNode(t),
  560. collection: vi.Collection,
  561. isEcVolume: false,
  562. isReadOnly: vi.ReadOnly,
  563. }
  564. }
  565. for _, ecShardInfo := range diskInfo.EcShardInfos {
  566. volumeIdToServer[dataNodeId][ecShardInfo.Id] = VInfo{
  567. server: pb.NewServerAddressFromDataNode(t),
  568. collection: ecShardInfo.Collection,
  569. isEcVolume: true,
  570. isReadOnly: true,
  571. }
  572. }
  573. }
  574. })
  575. if verbose {
  576. fmt.Fprintf(writer, "collected %d volumes and locations.\n", len(volumeIdToServer))
  577. }
  578. return
  579. }
  580. func (c *commandVolumeFsck) purgeFileIdsForOneVolume(volumeId uint32, fileIds []string, writer io.Writer) (err error) {
  581. fmt.Fprintf(writer, "purging orphan data for volume %d...\n", volumeId)
  582. locations, found := c.env.MasterClient.GetLocations(volumeId)
  583. if !found {
  584. return fmt.Errorf("failed to find volume %d locations", volumeId)
  585. }
  586. resultChan := make(chan []*volume_server_pb.DeleteResult, len(locations))
  587. var wg sync.WaitGroup
  588. for _, location := range locations {
  589. wg.Add(1)
  590. go func(server pb.ServerAddress, fidList []string) {
  591. defer wg.Done()
  592. if deleteResults, deleteErr := operation.DeleteFilesAtOneVolumeServer(server, c.env.option.GrpcDialOption, fidList, false); deleteErr != nil {
  593. err = deleteErr
  594. } else if deleteResults != nil {
  595. resultChan <- deleteResults
  596. }
  597. }(location.ServerAddress(), fileIds)
  598. }
  599. wg.Wait()
  600. close(resultChan)
  601. for results := range resultChan {
  602. for _, result := range results {
  603. if result.Error != "" {
  604. fmt.Fprintf(writer, "purge error: %s\n", result.Error)
  605. }
  606. }
  607. }
  608. return
  609. }
  610. func getVolumeFileIdFile(tempFolder string, dataNodeid string, vid uint32) string {
  611. return filepath.Join(tempFolder, fmt.Sprintf("%s_%d.idx", dataNodeid, vid))
  612. }
  613. func getFilerFileIdFile(tempFolder string, vid uint32) string {
  614. return filepath.Join(tempFolder, fmt.Sprintf("%d.fid", vid))
  615. }
  616. func writeToFile(bytes []byte, fileName string) error {
  617. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  618. dst, err := os.OpenFile(fileName, flags, 0644)
  619. if err != nil {
  620. return nil
  621. }
  622. defer dst.Close()
  623. dst.Write(bytes)
  624. return nil
  625. }