|
| 1 | +package unpivot |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/influxdata/telegraf" |
| 5 | + "github.com/influxdata/telegraf/plugins/processors" |
| 6 | +) |
| 7 | + |
| 8 | +const ( |
| 9 | + description = "Rotate multi field metric into several single field metrics" |
| 10 | + sampleConfig = ` |
| 11 | + ## Tag to use for the name. |
| 12 | + tag_key = "name" |
| 13 | + ## Field to use for the name of the value. |
| 14 | + value_key = "value" |
| 15 | +` |
| 16 | +) |
| 17 | + |
| 18 | +type Unpivot struct { |
| 19 | + TagKey string `toml:"tag_key"` |
| 20 | + ValueKey string `toml:"value_key"` |
| 21 | +} |
| 22 | + |
| 23 | +func (p *Unpivot) SampleConfig() string { |
| 24 | + return sampleConfig |
| 25 | +} |
| 26 | + |
| 27 | +func (p *Unpivot) Description() string { |
| 28 | + return description |
| 29 | +} |
| 30 | + |
| 31 | +func copyWithoutFields(metric telegraf.Metric) telegraf.Metric { |
| 32 | + m := metric.Copy() |
| 33 | + |
| 34 | + fieldKeys := make([]string, 0, len(m.FieldList())) |
| 35 | + for _, field := range m.FieldList() { |
| 36 | + fieldKeys = append(fieldKeys, field.Key) |
| 37 | + } |
| 38 | + |
| 39 | + for _, fk := range fieldKeys { |
| 40 | + m.RemoveField(fk) |
| 41 | + } |
| 42 | + |
| 43 | + return m |
| 44 | +} |
| 45 | + |
| 46 | +func (p *Unpivot) Apply(metrics ...telegraf.Metric) []telegraf.Metric { |
| 47 | + fieldCount := 0 |
| 48 | + for _, m := range metrics { |
| 49 | + fieldCount += len(m.FieldList()) |
| 50 | + } |
| 51 | + |
| 52 | + results := make([]telegraf.Metric, 0, fieldCount) |
| 53 | + |
| 54 | + for _, m := range metrics { |
| 55 | + base := copyWithoutFields(m) |
| 56 | + for _, field := range m.FieldList() { |
| 57 | + newMetric := base.Copy() |
| 58 | + newMetric.AddField(p.ValueKey, field.Value) |
| 59 | + newMetric.AddTag(p.TagKey, field.Key) |
| 60 | + results = append(results, newMetric) |
| 61 | + } |
| 62 | + m.Accept() |
| 63 | + } |
| 64 | + return results |
| 65 | +} |
| 66 | + |
| 67 | +func init() { |
| 68 | + processors.Add("unpivot", func() telegraf.Processor { |
| 69 | + return &Unpivot{} |
| 70 | + }) |
| 71 | +} |
0 commit comments