command_volume_fsck.go 24 KB

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