forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 2
/
unpivot.go
71 lines (58 loc) · 1.42 KB
/
unpivot.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
62
63
64
65
66
67
68
69
70
71
package unpivot
import (
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/processors"
)
const (
description = "Rotate multi field metric into several single field metrics"
sampleConfig = `
## Tag to use for the name.
tag_key = "name"
## Field to use for the name of the value.
value_key = "value"
`
)
type Unpivot struct {
TagKey string `toml:"tag_key"`
ValueKey string `toml:"value_key"`
}
func (p *Unpivot) SampleConfig() string {
return sampleConfig
}
func (p *Unpivot) Description() string {
return description
}
func copyWithoutFields(metric telegraf.Metric) telegraf.Metric {
m := metric.Copy()
fieldKeys := make([]string, 0, len(m.FieldList()))
for _, field := range m.FieldList() {
fieldKeys = append(fieldKeys, field.Key)
}
for _, fk := range fieldKeys {
m.RemoveField(fk)
}
return m
}
func (p *Unpivot) Apply(metrics ...telegraf.Metric) []telegraf.Metric {
fieldCount := 0
for _, m := range metrics {
fieldCount += len(m.FieldList())
}
results := make([]telegraf.Metric, 0, fieldCount)
for _, m := range metrics {
base := copyWithoutFields(m)
for _, field := range m.FieldList() {
newMetric := base.Copy()
newMetric.AddField(p.ValueKey, field.Value)
newMetric.AddTag(p.TagKey, field.Key)
results = append(results, newMetric)
}
m.Accept()
}
return results
}
func init() {
processors.Add("unpivot", func() telegraf.Processor {
return &Unpivot{}
})
}