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.

284 lines
8.7 KiB

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