You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
11 KiB

5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
  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(commandEnv, *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. err = c.findExtraChunksInVolumeServers(volumeIdToVInfo, tempFolder, writer, verbose, applyPurging)
  78. return err
  79. }
  80. func (c *commandVolumeFsck) findExtraChunksInVolumeServers(volumeIdToVInfo map[uint32]VInfo, tempFolder string, writer io.Writer, verbose *bool, applyPurging *bool) (error) {
  81. var totalInUseCount, totalOrphanChunkCount, totalOrphanDataSize uint64
  82. for volumeId, vinfo := range volumeIdToVInfo {
  83. inUseCount, orphanFileIds, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(tempFolder, volumeId, writer, *verbose)
  84. if checkErr != nil {
  85. return fmt.Errorf("failed to collect file ids from volume %d on %s: %v", volumeId, vinfo.server, checkErr)
  86. }
  87. totalInUseCount += inUseCount
  88. totalOrphanChunkCount += uint64(len(orphanFileIds))
  89. totalOrphanDataSize += orphanDataSize
  90. if *verbose {
  91. for _, fid := range orphanFileIds {
  92. fmt.Fprintf(writer, "%sxxxxxxxx\n", fid)
  93. }
  94. }
  95. if *applyPurging && len(orphanFileIds) > 0 {
  96. if vinfo.isEcVolume {
  97. fmt.Fprintf(writer, "Skip purging for Erasure Coded volumes.\n")
  98. }
  99. if err := c.purgeFileIdsForOneVolume(volumeId, orphanFileIds, writer); err != nil {
  100. return fmt.Errorf("purge for volume %d: %v\n", volumeId, err)
  101. }
  102. }
  103. }
  104. if totalOrphanChunkCount == 0 {
  105. fmt.Fprintf(writer, "no orphan data\n")
  106. return nil
  107. }
  108. if !*applyPurging {
  109. pct := float64(totalOrphanChunkCount*100) / (float64(totalOrphanChunkCount + totalInUseCount))
  110. fmt.Fprintf(writer, "\nTotal\t\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  111. totalOrphanChunkCount+totalInUseCount, totalOrphanChunkCount, pct, totalOrphanDataSize)
  112. fmt.Fprintf(writer, "This could be normal if multiple filers or no filers are used.\n")
  113. }
  114. return nil
  115. }
  116. func (c *commandVolumeFsck) collectOneVolumeFileIds(tempFolder string, volumeId uint32, vinfo VInfo, verbose bool, writer io.Writer) error {
  117. if verbose {
  118. fmt.Fprintf(writer, "collecting volume %d file ids from %s ...\n", volumeId, vinfo.server)
  119. }
  120. return operation.WithVolumeServerClient(vinfo.server, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
  121. ext := ".idx"
  122. if vinfo.isEcVolume {
  123. ext = ".ecx"
  124. }
  125. copyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  126. VolumeId: volumeId,
  127. Ext: ext,
  128. CompactionRevision: math.MaxUint32,
  129. StopOffset: math.MaxInt64,
  130. Collection: vinfo.collection,
  131. IsEcVolume: vinfo.isEcVolume,
  132. IgnoreSourceFileNotFound: false,
  133. })
  134. if err != nil {
  135. return fmt.Errorf("failed to start copying volume %d%s: %v", volumeId, ext, err)
  136. }
  137. err = writeToFile(copyFileClient, getVolumeFileIdFile(tempFolder, volumeId))
  138. if err != nil {
  139. return fmt.Errorf("failed to copy %d%s from %s: %v", volumeId, ext, vinfo.server, err)
  140. }
  141. return nil
  142. })
  143. }
  144. func (c *commandVolumeFsck) collectFilerFileIds(tempFolder string, volumeIdToServer map[uint32]VInfo, verbose bool, writer io.Writer) error {
  145. if verbose {
  146. fmt.Fprintf(writer, "collecting file ids from filer ...\n")
  147. }
  148. files := make(map[uint32]*os.File)
  149. for vid := range volumeIdToServer {
  150. dst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  151. if openErr != nil {
  152. return fmt.Errorf("failed to create file %s: %v", getFilerFileIdFile(tempFolder, vid), openErr)
  153. }
  154. files[vid] = dst
  155. }
  156. defer func() {
  157. for _, f := range files {
  158. f.Close()
  159. }
  160. }()
  161. type Item struct {
  162. vid uint32
  163. fileKey uint64
  164. }
  165. return doTraverseBfsAndSaving(c.env, nil, "/", false, func(outputChan chan interface{}) {
  166. buffer := make([]byte, 8)
  167. for item := range outputChan {
  168. i := item.(*Item)
  169. util.Uint64toBytes(buffer, i.fileKey)
  170. files[i.vid].Write(buffer)
  171. }
  172. }, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  173. dChunks, mChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.Chunks)
  174. if resolveErr != nil {
  175. return nil
  176. }
  177. dChunks = append(dChunks, mChunks...)
  178. for _, chunk := range dChunks {
  179. outputChan <- &Item{
  180. vid: chunk.Fid.VolumeId,
  181. fileKey: chunk.Fid.FileKey,
  182. }
  183. }
  184. return nil
  185. })
  186. }
  187. func (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(tempFolder string, volumeId uint32, writer io.Writer, verbose bool) (inUseCount uint64, orphanFileIds []string, orphanDataSize uint64, err error) {
  188. db := needle_map.NewMemDb()
  189. defer db.Close()
  190. if err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, volumeId)); err != nil {
  191. return
  192. }
  193. filerFileIdsData, err := ioutil.ReadFile(getFilerFileIdFile(tempFolder, volumeId))
  194. if err != nil {
  195. return
  196. }
  197. dataLen := len(filerFileIdsData)
  198. if dataLen%8 != 0 {
  199. return 0, nil, 0, fmt.Errorf("filer data is corrupted")
  200. }
  201. for i := 0; i < len(filerFileIdsData); i += 8 {
  202. fileKey := util.BytesToUint64(filerFileIdsData[i : i+8])
  203. db.Delete(types.NeedleId(fileKey))
  204. inUseCount++
  205. }
  206. var orphanFileCount uint64
  207. db.AscendingVisit(func(n needle_map.NeedleValue) error {
  208. // fmt.Printf("%d,%x\n", volumeId, n.Key)
  209. orphanFileIds = append(orphanFileIds, fmt.Sprintf("%d,%s", volumeId, n.Key.String()))
  210. orphanFileCount++
  211. orphanDataSize += uint64(n.Size)
  212. return nil
  213. })
  214. if orphanFileCount > 0 {
  215. pct := float64(orphanFileCount*100) / (float64(orphanFileCount + inUseCount))
  216. fmt.Fprintf(writer, "volume:%d\tentries:%d\torphan:%d\t%.2f%%\t%dB\n",
  217. volumeId, orphanFileCount+inUseCount, orphanFileCount, pct, orphanDataSize)
  218. }
  219. return
  220. }
  221. type VInfo struct {
  222. server string
  223. collection string
  224. isEcVolume bool
  225. }
  226. func (c *commandVolumeFsck) collectVolumeIds(commandEnv *CommandEnv, verbose bool, writer io.Writer) (volumeIdToServer map[uint32]VInfo, err error) {
  227. if verbose {
  228. fmt.Fprintf(writer, "collecting volume id and locations from master ...\n")
  229. }
  230. volumeIdToServer = make(map[uint32]VInfo)
  231. // collect topology information
  232. topologyInfo, _, err := collectTopologyInfo(commandEnv)
  233. if err != nil {
  234. return
  235. }
  236. eachDataNode(topologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {
  237. for _, diskInfo := range t.DiskInfos {
  238. for _, vi := range diskInfo.VolumeInfos {
  239. volumeIdToServer[vi.Id] = VInfo{
  240. server: t.Id,
  241. collection: vi.Collection,
  242. isEcVolume: false,
  243. }
  244. }
  245. for _, ecShardInfo := range diskInfo.EcShardInfos {
  246. volumeIdToServer[ecShardInfo.Id] = VInfo{
  247. server: t.Id,
  248. collection: ecShardInfo.Collection,
  249. isEcVolume: true,
  250. }
  251. }
  252. }
  253. })
  254. if verbose {
  255. fmt.Fprintf(writer, "collected %d volumes and locations.\n", len(volumeIdToServer))
  256. }
  257. return
  258. }
  259. func (c *commandVolumeFsck) purgeFileIdsForOneVolume(volumeId uint32, fileIds []string, writer io.Writer) (err error) {
  260. fmt.Fprintf(writer, "purging orphan data for volume %d...\n", volumeId)
  261. locations, found := c.env.MasterClient.GetLocations(volumeId)
  262. if !found {
  263. return fmt.Errorf("failed to find volume %d locations", volumeId)
  264. }
  265. resultChan := make(chan []*volume_server_pb.DeleteResult, len(locations))
  266. var wg sync.WaitGroup
  267. for _, location := range locations {
  268. wg.Add(1)
  269. go func(server string, fidList []string) {
  270. defer wg.Done()
  271. if deleteResults, deleteErr := operation.DeleteFilesAtOneVolumeServer(server, c.env.option.GrpcDialOption, fidList, false); deleteErr != nil {
  272. err = deleteErr
  273. } else if deleteResults != nil {
  274. resultChan <- deleteResults
  275. }
  276. }(location.Url, fileIds)
  277. }
  278. wg.Wait()
  279. close(resultChan)
  280. for results := range resultChan {
  281. for _, result := range results {
  282. if result.Error != "" {
  283. fmt.Fprintf(writer, "purge error: %s\n", result.Error)
  284. }
  285. }
  286. }
  287. return
  288. }
  289. func getVolumeFileIdFile(tempFolder string, vid uint32) string {
  290. return filepath.Join(tempFolder, fmt.Sprintf("%d.idx", vid))
  291. }
  292. func getFilerFileIdFile(tempFolder string, vid uint32) string {
  293. return filepath.Join(tempFolder, fmt.Sprintf("%d.fid", vid))
  294. }
  295. func writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string) error {
  296. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  297. dst, err := os.OpenFile(fileName, flags, 0644)
  298. if err != nil {
  299. return nil
  300. }
  301. defer dst.Close()
  302. for {
  303. resp, receiveErr := client.Recv()
  304. if receiveErr == io.EOF {
  305. break
  306. }
  307. if receiveErr != nil {
  308. return fmt.Errorf("receiving %s: %v", fileName, receiveErr)
  309. }
  310. dst.Write(resp.FileContent)
  311. }
  312. return nil
  313. }