-
Notifications
You must be signed in to change notification settings - Fork 1
/
translator.go
510 lines (463 loc) · 13.5 KB
/
translator.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Copyright (c) 2019 Arista Networks, Inc.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the COPYING file.
package snmpoc
import (
"context"
"crypto/md5"
"errors"
"fmt"
"regexp"
"strings"
"sync"
pgnmi "github.com/aristanetworks/cloudvision-go/provider/gnmi"
"github.com/aristanetworks/cloudvision-go/provider/snmp/pdu"
"github.com/aristanetworks/cloudvision-go/provider/snmp/smi"
"github.com/gosnmp/gosnmp"
"github.com/openconfig/gnmi/proto/gnmi"
"golang.org/x/sync/errgroup"
)
// NewTranslator returns a Translator.
func NewTranslator(mibStore smi.Store, gs *gosnmp.GoSNMP) (*Translator, error) {
ps, err := pdu.NewStore(mibStore)
if err != nil {
return nil, err
}
return &Translator{
Getter: gs.Get,
gosnmp: gs,
gosnmpLock: &sync.Mutex{},
Logger: &nonlogger{},
mapperData: &sync.Map{},
Mappings: DefaultMappings(),
mibStore: mibStore,
pathsMappingGroups: make(map[string]map[string]*mappingGroup),
pduStore: ps,
pollLock: &sync.Mutex{},
successfulMappings: make(map[string]Mapper),
successfulMappingsLock: &sync.RWMutex{},
Walker: gs.BulkWalk,
}, nil
}
// Logger defines an interface for logging.
type Logger interface {
Infof(format string, args ...interface{})
Debugf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
// model describes a set of paths rooted at rootPath for which
// we want to produce updates.
type model struct {
name string
rootPath string
dependencies []string
snmpGetOIDs []string
snmpWalkOIDs []string
}
func (m *model) Copy() *model {
m2 := &model{
name: m.name,
rootPath: m.rootPath,
dependencies: make([]string, len(m.dependencies)),
snmpGetOIDs: make([]string, len(m.snmpGetOIDs)),
snmpWalkOIDs: make([]string, len(m.snmpWalkOIDs)),
}
_ = copy(m2.dependencies, m.dependencies)
_ = copy(m2.snmpGetOIDs, m.snmpGetOIDs)
_ = copy(m2.snmpWalkOIDs, m.snmpWalkOIDs)
return m2
}
// A mappingGroup contains a set of paths and their associated models.
type mappingGroup struct {
name string
models map[string]*model
updatePaths map[string][]string
}
type nonlogger struct{}
func (n *nonlogger) Infof(format string, args ...interface{}) {}
func (n *nonlogger) Debugf(format string, args ...interface{}) {}
func (n *nonlogger) Errorf(format string, args ...interface{}) {}
// Translator defines an interface for producing translations from a
// set of received SNMP PDUs to a set of gNMI updates.
type Translator struct {
// auxiliary data stores
pduStore pdu.Store
mibStore smi.Store
mapperData *sync.Map
pathsMappingGroups map[string]map[string]*mappingGroup
// mapping state
Mappings map[string][]Mapper
successfulMappings map[string]Mapper
successfulMappingsLock *sync.RWMutex
// gosnmp state
gosnmp *gosnmp.GoSNMP
gosnmpLock *sync.Mutex
gosnmpConnected bool
// to ensure non-overlapping polls
pollLock *sync.Mutex
// logging
Logger Logger
// alternative get, walk, and time.Now for testing
Mock bool
Getter func([]string) (*gosnmp.SnmpPacket, error)
Walker func(string, gosnmp.WalkFunc) error
}
// Poll generates a set of updates for the paths specified. It
// accepts exact paths and regular expressions. Any path in the
// translator's mapping list that matches the provided expression
// is added to the set of updates to produce. It performs a poll for
// any required SNMP data and translates that data into gNMI updates,
// which it then transmits via the provided gNMI client's Set method.
func (t *Translator) Poll(ctx context.Context, client gnmi.GNMIClient,
paths []string) error {
t.pollLock.Lock()
defer t.pollLock.Unlock()
mappingGroups, err := t.mappingGroupsFromPaths(paths)
if err != nil {
return err
}
if len(mappingGroups) == 0 {
return errors.New("no models to translate")
}
// Clear data stores in preparation for filling them up again.
if err := t.pduStore.Clear(); err != nil {
return err
}
t.mapperData.Range(func(k interface{}, v interface{}) bool {
// Ideally we could just do t.mapperData = &sync.Map{} but
// the compiler says this is unsafe, so we have to use Range.
t.mapperData.Delete(k)
return true
})
// Produce updates for each mapping group.
setReqCh := make(chan *gnmi.SetRequest, len(mappingGroups))
errg, ctx := errgroup.WithContext(ctx)
var wg sync.WaitGroup
for _, mg := range mappingGroups {
mg := mg
wg.Add(1)
errg.Go(func() error {
defer wg.Done()
return t.mappingGroupUpdates(ctx, mg, setReqCh)
})
}
errg.Go(func() error {
wg.Wait()
close(setReqCh)
return nil
})
errg.Go(func() error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case sr, ok := <-setReqCh:
if !ok {
return nil
}
if _, err := client.Set(ctx, sr); err != nil {
return err
}
}
}
})
return errg.Wait()
}
// updates produces updates for the provided set of paths.
func (t *Translator) updates(paths []string) ([]*gnmi.Update, error) {
updates := []*gnmi.Update{}
for _, path := range paths {
// If we have a mapping that already worked, use it.
t.successfulMappingsLock.RLock()
mapping, ok := t.successfulMappings[path]
t.successfulMappingsLock.RUnlock()
if ok {
u, err := mapping(t.mibStore, t.pduStore, t.mapperData, t.Logger)
if err != nil {
return nil, err
}
updates = append(updates, u...)
continue
}
// Otherwise, try each mapping in order.
mappings, ok := t.Mappings[path]
if !ok {
return nil, fmt.Errorf("No mapping supplied for path %v", path)
}
for _, mapping := range mappings {
u, err := mapping(t.mibStore, t.pduStore, t.mapperData, t.Logger)
if err != nil {
return nil, err
} else if len(u) == 0 {
continue
}
t.successfulMappingsLock.Lock()
t.successfulMappings[path] = mapping
t.successfulMappingsLock.Unlock()
updates = append(updates, u...)
break
}
}
return updates, nil
}
var supportedModels = map[string]*model{
"interfaces": {
name: "interfaces",
rootPath: "/interfaces",
snmpWalkOIDs: []string{"ifTable", "ifXTable", "ipAddressTable"},
},
"system": {
name: "system",
rootPath: "/system",
snmpGetOIDs: []string{"sysName.0", "lldpLocSysName.0", "hrSystemUptime.0",
"sysUpTimeInstance"},
},
"lldp": {
name: "lldp",
rootPath: "/lldp",
dependencies: []string{"interfaces"},
snmpWalkOIDs: []string{"lldpLocalSystemData", "lldpRemTable", "lldpStatistics",
"lldpV2LocalSystemData", "lldpV2RemTable", "lldpV2Statistics"},
},
"platform": {
name: "platform",
rootPath: "/components",
snmpWalkOIDs: []string{"entPhysicalEntry"},
},
}
var supportedMappingGroups = map[string]*mappingGroup{
"interfaces-lldp": {
name: "interfaces-lldp",
models: map[string]*model{
"interfaces": supportedModels["interfaces"],
"lldp": supportedModels["lldp"],
},
},
"system": {
name: "system",
models: map[string]*model{
"system": supportedModels["system"],
},
},
"platform": {
name: "platform",
models: map[string]*model{
"platform": supportedModels["platform"],
},
},
}
func (t *Translator) storePDU(pdu gosnmp.SnmpPDU) error {
return t.pduStore.Add(&pdu)
}
// A critical error is an error that prevents us from continuing processing/querying snmp.
// I.e, errors that interrupt a poll cycle.
func criticalSNMPError(err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
errStr := strings.ToLower(err.Error())
if strings.Contains(errStr, "request timeout") {
return true
}
if strings.Contains(errStr, "closed network connection") {
return true
}
if strings.Contains(errStr, "error reading from socket") {
return true
}
return false
}
func (t *Translator) getSNMPData(mg *mappingGroup) error {
t.gosnmpLock.Lock()
defer t.gosnmpLock.Unlock()
// Connect to target.
if !t.gosnmpConnected && !t.Mock {
if err := t.gosnmp.Connect(); err != nil {
return fmt.Errorf("connect failed: %w", err)
}
t.gosnmpConnected = true
t.Logger.Infof("gosnmp.Connect complete")
}
// Get SNMP data for each model in this mappingGroup.
for _, model := range mg.models {
// Walk
for _, oid := range model.snmpWalkOIDs {
t.Logger.Debugf("SNMP Walk (OID = %s)", oid)
if err := t.Walker(oid, t.storePDU); err != nil {
if criticalSNMPError(err) {
return fmt.Errorf("SNMP Walker failed: %w", err)
}
t.Logger.Infof("Error walking OID %s: %s", oid, err)
} else {
t.Logger.Debugf("SNMP Walk complete (OID = %s)", oid)
}
}
// Get
if len(model.snmpGetOIDs) == 0 {
continue
}
t.Logger.Debugf("SNMP Get (OIDs = %s)",
strings.Join(model.snmpGetOIDs, " "))
pkt, err := t.Getter(model.snmpGetOIDs)
if err != nil {
if criticalSNMPError(err) {
return fmt.Errorf("SNMP Getter failed: %w", err)
}
t.Logger.Infof("Error getting OIDs %s: %s",
strings.Join(model.snmpGetOIDs, " "), err)
return nil
} else if pkt == nil {
t.Logger.Infof("SNMP Get returned nil packet")
return nil
} else {
t.Logger.Debugf("SNMP Get complete. pkt = %v, err = %v", pkt, err)
}
if pkt.Error != gosnmp.NoError {
errstr, ok := SNMPErrCodes[pkt.Error]
if !ok {
errstr = "Unknown error"
}
t.Logger.Infof("SNMP Get: Error in packet (%v): %s",
pkt, errstr)
}
for _, pdu := range pkt.Variables {
if err = t.storePDU(pdu); err != nil {
t.Logger.Infof("Error storing PDU: %s", err)
}
}
}
return nil
}
func (t *Translator) mappingGroupUpdates(ctx context.Context,
mg *mappingGroup, setReqCh chan *gnmi.SetRequest) error {
// Get SNMP data.
if err := t.getSNMPData(mg); err != nil {
// Errors only occur on connection issues, so we likely have not retrieved any data
// so just return
return err
}
// Produce updates and hand a SetRequest to the gNMI client.
// If there are more than numUpdatesPerSet updates, split
// across multiple SetRequests.
numUpdatesPerSet := 250
setRequests := []*gnmi.SetRequest{}
setRequest := new(gnmi.SetRequest)
setRequests = append(setRequests, setRequest)
for modelName, model := range mg.models {
setRequest.Delete = append(setRequest.Delete,
pgnmi.PathFromString(model.rootPath))
if up, ok := mg.updatePaths[modelName]; ok {
updates, err := t.updates(up)
if err != nil {
return err
}
if len(setRequest.Replace) > numUpdatesPerSet {
setRequest = new(gnmi.SetRequest)
setRequests = append(setRequests, setRequest)
}
setRequest.Replace = append(setRequest.Replace, updates...)
t.Logger.Debugf("Replace for mapping group %s, model %s has %d updates",
mg.name, modelName, len(setRequest.Replace))
} else {
return fmt.Errorf("No updatePath entries for model '%s'", modelName)
}
}
for _, sr := range setRequests {
select {
case <-ctx.Done():
return ctx.Err()
case setReqCh <- sr:
}
}
return nil
}
// A mappingGroup is a set of related translations that share dependencies.
func (t *Translator) mappingGroupsFromPaths(paths []string) (map[string]*mappingGroup,
error) {
phb := md5.Sum([]byte(strings.Join(paths, "")))
pathHash := string(phb[:])
// Get the paths of interest from the provided paths + patterns.
if len(paths) == 0 {
// If we're not given any paths, use all supported paths.
for p := range t.Mappings {
paths = append(paths, p)
}
} else {
// Check whether we've already created mapping groups for these
// paths.
if mgs, ok := t.pathsMappingGroups[pathHash]; ok {
return mgs, nil
}
// Expand the set of provided paths to include all paths matching
// regexes.
expPaths := []string{}
for _, p := range paths {
if _, ok := t.Mappings[p]; ok {
expPaths = append(expPaths, p)
continue
} else {
for mp := range t.Mappings {
m, err := regexp.MatchString(p, mp)
if err != nil {
return nil, err
}
if m {
expPaths = append(expPaths, mp)
}
}
}
}
if len(expPaths) == 0 {
return nil, fmt.Errorf("Provided paths expand to zero paths: %v", paths)
}
paths = expPaths
}
// Pare down mappingGroups to include only the models we need for the
// provided paths.
reducedMg := map[string]*mappingGroup{}
for _, mg := range supportedMappingGroups {
for _, mod := range mg.models {
for _, p := range paths {
match, err := regexp.MatchString(fmt.Sprintf("^%s/.*",
mod.rootPath), p)
if err != nil {
return nil, err
}
if match {
if _, ok := reducedMg[mg.name]; !ok {
reducedMg[mg.name] = &mappingGroup{
name: mg.name,
models: map[string]*model{},
updatePaths: map[string][]string{},
}
}
cmg := reducedMg[mg.name]
if _, ok := cmg.models[mod.name]; !ok {
cmg.models[mod.name] = mod.Copy()
// Swap text OIDs out for their numeric equivalents.
for i, oid := range cmg.models[mod.name].snmpGetOIDs {
obj := t.mibStore.GetObject(oid)
if obj != nil {
cmg.models[mod.name].snmpGetOIDs[i] = obj.Oid
// Add back ".0" for scalars
if oid[len(oid)-2:] == ".0" {
cmg.models[mod.name].snmpGetOIDs[i] += ".0"
}
}
}
for i, oid := range cmg.models[mod.name].snmpWalkOIDs {
obj := t.mibStore.GetObject(oid)
if obj != nil {
cmg.models[mod.name].snmpWalkOIDs[i] = obj.Oid
}
}
}
cmg.updatePaths[mod.name] = append(cmg.updatePaths[mod.name], p)
}
}
}
}
// Store mapping groups for these paths.
t.pathsMappingGroups[pathHash] = reducedMg
return reducedMg, nil
}