Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send messages containing metric batches in Kafka output #4517

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 27 additions & 12 deletions plugins/outputs/kafka/kafka.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ func (k *Kafka) GetTopicName(metric telegraf.Metric) string {
default:
topicName = k.Topic
}

return topicName
}

Expand Down Expand Up @@ -290,22 +291,37 @@ func (k *Kafka) routingKey(metric telegraf.Metric) string {
}

func (k *Kafka) Write(metrics []telegraf.Metric) error {
msgs := make([]*sarama.ProducerMessage, 0, len(metrics))
batches := make(map[string]map[string][]telegraf.Metric)
for _, metric := range metrics {
buf, err := k.serializer.Serialize(metric)
if err != nil {
return err
topicName := k.GetTopicName(metric)
if _, ok := batches[topicName]; !ok {
batches[topicName] = make(map[string][]telegraf.Metric)
}

m := &sarama.ProducerMessage{
Topic: k.GetTopicName(metric),
Value: sarama.ByteEncoder(buf),
}
key := k.routingKey(metric)
if key != "" {
m.Key = sarama.StringEncoder(key)
if _, ok := batches[topicName][key]; !ok {
batches[topicName][key] = make([]telegraf.Metric, 0)
}
batches[topicName][key] = append(batches[topicName][key], metric)
}

msgs := make([]*sarama.ProducerMessage, 0, len(metrics))
for topicName, v := range batches {
for routingKey, metrics := range v {

buf, err := k.serializer.SerializeBatch(metrics)
if err != nil {
return err
}

m := &sarama.ProducerMessage{
Topic: topicName,
Value: sarama.ByteEncoder(buf),
Key: sarama.StringEncoder(routingKey),
}

msgs = append(msgs, m)
}
msgs = append(msgs, m)
}

err := k.producer.SendMessages(msgs)
Expand All @@ -322,7 +338,6 @@ func (k *Kafka) Write(metrics []telegraf.Metric) error {
}
return err
}

return nil
}

Expand Down