2015-06-27 03:56:14 +00:00
|
|
|
package kafka_consumer
|
|
|
|
|
|
|
|
import (
|
2018-11-05 21:34:28 +00:00
|
|
|
"context"
|
2017-03-24 19:03:36 +00:00
|
|
|
"fmt"
|
2015-11-16 20:12:45 +00:00
|
|
|
"log"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2015-06-27 03:56:14 +00:00
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
"github.com/Shopify/sarama"
|
2016-01-27 21:21:36 +00:00
|
|
|
"github.com/influxdata/telegraf"
|
2018-05-04 23:33:23 +00:00
|
|
|
"github.com/influxdata/telegraf/internal/tls"
|
2016-01-20 18:57:35 +00:00
|
|
|
"github.com/influxdata/telegraf/plugins/inputs"
|
2016-02-06 00:36:35 +00:00
|
|
|
"github.com/influxdata/telegraf/plugins/parsers"
|
2018-11-05 21:34:28 +00:00
|
|
|
)
|
2015-11-16 20:12:45 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
const sampleConfig = `
|
|
|
|
## Kafka brokers.
|
2017-06-08 01:22:28 +00:00
|
|
|
brokers = ["localhost:9092"]
|
2019-07-30 03:41:12 +00:00
|
|
|
|
|
|
|
## Topics to consume.
|
2015-11-16 20:12:45 +00:00
|
|
|
topics = ["telegraf"]
|
2019-07-30 03:41:12 +00:00
|
|
|
|
|
|
|
## When set this tag will be added to all metrics with the topic as the value.
|
2018-11-29 00:29:26 +00:00
|
|
|
# topic_tag = ""
|
2018-07-13 20:59:45 +00:00
|
|
|
|
2018-07-13 20:53:56 +00:00
|
|
|
## Optional Client id
|
|
|
|
# client_id = "Telegraf"
|
2017-06-08 01:22:28 +00:00
|
|
|
|
2018-08-17 20:51:21 +00:00
|
|
|
## Set the minimal supported Kafka version. Setting this enables the use of new
|
2019-07-31 04:33:29 +00:00
|
|
|
## Kafka features and APIs. Must be 0.10.2.0 or greater.
|
2018-08-17 20:51:21 +00:00
|
|
|
## ex: version = "1.1.0"
|
|
|
|
# version = ""
|
|
|
|
|
2018-05-04 23:33:23 +00:00
|
|
|
## Optional TLS Config
|
|
|
|
# tls_ca = "/etc/telegraf/ca.pem"
|
|
|
|
# tls_cert = "/etc/telegraf/cert.pem"
|
|
|
|
# tls_key = "/etc/telegraf/key.pem"
|
|
|
|
## Use TLS but skip chain & host verification
|
2017-06-08 01:22:28 +00:00
|
|
|
# insecure_skip_verify = false
|
|
|
|
|
|
|
|
## Optional SASL Config
|
|
|
|
# sasl_username = "kafka"
|
|
|
|
# sasl_password = "secret"
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
## Name of the consumer group.
|
|
|
|
# consumer_group = "telegraf_metrics_consumers"
|
|
|
|
|
|
|
|
## Initial offset position; one of "oldest" or "newest".
|
|
|
|
# offset = "oldest"
|
|
|
|
|
2019-11-27 18:54:29 +00:00
|
|
|
## Consumer group partition assignment strategy; one of "range", "roundrobin" or "sticky".
|
|
|
|
# balance_strategy = "range"
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
## Maximum length of a message to consume, in bytes (default 0/unlimited);
|
|
|
|
## larger messages are dropped
|
|
|
|
max_message_len = 1000000
|
|
|
|
|
|
|
|
## Maximum messages to read from the broker that have not been written by an
|
|
|
|
## output. For best throughput set based on the number of metrics within
|
|
|
|
## each message and the size of the output's metric_batch_size.
|
|
|
|
##
|
|
|
|
## For example, if each message from the queue contains 10 metrics and the
|
|
|
|
## output metric_batch_size is 1000, setting this to 100 will ensure that a
|
|
|
|
## full batch is collected and the write is triggered immediately without
|
|
|
|
## waiting until the next flush_interval.
|
|
|
|
# max_undelivered_messages = 1000
|
2016-02-06 00:36:35 +00:00
|
|
|
|
2016-03-31 23:50:24 +00:00
|
|
|
## Data format to consume.
|
2017-04-11 19:05:39 +00:00
|
|
|
## Each data format has its own unique set of configuration options, read
|
2016-02-18 21:26:51 +00:00
|
|
|
## more about them here:
|
|
|
|
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
|
2016-02-06 00:36:35 +00:00
|
|
|
data_format = "influx"
|
2015-08-26 15:21:39 +00:00
|
|
|
`
|
2015-06-27 03:56:14 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
const (
|
|
|
|
defaultMaxUndeliveredMessages = 1000
|
|
|
|
defaultMaxMessageLen = 1000000
|
|
|
|
defaultConsumerGroup = "telegraf_metrics_consumers"
|
|
|
|
)
|
|
|
|
|
|
|
|
type empty struct{}
|
|
|
|
type semaphore chan empty
|
|
|
|
|
|
|
|
type KafkaConsumer struct {
|
|
|
|
Brokers []string `toml:"brokers"`
|
|
|
|
ClientID string `toml:"client_id"`
|
|
|
|
ConsumerGroup string `toml:"consumer_group"`
|
|
|
|
MaxMessageLen int `toml:"max_message_len"`
|
|
|
|
MaxUndeliveredMessages int `toml:"max_undelivered_messages"`
|
|
|
|
Offset string `toml:"offset"`
|
2019-11-27 18:54:29 +00:00
|
|
|
BalanceStrategy string `toml:"balance_strategy"`
|
2019-07-30 03:41:12 +00:00
|
|
|
Topics []string `toml:"topics"`
|
|
|
|
TopicTag string `toml:"topic_tag"`
|
|
|
|
Version string `toml:"version"`
|
|
|
|
SASLPassword string `toml:"sasl_password"`
|
|
|
|
SASLUsername string `toml:"sasl_username"`
|
|
|
|
|
|
|
|
tls.ClientConfig
|
|
|
|
|
|
|
|
ConsumerCreator ConsumerGroupCreator `toml:"-"`
|
|
|
|
consumer ConsumerGroup
|
|
|
|
config *sarama.Config
|
|
|
|
|
|
|
|
parser parsers.Parser
|
|
|
|
wg sync.WaitGroup
|
|
|
|
cancel context.CancelFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
type ConsumerGroup interface {
|
|
|
|
Consume(ctx context.Context, topics []string, handler sarama.ConsumerGroupHandler) error
|
|
|
|
Errors() <-chan error
|
|
|
|
Close() error
|
|
|
|
}
|
|
|
|
|
|
|
|
type ConsumerGroupCreator interface {
|
|
|
|
Create(brokers []string, group string, config *sarama.Config) (ConsumerGroup, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type SaramaCreator struct{}
|
|
|
|
|
|
|
|
func (*SaramaCreator) Create(brokers []string, group string, config *sarama.Config) (ConsumerGroup, error) {
|
|
|
|
return sarama.NewConsumerGroup(brokers, group, config)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *KafkaConsumer) SampleConfig() string {
|
2015-06-27 03:56:14 +00:00
|
|
|
return sampleConfig
|
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
func (k *KafkaConsumer) Description() string {
|
|
|
|
return "Read metrics from Kafka topics"
|
2016-02-06 00:36:35 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
func (k *KafkaConsumer) SetParser(parser parsers.Parser) {
|
2016-02-06 00:36:35 +00:00
|
|
|
k.parser = parser
|
2015-06-27 03:56:14 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
func (k *KafkaConsumer) Init() error {
|
|
|
|
if k.MaxUndeliveredMessages == 0 {
|
|
|
|
k.MaxUndeliveredMessages = defaultMaxUndeliveredMessages
|
|
|
|
}
|
|
|
|
if k.ConsumerGroup == "" {
|
|
|
|
k.ConsumerGroup = defaultConsumerGroup
|
|
|
|
}
|
2015-06-27 03:56:14 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
config := sarama.NewConfig()
|
|
|
|
config.Consumer.Return.Errors = true
|
2018-08-17 20:51:21 +00:00
|
|
|
|
2019-07-31 04:33:29 +00:00
|
|
|
// Kafka version 0.10.2.0 is required for consumer groups.
|
|
|
|
config.Version = sarama.V0_10_2_0
|
|
|
|
|
2018-08-17 20:51:21 +00:00
|
|
|
if k.Version != "" {
|
|
|
|
version, err := sarama.ParseKafkaVersion(k.Version)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-07-31 04:33:29 +00:00
|
|
|
|
2018-08-17 20:51:21 +00:00
|
|
|
config.Version = version
|
|
|
|
}
|
|
|
|
|
2018-05-04 23:33:23 +00:00
|
|
|
tlsConfig, err := k.ClientConfig.TLSConfig()
|
2017-06-08 01:22:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if tlsConfig != nil {
|
|
|
|
config.Net.TLS.Config = tlsConfig
|
|
|
|
config.Net.TLS.Enable = true
|
|
|
|
}
|
2019-07-30 03:41:12 +00:00
|
|
|
|
2017-06-08 01:22:28 +00:00
|
|
|
if k.SASLUsername != "" && k.SASLPassword != "" {
|
|
|
|
config.Net.SASL.User = k.SASLUsername
|
|
|
|
config.Net.SASL.Password = k.SASLPassword
|
|
|
|
config.Net.SASL.Enable = true
|
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
if k.ClientID != "" {
|
|
|
|
config.ClientID = k.ClientID
|
|
|
|
} else {
|
|
|
|
config.ClientID = "Telegraf"
|
|
|
|
}
|
|
|
|
|
2015-11-16 20:12:45 +00:00
|
|
|
switch strings.ToLower(k.Offset) {
|
|
|
|
case "oldest", "":
|
2017-06-08 01:22:28 +00:00
|
|
|
config.Consumer.Offsets.Initial = sarama.OffsetOldest
|
2015-11-16 20:12:45 +00:00
|
|
|
case "newest":
|
2017-06-08 01:22:28 +00:00
|
|
|
config.Consumer.Offsets.Initial = sarama.OffsetNewest
|
2015-11-16 20:12:45 +00:00
|
|
|
default:
|
2019-07-30 03:41:12 +00:00
|
|
|
return fmt.Errorf("invalid offset %q", k.Offset)
|
2015-11-16 20:12:45 +00:00
|
|
|
}
|
|
|
|
|
2019-11-27 18:54:29 +00:00
|
|
|
switch strings.ToLower(k.BalanceStrategy) {
|
|
|
|
case "range", "":
|
|
|
|
config.Consumer.Group.Rebalance.Strategy = sarama.BalanceStrategyRange
|
|
|
|
case "roundrobin":
|
|
|
|
config.Consumer.Group.Rebalance.Strategy = sarama.BalanceStrategyRoundRobin
|
|
|
|
case "sticky":
|
|
|
|
config.Consumer.Group.Rebalance.Strategy = sarama.BalanceStrategySticky
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid balance strategy %q", k.BalanceStrategy)
|
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
if k.ConsumerCreator == nil {
|
|
|
|
k.ConsumerCreator = &SaramaCreator{}
|
|
|
|
}
|
|
|
|
|
|
|
|
k.config = config
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *KafkaConsumer) Start(acc telegraf.Accumulator) error {
|
|
|
|
var err error
|
|
|
|
k.consumer, err = k.ConsumerCreator.Create(
|
|
|
|
k.Brokers,
|
|
|
|
k.ConsumerGroup,
|
|
|
|
k.config,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2015-06-27 03:56:14 +00:00
|
|
|
}
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
k.cancel = cancel
|
|
|
|
|
|
|
|
// Start consumer goroutine
|
|
|
|
k.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer k.wg.Done()
|
2019-07-30 03:41:12 +00:00
|
|
|
for ctx.Err() == nil {
|
|
|
|
handler := NewConsumerGroupHandler(acc, k.MaxUndeliveredMessages, k.parser)
|
|
|
|
handler.MaxMessageLen = k.MaxMessageLen
|
|
|
|
handler.TopicTag = k.TopicTag
|
|
|
|
err := k.consumer.Consume(ctx, k.Topics, handler)
|
|
|
|
if err != nil {
|
|
|
|
acc.AddError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err = k.consumer.Close()
|
|
|
|
if err != nil {
|
|
|
|
acc.AddError(err)
|
|
|
|
}
|
2018-11-05 21:34:28 +00:00
|
|
|
}()
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
k.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer k.wg.Done()
|
|
|
|
for err := range k.consumer.Errors() {
|
|
|
|
acc.AddError(err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *KafkaConsumer) Gather(acc telegraf.Accumulator) error {
|
2015-11-16 20:12:45 +00:00
|
|
|
return nil
|
|
|
|
}
|
2015-06-27 03:56:14 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
func (k *KafkaConsumer) Stop() {
|
|
|
|
k.cancel()
|
|
|
|
k.wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Message is an aggregate type binding the Kafka message and the session so
|
|
|
|
// that offsets can be updated.
|
|
|
|
type Message struct {
|
|
|
|
message *sarama.ConsumerMessage
|
|
|
|
session sarama.ConsumerGroupSession
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConsumerGroupHandler(acc telegraf.Accumulator, maxUndelivered int, parser parsers.Parser) *ConsumerGroupHandler {
|
|
|
|
handler := &ConsumerGroupHandler{
|
|
|
|
acc: acc.WithTracking(maxUndelivered),
|
|
|
|
sem: make(chan empty, maxUndelivered),
|
|
|
|
undelivered: make(map[telegraf.TrackingID]Message, maxUndelivered),
|
|
|
|
parser: parser,
|
|
|
|
}
|
|
|
|
return handler
|
|
|
|
}
|
|
|
|
|
|
|
|
// ConsumerGroupHandler is a sarama.ConsumerGroupHandler implementation.
|
|
|
|
type ConsumerGroupHandler struct {
|
|
|
|
MaxMessageLen int
|
|
|
|
TopicTag string
|
|
|
|
|
|
|
|
acc telegraf.TrackingAccumulator
|
|
|
|
sem semaphore
|
|
|
|
parser parsers.Parser
|
|
|
|
wg sync.WaitGroup
|
|
|
|
cancel context.CancelFunc
|
|
|
|
|
|
|
|
mu sync.Mutex
|
|
|
|
undelivered map[telegraf.TrackingID]Message
|
|
|
|
}
|
|
|
|
|
|
|
|
// Setup is called once when a new session is opened. It setups up the handler
|
|
|
|
// and begins processing delivered messages.
|
|
|
|
func (h *ConsumerGroupHandler) Setup(sarama.ConsumerGroupSession) error {
|
|
|
|
h.undelivered = make(map[telegraf.TrackingID]Message)
|
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
h.cancel = cancel
|
2018-11-05 21:34:28 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
h.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer h.wg.Done()
|
|
|
|
h.run(ctx)
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
}
|
2018-11-05 21:34:28 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
// Run processes any delivered metrics during the lifetime of the session.
|
|
|
|
func (h *ConsumerGroupHandler) run(ctx context.Context) error {
|
2015-06-27 03:56:14 +00:00
|
|
|
for {
|
|
|
|
select {
|
2018-11-05 21:34:28 +00:00
|
|
|
case <-ctx.Done():
|
2019-07-30 03:41:12 +00:00
|
|
|
return nil
|
|
|
|
case track := <-h.acc.Delivered():
|
|
|
|
h.onDelivery(track)
|
2015-06-27 03:56:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
func (h *ConsumerGroupHandler) onDelivery(track telegraf.DeliveryInfo) {
|
|
|
|
h.mu.Lock()
|
|
|
|
defer h.mu.Unlock()
|
|
|
|
|
|
|
|
msg, ok := h.undelivered[track.ID()]
|
|
|
|
if !ok {
|
|
|
|
log.Printf("E! [inputs.kafka_consumer] Could not mark message delivered: %d", track.ID())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if track.Delivered() {
|
|
|
|
msg.session.MarkMessage(msg.message, "")
|
|
|
|
}
|
|
|
|
|
|
|
|
delete(h.undelivered, track.ID())
|
|
|
|
<-h.sem
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reserve blocks until there is an available slot for a new message.
|
|
|
|
func (h *ConsumerGroupHandler) Reserve(ctx context.Context) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case h.sem <- empty{}:
|
|
|
|
return nil
|
2018-11-05 21:34:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
func (h *ConsumerGroupHandler) release() {
|
|
|
|
<-h.sem
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle processes a message and if successful saves it to be acknowledged
|
|
|
|
// after delivery.
|
|
|
|
func (h *ConsumerGroupHandler) Handle(session sarama.ConsumerGroupSession, msg *sarama.ConsumerMessage) error {
|
|
|
|
if h.MaxMessageLen != 0 && len(msg.Value) > h.MaxMessageLen {
|
|
|
|
session.MarkMessage(msg, "")
|
|
|
|
h.release()
|
|
|
|
return fmt.Errorf("message exceeds max_message_len (actual %d, max %d)",
|
|
|
|
len(msg.Value), h.MaxMessageLen)
|
2018-11-05 21:34:28 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
metrics, err := h.parser.Parse(msg.Value)
|
2018-11-05 21:34:28 +00:00
|
|
|
if err != nil {
|
2019-07-30 03:41:12 +00:00
|
|
|
h.release()
|
2018-11-05 21:34:28 +00:00
|
|
|
return err
|
|
|
|
}
|
2019-07-30 03:41:12 +00:00
|
|
|
|
|
|
|
if len(h.TopicTag) > 0 {
|
2018-11-29 00:29:26 +00:00
|
|
|
for _, metric := range metrics {
|
2019-07-30 03:41:12 +00:00
|
|
|
metric.AddTag(h.TopicTag, msg.Topic)
|
2018-11-29 00:29:26 +00:00
|
|
|
}
|
|
|
|
}
|
2018-11-05 21:34:28 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
h.mu.Lock()
|
2019-09-06 19:35:33 +00:00
|
|
|
id := h.acc.AddTrackingMetricGroup(metrics)
|
2019-07-30 03:41:12 +00:00
|
|
|
h.undelivered[id] = Message{session: session, message: msg}
|
|
|
|
h.mu.Unlock()
|
2018-11-05 21:34:28 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
// ConsumeClaim is called once each claim in a goroutine and must be
|
|
|
|
// thread-safe. Should run until the claim is closed.
|
|
|
|
func (h *ConsumerGroupHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
|
|
|
|
ctx := session.Context()
|
2018-11-05 21:34:28 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
for {
|
|
|
|
err := h.Reserve(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
2018-11-05 21:34:28 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil
|
|
|
|
case msg, ok := <-claim.Messages():
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
err := h.Handle(session, msg)
|
|
|
|
if err != nil {
|
|
|
|
h.acc.AddError(err)
|
|
|
|
}
|
|
|
|
}
|
2015-11-16 20:12:45 +00:00
|
|
|
}
|
|
|
|
}
|
2015-06-27 03:56:14 +00:00
|
|
|
|
2019-07-30 03:41:12 +00:00
|
|
|
// Cleanup stops the internal goroutine and is called after all ConsumeClaim
|
|
|
|
// functions have completed.
|
|
|
|
func (h *ConsumerGroupHandler) Cleanup(sarama.ConsumerGroupSession) error {
|
|
|
|
h.cancel()
|
|
|
|
h.wg.Wait()
|
2015-11-16 20:12:45 +00:00
|
|
|
return nil
|
2015-06-27 03:56:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
2016-01-27 21:21:36 +00:00
|
|
|
inputs.Add("kafka_consumer", func() telegraf.Input {
|
2019-07-30 03:41:12 +00:00
|
|
|
return &KafkaConsumer{}
|
2015-06-27 03:56:14 +00:00
|
|
|
})
|
|
|
|
}
|