forked from prometheus/snmp_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.go
487 lines (443 loc) · 13.1 KB
/
tree.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"regexp"
"sort"
"strconv"
"strings"
"github.com/prometheus/common/log"
"github.com/prometheus/snmp_exporter/config"
)
// These types have one following the other.
// We need to check indexes and sequences have them
// in the right order, so the exporter can handle them.
var combinedTypes = map[string]string{
"InetAddress": "InetAddressType",
"InetAddressMissingSize": "InetAddressType",
"LldpPortId": "LldpPortIdSubtype",
}
// Helper to walk MIB nodes.
func walkNode(n *Node, f func(n *Node)) {
f(n)
for _, c := range n.Children {
walkNode(c, f)
}
}
// Transform the tree.
func prepareTree(nodes *Node) map[string]*Node {
// Build a map from names and oids to nodes.
nameToNode := map[string]*Node{}
walkNode(nodes, func(n *Node) {
nameToNode[n.Oid] = n
nameToNode[n.Label] = n
})
// Trim down description to first sentence, removing extra whitespace.
walkNode(nodes, func(n *Node) {
s := strings.Join(strings.Fields(n.Description), " ")
n.Description = strings.Split(s, ". ")[0]
})
// Fix indexes to "INTEGER" rather than an object name.
// Example: snSlotsEntry in LANOPTICS-HUB-MIB.
walkNode(nodes, func(n *Node) {
indexes := []string{}
for _, i := range n.Indexes {
if i == "INTEGER" {
// Use the TableEntry name.
indexes = append(indexes, n.Label)
} else {
indexes = append(indexes, i)
}
}
n.Indexes = indexes
})
// Copy over indexes based on augments.
walkNode(nodes, func(n *Node) {
if n.Augments == "" {
return
}
augmented, ok := nameToNode[n.Augments]
if !ok {
log.Warnf("Can't find augmenting oid %s for %s", n.Augments, n.Label)
return
}
for _, c := range n.Children {
c.Indexes = augmented.Indexes
c.ImpliedIndex = augmented.ImpliedIndex
}
n.Indexes = augmented.Indexes
n.ImpliedIndex = augmented.ImpliedIndex
})
// Copy indexes from table entries down to the entries.
walkNode(nodes, func(n *Node) {
if len(n.Indexes) != 0 {
for _, c := range n.Children {
c.Indexes = n.Indexes
c.ImpliedIndex = n.ImpliedIndex
}
}
})
// Include both ASCII and UTF-8 in DisplayString, even though DisplayString
// is technically only ASCII.
displayStringRe := regexp.MustCompile(`^\d+[at]$`)
// Apply various tweaks to the types.
walkNode(nodes, func(n *Node) {
// Set type on MAC addresses and strings.
// RFC 2579
switch n.Hint {
case "1x:":
n.Type = "PhysAddress48"
}
if displayStringRe.MatchString(n.Hint) {
n.Type = "DisplayString"
}
// Some MIBs refer to RFC1213 for this, which is too
// old to have the right hint set.
if n.TextualConvention == "DisplayString" {
n.Type = "DisplayString"
}
if n.TextualConvention == "PhysAddress" {
n.Type = "PhysAddress48"
}
// Promote Opaque Float/Double textual convention to type.
if n.TextualConvention == "Float" || n.TextualConvention == "Double" {
n.Type = n.TextualConvention
}
// Convert RFC 2579 DateAndTime textual convention to type.
if n.TextualConvention == "DateAndTime" {
n.Type = "DateAndTime"
}
// Convert RFC 4001 InetAddress types textual convention to type.
if n.TextualConvention == "InetAddressIPv4" || n.TextualConvention == "InetAddressIPv6" || n.TextualConvention == "InetAddress" {
n.Type = n.TextualConvention
}
// Convert LLDP-MIB LldpPortId type textual convention to type.
if n.TextualConvention == "LldpPortId" {
n.Type = n.TextualConvention
}
})
return nameToNode
}
func metricType(t string) (string, bool) {
if _, ok := combinedTypes[t]; ok {
return t, true
}
switch t {
case "gauge", "INTEGER", "GAUGE", "TIMETICKS", "UINTEGER", "UNSIGNED32", "INTEGER32":
return "gauge", true
case "counter", "COUNTER", "COUNTER64":
return "counter", true
case "OctetString", "OCTETSTR", "BITSTRING":
return "OctetString", true
case "InetAddressIPv4", "IpAddr", "IPADDR", "NETADDR":
return "InetAddressIPv4", true
case "PhysAddress48", "DisplayString", "Float", "Double", "InetAddressIPv6":
return t, true
case "DateAndTime":
return t, true
case "EnumAsInfo", "EnumAsStateSet":
return t, true
default:
// Unsupported type.
return "", false
}
}
func metricAccess(a string) bool {
switch a {
case "ACCESS_READONLY", "ACCESS_READWRITE", "ACCESS_CREATE", "ACCESS_NOACCESS":
return true
default:
// the others are inaccessible metrics.
return false
}
}
// Reduce a set of overlapping OID subtrees.
func minimizeOids(oids []string) []string {
sort.Strings(oids)
prevOid := ""
minimized := []string{}
for _, oid := range oids {
if !strings.HasPrefix(oid+".", prevOid) || prevOid == "" {
minimized = append(minimized, oid)
prevOid = oid + "."
}
}
return minimized
}
// Search node tree for the longest OID match.
func searchNodeTree(oid string, node *Node) *Node {
if node == nil || !strings.HasPrefix(oid+".", node.Oid+".") {
return nil
}
for _, child := range node.Children {
match := searchNodeTree(oid, child)
if match != nil {
return match
}
}
return node
}
type oidMetricType uint8
const (
oidNotFound oidMetricType = iota
oidScalar
oidInstance
oidSubtree
)
// Find node in SNMP MIB tree that represents the metric.
func getMetricNode(oid string, node *Node, nameToNode map[string]*Node) (*Node, oidMetricType) {
// Check if is a known OID/name.
n, ok := nameToNode[oid]
if ok {
// Known node, check if OID is a valid metric or a subtree.
_, ok = metricType(n.Type)
if ok && metricAccess(n.Access) && len(n.Indexes) == 0 {
return n, oidScalar
} else {
return n, oidSubtree
}
}
// Unknown OID/name, search Node tree for longest match.
n = searchNodeTree(oid, node)
if n == nil {
return nil, oidNotFound
}
// Table instances must be a valid metric node and have an index.
_, ok = metricType(n.Type)
ok = ok && metricAccess(n.Access)
if !ok || len(n.Indexes) == 0 {
return nil, oidNotFound
}
return n, oidInstance
}
func generateConfigModule(cfg *ModuleConfig, node *Node, nameToNode map[string]*Node) *config.Module {
out := &config.Module{}
needToWalk := map[string]struct{}{}
tableInstances := map[string][]string{}
// Apply type overrides for the current module.
for name, params := range cfg.Overrides {
if params.Type == "" {
continue
}
// Find node to override.
n, ok := nameToNode[name]
if !ok {
log.Warnf("Could not find metric '%s' to override type", name)
continue
}
// params.Type validated at generator configuration.
n.Type = params.Type
}
// Remove redundant OIDs to be walked.
toWalk := []string{}
for _, oid := range cfg.Walk {
// Resolve name to OID if possible.
n, ok := nameToNode[oid]
if ok {
toWalk = append(toWalk, n.Oid)
} else {
toWalk = append(toWalk, oid)
}
}
toWalk = minimizeOids(toWalk)
// Find all top-level nodes.
metricNodes := map[*Node]struct{}{}
for _, oid := range toWalk {
metricNode, oidType := getMetricNode(oid, node, nameToNode)
switch oidType {
case oidNotFound:
log.Fatalf("Cannot find oid '%s' to walk", oid)
case oidSubtree:
needToWalk[oid] = struct{}{}
case oidInstance:
// Add a trailing period to the OID to indicate a "Get" instead of a "Walk".
needToWalk[oid+"."] = struct{}{}
// Save instance index for lookup.
index := strings.Replace(oid, metricNode.Oid, "", 1)
tableInstances[metricNode.Oid] = append(tableInstances[metricNode.Oid], index)
case oidScalar:
// Scalar OIDs must be accessed using index 0.
needToWalk[oid+".0."] = struct{}{}
}
metricNodes[metricNode] = struct{}{}
}
// Sort the metrics by OID to make the output deterministic.
metrics := make([]*Node, 0, len(metricNodes))
for key := range metricNodes {
metrics = append(metrics, key)
}
sort.Slice(metrics, func(i, j int) bool {
return metrics[i].Oid < metrics[j].Oid
})
// Find all the usable metrics.
for _, metricNode := range metrics {
walkNode(metricNode, func(n *Node) {
t, ok := metricType(n.Type)
if !ok {
return // Unsupported type.
}
if !metricAccess(n.Access) {
return // Inaccessible metrics.
}
metric := &config.Metric{
Name: sanitizeLabelName(n.Label),
Oid: n.Oid,
Type: t,
Help: n.Description + " - " + n.Oid,
Indexes: []*config.Index{},
Lookups: []*config.Lookup{},
EnumValues: n.EnumValues,
}
if cfg.Overrides[metric.Name].Ignore {
return // Ignored metric.
}
prevType := ""
for count, i := range n.Indexes {
index := &config.Index{Labelname: i}
indexNode, ok := nameToNode[i]
if !ok {
log.Warnf("Error, can't find index %s for node %s", i, n.Label)
return
}
index.Type, ok = metricType(indexNode.Type)
if !ok {
log.Warnf("Error, can't handle index type %s for index %s on node %s", indexNode.Type, i, n.Label)
return
}
index.FixedSize = indexNode.FixedSize
if n.ImpliedIndex && count+1 == len(n.Indexes) {
index.Implied = true
}
// Convert (InetAddressType,InetAddress) to (InetAddress)
if subtype, ok := combinedTypes[index.Type]; ok {
if prevType == subtype {
metric.Indexes = metric.Indexes[:len(metric.Indexes)-1]
} else {
log.Warnf("Error, can't handle index for node %s: %s without preceding %s", index.Type, subtype, n.Label)
return
}
}
prevType = indexNode.TextualConvention
metric.Indexes = append(metric.Indexes, index)
}
out.Metrics = append(out.Metrics, metric)
})
}
// Apply lookups.
for _, metric := range out.Metrics {
toDelete := []string{}
for _, lookup := range cfg.Lookups {
foundIndexes := 0
// See if all lookup indexes are present.
for _, index := range metric.Indexes {
for _, lookupIndex := range lookup.SourceIndexes {
if index.Labelname == lookupIndex {
foundIndexes++
}
}
}
if foundIndexes == len(lookup.SourceIndexes) {
if _, ok := nameToNode[lookup.Lookup]; !ok {
log.Fatalf("Unknown index '%s'", lookup.Lookup)
}
indexNode := nameToNode[lookup.Lookup]
typ, ok := metricType(indexNode.Type)
if !ok {
log.Fatalf("Unknown index type %s for %s", indexNode.Type, lookup.Lookup)
}
l := &config.Lookup{
Labelname: sanitizeLabelName(indexNode.Label),
Type: typ,
Oid: indexNode.Oid,
}
for _, oldIndex := range lookup.SourceIndexes {
l.Labels = append(l.Labels, sanitizeLabelName(oldIndex))
}
metric.Lookups = append(metric.Lookups, l)
// Make sure we walk the lookup OID(s).
if len(tableInstances[metric.Oid]) > 0 {
for _, index := range tableInstances[metric.Oid] {
needToWalk[indexNode.Oid+index+"."] = struct{}{}
}
} else {
needToWalk[indexNode.Oid] = struct{}{}
}
if lookup.DropSourceIndexes {
// Avoid leaving the old labelname around.
toDelete = append(toDelete, lookup.SourceIndexes...)
}
}
}
for _, l := range toDelete {
metric.Lookups = append(metric.Lookups, &config.Lookup{
Labelname: sanitizeLabelName(l),
})
}
}
// Ensure index label names are sane.
for _, metric := range out.Metrics {
for _, index := range metric.Indexes {
index.Labelname = sanitizeLabelName(index.Labelname)
}
}
// Check that the object before an InetAddress is an InetAddressType,
// if not, change it to an OctetString.
for _, metric := range out.Metrics {
if metric.Type == "InetAddress" || metric.Type == "InetAddressMissingSize" {
// Get previous oid.
oids := strings.Split(metric.Oid, ".")
i, _ := strconv.Atoi(oids[len(oids)-1])
oids[len(oids)-1] = strconv.Itoa(i - 1)
prevOid := strings.Join(oids, ".")
if prevObj, ok := nameToNode[prevOid]; !ok || prevObj.TextualConvention != "InetAddressType" {
metric.Type = "OctetString"
} else {
// Make sure the InetAddressType is included.
if len(tableInstances[metric.Oid]) > 0 {
for _, index := range tableInstances[metric.Oid] {
needToWalk[prevOid+index+"."] = struct{}{}
}
} else {
needToWalk[prevOid] = struct{}{}
}
}
}
}
// Apply module config overrides to their corresponding metrics.
for name, params := range cfg.Overrides {
for _, metric := range out.Metrics {
if name == metric.Name || name == metric.Oid {
metric.RegexpExtracts = params.RegexpExtracts
}
}
}
oids := []string{}
for k := range needToWalk {
oids = append(oids, k)
}
// Remove redundant OIDs and separate Walk and Get OIDs.
for _, k := range minimizeOids(oids) {
if k[len(k)-1:] == "." {
out.Get = append(out.Get, k[:len(k)-1])
} else {
out.Walk = append(out.Walk, k)
}
}
return out
}
var (
invalidLabelCharRE = regexp.MustCompile(`[^a-zA-Z0-9_]`)
)
func sanitizeLabelName(name string) string {
return invalidLabelCharRE.ReplaceAllString(name, "_")
}