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.

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