/
topic_name_generator.go
61 lines (55 loc) · 1.4 KB
/
topic_name_generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package mqtt
import (
"fmt"
"strings"
"text/template"
"github.com/influxdata/telegraf"
)
type TopicNameGenerator struct {
Hostname string
TopicPrefix string
PluginName string
metric telegraf.Metric
template *template.Template
}
func NewTopicNameGenerator(topicPrefix string, topic string) (*TopicNameGenerator, error) {
tt, err := template.New("topic_name").Parse(topic)
if err != nil {
return nil, err
}
for _, p := range strings.Split(topic, "/") {
if strings.ContainsAny(p, "#+") {
return nil, fmt.Errorf("found forbidden character %s in the topic name %s", p, topic)
}
}
return &TopicNameGenerator{TopicPrefix: topicPrefix, template: tt}, nil
}
func (t *TopicNameGenerator) Tag(key string) string {
tagString, _ := t.metric.GetTag(key)
return tagString
}
func (t *TopicNameGenerator) Generate(hostname string, m telegraf.Metric) (string, error) {
t.Hostname = hostname
t.metric = m
t.PluginName = m.Name()
var b strings.Builder
err := t.template.Execute(&b, t)
if err != nil {
return "", err
}
var ts []string
for _, p := range strings.Split(b.String(), "/") {
if p != "" {
ts = append(ts, p)
}
}
topic := strings.Join(ts, "/")
// This is to keep backward compatibility with previous behaviour where the plugin name was always present
if topic == "" {
return m.Name(), nil
}
if strings.HasPrefix(b.String(), "/") {
topic = "/" + topic
}
return topic, nil
}