operation.go 13.5 KB
Newer Older
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
// Copyright (c) 2017 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 gnmi

import (
	"bufio"
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	pb "github.com/openconfig/gnmi/proto/gnmi"
	"github.com/openconfig/gnmi/proto/gnmi_ext"
)

// GetWithRequest takes a fully formed GetRequest, performs the Get,
// and displays any response.
func GetWithRequest(ctx context.Context, client pb.GNMIClient,
	req *pb.GetRequest) error {
	resp, err := client.Get(ctx, req)
	if err != nil {
		return err
	}
	for _, notif := range resp.Notification {
		prefix := StrPath(notif.Prefix)
		for _, update := range notif.Update {
			fmt.Printf("%s:\n", path.Join(prefix, StrPath(update.Path)))
			fmt.Println(StrUpdateVal(update))
		}
	}
	return nil
}

46
// Get sends a GetRequest to the given server.
47
48
func Get(ctx context.Context, client pb.GNMIClient, paths [][]string,
	origin string) error {
49
	req, err := NewGetRequest(ctx, paths, origin)
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
	if err != nil {
		return err
	}
	return GetWithRequest(ctx, client, req)
}

// val may be a path to a file or it may be json. First see if it is a
// file, if so return its contents, otherwise return val
func extractJSON(val string) []byte {
	if jsonBytes, err := ioutil.ReadFile(val); err == nil {
		return jsonBytes
	}
	// Best effort check if the value might a string literal, in which
	// case wrap it in quotes. This is to allow a user to do:
	//   gnmi update ../hostname host1234
	//   gnmi update ../description 'This is a description'
	// instead of forcing them to quote the string:
	//   gnmi update ../hostname '"host1234"'
	//   gnmi update ../description '"This is a description"'
	maybeUnquotedStringLiteral := func(s string) bool {
		if s == "true" || s == "false" || s == "null" || // JSON reserved words
			strings.ContainsAny(s, `"'{}[]`) { // Already quoted or is a JSON object or array
			return false
		} else if _, err := strconv.ParseInt(s, 0, 32); err == nil {
			// Integer. Using byte size of 32 because larger integer
			// types are supposed to be sent as strings in JSON.
			return false
		} else if _, err := strconv.ParseFloat(s, 64); err == nil {
			// Float
			return false
		}

		return true
	}
	if maybeUnquotedStringLiteral(val) {
		out := make([]byte, len(val)+2)
		out[0] = '"'
		copy(out[1:], val)
		out[len(out)-1] = '"'
		return out
	}
	return []byte(val)
}

// StrUpdateVal will return a string representing the value within the supplied update
func StrUpdateVal(u *pb.Update) string {
	if u.Value != nil {
		// Backwards compatibility with pre-v0.4 gnmi
		switch u.Value.Type {
		case pb.Encoding_JSON, pb.Encoding_JSON_IETF:
			return strJSON(u.Value.Value)
		case pb.Encoding_BYTES, pb.Encoding_PROTO:
			return base64.StdEncoding.EncodeToString(u.Value.Value)
		case pb.Encoding_ASCII:
			return string(u.Value.Value)
		default:
			return string(u.Value.Value)
		}
	}
	return StrVal(u.Val)
}

// StrVal will return a string representing the supplied value
func StrVal(val *pb.TypedValue) string {
	switch v := val.GetValue().(type) {
	case *pb.TypedValue_StringVal:
		return v.StringVal
	case *pb.TypedValue_JsonIetfVal:
		return strJSON(v.JsonIetfVal)
	case *pb.TypedValue_JsonVal:
		return strJSON(v.JsonVal)
	case *pb.TypedValue_IntVal:
		return strconv.FormatInt(v.IntVal, 10)
	case *pb.TypedValue_UintVal:
		return strconv.FormatUint(v.UintVal, 10)
	case *pb.TypedValue_BoolVal:
		return strconv.FormatBool(v.BoolVal)
	case *pb.TypedValue_BytesVal:
		return base64.StdEncoding.EncodeToString(v.BytesVal)
	case *pb.TypedValue_DecimalVal:
		return strDecimal64(v.DecimalVal)
	case *pb.TypedValue_FloatVal:
		return strconv.FormatFloat(float64(v.FloatVal), 'g', -1, 32)
	case *pb.TypedValue_LeaflistVal:
		return strLeaflist(v.LeaflistVal)
	case *pb.TypedValue_AsciiVal:
		return v.AsciiVal
	case *pb.TypedValue_AnyVal:
		return v.AnyVal.String()
	case *pb.TypedValue_ProtoBytes:
		return base64.StdEncoding.EncodeToString(v.ProtoBytes)
	default:
		panic(v)
	}
}

