command_volume_fsck.go 23 KB

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