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.

163 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
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/filer"
  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. startTime = startTime.UTC()
  109. startDate := fmt.Sprintf("%04d-%02d-%02d", startTime.Year(), startTime.Month(), startTime.Day())
  110. startHourMinute := fmt.Sprintf("%02d-%02d.segment", startTime.Hour(), startTime.Minute())
  111. sizeBuf := make([]byte, 4)
  112. startTsNs := startTime.UnixNano()
  113. topicDir := genTopicDir(tp.Namespace, tp.Topic)
  114. partitionSuffix := fmt.Sprintf(".part%02d", tp.Partition)
  115. return filer_pb.List(broker, topicDir, "", func(dayEntry *filer_pb.Entry, isLast bool) error {
  116. dayDir := fmt.Sprintf("%s/%s", topicDir, dayEntry.Name)
  117. return filer_pb.List(broker, dayDir, "", func(hourMinuteEntry *filer_pb.Entry, isLast bool) error {
  118. if dayEntry.Name == startDate {
  119. if strings.Compare(hourMinuteEntry.Name, startHourMinute) < 0 {
  120. return nil
  121. }
  122. }
  123. if !strings.HasSuffix(hourMinuteEntry.Name, partitionSuffix) {
  124. return nil
  125. }
  126. // println("partition", tp.Partition, "processing", dayDir, "/", hourMinuteEntry.Name)
  127. chunkedFileReader := filer.NewChunkStreamReader(broker, hourMinuteEntry.Chunks)
  128. defer chunkedFileReader.Close()
  129. if _, err := filer.ReadEachLogEntry(chunkedFileReader, sizeBuf, startTsNs, eachLogEntryFn); err != nil {
  130. chunkedFileReader.Close()
  131. if err == io.EOF {
  132. return err
  133. }
  134. return fmt.Errorf("reading %s/%s: %v", dayDir, hourMinuteEntry.Name, err)
  135. }
  136. return nil
  137. }, "", false, 24*60)
  138. }, startDate, true, 366)
  139. }