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.

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