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.

173 lines
4.9 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
5 years ago
  1. package broker
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/util/log_buffer"
  5. "io"
  6. "strings"
  7. "time"
  8. "github.com/golang/protobuf/proto"
  9. "github.com/chrislusf/seaweedfs/weed/filer"
  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. go func() {
  44. for isConnected {
  45. if _, err := stream.Recv(); err != nil {
  46. // println("disconnecting connection to", subscriberId, tp.String())
  47. isConnected = false
  48. lock.cond.Signal()
  49. }
  50. }
  51. }()
  52. lastReadTime := time.Now()
  53. switch in.Init.StartPosition {
  54. case messaging_pb.SubscriberMessage_InitMessage_TIMESTAMP:
  55. lastReadTime = time.Unix(0, in.Init.TimestampNs)
  56. case messaging_pb.SubscriberMessage_InitMessage_LATEST:
  57. case messaging_pb.SubscriberMessage_InitMessage_EARLIEST:
  58. lastReadTime = time.Unix(0, 0)
  59. }
  60. // how to process each message
  61. // an error returned will end the subscription
  62. eachMessageFn := func(m *messaging_pb.Message) error {
  63. err := stream.Send(&messaging_pb.BrokerMessage{
  64. Data: m,
  65. })
  66. if err != nil {
  67. glog.V(0).Infof("=> subscriber %v: %+v", subscriberId, err)
  68. }
  69. return err
  70. }
  71. eachLogEntryFn := func(logEntry *filer_pb.LogEntry) error {
  72. m := &messaging_pb.Message{}
  73. if err = proto.Unmarshal(logEntry.Data, m); err != nil {
  74. glog.Errorf("unexpected unmarshal messaging_pb.Message: %v", err)
  75. return err
  76. }
  77. // fmt.Printf("sending : %d bytes ts %d\n", len(m.Value), logEntry.TsNs)
  78. if err = eachMessageFn(m); err != nil {
  79. glog.Errorf("sending %d bytes to %s: %s", len(m.Value), subscriberId, err)
  80. return err
  81. }
  82. if m.IsClose {
  83. // println("processed EOF")
  84. return io.EOF
  85. }
  86. processedTsNs = logEntry.TsNs
  87. messageCount++
  88. return nil
  89. }
  90. if err = broker.readPersistedLogBuffer(&tp, lastReadTime, eachLogEntryFn); err != nil {
  91. if err != io.EOF {
  92. // println("stopping from persisted logs", err.Error())
  93. return err
  94. }
  95. }
  96. if processedTsNs != 0 {
  97. lastReadTime = time.Unix(0, processedTsNs)
  98. }
  99. // fmt.Printf("subscriber %s read %d on disk log %v\n", subscriberId, messageCount, lastReadTime)
  100. for {
  101. lastReadTime, err = lock.logBuffer.LoopProcessLogData(lastReadTime, func() bool {
  102. lock.Mutex.Lock()
  103. lock.cond.Wait()
  104. lock.Mutex.Unlock()
  105. return isConnected
  106. }, eachLogEntryFn)
  107. if err != nil {
  108. glog.Errorf("processed to %v: %v", lastReadTime, err)
  109. time.Sleep(3127 * time.Millisecond)
  110. if err != log_buffer.ResumeError {
  111. break
  112. }
  113. }
  114. }
  115. return err
  116. }
  117. func (broker *MessageBroker) readPersistedLogBuffer(tp *TopicPartition, startTime time.Time, eachLogEntryFn func(logEntry *filer_pb.LogEntry) error) (err error) {
  118. startTime = startTime.UTC()
  119. startDate := fmt.Sprintf("%04d-%02d-%02d", startTime.Year(), startTime.Month(), startTime.Day())
  120. startHourMinute := fmt.Sprintf("%02d-%02d.segment", startTime.Hour(), startTime.Minute())
  121. sizeBuf := make([]byte, 4)
  122. startTsNs := startTime.UnixNano()
  123. topicDir := genTopicDir(tp.Namespace, tp.Topic)
  124. partitionSuffix := fmt.Sprintf(".part%02d", tp.Partition)
  125. return filer_pb.List(broker, topicDir, "", func(dayEntry *filer_pb.Entry, isLast bool) error {
  126. dayDir := fmt.Sprintf("%s/%s", topicDir, dayEntry.Name)
  127. return filer_pb.List(broker, dayDir, "", func(hourMinuteEntry *filer_pb.Entry, isLast bool) error {
  128. if dayEntry.Name == startDate {
  129. if strings.Compare(hourMinuteEntry.Name, startHourMinute) < 0 {
  130. return nil
  131. }
  132. }
  133. if !strings.HasSuffix(hourMinuteEntry.Name, partitionSuffix) {
  134. return nil
  135. }
  136. // println("partition", tp.Partition, "processing", dayDir, "/", hourMinuteEntry.Name)
  137. chunkedFileReader := filer.NewChunkStreamReader(broker, hourMinuteEntry.Chunks)
  138. defer chunkedFileReader.Close()
  139. if _, err := filer.ReadEachLogEntry(chunkedFileReader, sizeBuf, startTsNs, eachLogEntryFn); err != nil {
  140. chunkedFileReader.Close()
  141. if err == io.EOF {
  142. return err
  143. }
  144. return fmt.Errorf("reading %s/%s: %v", dayDir, hourMinuteEntry.Name, err)
  145. }
  146. return nil
  147. }, "", false, 24*60)
  148. }, startDate, true, 366)
  149. }