command_fs_verify.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package shell
  2. import (
  3. "bytes"
  4. "context"
  5. "flag"
  6. "fmt"
  7. "github.com/seaweedfs/seaweedfs/weed/filer"
  8. "github.com/seaweedfs/seaweedfs/weed/operation"
  9. "github.com/seaweedfs/seaweedfs/weed/pb"
  10. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  11. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  13. "github.com/seaweedfs/seaweedfs/weed/storage"
  14. "github.com/seaweedfs/seaweedfs/weed/util"
  15. "go.uber.org/atomic"
  16. "golang.org/x/exp/slices"
  17. "io"
  18. "math"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. func init() {
  24. Commands = append(Commands, &commandFsVerify{})
  25. }
  26. type commandFsVerify struct {
  27. env *CommandEnv
  28. volumeServers []pb.ServerAddress
  29. volumeIds map[uint32][]pb.ServerAddress
  30. verbose *bool
  31. metadataFromLog *bool
  32. concurrency *int
  33. modifyTimeAgoAtSec int64
  34. writer io.Writer
  35. waitChan map[string]chan struct{}
  36. waitChanLock sync.RWMutex
  37. }
  38. func (c *commandFsVerify) Name() string {
  39. return "fs.verify"
  40. }
  41. func (c *commandFsVerify) Help() string {
  42. return `recursively verify all files under a directory
  43. fs.verify [-v] [-modifyTimeAgo 1h] /buckets/dir
  44. `
  45. }
  46. func (c *commandFsVerify) HasTag(CommandTag) bool {
  47. return false
  48. }
  49. func (c *commandFsVerify) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  50. c.env = commandEnv
  51. c.writer = writer
  52. fsVerifyCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  53. c.verbose = fsVerifyCommand.Bool("v", false, "print out each processed files")
  54. modifyTimeAgo := fsVerifyCommand.Duration("modifyTimeAgo", 0, "only include files after this modify time to verify")
  55. c.concurrency = fsVerifyCommand.Int("concurrency", 0, "number of parallel verification per volume server")
  56. c.metadataFromLog = fsVerifyCommand.Bool("metadataFromLog", false, "Using filer log to get metadata")
  57. if err = fsVerifyCommand.Parse(args); err != nil {
  58. return err
  59. }
  60. path, parseErr := commandEnv.parseUrl(findInputDirectory(fsVerifyCommand.Args()))
  61. if parseErr != nil {
  62. return parseErr
  63. }
  64. c.modifyTimeAgoAtSec = int64(modifyTimeAgo.Seconds())
  65. c.volumeIds = make(map[uint32][]pb.ServerAddress)
  66. c.waitChan = make(map[string]chan struct{})
  67. c.volumeServers = []pb.ServerAddress{}
  68. defer func() {
  69. c.modifyTimeAgoAtSec = 0
  70. c.volumeIds = nil
  71. c.waitChan = nil
  72. c.volumeServers = nil
  73. }()
  74. if err := c.collectVolumeIds(); err != nil {
  75. return parseErr
  76. }
  77. if *c.concurrency > 0 {
  78. for _, volumeServer := range c.volumeServers {
  79. volumeServerStr := string(volumeServer)
  80. c.waitChan[volumeServerStr] = make(chan struct{}, *c.concurrency)
  81. defer close(c.waitChan[volumeServerStr])
  82. }
  83. }
  84. var fCount, eCount uint64
  85. if *c.metadataFromLog {
  86. var wg sync.WaitGroup
  87. fCount, eCount, err = c.verifyProcessMetadata(path, &wg)
  88. wg.Wait()
  89. if err != nil {
  90. return err
  91. }
  92. } else {
  93. fCount, eCount, err = c.verifyTraverseBfs(path)
  94. }
  95. fmt.Fprintf(writer, "verified %d files, error %d files \n", fCount, eCount)
  96. return err
  97. }
  98. func (c *commandFsVerify) collectVolumeIds() error {
  99. topologyInfo, _, err := collectTopologyInfo(c.env, 0)
  100. if err != nil {
  101. return err
  102. }
  103. eachDataNode(topologyInfo, func(dc string, rack RackId, nodeInfo *master_pb.DataNodeInfo) {
  104. for _, diskInfo := range nodeInfo.DiskInfos {
  105. for _, vi := range diskInfo.VolumeInfos {
  106. volumeServer := pb.NewServerAddressFromDataNode(nodeInfo)
  107. c.volumeIds[vi.Id] = append(c.volumeIds[vi.Id], volumeServer)
  108. if !slices.Contains(c.volumeServers, volumeServer) {
  109. c.volumeServers = append(c.volumeServers, volumeServer)
  110. }
  111. }
  112. for _, vi := range diskInfo.EcShardInfos {
  113. volumeServer := pb.NewServerAddressFromDataNode(nodeInfo)
  114. c.volumeIds[vi.Id] = append(c.volumeIds[vi.Id], volumeServer)
  115. if !slices.Contains(c.volumeServers, volumeServer) {
  116. c.volumeServers = append(c.volumeServers, volumeServer)
  117. }
  118. }
  119. }
  120. })
  121. return nil
  122. }
  123. func (c *commandFsVerify) verifyChunk(volumeServer pb.ServerAddress, fileId *filer_pb.FileId) error {
  124. err := operation.WithVolumeServerClient(false, volumeServer, c.env.option.GrpcDialOption,
  125. func(client volume_server_pb.VolumeServerClient) error {
  126. _, err := client.VolumeNeedleStatus(context.Background(),
  127. &volume_server_pb.VolumeNeedleStatusRequest{
  128. VolumeId: fileId.VolumeId,
  129. NeedleId: fileId.FileKey})
  130. return err
  131. },
  132. )
  133. if err != nil && !strings.Contains(err.Error(), storage.ErrorDeleted.Error()) {
  134. return err
  135. }
  136. return nil
  137. }
  138. type ItemEntry struct {
  139. chunks []*filer_pb.FileChunk
  140. path util.FullPath
  141. }
  142. func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup) (fileCount uint64, errCount uint64, err error) {
  143. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  144. message := resp.EventNotification
  145. if resp.EventNotification.NewEntry == nil {
  146. return nil
  147. }
  148. chunkCount := len(message.NewEntry.Chunks)
  149. if chunkCount == 0 {
  150. return nil
  151. }
  152. entryPath := fmt.Sprintf("%s/%s", message.NewParentPath, message.NewEntry.Name)
  153. errorChunksCount := atomic.NewUint64(0)
  154. if !c.verifyEntry(entryPath, message.NewEntry.Chunks, errorChunksCount, wg) {
  155. if err = c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  156. entryResp, errReq := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
  157. Directory: message.NewParentPath,
  158. Name: message.NewEntry.Name,
  159. })
  160. if errReq != nil {
  161. if strings.HasSuffix(errReq.Error(), "no entry is found in filer store") {
  162. return nil
  163. }
  164. return errReq
  165. }
  166. if entryResp.Entry.Attributes.Mtime == message.NewEntry.Attributes.Mtime &&
  167. bytes.Equal(entryResp.Entry.Attributes.Md5, message.NewEntry.Attributes.Md5) {
  168. fmt.Fprintf(c.writer, "file: %s needles:%d failed:%d\n", entryPath, chunkCount, errorChunksCount.Load())
  169. errCount++
  170. }
  171. return nil
  172. }); err != nil {
  173. return err
  174. }
  175. return nil
  176. }
  177. if *c.verbose {
  178. fmt.Fprintf(c.writer, "file: %s needles:%d verifed\n", entryPath, chunkCount)
  179. }
  180. fileCount++
  181. return nil
  182. }
  183. metadataFollowOption := &pb.MetadataFollowOption{
  184. ClientName: "shell_verify",
  185. ClientId: util.RandomInt32(),
  186. ClientEpoch: 0,
  187. SelfSignature: 0,
  188. PathPrefix: path,
  189. AdditionalPathPrefixes: nil,
  190. DirectoriesToWatch: nil,
  191. StartTsNs: time.Now().Add(-1 * time.Second * time.Duration(c.modifyTimeAgoAtSec)).UnixNano(),
  192. StopTsNs: time.Now().UnixNano(),
  193. EventErrorType: pb.DontLogError,
  194. }
  195. return fileCount, errCount, pb.FollowMetadata(c.env.option.FilerAddress, c.env.option.GrpcDialOption, metadataFollowOption, processEventFn)
  196. }
  197. func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk, errorCount *atomic.Uint64, wg *sync.WaitGroup) bool {
  198. fileMsg := fmt.Sprintf("file:%s", path)
  199. itemIsVerifed := atomic.NewBool(true)
  200. for _, chunk := range chunks {
  201. if volumeIds, ok := c.volumeIds[chunk.Fid.VolumeId]; ok {
  202. for _, volumeServer := range volumeIds {
  203. if *c.concurrency == 0 {
  204. if err := c.verifyChunk(volumeServer, chunk.Fid); err != nil {
  205. if !(*c.metadataFromLog && strings.HasSuffix(err.Error(), "not found")) {
  206. fmt.Fprintf(c.writer, "%s failed verify fileId %s: %+v, at volume server %v\n",
  207. fileMsg, chunk.GetFileIdString(), err, volumeServer)
  208. }
  209. if itemIsVerifed.Load() {
  210. itemIsVerifed.Store(false)
  211. errorCount.Add(1)
  212. }
  213. }
  214. continue
  215. }
  216. c.waitChanLock.RLock()
  217. waitChan, ok := c.waitChan[string(volumeServer)]
  218. c.waitChanLock.RUnlock()
  219. if !ok {
  220. fmt.Fprintf(c.writer, "%s failed to get channel for %s fileId: %s\n",
  221. string(volumeServer), fileMsg, chunk.GetFileIdString())
  222. if itemIsVerifed.Load() {
  223. itemIsVerifed.Store(false)
  224. errorCount.Add(1)
  225. }
  226. continue
  227. }
  228. wg.Add(1)
  229. waitChan <- struct{}{}
  230. go func(fChunk *filer_pb.FileChunk, path string, volumeServer pb.ServerAddress, msg string) {
  231. defer wg.Done()
  232. if err := c.verifyChunk(volumeServer, fChunk.Fid); err != nil {
  233. if !(*c.metadataFromLog && strings.HasSuffix(err.Error(), "not found")) {
  234. fmt.Fprintf(c.writer, "%s failed verify fileId %s: %+v, at volume server %v\n",
  235. msg, fChunk.GetFileIdString(), err, volumeServer)
  236. }
  237. if itemIsVerifed.Load() {
  238. itemIsVerifed.Store(false)
  239. errorCount.Add(1)
  240. }
  241. }
  242. <-waitChan
  243. }(chunk, path, volumeServer, fileMsg)
  244. }
  245. } else {
  246. if !*c.metadataFromLog {
  247. err := fmt.Errorf("volumeId %d not found", chunk.Fid.VolumeId)
  248. fmt.Fprintf(c.writer, "%s failed verify fileId %s: %+v\n",
  249. fileMsg, chunk.GetFileIdString(), err)
  250. }
  251. if itemIsVerifed.Load() {
  252. itemIsVerifed.Store(false)
  253. errorCount.Add(1)
  254. }
  255. break
  256. }
  257. }
  258. return itemIsVerifed.Load()
  259. }
  260. func (c *commandFsVerify) verifyTraverseBfs(path string) (fileCount uint64, errCount uint64, err error) {
  261. timeNowAtSec := time.Now().Unix()
  262. return fileCount, errCount, doTraverseBfsAndSaving(c.env, c.writer, path, false,
  263. func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
  264. if c.modifyTimeAgoAtSec > 0 {
  265. if entry.Entry.Attributes != nil && c.modifyTimeAgoAtSec < timeNowAtSec-entry.Entry.Attributes.Mtime {
  266. return nil
  267. }
  268. }
  269. dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(filer.LookupFn(c.env), entry.Entry.GetChunks(), 0, math.MaxInt64)
  270. if resolveErr != nil {
  271. return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
  272. }
  273. dataChunks = append(dataChunks, manifestChunks...)
  274. if len(dataChunks) > 0 {
  275. outputChan <- &ItemEntry{
  276. chunks: dataChunks,
  277. path: util.NewFullPath(entry.Dir, entry.Entry.Name),
  278. }
  279. }
  280. return nil
  281. },
  282. func(outputChan chan interface{}) {
  283. var wg sync.WaitGroup
  284. itemErrCount := atomic.NewUint64(0)
  285. for itemEntry := range outputChan {
  286. i := itemEntry.(*ItemEntry)
  287. itemPath := string(i.path)
  288. if c.verifyEntry(itemPath, i.chunks, itemErrCount, &wg) {
  289. if *c.verbose {
  290. fmt.Fprintf(c.writer, "file: %s needles:%d verifed\n", itemPath, len(i.chunks))
  291. }
  292. fileCount++
  293. }
  294. }
  295. wg.Wait()
  296. errCount = itemErrCount.Load()
  297. })
  298. }