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.

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