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.

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