func strJSON(inJSON []byte) string {
	var (
		out bytes.Buffer
		err error
	)
	// Check for ',' as simple heuristic on whether to expand JSON
	// onto multiple lines, or compact it to a single line.
	if bytes.Contains(inJSON, []byte{','}) {
		err = json.Indent(&out, inJSON, "", "  ")
	} else {
		err = json.Compact(&out, inJSON)
	}
	if err != nil {
		return fmt.Sprintf("(error unmarshalling json: %s)\n", err) + string(inJSON)
	}
	return out.String()
}

func strDecimal64(d *pb.Decimal64) string {
	var i, frac int64
	if d.Precision > 0 {
		div := int64(10)
		it := d.Precision - 1
		for it > 0 {
			div *= 10
			it--
		}
		i = d.Digits / div
		frac = d.Digits % div
	} else {
		i = d.Digits
	}
	if frac < 0 {
		frac = -frac
	}
	return fmt.Sprintf("%d.%d", i, frac)
}

// strLeafList builds a human-readable form of a leaf-list. e.g. [1, 2, 3] or [a, b, c]
func strLeaflist(v *pb.ScalarArray) string {
	var b strings.Builder
	b.WriteByte('[')

	for i, elm := range v.Element {
		b.WriteString(StrVal(elm))
		if i < len(v.Element)-1 {
			b.WriteString(", ")
		}
	}

	b.WriteByte(']')
	return b.String()
}

// TypedValue marshals an interface into a gNMI TypedValue value
func TypedValue(val interface{}) *pb.TypedValue {
	// TODO: handle more types:
	// float64
	// maps
	// key.Key
	// key.Map
	// ... etc
	switch v := val.(type) {
	case string:
		return &pb.TypedValue{Value: &pb.TypedValue_StringVal{StringVal: v}}
	case int:
		return &pb.TypedValue{Value: &pb.TypedValue_IntVal{IntVal: int64(v)}}
	case int8:
		return &pb.TypedValue{Value: &pb.TypedValue_IntVal{IntVal: int64(v)}}
	case int16:
		return &pb.TypedValue{Value: &pb.TypedValue_IntVal{IntVal: int64(v)}}
	case int32:
		return &pb.TypedValue{Value: &pb.TypedValue_IntVal{IntVal: int64(v)}}
	case int64:
		return &pb.TypedValue{Value: &pb.TypedValue_IntVal{IntVal: v}}
	case uint:
		return &pb.TypedValue{Value: &pb.TypedValue_UintVal{UintVal: uint64(v)}}
	case uint8:
		return &pb.TypedValue{Value: &pb.TypedValue_UintVal{UintVal: uint64(v)}}
	case uint16:
		return &pb.TypedValue{Value: &pb.TypedValue_UintVal{UintVal: uint64(v)}}
	case uint32:
		return &pb.TypedValue{Value: &pb.TypedValue_UintVal{UintVal: uint64(v)}}
	case uint64:
		return &pb.TypedValue{Value: &pb.TypedValue_UintVal{UintVal: v}}
	case bool:
		return &pb.TypedValue{Value: &pb.TypedValue_BoolVal{BoolVal: v}}
	case float32:
		return &pb.TypedValue{Value: &pb.TypedValue_FloatVal{FloatVal: v}}
	case []interface{}:
		gnmiElems := make([]*pb.TypedValue, len(v))
		for i, elem := range v {
			gnmiElems[i] = TypedValue(elem)
		}
		return &pb.TypedValue{
			Value: &pb.TypedValue_LeaflistVal{
				LeaflistVal: &pb.ScalarArray{
					Element: gnmiElems,
				}}}
	default:
		panic(fmt.Sprintf("unexpected type %T for value %v", val, val))
	}
}

