command_volume_fsck.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. package shell
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "math"
  9. "os"
  10. "path/filepath"
  11. "sync"
  12. "github.com/chrislusf/seaweedfs/weed/filer"
  13. "github.com/chrislusf/seaweedfs/weed/operation"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  16. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  17. "github.com/chrislusf/seaweedfs/weed/storage/needle_map"
  18. "github.com/chrislusf/seaweedfs/weed/storage/types"
  19. "github.com/chrislusf/seaweedfs/weed/util"
  20. )
  21. func init() {
  22. Commands = append(Commands, &commandVolumeFsck{})
  23. }
  24. type commandVolumeFsck struct {
  25. env *CommandEnv
  26. }
  27. func (c *commandVolumeFsck) Name() string {
  28. return "volume.fsck"
  29. }
  30. func (c *commandVolumeFsck) Help() string {
  31. return `check all volumes to find entries not used by the filer
  32. Important assumption!!!
  33. the system is all used by one filer.
  34. This command works this way:
  35. 1. collect all file ids from all volumes, as set A
  36. 2. collect all file ids from the filer, as set B
  37. 3. find out the set A subtract B
  38. `
  39. }
  40. func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  41. if err = commandEnv.confirmIsLocked(); err != nil {
  42. return
  43. }
  44. fsckCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  45. verbose := fsckCommand.Bool("v", false, "verbose mode")
  46. applyPurging := fsckCommand.Bool("reallyDeleteFromVolume", false, "<expert only> delete data not referenced by the filer")
  47. if err = fsckCommand.Parse(args); err != nil {
  48. return nil
  49. }
  50. c.env = commandEnv
  51. // create a temp folder
  52. tempFolder, err := ioutil.TempDir("", "sw_fsck")
  53. if err != nil {
  54. return fmt.Errorf("failed to create temp folder: %v", err)
  55. }
  56. if *verbose {
  57. fmt.Fprintf(writer, "working directory: %s\n", tempFolder)
  58. }
  59. defer os.RemoveAll(tempFolder)
  60. // collect all volume id locations
  61. volumeIdToVInfo, err := c.collectVolumeIds(*verbose, writer)
  62. if err != nil {
  63. return fmt.Errorf("failed to collect all volume locations: %v", err)
  64. }
  65. // collect each volume file ids
  66. for volumeId, vinfo := range volumeIdToVInfo {
  67. err = c.collectOneVolumeFileIds(tempFolder, volumeId, vinfo, *verbose, writer)
  68. if err != nil {
  69. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, err)
  70. }
  71. }
  72. // collect all filer file ids
  73. if err = c.collectFilerFileIds(tempFolder, volumeIdToVInfo, *verbose, writer); err != nil {
  74. return fmt.Errorf("failed to collect file ids from filer: %v", err)
  75. }
  76. // volume file ids substract filer file ids
  77. var totalInUseCount, totalOrphanChunkCount, totalOrphanDataSize uint64
  78. for volumeId, vinfo := range volumeIdToVInfo {
  79. inUseCount, orphanFileIds, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(tempFolder, volumeId, writer, *verbose)
  80. if checkErr != nil {
  81. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  82. }
  83. totalInUseCount += inUseCount
  84. totalOrphanChunkCount += uint64(len(orphanFileIds))
  85. totalOrphanDataSize += orphanDataSize
  86. if *verbose {
  87. for _, fid := range orphanFileIds {
  88. fmt.Fprintf(writer, "%sxxxxxxxx\n", fid)
  89. }
  90. }
  91. if *applyPurging && len(orphanFileIds) > 0 {
  92. if vinfo.isEcVolume {
  93. fmt.Fprintf(writer, "Skip purging for Erasure Coded volumes.\n")
  94. }
  95. if err = c.purgeFileIdsForOneVolume(volumeId, orphanFileIds, writer); err != nil {
  96. return fmt.Errorf("purge for volume %d: %v\n", volumeId, err)
  97. }
  98. }
  99. }
  100. if totalOrphanChunkCount == 0 {
  101. fmt.Fprintf(writer, "no orphan data\n")
  102. return nil
  103. }
  104. if !*applyPurging {
  105. pct := float64(totalOrphanChunkCount*100) / (float64(totalOrphanChunkCount + totalInUseCount))
  106. fmt.Fprintf(writer, "\nTotal\t\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  107. totalOrphanChunkCount+totalInUseCount, totalOrphanChunkCount, pct, totalOrphanDataSize)
  108. fmt.Fprintf(writer, "This could be normal if multiple filers or no filers are used.\n")
  109. }
  110. return nil
  111. }
  112. func (c *commandVolumeFsck) collectOneVolumeFileIds(tempFolder string, volumeId uint32, vinfo VInfo, verbose bool, writer io.Writer) error {
  113. if verbose {
  114. fmt.Fprintf(writer, "collecting volume %d file ids from %s ...\n", volumeId, vinfo.server)
  115. }
  116. return operation.WithVolumeServerClient(vinfo.server, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  117. ext := ".idx"
  118. if vinfo.isEcVolume {
  119. ext = ".ecx"
  120. }
  121. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  122. VolumeId: volumeId,
  123. Ext: ext,
  124. CompactionRevision: math.MaxUint32,
  125. StopOffset: math.MaxInt64,
  126. Collection: vinfo.collection,
  127. IsEcVolume: vinfo.isEcVolume,
  128. IgnoreSourceFileNotFound: false,
  129. })
  130. if err != nil {
  131. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  132. }
  133. err = writeToFile(copyFileClient, getVolumeFileIdFile(tempFolder, volumeId))
  134. if err != nil {
  135. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, vinfo.server, err)
  136. }
  137. return nil
  138. })
  139. }
  140. func (c *commandVolumeFsck) collectFilerFileIds(tempFolder string, volumeIdToServer map[uint32]VInfo, verbose bool, writer io.Writer) error {
  141. if verbose {
  142. fmt.Fprintf(writer, "collecting file ids from filer ...\n")
  143. }
  144. files := make(map[uint32]*os.File)
  145. for vid := range volumeIdToServer {
  146. dst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  147. if openErr != nil {
  148. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(tempFolder, vid), openErr)
  149. }
  150. files[vid] = dst
  151. }
  152. defer func() {
  153. for _, f := range files {
  154. f.Close()
  155. }
  156. }()
  157. type Item struct {
  158. vid uint32
  159. fileKey uint64
  160. }
  161. return doTraverseBfsAndSaving(c.env, nil, "/", false, func(outputChan chan interface{}) {
  162. buffer := make([]byte, 8)
  163. for item := range outputChan {
  164. i := item.(*Item)
  165. util.Uint64toBytes(buffer, i.fileKey)
  166. files[i.vid].Write(buffer)
  167. }
  168. }, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  169. dChunks, mChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks)
  170. if resolveErr != nil {
  171. return nil
  172. }
  173. dChunks = append(dChunks, mChunks...)
  174. for _, chunk := range dChunks {
  175. outputChan <- &Item{
  176. vid: chunk.Fid.VolumeId,
  177. fileKey: chunk.Fid.FileKey,
  178. }
  179. }
  180. return nil
  181. })
  182. }
  183. func (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(tempFolder string, volumeId uint32, writer io.Writer, verbose bool) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  184. db := needle_map.NewMemDb()
  185. defer db.Close()
  186. if err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, volumeId)); err != nil {
  187. return
  188. }
  189. filerFileIdsData, err := ioutil.ReadFile(getFilerFileIdFile(tempFolder, volumeId))
  190. if err != nil {
  191. return
  192. }
  193. dataLen := len(filerFileIdsData)
  194. if dataLen%8 != 0 {
  195. return 0, nil, 0, fmt.Errorf("filer data is corrupted")
  196. }
  197. for i := 0; i < len(filerFileIdsData); i += 8 {
  198. fileKey := util.BytesToUint64(filerFileIdsData[i : i+8])
  199. db.Delete(types.NeedleId(fileKey))
  200. inUseCount++
  201. }
  202. var orphanFileCount uint64
  203. db.AscendingVisit(func(n needle_map.NeedleValue) error {
  204. // fmt.Printf("%d,%x\n", volumeId, n.Key)
  205. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s", volumeId, n.Key.String()))
  206. orphanFileCount++
  207. orphanDataSize += uint64(n.Size)
  208. return nil
  209. })
  210. if orphanFileCount > 0 {
  211. pct := float64(orphanFileCount*100) / (float64(orphanFileCount + inUseCount))
  212. fmt.Fprintf(writer, "volume:%d\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  213. volumeId, orphanFileCount+inUseCount, orphanFileCount, pct, orphanDataSize)
  214. }
  215. return
  216. }
  217. type VInfo struct {
  218. server string
  219. collection string
  220. isEcVolume bool
  221. }
  222. func (c *commandVolumeFsck) collectVolumeIds(verbose bool, writer io.Writer) (volumeIdToServer map[uint32]VInfo, err error) {
  223. if verbose {
  224. fmt.Fprintf(writer, "collecting volume id and locations from master ...\n")
  225. }
  226. volumeIdToServer = make(map[uint32]VInfo)
  227. var resp *master_pb.VolumeListResponse
  228. err = c.env.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  229. resp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
  230. return err
  231. })
  232. if err != nil {
  233. return
  234. }
  235. eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {
  236. for _, vi := range t.VolumeInfos {
  237. volumeIdToServer[vi.Id] = VInfo{
  238. server: t.Id,
  239. collection: vi.Collection,
  240. isEcVolume: false,
  241. }
  242. }
  243. for _, ecShardInfo := range t.EcShardInfos {
  244. volumeIdToServer[ecShardInfo.Id] = VInfo{
  245. server: t.Id,
  246. collection: ecShardInfo.Collection,
  247. isEcVolume: true,
  248. }
  249. }
  250. })
  251. if verbose {
  252. fmt.Fprintf(writer, "collected %d volumes and locations.\n", len(volumeIdToServer))
  253. }
  254. return
  255. }
  256. func (c *commandVolumeFsck) purgeFileIdsForOneVolume(volumeId uint32, fileIds []string, writer io.Writer) (err error) {
  257. fmt.Fprintf(writer, "purging orphan data for volume %d...\n", volumeId)
  258. locations, found := c.env.MasterClient.GetLocations(volumeId)
  259. if !found {
  260. return fmt.Errorf("failed to find volume %d locations", volumeId)
  261. }
  262. resultChan := make(chan []*volume_server_pb.DeleteResult, len(locations))
  263. var wg sync.WaitGroup
  264. for _, location := range locations {
  265. wg.Add(1)
  266. go func(server string, fidList []string) {
  267. defer wg.Done()
  268. if deleteResults, deleteErr := operation.DeleteFilesAtOneVolumeServer(server, c.env.option.GrpcDialOption, fidList, false); deleteErr != nil {
  269. err = deleteErr
  270. } else if deleteResults != nil {
  271. resultChan <- deleteResults
  272. }
  273. }(location.Url, fileIds)
  274. }
  275. wg.Wait()
  276. close(resultChan)
  277. for results := range resultChan {
  278. for _, result := range results {
  279. if result.Error != "" {
  280. fmt.Fprintf(writer, "purge error: %s\n", result.Error)
  281. }
  282. }
  283. }
  284. return
  285. }
  286. func getVolumeFileIdFile(tempFolder string, vid uint32) string {
  287. return filepath.Join(tempFolder, fmt.Sprintf("%d.idx", vid))
  288. }
  289. func getFilerFileIdFile(tempFolder string, vid uint32) string {
  290. return filepath.Join(tempFolder, fmt.Sprintf("%d.fid", vid))
  291. }
  292. func writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string) error {
  293. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  294. dst, err := os.OpenFile(fileName, flags, 0644)
  295. if err != nil {
  296. return nil
  297. }
  298. defer dst.Close()
  299. for {
  300. resp, receiveErr := client.Recv()
  301. if receiveErr == io.EOF {
  302. break
  303. }
  304. if receiveErr != nil {
  305. return fmt.Errorf("receiving %s: %v", fileName, receiveErr)
  306. }
  307. dst.Write(resp.FileContent)
  308. }
  309. return nil
  310. }