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