/
defaults.go
56 lines (47 loc) · 1.57 KB
/
defaults.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
//go:generate ../../../tools/readme_config_includer/generator
package defaults
import (
_ "embed"
"strings"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/processors"
)
//go:embed sample.conf
var sampleConfig string
// Defaults is a processor for ensuring certain fields always exist
// on your Metrics with at least a default value.
type Defaults struct {
DefaultFieldsSets map[string]interface{} `toml:"fields"`
}
func (*Defaults) SampleConfig() string {
return sampleConfig
}
// Apply contains the main implementation of this processor.
// For each metric in 'inputMetrics', it goes over each default pair.
// If the field in the pair does not exist on the metric, the associated default is added.
// If the field was found, then, if its value is the empty string or one or more spaces, it is replaced
// by the associated default.
func (def *Defaults) Apply(inputMetrics ...telegraf.Metric) []telegraf.Metric {
for _, metric := range inputMetrics {
for defField, defValue := range def.DefaultFieldsSets {
if maybeCurrent, isSet := metric.GetField(defField); !isSet {
metric.AddField(defField, defValue)
} else if trimmed, isStr := maybeTrimmedString(maybeCurrent); isStr && trimmed == "" {
metric.RemoveField(defField)
metric.AddField(defField, defValue)
}
}
}
return inputMetrics
}
func maybeTrimmedString(v interface{}) (string, bool) {
if value, ok := v.(string); ok {
return strings.TrimSpace(value), true
}
return "", false
}
func init() {
processors.Add("defaults", func() telegraf.Processor {
return &Defaults{}
})
}