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.

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