filer_grpc_server_sub_meta.go 11 KB

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