/
bond.go
320 lines (292 loc) · 8.14 KB
/
bond.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//go:generate ../../../tools/readme_config_includer/generator
package bond
import (
"bufio"
_ "embed"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
)
// DO NOT REMOVE THE NEXT TWO LINES! This is required to embed the sampleConfig data.
//go:embed sample.conf
var sampleConfig string
// default host proc path
const defaultHostProc = "/proc"
const defaultHostSys = "/sys"
// env host proc variable name
const envProc = "HOST_PROC"
const envSys = "HOST_SYS"
type Bond struct {
HostProc string `toml:"host_proc"`
HostSys string `toml:"host_sys"`
SysDetails bool `toml:"collect_sys_details"`
BondInterfaces []string `toml:"bond_interfaces"`
BondType string
}
type sysFiles struct {
ModeFile string
SlaveFile string
ADPortsFile string
}
func (*Bond) SampleConfig() string {
return sampleConfig
}
func (bond *Bond) Gather(acc telegraf.Accumulator) error {
// load proc path, get default value if config value and env variable are empty
bond.loadPaths()
// list bond interfaces from bonding directory or gather all interfaces.
bondNames, err := bond.listInterfaces()
if err != nil {
return err
}
for _, bondName := range bondNames {
bondAbsPath := bond.HostProc + "/net/bonding/" + bondName
file, err := os.ReadFile(bondAbsPath)
if err != nil {
acc.AddError(fmt.Errorf("error inspecting %q interface: %v", bondAbsPath, err))
continue
}
rawProcFile := strings.TrimSpace(string(file))
err = bond.gatherBondInterface(bondName, rawProcFile, acc)
if err != nil {
acc.AddError(fmt.Errorf("error inspecting %q interface: %v", bondName, err))
}
/*
Some details about bonds only exist in /sys/class/net/
In particular, LACP bonds track upstream port state here
*/
if bond.SysDetails {
files, err := bond.readSysFiles(bond.HostSys + "/class/net/" + bondName)
if err != nil {
acc.AddError(err)
}
bond.gatherSysDetails(bondName, files, acc)
}
}
return nil
}
func (bond *Bond) gatherBondInterface(bondName string, rawFile string, acc telegraf.Accumulator) error {
splitIndex := strings.Index(rawFile, "Slave Interface:")
if splitIndex == -1 {
splitIndex = len(rawFile)
}
bondPart := rawFile[:splitIndex]
slavePart := rawFile[splitIndex:]
err := bond.gatherBondPart(bondName, bondPart, acc)
if err != nil {
return err
}
err = bond.gatherSlavePart(bondName, slavePart, acc)
if err != nil {
return err
}
return nil
}
func (bond *Bond) gatherBondPart(bondName string, rawFile string, acc telegraf.Accumulator) error {
fields := make(map[string]interface{})
tags := map[string]string{
"bond": bondName,
}
scanner := bufio.NewScanner(strings.NewReader(rawFile))
/*
/proc/bond/... files are formatted in a way that is difficult
to use regexes to parse. Because of that, we scan through
the file one line at a time and rely on specific lines to
mark "ends" of blocks. It's a hack that should be resolved,
but for now, it works.
*/
for scanner.Scan() {
line := scanner.Text()
stats := strings.Split(line, ":")
if len(stats) < 2 {
continue
}
name := strings.TrimSpace(stats[0])
value := strings.TrimSpace(stats[1])
if name == "Bonding Mode" {
bond.BondType = value
}
if strings.Contains(name, "Currently Active Slave") {
fields["active_slave"] = value
}
if strings.Contains(name, "MII Status") {
fields["status"] = 0
if value == "up" {
fields["status"] = 1
}
acc.AddFields("bond", fields, tags)
return nil
}
}
if err := scanner.Err(); err != nil {
return err
}
return fmt.Errorf("Couldn't find status info for '%s' ", bondName)
}
func (bond *Bond) readSysFiles(bondDir string) (sysFiles, error) {
/*
Files we may need
bonding/mode
bonding/slaves
bonding/ad_num_ports
We load files here first to allow for easier testing
*/
var output sysFiles
file, err := os.ReadFile(bondDir + "/bonding/mode")
if err != nil {
return sysFiles{}, fmt.Errorf("error inspecting %q interface: %v", bondDir+"/bonding/mode", err)
}
output.ModeFile = strings.TrimSpace(string(file))
file, err = os.ReadFile(bondDir + "/bonding/slaves")
if err != nil {
return sysFiles{}, fmt.Errorf("error inspecting %q interface: %v", bondDir+"/bonding/slaves", err)
}
output.SlaveFile = strings.TrimSpace(string(file))
if bond.BondType == "IEEE 802.3ad Dynamic link aggregation" {
file, err = os.ReadFile(bondDir + "/bonding/ad_num_ports")
if err != nil {
return sysFiles{}, fmt.Errorf("error inspecting %q interface: %v", bondDir+"/bonding/ad_num_ports", err)
}
output.ADPortsFile = strings.TrimSpace(string(file))
}
return output, nil
}
func (bond *Bond) gatherSysDetails(bondName string, files sysFiles, acc telegraf.Accumulator) {
var slaves []string
var adPortCount int
// To start with, we get the bond operating mode
mode := strings.TrimSpace(strings.Split(files.ModeFile, " ")[0])
tags := map[string]string{
"bond": bondName,
"mode": mode,
}
// Next we collect the number of bond slaves the system expects
slavesTmp := strings.Split(files.SlaveFile, " ")
for _, slave := range slavesTmp {
if slave != "" {
slaves = append(slaves, slave)
}
}
if mode == "802.3ad" {
/*
If we're in LACP mode, we should check on how the bond ports are
interacting with the upstream switch ports
a failed conversion can be treated as 0 ports
*/
adPortCount, _ = strconv.Atoi(strings.TrimSpace(files.ADPortsFile))
} else {
adPortCount = len(slaves)
}
fields := map[string]interface{}{
"slave_count": len(slaves),
"ad_port_count": adPortCount,
}
acc.AddFields("bond_sys", fields, tags)
}
func (bond *Bond) gatherSlavePart(bondName string, rawFile string, acc telegraf.Accumulator) error {
var slaveCount int
tags := map[string]string{
"bond": bondName,
}
fields := map[string]interface{}{
"status": 0,
}
var scanPast bool
if bond.BondType == "IEEE 802.3ad Dynamic link aggregation" {
scanPast = true
}
scanner := bufio.NewScanner(strings.NewReader(rawFile))
for scanner.Scan() {
line := scanner.Text()
stats := strings.Split(line, ":")
if len(stats) < 2 {
continue
}
name := strings.TrimSpace(stats[0])
value := strings.TrimSpace(stats[1])
if strings.Contains(name, "Slave Interface") {
tags["interface"] = value
slaveCount++
}
if strings.Contains(name, "MII Status") && value == "up" {
fields["status"] = 1
}
if strings.Contains(name, "Link Failure Count") {
count, err := strconv.Atoi(value)
if err != nil {
return err
}
fields["failures"] = count
if !scanPast {
acc.AddFields("bond_slave", fields, tags)
}
}
if strings.Contains(name, "Actor Churned Count") {
count, err := strconv.Atoi(value)
if err != nil {
return err
}
fields["actor_churned"] = count
}
if strings.Contains(name, "Partner Churned Count") {
count, err := strconv.Atoi(value)
if err != nil {
return err
}
fields["partner_churned"] = count
fields["total_churned"] = fields["actor_churned"].(int) + fields["partner_churned"].(int)
acc.AddFields("bond_slave", fields, tags)
}
}
tags = map[string]string{
"bond": bondName,
}
fields = map[string]interface{}{
"count": slaveCount,
}
acc.AddFields("bond_slave", fields, tags)
return scanner.Err()
}
// loadPaths can be used to read path firstly from config
// if it is empty then try read from env variable
func (bond *Bond) loadPaths() {
if bond.HostProc == "" {
bond.HostProc = proc(envProc, defaultHostProc)
}
if bond.HostSys == "" {
bond.HostSys = proc(envSys, defaultHostSys)
}
}
// proc can be used to read file paths from env
func proc(env, path string) string {
// try to read full file path
if p := os.Getenv(env); p != "" {
return p
}
// return default path
return path
}
func (bond *Bond) listInterfaces() ([]string, error) {
var interfaces []string
if len(bond.BondInterfaces) > 0 {
interfaces = bond.BondInterfaces
} else {
paths, err := filepath.Glob(bond.HostProc + "/net/bonding/*")
if err != nil {
return nil, err
}
for _, p := range paths {
interfaces = append(interfaces, filepath.Base(p))
}
}
return interfaces, nil
}
func init() {
inputs.Add("bond", func() telegraf.Input {
return &Bond{}
})
}