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.

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