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.

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