Skip to content

Commit 0a06dd2

Browse files
committed
feat(outputs.nats): rebase off master, refactored tests and moved layout handling into its own file
1 parent 6f5d885 commit 0a06dd2

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package nats
2+
3+
import (
4+
"text/template/parse"
5+
6+
"github.com/influxdata/telegraf"
7+
)
8+
9+
type subMsgPair struct {
10+
subject string
11+
metric telegraf.Metric
12+
}
13+
type metricSubjectTmplCtx struct {
14+
Name string
15+
getTag func(string) string
16+
getField func() string
17+
}
18+
19+
func (m metricSubjectTmplCtx) GetTag(key string) string {
20+
return m.getTag(key)
21+
}
22+
23+
func (m metricSubjectTmplCtx) Field() string {
24+
return m.getField()
25+
}
26+
27+
func createmetricSubjectTmplCtx(metric telegraf.Metric) metricSubjectTmplCtx {
28+
return metricSubjectTmplCtx{
29+
Name: metric.Name(),
30+
getTag: func(key string) string {
31+
tagList := metric.TagList()
32+
for _, tag := range tagList {
33+
if tag.Key == key {
34+
return tag.Value
35+
}
36+
}
37+
return ""
38+
},
39+
getField: func() string {
40+
fields := metric.FieldList()
41+
if len(fields) == 0 {
42+
return "emptyFields"
43+
}
44+
if len(fields) > 1 {
45+
return "tooManyFields"
46+
}
47+
48+
return fields[0].Key
49+
},
50+
}
51+
}
52+
53+
// Check the template for any references to `.Field`.
54+
// If the template includes a `.Field` reference, we will need to split the metric
55+
// into separate messages based on the field.
56+
func usesFieldField(node parse.Node) bool {
57+
switch n := node.(type) {
58+
case *parse.ListNode:
59+
for _, sub := range n.Nodes {
60+
if usesFieldField(sub) {
61+
return true
62+
}
63+
}
64+
case *parse.ActionNode:
65+
return usesFieldField(n.Pipe)
66+
case *parse.PipeNode:
67+
for _, cmd := range n.Cmds {
68+
if usesFieldField(cmd) {
69+
return true
70+
}
71+
}
72+
case *parse.CommandNode:
73+
for _, arg := range n.Args {
74+
if usesFieldField(arg) {
75+
return true
76+
}
77+
}
78+
case *parse.FieldNode:
79+
// .Field will be represented as []string{"Field"}
80+
return len(n.Ident) == 1 && n.Ident[0] == "Field"
81+
}
82+
return false
83+
}
84+
85+
// splitMetricByField will create a new metric that only contains the specified field.
86+
// This is used when the user wants to include the field name in the subject.
87+
func splitMetricByField(metric telegraf.Metric, field string) telegraf.Metric {
88+
metricCopy := metric.Copy()
89+
90+
for _, f := range metric.FieldList() {
91+
if f.Key != field {
92+
// Remove all fields that are not the specified field
93+
metricCopy.RemoveField(f.Key)
94+
}
95+
}
96+
97+
return metricCopy
98+
}

0 commit comments

Comments
 (0)