// ExtractValue pulls a value out of a gNMI Update, parsing JSON if present.
// Possible return types:
//  string
//  int64
//  uint64
//  bool
//  []byte
//  float32
//  *gnmi.Decimal64
//  json.Number
//  *any.Any
//  []interface{}
//  map[string]interface{}
func ExtractValue(update *pb.Update) (interface{}, error) {
	var i interface{}
	var err error
	if update == nil {
		return nil, fmt.Errorf("empty update")
	}
	if update.Val != nil {
		i, err = extractValueV04(update.Val)
	} else if update.Value != nil {
		i, err = extractValueV03(update.Value)
	}
	return i, err
}

func extractValueV04(val *pb.TypedValue) (interface{}, error) {
	switch v := val.Value.(type) {
	case *pb.TypedValue_StringVal:
		return v.StringVal, nil
	case *pb.TypedValue_IntVal:
		return v.IntVal, nil
	case *pb.TypedValue_UintVal:
		return v.UintVal, nil
	case *pb.TypedValue_BoolVal:
		return v.BoolVal, nil
	case *pb.TypedValue_BytesVal:
		return v.BytesVal, nil
	case *pb.TypedValue_FloatVal:
		return v.FloatVal, nil
	case *pb.TypedValue_DecimalVal:
		return v.DecimalVal, nil
	case *pb.TypedValue_LeaflistVal:
		elementList := v.LeaflistVal.Element
		l := make([]interface{}, len(elementList))
		for i, element := range elementList {
			el, err := extractValueV04(element)
			if err != nil {
				return nil, err
			}
			l[i] = el
		}
		return l, nil
	case *pb.TypedValue_AnyVal:
		return v.AnyVal, nil
	case *pb.TypedValue_JsonVal:
		return decode(v.JsonVal)
	case *pb.TypedValue_JsonIetfVal:
		return decode(v.JsonIetfVal)
	case *pb.TypedValue_AsciiVal:
		return v.AsciiVal, nil
	case *pb.TypedValue_ProtoBytes:
		return v.ProtoBytes, nil
	}
	return nil, fmt.Errorf("unhandled type of value %v", val.GetValue())
}

func extractValueV03(val *pb.Value) (interface{}, error) {
	switch val.Type {
	case pb.Encoding_JSON, pb.Encoding_JSON_IETF:
		return decode(val.Value)
	case pb.Encoding_BYTES, pb.Encoding_PROTO:
		return val.Value, nil
	case pb.Encoding_ASCII:
		return string(val.Value), nil
	}
	return nil, fmt.Errorf("unhandled type of value %v", val.GetValue())
}

func decode(byteArr []byte) (interface{}, error) {
	decoder := json.NewDecoder(bytes.NewReader(byteArr))
	decoder.UseNumber()
	var value interface{}
	err := decoder.Decode(&value)
	return value, err
}

// DecimalToFloat converts a gNMI Decimal64 to a float64
func DecimalToFloat(dec *pb.Decimal64) float64 {
	return float64(dec.Digits) / math.Pow10(int(dec.Precision))
}

func update(p *pb.Path, val string) (*pb.Update, error) {
	var v *pb.TypedValue
	switch p.Origin {
	case "":
		v = &pb.TypedValue{
			Value: &pb.TypedValue_JsonIetfVal{JsonIetfVal: extractJSON(val)}}
	case "eos_native":
		v = &pb.TypedValue{
			Value: &pb.TypedValue_JsonVal{JsonVal: extractJSON(val)}}
	case "cli", "test-regen-cli":
		v = &pb.TypedValue{
			Value: &pb.TypedValue_AsciiVal{AsciiVal: val}}
	case "p4_config":
		b, err := ioutil.ReadFile(val)
		if err != nil {
			return nil, err
		}
		v = &pb.TypedValue{
			Value: &pb.TypedValue_ProtoBytes{ProtoBytes: b}}
	default:
		return nil, fmt.Errorf("unexpected origin: %q", p.Origin)
	}

	return &pb.Update{Path: p, Val: v}, nil
}

// Operation describes an gNMI operation.
type Operation struct {
	Type   string
	Origin string
	Target string
	Path   []string
	Val    string
}

