/
gnmi.go
390 lines (349 loc) · 11.8 KB
/
gnmi.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
//go:generate ../../../tools/readme_config_includer/generator
package gnmi
import (
"context"
_ "embed"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/google/gnxi/utils/xpath"
gnmiLib "github.com/openconfig/gnmi/proto/gnmi"
"google.golang.org/grpc/metadata"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/choice"
internaltls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
//go:embed sample.conf
var sampleConfig string
// Define the warning to show if we cannot get a metric name.
const emptyNameWarning = `Got empty metric-name for response, usually indicating
configuration issues as the response cannot be related to any subscription.
Please open an issue on https://github.com/influxdata/telegraf including your
device model and the following response data:
%+v
This message is only printed once.`
// Currently supported GNMI Extensions
var supportedExtensions = []string{"juniper_header"}
// gNMI plugin instance
type GNMI struct {
Addresses []string `toml:"addresses"`
Subscriptions []Subscription `toml:"subscription"`
TagSubscriptions []TagSubscription `toml:"tag_subscription"`
Aliases map[string]string `toml:"aliases"`
Encoding string `toml:"encoding"`
Origin string `toml:"origin"`
Prefix string `toml:"prefix"`
Target string `toml:"target"`
UpdatesOnly bool `toml:"updates_only"`
VendorSpecific []string `toml:"vendor_specific"`
Username string `toml:"username"`
Password string `toml:"password"`
Redial config.Duration `toml:"redial"`
MaxMsgSize config.Size `toml:"max_msg_size"`
Trace bool `toml:"dump_responses"`
CanonicalFieldNames bool `toml:"canonical_field_names"`
TrimFieldNames bool `toml:"trim_field_names"`
GuessPathTag bool `toml:"guess_path_tag" deprecated:"1.30.0;use 'path_guessing_strategy' instead"`
GuessPathStrategy string `toml:"path_guessing_strategy"`
EnableTLS bool `toml:"enable_tls" deprecated:"1.27.0;use 'tls_enable' instead"`
Log telegraf.Logger `toml:"-"`
internaltls.ClientConfig
// Internal state
internalAliases map[*pathInfo]string
cancel context.CancelFunc
wg sync.WaitGroup
}
// Subscription for a gNMI client
type Subscription struct {
Name string `toml:"name"`
Origin string `toml:"origin"`
Path string `toml:"path"`
SubscriptionMode string `toml:"subscription_mode"`
SampleInterval config.Duration `toml:"sample_interval"`
SuppressRedundant bool `toml:"suppress_redundant"`
HeartbeatInterval config.Duration `toml:"heartbeat_interval"`
TagOnly bool `toml:"tag_only" deprecated:"1.25.0;2.0.0;please use 'tag_subscription's instead"`
fullPath *gnmiLib.Path
}
// Tag Subscription for a gNMI client
type TagSubscription struct {
Subscription
Match string `toml:"match"`
Elements []string `toml:"elements"`
}
func (*GNMI) SampleConfig() string {
return sampleConfig
}
func (c *GNMI) Init() error {
// Check options
if time.Duration(c.Redial) <= 0 {
return errors.New("redial duration must be positive")
}
// Check vendor_specific options configured by user
if err := choice.CheckSlice(c.VendorSpecific, supportedExtensions); err != nil {
return fmt.Errorf("unsupported vendor_specific option: %w", err)
}
// Check path guessing and handle deprecated option
if c.GuessPathTag {
if c.GuessPathStrategy == "" {
c.GuessPathStrategy = "common path"
}
if c.GuessPathStrategy != "common path" {
return errors.New("conflicting settings between 'guess_path_tag' and 'path_guessing_strategy'")
}
}
switch c.GuessPathStrategy {
case "", "none", "common path", "subscription":
default:
return fmt.Errorf("invalid 'path_guessing_strategy' %q", c.GuessPathStrategy)
}
// Use the new TLS option for enabling
// Honor deprecated option
enable := (c.ClientConfig.Enable != nil && *c.ClientConfig.Enable) || c.EnableTLS
c.ClientConfig.Enable = &enable
// Split the subscriptions into "normal" and "tag" subscription
// and prepare them.
for i := len(c.Subscriptions) - 1; i >= 0; i-- {
subscription := c.Subscriptions[i]
// Check the subscription
if subscription.Name == "" {
return fmt.Errorf("empty 'name' found for subscription %d", i+1)
}
if subscription.Path == "" {
return fmt.Errorf("empty 'path' found for subscription %d", i+1)
}
// Support and convert legacy TagOnly subscriptions
if subscription.TagOnly {
tagSub := TagSubscription{
Subscription: subscription,
Match: "name",
}
c.TagSubscriptions = append(c.TagSubscriptions, tagSub)
// Remove from the original subscriptions list
c.Subscriptions = append(c.Subscriptions[:i], c.Subscriptions[i+1:]...)
continue
}
if err := subscription.buildFullPath(c); err != nil {
return err
}
}
for idx := range c.TagSubscriptions {
if err := c.TagSubscriptions[idx].buildFullPath(c); err != nil {
return err
}
if c.TagSubscriptions[idx].TagOnly != c.TagSubscriptions[0].TagOnly {
return errors.New("do not mix legacy tag_only subscriptions and tag subscriptions")
}
switch c.TagSubscriptions[idx].Match {
case "":
if len(c.TagSubscriptions[idx].Elements) > 0 {
c.TagSubscriptions[idx].Match = "elements"
} else {
c.TagSubscriptions[idx].Match = "name"
}
case "unconditional":
case "name":
case "elements":
if len(c.TagSubscriptions[idx].Elements) == 0 {
return errors.New("tag_subscription must have at least one element")
}
default:
return fmt.Errorf("unknown match type %q for tag-subscription %q", c.TagSubscriptions[idx].Match, c.TagSubscriptions[idx].Name)
}
}
// Invert explicit alias list and prefill subscription names
c.internalAliases = make(map[*pathInfo]string, len(c.Subscriptions)+len(c.Aliases)+len(c.TagSubscriptions))
for _, s := range c.Subscriptions {
if err := s.buildAlias(c.internalAliases); err != nil {
return err
}
}
for _, s := range c.TagSubscriptions {
if err := s.buildAlias(c.internalAliases); err != nil {
return err
}
}
for alias, encodingPath := range c.Aliases {
c.internalAliases[newInfoFromString(encodingPath)] = alias
}
c.Log.Debugf("Internal alias mapping: %+v", c.internalAliases)
return nil
}
func (c *GNMI) Start(acc telegraf.Accumulator) error {
// Validate configuration
request, err := c.newSubscribeRequest()
if err != nil {
return err
}
// Generate TLS config if enabled
tlscfg, err := c.ClientConfig.TLSConfig()
if err != nil {
return err
}
// Prepare the context, optionally with credentials
var ctx context.Context
ctx, c.cancel = context.WithCancel(context.Background())
if len(c.Username) > 0 {
ctx = metadata.AppendToOutgoingContext(ctx, "username", c.Username, "password", c.Password)
}
// Create a goroutine for each device, dial and subscribe
c.wg.Add(len(c.Addresses))
for _, addr := range c.Addresses {
go func(addr string) {
defer c.wg.Done()
h := handler{
address: addr,
aliases: c.internalAliases,
tagsubs: c.TagSubscriptions,
maxMsgSize: int(c.MaxMsgSize),
vendorExt: c.VendorSpecific,
tagStore: newTagStore(c.TagSubscriptions),
trace: c.Trace,
canonicalFieldNames: c.CanonicalFieldNames,
trimSlash: c.TrimFieldNames,
guessPathStrategy: c.GuessPathStrategy,
log: c.Log,
}
for ctx.Err() == nil {
if err := h.subscribeGNMI(ctx, acc, tlscfg, request); err != nil && ctx.Err() == nil {
acc.AddError(err)
}
select {
case <-ctx.Done():
case <-time.After(time.Duration(c.Redial)):
}
}
}(addr)
}
return nil
}
func (s *Subscription) buildSubscription() (*gnmiLib.Subscription, error) {
gnmiPath, err := parsePath(s.Origin, s.Path, "")
if err != nil {
return nil, err
}
mode, ok := gnmiLib.SubscriptionMode_value[strings.ToUpper(s.SubscriptionMode)]
if !ok {
return nil, fmt.Errorf("invalid subscription mode %s", s.SubscriptionMode)
}
return &gnmiLib.Subscription{
Path: gnmiPath,
Mode: gnmiLib.SubscriptionMode(mode),
HeartbeatInterval: uint64(time.Duration(s.HeartbeatInterval).Nanoseconds()),
SampleInterval: uint64(time.Duration(s.SampleInterval).Nanoseconds()),
SuppressRedundant: s.SuppressRedundant,
}, nil
}
// Create a new gNMI SubscribeRequest
func (c *GNMI) newSubscribeRequest() (*gnmiLib.SubscribeRequest, error) {
// Create subscription objects
subscriptions := make([]*gnmiLib.Subscription, 0, len(c.Subscriptions)+len(c.TagSubscriptions))
for _, subscription := range c.TagSubscriptions {
sub, err := subscription.buildSubscription()
if err != nil {
return nil, err
}
subscriptions = append(subscriptions, sub)
}
for _, subscription := range c.Subscriptions {
sub, err := subscription.buildSubscription()
if err != nil {
return nil, err
}
subscriptions = append(subscriptions, sub)
}
// Construct subscribe request
gnmiPath, err := parsePath(c.Origin, c.Prefix, c.Target)
if err != nil {
return nil, err
}
// Do not provide an empty prefix. Required for Huawei NE40 router v8.21
// (and possibly others). See https://github.com/influxdata/telegraf/issues/12273.
if gnmiPath.Origin == "" && gnmiPath.Target == "" && len(gnmiPath.Elem) == 0 {
gnmiPath = nil
}
if c.Encoding != "proto" && c.Encoding != "json" && c.Encoding != "json_ietf" && c.Encoding != "bytes" {
return nil, fmt.Errorf("unsupported encoding %s", c.Encoding)
}
return &gnmiLib.SubscribeRequest{
Request: &gnmiLib.SubscribeRequest_Subscribe{
Subscribe: &gnmiLib.SubscriptionList{
Prefix: gnmiPath,
Mode: gnmiLib.SubscriptionList_STREAM,
Encoding: gnmiLib.Encoding(gnmiLib.Encoding_value[strings.ToUpper(c.Encoding)]),
Subscription: subscriptions,
UpdatesOnly: c.UpdatesOnly,
},
},
}, nil
}
// ParsePath from XPath-like string to gNMI path structure
func parsePath(origin string, pathToParse string, target string) (*gnmiLib.Path, error) {
gnmiPath, err := xpath.ToGNMIPath(pathToParse)
if err != nil {
return nil, err
}
gnmiPath.Origin = origin
gnmiPath.Target = target
return gnmiPath, err
}
// Stop listener and cleanup
func (c *GNMI) Stop() {
c.cancel()
c.wg.Wait()
}
// Gather plugin measurements (unused)
func (c *GNMI) Gather(_ telegraf.Accumulator) error {
return nil
}
func New() telegraf.Input {
return &GNMI{
Encoding: "proto",
Redial: config.Duration(10 * time.Second),
}
}
func init() {
inputs.Add("gnmi", New)
// Backwards compatible alias:
inputs.Add("cisco_telemetry_gnmi", New)
}
func (s *Subscription) buildFullPath(c *GNMI) error {
var err error
if s.fullPath, err = xpath.ToGNMIPath(s.Path); err != nil {
return err
}
s.fullPath.Origin = s.Origin
s.fullPath.Target = c.Target
if c.Prefix != "" {
prefix, err := xpath.ToGNMIPath(c.Prefix)
if err != nil {
return err
}
s.fullPath.Elem = append(prefix.Elem, s.fullPath.Elem...)
if s.Origin == "" && c.Origin != "" {
s.fullPath.Origin = c.Origin
}
}
return nil
}
func (s *Subscription) buildAlias(aliases map[*pathInfo]string) error {
// Build the subscription path without keys
path, err := parsePath(s.Origin, s.Path, "")
if err != nil {
return err
}
info := newInfoFromPathWithoutKeys(path)
// If the user didn't provide a measurement name, use last path element
name := s.Name
if name == "" && len(info.segments) > 0 {
name = info.segments[len(info.segments)-1]
}
if name != "" {
aliases[info] = name
}
return nil
}