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.

317 lines
10 KiB

3 months ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
  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. }