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.

83 lines
1.9 KiB

  1. package replication
  2. import (
  3. "github.com/Shopify/sarama"
  4. "github.com/chrislusf/seaweedfs/weed/util"
  5. "github.com/golang/protobuf/proto"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "fmt"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. )
  10. func init() {
  11. NotificationInputs = append(NotificationInputs, &KafkaInput{
  12. })
  13. }
  14. type KafkaInput struct {
  15. topic string
  16. consumer sarama.Consumer
  17. messageChan chan *sarama.ConsumerMessage
  18. }
  19. func (k *KafkaInput) GetName() string {
  20. return "kafka"
  21. }
  22. func (k *KafkaInput) Initialize(configuration util.Configuration) error {
  23. glog.V(0).Infof("replication.notification.kafka.hosts: %v\n", configuration.GetStringSlice("hosts"))
  24. glog.V(0).Infof("replication.notification.kafka.topic: %v\n", configuration.GetString("topic"))
  25. return k.initialize(
  26. configuration.GetStringSlice("hosts"),
  27. configuration.GetString("topic"),
  28. )
  29. }
  30. func (k *KafkaInput) initialize(hosts []string, topic string) (err error) {
  31. config := sarama.NewConfig()
  32. config.Consumer.Return.Errors = true
  33. k.consumer, err = sarama.NewConsumer(hosts, config)
  34. if err != nil {
  35. panic(err)
  36. } else {
  37. glog.V(0).Infof("connected to %v", hosts)
  38. }
  39. k.topic = topic
  40. k.messageChan = make(chan *sarama.ConsumerMessage, 1)
  41. partitions, err := k.consumer.Partitions(topic)
  42. if err != nil {
  43. panic(err)
  44. }
  45. for _, partition := range partitions {
  46. partitionConsumer, err := k.consumer.ConsumePartition(topic, partition, sarama.OffsetNewest)
  47. if err != nil {
  48. panic(err)
  49. }
  50. go func() {
  51. for {
  52. select {
  53. case err := <-partitionConsumer.Errors():
  54. fmt.Println(err)
  55. case msg := <-partitionConsumer.Messages():
  56. k.messageChan <- msg
  57. }
  58. }
  59. }()
  60. }
  61. return nil
  62. }
  63. func (k *KafkaInput) ReceiveMessage() (key string, message *filer_pb.EventNotification, err error) {
  64. msg := <-k.messageChan
  65. key = string(msg.Key)
  66. message = &filer_pb.EventNotification{}
  67. err = proto.Unmarshal(msg.Value, message)
  68. return
  69. }