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.

361 lines
10 KiB

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