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