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.

94 lines
2.3 KiB

  1. package broker
  2. import (
  3. "fmt"
  4. "io"
  5. "time"
  6. "github.com/golang/protobuf/proto"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  10. )
  11. func (broker *MessageBroker) Subscribe(stream messaging_pb.SeaweedMessaging_SubscribeServer) error {
  12. // process initial request
  13. in, err := stream.Recv()
  14. if err == io.EOF {
  15. return nil
  16. }
  17. if err != nil {
  18. return err
  19. }
  20. var messageCount int64
  21. subscriberId := in.Init.SubscriberId
  22. fmt.Printf("+ subscriber %s\n", subscriberId)
  23. defer func() {
  24. fmt.Printf("- subscriber %s: %d messages\n", subscriberId, messageCount)
  25. }()
  26. // TODO look it up
  27. topicConfig := &messaging_pb.TopicConfiguration{
  28. IsTransient: true,
  29. }
  30. if err = stream.Send(&messaging_pb.BrokerMessage{
  31. Redirect: nil,
  32. }); err != nil {
  33. return err
  34. }
  35. // get lock
  36. tp := TopicPartition{
  37. Namespace: in.Init.Namespace,
  38. Topic: in.Init.Topic,
  39. Partition: in.Init.Partition,
  40. }
  41. lock := broker.topicLocks.RequestLock(tp, topicConfig, false)
  42. defer broker.topicLocks.ReleaseLock(tp, false)
  43. lastReadTime := time.Now()
  44. switch in.Init.StartPosition {
  45. case messaging_pb.SubscriberMessage_InitMessage_TIMESTAMP:
  46. lastReadTime = time.Unix(0, in.Init.TimestampNs)
  47. case messaging_pb.SubscriberMessage_InitMessage_LATEST:
  48. case messaging_pb.SubscriberMessage_InitMessage_EARLIEST:
  49. }
  50. // how to process each message
  51. // an error returned will end the subscription
  52. eachMessageFn := func(m *messaging_pb.Message) error {
  53. err := stream.Send(&messaging_pb.BrokerMessage{
  54. Data: m,
  55. })
  56. if err != nil {
  57. glog.V(0).Infof("=> subscriber %v: %+v", subscriberId, err)
  58. }
  59. return err
  60. }
  61. messageCount, err = lock.logBuffer.LoopProcessLogData(lastReadTime, func() bool {
  62. lock.Mutex.Lock()
  63. lock.cond.Wait()
  64. lock.Mutex.Unlock()
  65. return true
  66. }, func(logEntry *filer_pb.LogEntry) error {
  67. m := &messaging_pb.Message{}
  68. if err = proto.Unmarshal(logEntry.Data, m); err != nil {
  69. glog.Errorf("unexpected unmarshal messaging_pb.Message: %v", err)
  70. return err
  71. }
  72. // fmt.Printf("sending : %d bytes\n", len(m.Value))
  73. if err = eachMessageFn(m); err != nil {
  74. glog.Errorf("sending %d bytes to %s: %s", len(m.Value), subscriberId, err)
  75. return err
  76. }
  77. return nil
  78. })
  79. return err
  80. }