filer_grpc_server_sub_meta.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package weed_server
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/golang/protobuf/proto"
  7. "github.com/chrislusf/seaweedfs/weed/filer"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  10. "github.com/chrislusf/seaweedfs/weed/util"
  11. "github.com/chrislusf/seaweedfs/weed/util/log_buffer"
  12. )
  13. const (
  14. // MaxUnsyncedEvents send empty notification with timestamp when certain amount of events have been filtered
  15. MaxUnsyncedEvents = 1e3
  16. )
  17. func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error {
  18. peerAddress := findClientAddress(stream.Context(), 0)
  19. alreadyKnown, clientName := fs.addClient(req.ClientName, peerAddress, req.ClientId)
  20. if alreadyKnown {
  21. return fmt.Errorf("duplicated subscription detected for client %s id %d", clientName, req.ClientId)
  22. }
  23. defer fs.deleteClient(clientName, req.ClientId)
  24. lastReadTime := time.Unix(0, req.SinceNs)
  25. glog.V(0).Infof(" %v starts to subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
  26. eachEventNotificationFn := fs.eachEventNotificationFn(req, stream, clientName)
  27. eachLogEntryFn := eachLogEntryFn(eachEventNotificationFn)
  28. var processedTsNs int64
  29. var readPersistedLogErr error
  30. var readInMemoryLogErr error
  31. for {
  32. glog.V(4).Infof("read on disk %v aggregated subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
  33. processedTsNs, readPersistedLogErr = fs.filer.ReadPersistedLogBuffer(lastReadTime, eachLogEntryFn)
  34. if readPersistedLogErr != nil {
  35. return fmt.Errorf("reading from persisted logs: %v", readPersistedLogErr)
  36. }
  37. if processedTsNs != 0 {
  38. lastReadTime = time.Unix(0, processedTsNs)
  39. }
  40. glog.V(4).Infof("read in memory %v aggregated subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
  41. lastReadTime, readInMemoryLogErr = fs.filer.MetaAggregator.MetaLogBuffer.LoopProcessLogData("aggMeta:"+clientName, lastReadTime, func() bool {
  42. fs.filer.MetaAggregator.ListenersLock.Lock()
  43. fs.filer.MetaAggregator.ListenersCond.Wait()
  44. fs.filer.MetaAggregator.ListenersLock.Unlock()
  45. return true
  46. }, eachLogEntryFn)
  47. if readInMemoryLogErr != nil {
  48. if readInMemoryLogErr == log_buffer.ResumeFromDiskError {
  49. time.Sleep(1127 * time.Millisecond)
  50. continue
  51. }
  52. glog.Errorf("processed to %v: %v", lastReadTime, readInMemoryLogErr)
  53. if readInMemoryLogErr != log_buffer.ResumeError {
  54. break
  55. }
  56. }
  57. time.Sleep(1127 * time.Millisecond)
  58. }
  59. return readInMemoryLogErr
  60. }
  61. func (fs *FilerServer) SubscribeLocalMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeLocalMetadataServer) error {
  62. peerAddress := findClientAddress(stream.Context(), 0)
  63. _, clientName := fs.addClient(req.ClientName, peerAddress, 0)
  64. defer fs.deleteClient(clientName, 0)
  65. lastReadTime := time.Unix(0, req.SinceNs)
  66. glog.V(0).Infof(" %v local subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
  67. eachEventNotificationFn := fs.eachEventNotificationFn(req, stream, clientName)
  68. eachLogEntryFn := eachLogEntryFn(eachEventNotificationFn)
  69. var processedTsNs int64
  70. var readPersistedLogErr error
  71. var readInMemoryLogErr error
  72. for {
  73. // println("reading from persisted logs ...")
  74. glog.V(0).Infof("read on disk %v local subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
  75. processedTsNs, readPersistedLogErr = fs.filer.ReadPersistedLogBuffer(lastReadTime, eachLogEntryFn)
  76. if readPersistedLogErr != nil {
  77. glog.V(0).Infof("read on disk %v local subscribe %s from %+v: %v", clientName, req.PathPrefix, lastReadTime, readPersistedLogErr)
  78. return fmt.Errorf("reading from persisted logs: %v", readPersistedLogErr)
  79. }
  80. if processedTsNs != 0 {
  81. lastReadTime = time.Unix(0, processedTsNs)
  82. } else {
  83. if readInMemoryLogErr == log_buffer.ResumeFromDiskError {
  84. time.Sleep(1127 * time.Millisecond)
  85. continue
  86. }
  87. }
  88. glog.V(0).Infof("read in memory %v local subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
  89. lastReadTime, readInMemoryLogErr = fs.filer.LocalMetaLogBuffer.LoopProcessLogData("localMeta:"+clientName, lastReadTime, func() bool {
  90. fs.listenersLock.Lock()
  91. fs.listenersCond.Wait()
  92. fs.listenersLock.Unlock()
  93. return true
  94. }, eachLogEntryFn)
  95. if readInMemoryLogErr != nil {
  96. time.Sleep(1127 * time.Millisecond)
  97. if readInMemoryLogErr == log_buffer.ResumeFromDiskError {
  98. continue
  99. }
  100. glog.Errorf("processed to %v: %v", lastReadTime, readInMemoryLogErr)
  101. if readInMemoryLogErr != log_buffer.ResumeError {
  102. break
  103. }
  104. }
  105. }
  106. return readInMemoryLogErr
  107. }
  108. func eachLogEntryFn(eachEventNotificationFn func(dirPath string, eventNotification *filer_pb.EventNotification, tsNs int64) error) func(logEntry *filer_pb.LogEntry) error {
  109. return func(logEntry *filer_pb.LogEntry) error {
  110. event := &filer_pb.SubscribeMetadataResponse{}
  111. if err := proto.Unmarshal(logEntry.Data, event); err != nil {
  112. glog.Errorf("unexpected unmarshal filer_pb.SubscribeMetadataResponse: %v", err)
  113. return fmt.Errorf("unexpected unmarshal filer_pb.SubscribeMetadataResponse: %v", err)
  114. }
  115. if err := eachEventNotificationFn(event.Directory, event.EventNotification, event.TsNs); err != nil {
  116. return err
  117. }
  118. return nil
  119. }
  120. }
  121. func (fs *FilerServer) eachEventNotificationFn(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer, clientName string) func(dirPath string, eventNotification *filer_pb.EventNotification, tsNs int64) error {
  122. filtered := 0
  123. return func(dirPath string, eventNotification *filer_pb.EventNotification, tsNs int64) error {
  124. defer func() {
  125. if filtered > MaxUnsyncedEvents {
  126. if err := stream.Send(&filer_pb.SubscribeMetadataResponse{
  127. EventNotification: &filer_pb.EventNotification{},
  128. TsNs: tsNs,
  129. }); err == nil {
  130. filtered = 0
  131. }
  132. }
  133. }()
  134. filtered++
  135. foundSelf := false
  136. for _, sig := range eventNotification.Signatures {
  137. if sig == req.Signature && req.Signature != 0 {
  138. return nil
  139. }
  140. if sig == fs.filer.Signature {
  141. foundSelf = true
  142. }
  143. }
  144. if !foundSelf {
  145. eventNotification.Signatures = append(eventNotification.Signatures, fs.filer.Signature)
  146. }
  147. // get complete path to the file or directory
  148. var entryName string
  149. if eventNotification.OldEntry != nil {
  150. entryName = eventNotification.OldEntry.Name
  151. } else if eventNotification.NewEntry != nil {
  152. entryName = eventNotification.NewEntry.Name
  153. }
  154. fullpath := util.Join(dirPath, entryName)
  155. // skip on filer internal meta logs
  156. if strings.HasPrefix(fullpath, filer.SystemLogDir) {
  157. return nil
  158. }
  159. if hasPrefixIn(fullpath, req.PathPrefixes) {
  160. // good
  161. } else {
  162. if !strings.HasPrefix(fullpath, req.PathPrefix) {
  163. if eventNotification.NewParentPath != "" {
  164. newFullPath := util.Join(eventNotification.NewParentPath, entryName)
  165. if !strings.HasPrefix(newFullPath, req.PathPrefix) {
  166. return nil
  167. }
  168. } else {
  169. return nil
  170. }
  171. }
  172. }
  173. message := &filer_pb.SubscribeMetadataResponse{
  174. Directory: dirPath,
  175. EventNotification: eventNotification,
  176. TsNs: tsNs,
  177. }
  178. // println("sending", dirPath, entryName)
  179. if err := stream.Send(message); err != nil {
  180. glog.V(0).Infof("=> client %v: %+v", clientName, err)
  181. return err
  182. }
  183. filtered = 0
  184. return nil
  185. }
  186. }
  187. func hasPrefixIn(text string, prefixes []string) bool {
  188. for _, p := range prefixes {
  189. if strings.HasPrefix(text, p) {
  190. return true
  191. }
  192. }
  193. return false
  194. }
  195. func (fs *FilerServer) addClient(clientType string, clientAddress string, clientId int32) (alreadyKnown bool, clientName string) {
  196. clientName = clientType + "@" + clientAddress
  197. glog.V(0).Infof("+ listener %v", clientName)
  198. if clientId != 0 {
  199. fs.knownListenersLock.Lock()
  200. _, alreadyKnown = fs.knownListeners[clientId]
  201. fs.knownListenersLock.Unlock()
  202. }
  203. return
  204. }
  205. func (fs *FilerServer) deleteClient(clientName string, clientId int32) {
  206. glog.V(0).Infof("- listener %v", clientName)
  207. if clientId != 0 {
  208. fs.knownListenersLock.Lock()
  209. delete(fs.knownListeners, clientId)
  210. fs.knownListenersLock.Unlock()
  211. }
  212. }