meta_cache_subscribe.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package meta_cache
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/filer"
  8. "github.com/chrislusf/seaweedfs/weed/util/log"
  9. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  10. "github.com/chrislusf/seaweedfs/weed/util"
  11. )
  12. func SubscribeMetaEvents(mc *MetaCache, selfSignature int32, client filer_pb.FilerClient, dir string, lastTsNs int64) error {
  13. processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
  14. message := resp.EventNotification
  15. for _, sig := range message.Signatures {
  16. if sig == selfSignature && selfSignature != 0 {
  17. return nil
  18. }
  19. }
  20. dir := resp.Directory
  21. var oldPath util.FullPath
  22. var newEntry *filer.Entry
  23. if message.OldEntry != nil {
  24. oldPath = util.NewFullPath(dir, message.OldEntry.Name)
  25. log.Tracef("deleting %v", oldPath)
  26. }
  27. if message.NewEntry != nil {
  28. if message.NewParentPath != "" {
  29. dir = message.NewParentPath
  30. }
  31. key := util.NewFullPath(dir, message.NewEntry.Name)
  32. log.Tracef("creating %v", key)
  33. newEntry = filer.FromPbEntry(dir, message.NewEntry)
  34. }
  35. err := mc.AtomicUpdateEntryFromFiler(context.Background(), oldPath, newEntry)
  36. if err == nil && message.OldEntry != nil && message.NewEntry != nil {
  37. key := util.NewFullPath(dir, message.NewEntry.Name)
  38. mc.invalidateFunc(key)
  39. }
  40. return err
  41. }
  42. for {
  43. err := client.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  44. ctx, cancel := context.WithCancel(context.Background())
  45. defer cancel()
  46. stream, err := client.SubscribeMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
  47. ClientName: "mount",
  48. PathPrefix: dir,
  49. SinceNs: lastTsNs,
  50. Signature: selfSignature,
  51. })
  52. if err != nil {
  53. return fmt.Errorf("subscribe: %v", err)
  54. }
  55. for {
  56. resp, listenErr := stream.Recv()
  57. if listenErr == io.EOF {
  58. return nil
  59. }
  60. if listenErr != nil {
  61. return listenErr
  62. }
  63. if err := processEventFn(resp); err != nil {
  64. log.Fatalf("process %v: %v", resp, err)
  65. }
  66. lastTsNs = resp.TsNs
  67. }
  68. })
  69. if err != nil {
  70. log.Errorf("subscribing filer meta change: %v", err)
  71. }
  72. time.Sleep(time.Second)
  73. }
  74. }