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.

175 lines
5.0 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package broker
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/golang/protobuf/proto"
  9. "github.com/chrislusf/seaweedfs/weed/filer2"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  12. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  13. )
  14. func (broker *MessageBroker) Subscribe(stream messaging_pb.SeaweedMessaging_SubscribeServer) error {
  15. // process initial request
  16. in, err := stream.Recv()
  17. if err == io.EOF {
  18. return nil
  19. }
  20. if err != nil {
  21. return err
  22. }
  23. var processedTsNs int64
  24. var messageCount int64
  25. subscriberId := in.Init.SubscriberId
  26. // TODO look it up
  27. topicConfig := &messaging_pb.TopicConfiguration{
  28. // IsTransient: true,
  29. }
  30. // get lock
  31. tp := TopicPartition{
  32. Namespace: in.Init.Namespace,
  33. Topic: in.Init.Topic,
  34. Partition: in.Init.Partition,
  35. }
  36. fmt.Printf("+ subscriber %s for %s\n", subscriberId, tp.String())
  37. defer func() {
  38. fmt.Printf("- subscriber %s for %s %d messages last %v\n", subscriberId, tp.String(), messageCount, time.Unix(0, processedTsNs))
  39. }()
  40. lock := broker.topicManager.RequestLock(tp, topicConfig, false)
  41. defer broker.topicManager.ReleaseLock(tp, false)
  42. isConnected := true
  43. var streamLock sync.Mutex // https://github.com/grpc/grpc-go/issues/948
  44. go func() {
  45. lastActiveTime := time.Now().UnixNano()
  46. sleepTime := 1737 * time.Millisecond
  47. for isConnected {
  48. time.Sleep(sleepTime)
  49. if lastActiveTime != processedTsNs {
  50. lastActiveTime = processedTsNs
  51. continue
  52. }
  53. streamLock.Lock()
  54. // println("checking connection health to", subscriberId, tp.String())
  55. if err = stream.Send(&messaging_pb.BrokerMessage{}); err != nil {
  56. isConnected = false
  57. lock.cond.Signal()
  58. }
  59. streamLock.Unlock()
  60. }
  61. }()
  62. lastReadTime := time.Now()
  63. switch in.Init.StartPosition {
  64. case messaging_pb.SubscriberMessage_InitMessage_TIMESTAMP:
  65. lastReadTime = time.Unix(0, in.Init.TimestampNs)
  66. case messaging_pb.SubscriberMessage_InitMessage_LATEST:
  67. case messaging_pb.SubscriberMessage_InitMessage_EARLIEST:
  68. lastReadTime = time.Unix(0, 0)
  69. }
  70. // how to process each message
  71. // an error returned will end the subscription
  72. eachMessageFn := func(m *messaging_pb.Message) error {
  73. streamLock.Lock()
  74. err := stream.Send(&messaging_pb.BrokerMessage{
  75. Data: m,
  76. })
  77. streamLock.Unlock()
  78. if err != nil {
  79. glog.V(0).Infof("=> subscriber %v: %+v", subscriberId, err)
  80. }
  81. return err
  82. }
  83. eachLogEntryFn := func(logEntry *filer_pb.LogEntry) error {
  84. m := &messaging_pb.Message{}
  85. if err = proto.Unmarshal(logEntry.Data, m); err != nil {
  86. glog.Errorf("unexpected unmarshal messaging_pb.Message: %v", err)
  87. return err
  88. }
  89. // fmt.Printf("sending : %d bytes ts %d\n", len(m.Value), logEntry.TsNs)
  90. if err = eachMessageFn(m); err != nil {
  91. glog.Errorf("sending %d bytes to %s: %s", len(m.Value), subscriberId, err)
  92. return err
  93. }
  94. if m.IsClose {
  95. // println("processed EOF")
  96. return io.EOF
  97. }
  98. processedTsNs = logEntry.TsNs
  99. messageCount++
  100. return nil
  101. }
  102. if err := broker.readPersistedLogBuffer(&tp, lastReadTime, eachLogEntryFn); err != nil {
  103. if err != io.EOF {
  104. // println("stopping from persisted logs", err.Error())
  105. return err
  106. }
  107. }
  108. if processedTsNs != 0 {
  109. lastReadTime = time.Unix(0, processedTsNs)
  110. }
  111. // fmt.Printf("subscriber %s read %d on disk log %v\n", subscriberId, messageCount, lastReadTime)
  112. err = lock.logBuffer.LoopProcessLogData(lastReadTime, func() bool {
  113. lock.Mutex.Lock()
  114. lock.cond.Wait()
  115. lock.Mutex.Unlock()
  116. return isConnected
  117. }, eachLogEntryFn)
  118. return err
  119. }
  120. func (broker *MessageBroker) readPersistedLogBuffer(tp *TopicPartition, startTime time.Time, eachLogEntryFn func(logEntry *filer_pb.LogEntry) error) (err error) {
  121. startDate := fmt.Sprintf("%04d-%02d-%02d", startTime.Year(), startTime.Month(), startTime.Day())
  122. startHourMinute := fmt.Sprintf("%02d-%02d.segment", startTime.Hour(), startTime.Minute())
  123. sizeBuf := make([]byte, 4)
  124. startTsNs := startTime.UnixNano()
  125. topicDir := genTopicDir(tp.Namespace, tp.Topic)
  126. partitionSuffix := fmt.Sprintf(".part%02d", tp.Partition)
  127. return filer_pb.List(broker, topicDir, "", func(dayEntry *filer_pb.Entry, isLast bool) error {
  128. dayDir := fmt.Sprintf("%s/%s", topicDir, dayEntry.Name)
  129. return filer_pb.List(broker, dayDir, "", func(hourMinuteEntry *filer_pb.Entry, isLast bool) error {
  130. if dayEntry.Name == startDate {
  131. if strings.Compare(hourMinuteEntry.Name, startHourMinute) < 0 {
  132. return nil
  133. }
  134. }
  135. if !strings.HasSuffix(hourMinuteEntry.Name, partitionSuffix) {
  136. return nil
  137. }
  138. // println("partition", tp.Partition, "processing", dayDir, "/", hourMinuteEntry.Name)
  139. chunkedFileReader := filer2.NewChunkStreamReader(broker, hourMinuteEntry.Chunks)
  140. defer chunkedFileReader.Close()
  141. if err := filer2.ReadEachLogEntry(chunkedFileReader, sizeBuf, startTsNs, eachLogEntryFn); err != nil {
  142. chunkedFileReader.Close()
  143. if err == io.EOF {
  144. return err
  145. }
  146. return fmt.Errorf("reading %s/%s: %v", dayDir, hourMinuteEntry.Name, err)
  147. }
  148. return nil
  149. }, "", false, 24*60)
  150. }, startDate, true, 366)
  151. }