-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
ifname.go
405 lines (329 loc) · 9.25 KB
/
ifname.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package ifname
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/snmp"
"github.com/influxdata/telegraf/plugins/common/parallel"
si "github.com/influxdata/telegraf/plugins/inputs/snmp"
"github.com/influxdata/telegraf/plugins/processors"
)
var sampleConfig = `
## Name of tag holding the interface number
# tag = "ifIndex"
## Name of output tag where service name will be added
# dest = "ifName"
## Name of tag of the SNMP agent to request the interface name from
# agent = "agent"
## Timeout for each request.
# timeout = "5s"
## SNMP version; can be 1, 2, or 3.
# version = 2
## SNMP community string.
# community = "public"
## Number of retries to attempt.
# retries = 3
## The GETBULK max-repetitions parameter.
# max_repetitions = 10
## SNMPv3 authentication and encryption options.
##
## Security Name.
# sec_name = "myuser"
## Authentication protocol; one of "MD5", "SHA", or "".
# auth_protocol = "MD5"
## Authentication password.
# auth_password = "pass"
## Security Level; one of "noAuthNoPriv", "authNoPriv", or "authPriv".
# sec_level = "authNoPriv"
## Context Name.
# context_name = ""
## Privacy protocol used for encrypted messages; one of "DES", "AES" or "".
# priv_protocol = ""
## Privacy password used for encrypted messages.
# priv_password = ""
## max_parallel_lookups is the maximum number of SNMP requests to
## make at the same time.
# max_parallel_lookups = 100
## ordered controls whether or not the metrics need to stay in the
## same order this plugin received them in. If false, this plugin
## may change the order when data is cached. If you need metrics to
## stay in order set this to true. keeping the metrics ordered may
## be slightly slower
# ordered = false
## cache_ttl is the amount of time interface names are cached for a
## given agent. After this period elapses if names are needed they
## will be retrieved again.
# cache_ttl = "8h"
`
type nameMap map[uint64]string
type keyType = string
type valType = nameMap
type mapFunc func(agent string) (nameMap, error)
type makeTableFunc func(string) (*si.Table, error)
type sigMap map[string](chan struct{})
type IfName struct {
SourceTag string `toml:"tag"`
DestTag string `toml:"dest"`
AgentTag string `toml:"agent"`
snmp.ClientConfig
CacheSize uint `toml:"max_cache_entries"`
MaxParallelLookups int `toml:"max_parallel_lookups"`
Ordered bool `toml:"ordered"`
CacheTTL config.Duration `toml:"cache_ttl"`
Log telegraf.Logger `toml:"-"`
ifTable *si.Table `toml:"-"`
ifXTable *si.Table `toml:"-"`
lock sync.Mutex `toml:"-"`
cache *TTLCache `toml:"-"`
parallel parallel.Parallel `toml:"-"`
acc telegraf.Accumulator `toml:"-"`
getMapRemote mapFunc `toml:"-"`
makeTable makeTableFunc `toml:"-"`
gsBase snmp.GosnmpWrapper `toml:"-"`
sigs sigMap `toml:"-"`
}
const minRetry time.Duration = 5 * time.Minute
func (d *IfName) SampleConfig() string {
return sampleConfig
}
func (d *IfName) Description() string {
return "Add a tag of the network interface name looked up over SNMP by interface number"
}
func (d *IfName) Init() error {
d.getMapRemote = d.getMapRemoteNoMock
d.makeTable = makeTableNoMock
c := NewTTLCache(time.Duration(d.CacheTTL), d.CacheSize)
d.cache = &c
d.sigs = make(sigMap)
return nil
}
func (d *IfName) addTag(metric telegraf.Metric) error {
agent, ok := metric.GetTag(d.AgentTag)
if !ok {
d.Log.Warn("Agent tag missing.")
return nil
}
numS, ok := metric.GetTag(d.SourceTag)
if !ok {
d.Log.Warn("Source tag missing.")
return nil
}
num, err := strconv.ParseUint(numS, 10, 64)
if err != nil {
return fmt.Errorf("couldn't parse source tag as uint")
}
firstTime := true
for {
m, age, err := d.getMap(agent)
if err != nil {
return fmt.Errorf("couldn't retrieve the table of interface names: %w", err)
}
name, found := m[num]
if found {
// success
metric.AddTag(d.DestTag, name)
return nil
}
// We have the agent's interface map but it doesn't contain
// the interface we're interested in. If the entry is old
// enough, retrieve it from the agent once more.
if age < minRetry {
return fmt.Errorf("interface number %d isn't in the table of interface names", num)
}
if firstTime {
d.invalidate(agent)
firstTime = false
continue
}
// not found, cache hit, retrying
return fmt.Errorf("missing interface but couldn't retrieve table")
}
}
func (d *IfName) invalidate(agent string) {
d.lock.Lock()
d.cache.Delete(agent)
d.lock.Unlock()
}
func (d *IfName) Start(acc telegraf.Accumulator) error {
d.acc = acc
var err error
d.gsBase, err = snmp.NewWrapper(d.ClientConfig)
if err != nil {
return fmt.Errorf("parsing SNMP client config: %w", err)
}
d.ifTable, err = d.makeTable("IF-MIB::ifDescr")
if err != nil {
return fmt.Errorf("looking up ifDescr in local MIB: %w", err)
}
d.ifXTable, err = d.makeTable("IF-MIB::ifName")
if err != nil {
return fmt.Errorf("looking up ifName in local MIB: %w", err)
}
fn := func(m telegraf.Metric) []telegraf.Metric {
err := d.addTag(m)
if err != nil {
d.Log.Debugf("Error adding tag %v", err)
}
return []telegraf.Metric{m}
}
if d.Ordered {
d.parallel = parallel.NewOrdered(acc, fn, 10000, d.MaxParallelLookups)
} else {
d.parallel = parallel.NewUnordered(acc, fn, d.MaxParallelLookups)
}
return nil
}
func (d *IfName) Add(metric telegraf.Metric, _ telegraf.Accumulator) error {
d.parallel.Enqueue(metric)
return nil
}
func (d *IfName) Stop() error {
d.parallel.Stop()
return nil
}
// getMap gets the interface names map either from cache or from the SNMP
// agent
func (d *IfName) getMap(agent string) (entry nameMap, age time.Duration, err error) {
var sig chan struct{}
d.lock.Lock()
// Check cache
m, ok, age := d.cache.Get(agent)
if ok {
d.lock.Unlock()
return m, age, nil
}
// cache miss. Is this the first request for this agent?
sig, found := d.sigs[agent]
if !found {
// This is the first request. Make signal for subsequent requests to wait on
s := make(chan struct{})
d.sigs[agent] = s
sig = s
}
d.lock.Unlock()
if found {
// This is not the first request. Wait for first to finish.
<-sig
// Check cache again
d.lock.Lock()
m, ok, age := d.cache.Get(agent)
d.lock.Unlock()
if ok {
return m, age, nil
}
return nil, 0, fmt.Errorf("getting remote table from cache")
}
// The cache missed and this is the first request for this
// agent. Make the SNMP request
m, err = d.getMapRemote(agent)
d.lock.Lock()
if err != nil {
//snmp failure. signal without saving to cache
close(sig)
delete(d.sigs, agent)
d.lock.Unlock()
return nil, 0, fmt.Errorf("getting remote table: %w", err)
}
// snmp success. Cache response, then signal any other waiting
// requests for this agent and clean up
d.cache.Put(agent, m)
close(sig)
delete(d.sigs, agent)
d.lock.Unlock()
return m, 0, nil
}
func (d *IfName) getMapRemoteNoMock(agent string) (nameMap, error) {
gs := d.gsBase
err := gs.SetAgent(agent)
if err != nil {
return nil, fmt.Errorf("parsing agent tag: %w", err)
}
err = gs.Connect()
if err != nil {
return nil, fmt.Errorf("connecting when fetching interface names: %w", err)
}
//try ifXtable and ifName first. if that fails, fall back to
//ifTable and ifDescr
var m nameMap
m, err = buildMap(gs, d.ifXTable, "ifName")
if err == nil {
return m, nil
}
m, err = buildMap(gs, d.ifTable, "ifDescr")
if err == nil {
return m, nil
}
return nil, fmt.Errorf("fetching interface names: %w", err)
}
func init() {
processors.AddStreaming("ifname", func() telegraf.StreamingProcessor {
return &IfName{
SourceTag: "ifIndex",
DestTag: "ifName",
AgentTag: "agent",
CacheSize: 100,
MaxParallelLookups: 100,
ClientConfig: snmp.ClientConfig{
Retries: 3,
MaxRepetitions: 10,
Timeout: config.Duration(5 * time.Second),
Version: 2,
Community: "public",
},
CacheTTL: config.Duration(8 * time.Hour),
}
})
}
func makeTableNoMock(fieldName string) (*si.Table, error) {
var err error
tab := si.Table{
Name: "ifTable",
IndexAsTag: true,
Fields: []si.Field{
{Oid: fieldName},
},
}
err = tab.Init()
if err != nil {
//Init already wraps
return nil, err
}
return &tab, nil
}
func buildMap(gs snmp.GosnmpWrapper, tab *si.Table, column string) (nameMap, error) {
var err error
rtab, err := tab.Build(gs, true)
if err != nil {
//Build already wraps
return nil, err
}
if len(rtab.Rows) == 0 {
return nil, fmt.Errorf("empty table")
}
t := make(nameMap)
for _, v := range rtab.Rows {
iStr, ok := v.Tags["index"]
if !ok {
//should always have an index tag because the table should
//always have IndexAsTag true
return nil, fmt.Errorf("no index tag")
}
i, err := strconv.ParseUint(iStr, 10, 64)
if err != nil {
return nil, fmt.Errorf("index tag isn't a uint")
}
nameIf, ok := v.Fields[column]
if !ok {
return nil, fmt.Errorf("field %s is missing", column)
}
name, ok := nameIf.(string)
if !ok {
return nil, fmt.Errorf("field %s isn't a string", column)
}
t[i] = name
}
return t, nil
}