/
multifile.go
116 lines (94 loc) · 2.03 KB
/
multifile.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//go:generate ../../../tools/readme_config_includer/generator
package multifile
import (
"bytes"
_ "embed"
"fmt"
"math"
"os"
"path"
"strconv"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
)
//go:embed sample.conf
var sampleConfig string
type MultiFile struct {
BaseDir string
FailEarly bool
Files []File `toml:"file"`
}
type File struct {
Name string `toml:"file"`
Dest string
Conversion string
}
func (*MultiFile) SampleConfig() string {
return sampleConfig
}
func (m *MultiFile) Init() error {
for i, file := range m.Files {
if m.BaseDir != "" {
m.Files[i].Name = path.Join(m.BaseDir, file.Name)
}
if file.Dest == "" {
m.Files[i].Dest = path.Base(file.Name)
}
}
return nil
}
func (m *MultiFile) Gather(acc telegraf.Accumulator) error {
now := time.Now()
fields := make(map[string]interface{})
tags := make(map[string]string)
for _, file := range m.Files {
fileContents, err := os.ReadFile(file.Name)
if err != nil {
if m.FailEarly {
return err
}
continue
}
vStr := string(bytes.TrimSpace(bytes.Trim(fileContents, "\x00")))
if file.Conversion == "tag" {
tags[file.Dest] = vStr
continue
}
var value interface{}
var d int
if _, errfmt := fmt.Sscanf(file.Conversion, "float(%d)", &d); errfmt == nil || file.Conversion == "float" {
var v float64
v, err = strconv.ParseFloat(vStr, 64)
value = v / math.Pow10(d)
}
if file.Conversion == "int" {
value, err = strconv.ParseInt(vStr, 10, 64)
}
if file.Conversion == "string" || file.Conversion == "" {
value = vStr
}
if file.Conversion == "bool" {
value, err = strconv.ParseBool(vStr)
}
if err != nil {
if m.FailEarly {
return err
}
continue
}
if value == nil {
return fmt.Errorf("invalid conversion %v", file.Conversion)
}
fields[file.Dest] = value
}
acc.AddGauge("multifile", fields, tags, now)
return nil
}
func init() {
inputs.Add("multifile", func() telegraf.Input {
return &MultiFile{
FailEarly: true,
}
})
}