func newSetRequest(setOps []*Operation, exts ...*gnmi_ext.Extension) (*pb.SetRequest, error) {
	req := &pb.SetRequest{}
	for _, op := range setOps {
		p, err := ParseGNMIElements(op.Path)
		if err != nil {
			return nil, err
		}
		p.Origin = op.Origin

		// Target must apply to the entire SetRequest.
		if op.Target != "" {
			req.Prefix = &pb.Path{
				Target: op.Target,
			}
		}

		switch op.Type {
		case "delete":
			req.Delete = append(req.Delete, p)
		case "update":
			u, err := update(p, op.Val)
			if err != nil {
				return nil, err
			}
			req.Update = append(req.Update, u)
		case "replace":
			u, err := update(p, op.Val)
			if err != nil {
				return nil, err
			}
			req.Replace = append(req.Replace, u)
		}
	}
	for _, ext := range exts {
		req.Extension = append(req.Extension, ext)
	}
	return req, nil
}

Manuel Max Kieweg's avatar
Manuel Max Kieweg committed
417
// Set sends a SetRequest to the given client.
418
func Set(ctx context.Context, client pb.GNMIClient, setOps []*Operation,
Manuel Max Kieweg's avatar
Manuel Max Kieweg committed
419
	exts ...*gnmi_ext.Extension) (*pb.SetResponse, error) {
420
421
	req, err := newSetRequest(setOps, exts...)
	if err != nil {
Manuel Max Kieweg's avatar
Manuel Max Kieweg committed
422
		return nil, err
423
	}
Manuel Max Kieweg's avatar
Manuel Max Kieweg committed
424
	return client.Set(ctx, req)
425
426
}

Manuel Max Kieweg's avatar
Manuel Max Kieweg committed
427
// Subscribe sends a SubscribeRequest to the given client.
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
511
512
513
514
515
516
517
// Deprecated: Use SubscribeErr instead.
func Subscribe(ctx context.Context, client pb.GNMIClient, subscribeOptions *SubscribeOptions,
	respChan chan<- *pb.SubscribeResponse, errChan chan<- error) {
	defer close(errChan)
	if err := SubscribeErr(ctx, client, subscribeOptions, respChan); err != nil {
		errChan <- err
	}
}

// SubscribeErr makes a gNMI.Subscribe call and writes the responses
// to the respChan. Before returning respChan will be closed.
func SubscribeErr(ctx context.Context, client pb.GNMIClient, subscribeOptions *SubscribeOptions,
	respChan chan<- *pb.SubscribeResponse) error {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	defer close(respChan)

	stream, err := client.Subscribe(ctx)
	if err != nil {
		return err
	}
	req, err := NewSubscribeRequest(subscribeOptions)
	if err != nil {
		return err
	}
	if err := stream.Send(req); err != nil {
		return err
	}

	for {
		resp, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
		respChan <- resp

		// For POLL subscriptions, initiate a poll request by pressing ENTER
		if subscribeOptions.Mode == "poll" {
			switch resp.Response.(type) {
			case *pb.SubscribeResponse_SyncResponse:
				fmt.Print("Press ENTER to send a poll request: ")
				reader := bufio.NewReader(os.Stdin)
				reader.ReadString('\n')

				pollReq := &pb.SubscribeRequest{
					Request: &pb.SubscribeRequest_Poll{
						Poll: &pb.Poll{},
					},
				}
				if err := stream.Send(pollReq); err != nil {
					return err
				}
			}
		}
	}
}

// LogSubscribeResponse logs update responses to stderr.
func LogSubscribeResponse(response *pb.SubscribeResponse) error {
	switch resp := response.Response.(type) {
	case *pb.SubscribeResponse_Error:
		return errors.New(resp.Error.Message)
	case *pb.SubscribeResponse_SyncResponse:
		if !resp.SyncResponse {
			return errors.New("initial sync failed")
		}
	case *pb.SubscribeResponse_Update:
		t := time.Unix(0, resp.Update.Timestamp).UTC()
		prefix := StrPath(resp.Update.Prefix)
		var target string
		if t := resp.Update.Prefix.GetTarget(); t != "" {
			target = "(" + t + ") "
		}
		for _, update := range resp.Update.Update {
			fmt.Printf("[%s] %s%s = %s\n", t.Format(time.RFC3339Nano),
				target,
				path.Join(prefix, StrPath(update.Path)),
				StrUpdateVal(update))
		}
		for _, del := range resp.Update.Delete {
			fmt.Printf("[%s] %sDeleted %s\n", t.Format(time.RFC3339Nano),
				target,
				path.Join(prefix, StrPath(del)))
		}
	}
	return nil
}