-
Notifications
You must be signed in to change notification settings - Fork 105
/
render.go
1870 lines (1687 loc) · 60.1 KB
/
render.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 Google Inc.
//
// 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 ygot
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/openconfig/gnmi/errlist"
"github.com/openconfig/gnmi/value"
"github.com/openconfig/ygot/internal/yreflect"
"github.com/openconfig/ygot/util"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
gnmipb "github.com/openconfig/gnmi/proto/gnmi"
)
const (
// BinaryTypeName is the name of the type that is used for YANG
// binary fields in the output structs.
BinaryTypeName string = "Binary"
// EmptyTypeName is the name of the type that is used for YANG
// empty fields in the output structs.
EmptyTypeName string = "YANGEmpty"
)
var (
// SimpleUnionBuiltinGoTypes stores the valid types that the Go code
// generation produces for simple union types given a regular leaf type
// name in Go.
SimpleUnionBuiltinGoTypes = map[string]string{
"int8": "UnionInt8",
"int16": "UnionInt16",
"int32": "UnionInt32",
"int64": "UnionInt64",
"uint8": "UnionUint8",
"uint16": "UnionUint16",
"uint32": "UnionUint32",
"uint64": "UnionUint64",
"float64": "UnionFloat64",
"string": "UnionString",
"bool": "UnionBool",
"interface{}": "*UnionUnsupported",
BinaryTypeName: BinaryTypeName,
EmptyTypeName: EmptyTypeName,
}
// unionSingletonUnderlyingTypes stores the underlying types of the
// singleton (i.e. non-struct, non-slice, non-map) typedefs used to
// represent union subtypes for the "Simplified Union Leaf" way of
// representatiing unions in the Go generated code.
unionSingletonUnderlyingTypes = map[string]reflect.Type{
"UnionInt8": reflect.TypeOf(int8(0)),
"UnionInt16": reflect.TypeOf(int16(0)),
"UnionInt32": reflect.TypeOf(int32(0)),
"UnionInt64": reflect.TypeOf(int64(0)),
"UnionUint8": reflect.TypeOf(uint8(0)),
"UnionUint16": reflect.TypeOf(uint16(0)),
"UnionUint32": reflect.TypeOf(uint32(0)),
"UnionUint64": reflect.TypeOf(uint64(0)),
"UnionFloat64": reflect.TypeOf(float64(0.0)),
"UnionString": reflect.TypeOf(string("")),
"UnionBool": reflect.TypeOf(bool(true)),
EmptyTypeName: reflect.TypeOf(bool(true)),
// Note: BinaryTypeName is missing here since it's a slice.
}
)
// path stores the elements of a path for a particular leaf,
// such that it can be used as a key for maps.
type path struct {
p *gnmiPath
}
func (p *path) String() string {
if p.p.isPathElemPath() {
return prototext.Format(&gnmipb.Path{Elem: p.p.pathElemPath})
}
return fmt.Sprintf("%v", p.p.pathElemPath)
}
// pathval combines path and the value for the relative or absolute path.
type pathval struct {
path *path
val any
}
// gnmiPath provides a wrapper for gNMI path types, particularly
// containing the Element-based paths which are used in gNMI pre-0.3.1 and
// PathElem-based paths which are used in gNMI 0.4.0 and above.
type gnmiPath struct {
// stringSlicePath stores a path expressed as a series of scalar elements. On output it is
// rendered to a []string which is placed in the gNMI element field.
stringSlicePath []string
// pathElemPath stores a path expressed as a series of PathElem messages.
pathElemPath []*gnmipb.PathElem
// isAbsolute determines whether the stored path is absolute (when set), or relative
// when unset.
isAbsolute bool
}
// newStringSliceGNMIPath returns a new gnmiPath with a string slice path.
func newStringSliceGNMIPath(s []string) *gnmiPath {
if s == nil {
s = []string{}
}
return &gnmiPath{stringSlicePath: s}
}
// newPathElemGNMIPath returns a new gnmiPath with a PathElem path.
func newPathElemGNMIPath(e []*gnmipb.PathElem) *gnmiPath {
if e == nil {
e = []*gnmipb.PathElem{}
}
return &gnmiPath{pathElemPath: e}
}
// isValid determines whether a gnmiPath is valid by determining whether the
// elementPath and structuredPath are both set or both unset.
func (g *gnmiPath) isValid() bool {
return (g.stringSlicePath == nil) != (g.pathElemPath == nil)
}
// isStringSlicePath determines whether the gnmiPath receiver describes a simple
// string slice path, or a structured path using gnmipb.PathElem values.
func (g *gnmiPath) isStringSlicePath() bool {
return g.stringSlicePath != nil
}
// isPathElemPath determines whether the gnmiPath receiver describes a structured
// PathElem based gNMI path.
func (g *gnmiPath) isPathElemPath() bool {
return g.pathElemPath != nil
}
// Copy returns a shallow copy of the current gnmiPath.
//
// In particular, the pre-0.4.0 gNMI path is a deep copy, but the PathElem gNMI
// path will be a shallow copy.
func (g *gnmiPath) Copy() *gnmiPath {
n := &gnmiPath{}
if g.isStringSlicePath() {
n.stringSlicePath = make([]string, len(g.stringSlicePath))
copy(n.stringSlicePath, g.stringSlicePath)
return n
}
n.pathElemPath = make([]*gnmipb.PathElem, len(g.pathElemPath))
copy(n.pathElemPath, g.pathElemPath)
return n
}
// Len returns the length of the path specified by gnmiPath.
func (g *gnmiPath) Len() int {
if g.isStringSlicePath() {
return len(g.stringSlicePath)
}
return len(g.pathElemPath)
}
// AppendName appends the string n as a new name within the gnmiPath.
// If the supplied name is nil, it is not appended.
func (g *gnmiPath) AppendName(n string) error {
if !g.isValid() {
return fmt.Errorf("cannot append to invalid path")
}
if n == "" {
return nil
}
if g.isStringSlicePath() {
g.stringSlicePath = append(g.stringSlicePath, n)
return nil
}
g.pathElemPath = append(g.pathElemPath, &gnmipb.PathElem{Name: n})
return nil
}
// Pop removes the last element from the gnmiPath.
// If the supplied path is empty, then an error is returned.
func (g *gnmiPath) Pop() error {
if !g.isValid() {
return fmt.Errorf("cannot pop from invalid path")
}
if g.Len() == 0 {
return fmt.Errorf("cannot pop from empty path")
}
if g.isStringSlicePath() {
g.stringSlicePath = g.stringSlicePath[:len(g.stringSlicePath)-1]
} else {
g.pathElemPath = g.pathElemPath[:g.Len()-1]
}
return nil
}
// LastPathElem returns the last PathElem element in the gnmiPath.
func (g *gnmiPath) LastPathElem() (*gnmipb.PathElem, error) {
return g.PathElemAt(g.Len() - 1)
}
// LastStringElem returns the last string element of the gnmiPath.
func (g *gnmiPath) LastStringElem() (string, error) {
return g.StringElemAt(g.Len() - 1)
}
// PathElemAt returns the PathElem at index i in the gnmiPath. It returns an error if the
// path is invalid, is not a path elem path, or the index is greater than the length
// of the path.
func (g *gnmiPath) PathElemAt(i int) (*gnmipb.PathElem, error) {
if !g.isValid() || !g.isPathElemPath() {
return nil, errors.New("invalid call to PathElemAt() on a non-PathElem path")
}
if i > g.Len() || i < 0 {
return nil, fmt.Errorf("invalid index %d for gnmiPath len %d", i, g.Len())
}
return g.pathElemPath[i], nil
}
// StringElemAt returns the string element at index i in the gnmiPath. It returns an error
// if the path is invalid, is not a string slice path, or the index is greater than the
// length of the path.
func (g *gnmiPath) StringElemAt(i int) (string, error) {
if !g.isValid() || !g.isStringSlicePath() {
return "", errors.New("invalid call to StringElemAt() on a non-string element path")
}
if i > g.Len() || i < 0 {
return "", fmt.Errorf("invalid index %d for gnmiPath len %d", i, g.Len())
}
return g.stringSlicePath[i], nil
}
// SetIndex sets the element at index i to the value v.
func (g *gnmiPath) SetIndex(i int, v any) error {
if i > g.Len() {
return fmt.Errorf("invalid index, out of range, got: %d, length: %d", i, g.Len())
}
switch v := v.(type) {
case string:
if !g.isStringSlicePath() {
return fmt.Errorf("cannot set index %d of %v to %v, wrong type %T, expected string", i, v, g, v)
}
g.stringSlicePath[i] = v
return nil
case *gnmipb.PathElem:
if !g.isPathElemPath() {
return fmt.Errorf("cannot set index %d of %v to %v, wrong type %T, expected gnmipb.PathElem", i, v, g, v)
}
g.pathElemPath[i] = v
return nil
}
return fmt.Errorf("cannot set index %d of %v to %v, wrong type %T", i, v, g, v)
}
// ToProto returns the gnmiPath as a gnmi.proto Path message.
func (g *gnmiPath) ToProto() (*gnmipb.Path, error) {
if !g.isValid() {
return nil, errors.New("invalid path")
}
if g.Len() == 0 {
return nil, nil
}
if g.isStringSlicePath() {
return &gnmipb.Path{Element: g.stringSlicePath}, nil
}
return &gnmipb.Path{Elem: g.pathElemPath}, nil
}
// isSameType returns true if the path supplied is the same type as the
// receiver.
func (g *gnmiPath) isSameType(p *gnmiPath) bool {
return g.isStringSlicePath() == p.isStringSlicePath()
}
// StripPrefix removes the prefix pfx from the supplied path, and returns the more
// specific path elements of the path. It returns an error if the paths are invalid,
// their types are different, or the prefix does not match the path.
func (g *gnmiPath) StripPrefix(pfx *gnmiPath) (*gnmiPath, error) {
if !g.isSameType(pfx) {
return nil, fmt.Errorf("mismatched path formats in prefix and path, isElementPath: %v != %v", g.isStringSlicePath(), pfx.isStringSlicePath())
}
if !g.isValid() || !pfx.isValid() {
return nil, fmt.Errorf("invalid paths supplied for stripPrefix: %v, %v", g, pfx)
}
if pfx.isStringSlicePath() {
for i, e := range pfx.stringSlicePath {
if g.stringSlicePath[i] != e {
return nil, fmt.Errorf("prefix is not a prefix of the supplied path, %v is not a subset of %v", pfx, g)
}
}
return newStringSliceGNMIPath(g.stringSlicePath[len(pfx.stringSlicePath):]), nil
}
for i, e := range pfx.pathElemPath {
if !util.PathElemsEqual(g.pathElemPath[i], e) {
return nil, fmt.Errorf("prefix is not a prefix of the supplied path, %v is not a subset of %v", pfx, g)
}
}
return newPathElemGNMIPath(g.pathElemPath[len(pfx.pathElemPath):]), nil
}
// GNMINotificationsConfig specifies arguments determining how the
// gNMI output should be created by ygot.
type GNMINotificationsConfig struct {
// UsePathElem specifies whether the elem field of the gNMI Path
// message should be used for the paths in the output notification. If
// set to false, the element field is used.
UsePathElem bool
// ElementPrefix stores the prefix that should be used within the
// Prefix field of the gNMI Notification message expressed as a slice
// of strings as per the path definition in gNMI 0.3.1 and below.
// Used if UsePathElem is unset.
//
// If there is an ordered map, which will always be marshalled within
// its own Notification message, then the ordered map will be given a
// prefix that concatenates the given prefix with the relative path of
// the ordered map from the given node.
StringSlicePrefix []string
// PathElemPrefix stores the prefix that should be used within the
// Prefix field of the gNMI Notification message, expressed as a slice
// of PathElem messages. This path format is used by gNMI 0.4.0 and
// above. Used if PathElem is set.
//
// If there is an ordered map, which will always be marshalled within
// its own Notification message, then the ordered map will be given a
// prefix that concatenates the given prefix with the relative path of
// the ordered map from the given node.
PathElemPrefix []*gnmipb.PathElem
}
// TogNMINotifications takes an input GoStruct and renders it to slice of
// Notification messages, marked with the specified timestamp. The configuration
// provided determines the path format utilised, and the prefix to be included
// in the message if relevant. If there are any `ordered-by user` lists within
// the input struct, then they will be treated as "telemetry-atomic", and put
// into separate atomic notifications after the initial notification containing
// the non-atomic updates.
//
// Note: Within the generated notifications there could be data sharing for
// space and compute optimization. Make a deep copy if one plans to modify the
// generated message.
//
// TODO(robjs): When we have deprecated the string slice paths, then this function
// can be simplified to remove support for them - including removing the gnmiPath
// abstraction. It can also be refactored to simply use the findSetleaves function
// which has a cleaner implementation using the reworked iterfunction util.
func TogNMINotifications(s GoStruct, ts int64, cfg GNMINotificationsConfig) ([]*gnmipb.Notification, error) {
var pfx *gnmiPath
if cfg.UsePathElem {
pfx = newPathElemGNMIPath(cfg.PathElemPrefix)
} else {
pfx = newStringSliceGNMIPath(cfg.StringSlicePrefix)
}
leaves := map[*path]any{}
if err := findUpdatedLeaves(leaves, s, pfx); err != nil {
return nil, err
}
msgs, err := leavesToNotifications(leaves, ts, pfx)
if err != nil {
return nil, err
}
return msgs, nil
}
// findUpdatedOrderedListLeaves appends the valid leaves that are within the supplied
// GoOrderedLst (assumed to be rooted at parentPath) to the supplied leaves map.
// If errors are encountered they are appended to the errlist.List supplied. If
// the GoOrderedLst contains fields that are themselves structured objects (YANG
// lists, or containers - represented as maps or struct pointers), then we
// recursively update them.
//
// Note: the returned paths use a shallow copy of the parentPath.
//
// Limitation: nested ordered lists are not supported.
func findUpdatedOrderedListLeaves(leaves any, s GoOrderedMap, parent *gnmiPath) error {
var errs errlist.List
var leavesMap map[*path]any
switch leaves := leaves.(type) {
case map[*path]any:
leavesMap = leaves
case *[]*pathval:
// TODO: Support nested ordered lists/atomic elements -- they should marshal in
// the regular way without creating a second []*pathval.
return fmt.Errorf("detected nested `ordered-by user` list, this is not supported")
default:
return fmt.Errorf("internal ygot error: leaves is not an expected type: %T", leaves)
}
atomicLeaves, subtreePath, err := orderedMapLeaves(s, parent)
if err != nil {
errs.Add(err)
return errs.Err()
}
if len(atomicLeaves) > 0 {
leavesMap[&path{subtreePath}] = atomicLeaves
}
return errs.Err()
}
// findUpdatedLeaves appends the valid leaves that are within the supplied
// GoStruct (assumed to the rooted at parentPath) to the supplied leaves map.
// If errors are encountered they are appended to the errlist.List supplied. If
// the GoStruct contains fields that are themselves structured objects (YANG
// lists, or containers - represented as maps or struct pointers), the function
// is called recursively on them.
//
// Note: the returned paths use a shallow copy of the parentPath.
func findUpdatedLeaves(leaves any, s GoStruct, parent *gnmiPath) error {
// addLeaf is the function that must be used to add a single leaf or
// atomic update to the input cache of leaves. The reason this is
// different is because atomic values must be added in a different way
// than a regular leaf value: whereas the ordering of leaves doesn't
// matter, the ordering of leaves in an atomic subtree node may matter,
// for example in the case of YANG `ordered-by user` lists, where the
// leaves must be marshalled in the right key order.
var addLeaf func(path *path, value any)
switch leaves := leaves.(type) {
case map[*path]any:
addLeaf = func(path *path, value any) {
leaves[path] = value
}
case *[]*pathval:
addLeaf = func(path *path, value any) {
*leaves = append(*leaves, &pathval{
path: path,
val: value,
})
}
default:
return fmt.Errorf("internal ygot error: leaves is not an expected type: %T", leaves)
}
var errs errlist.List
if !parent.isValid() {
return fmt.Errorf("invalid parent specified: %v", parent)
}
sval := reflect.ValueOf(s)
if s == nil || util.IsValueNil(sval) || !sval.IsValid() || !util.IsValueStructPtr(sval) {
errs.Add(fmt.Errorf("input struct for %v was not valid", parent))
return errs.Err()
}
sval = sval.Elem()
stype := sval.Type()
for i := 0; i < sval.NumField(); i++ {
fval := sval.Field(i)
ftype := stype.Field(i)
// Handle nil values, and enumerations specifically.
switch fval.Kind() {
case reflect.Map, reflect.Slice, reflect.Ptr, reflect.Interface:
if fval.IsNil() {
continue
}
}
mapPaths, err := structTagToLibPaths(ftype, parent, false)
if err != nil {
errs.Add(fmt.Errorf("%v->%s: %v", parent, ftype.Name, err))
continue
}
switch fval.Kind() {
case reflect.Map:
// We need to map each child along with its key value.
for _, k := range fval.MapKeys() {
childPath, err := mapValuePath(k, fval.MapIndex(k), mapPaths[0])
if err != nil {
errs.Add(err)
continue
}
goStruct, ok := fval.MapIndex(k).Interface().(GoStruct)
if !ok {
errs.Add(fmt.Errorf("%v: was not a valid GoStruct", mapPaths[0]))
continue
}
errs.Add(findUpdatedLeaves(leaves, goStruct, childPath))
}
case reflect.Ptr:
if ol, ok := fval.Interface().(GoOrderedMap); ok {
// This is an ordered-map for YANG "ordered-by user" lists.
errs.Add(findUpdatedOrderedListLeaves(leaves, ol, mapPaths[0]))
} else {
// Otherwise this is a pointer to a struct (another YANG container), or a leaf.
switch fval.Elem().Kind() {
case reflect.Struct:
goStruct, ok := fval.Interface().(GoStruct)
if !ok {
errs.Add(fmt.Errorf("%v: was not a valid GoStruct", mapPaths[0]))
continue
}
errs.Add(findUpdatedLeaves(leaves, goStruct, mapPaths[0]))
default:
for _, p := range mapPaths {
addLeaf(&path{p}, fval.Interface())
}
}
}
case reflect.Slice:
if fval.Type().Elem().Kind() == reflect.Ptr {
// This is a keyless list - currently unsupported for mapping since there is
// not an explicit path that can be used.
errs.Add(fmt.Errorf("unimplemented: keyless list cannot be output: %v", mapPaths[0]))
continue
}
// This is a leaf-list, so add it as though it were a leaf.
for _, p := range mapPaths {
addLeaf(&path{p}, fval.Interface())
}
case reflect.Int64:
name, set, err := enumFieldToString(fval, false)
if err != nil {
errs.Add(err)
continue
}
// Skip if the enum has not been explicitly set in the schema.
if !set {
continue
}
for _, p := range mapPaths {
addLeaf(&path{p}, name)
}
continue
case reflect.Interface:
// This is a union value.
for _, p := range mapPaths {
addLeaf(&path{p}, fval.Interface())
}
continue
}
}
return errs.Err()
}
// mapValuePath calculates the gNMI Path of a map element with the specified
// key and value. The format of the path returned depends on the input format
// of the parentPath.
func mapValuePath(key, value reflect.Value, parentPath *gnmiPath) (*gnmiPath, error) {
var childPath *gnmiPath
if parentPath == nil {
return nil, fmt.Errorf("nil map paths supplied to mapValuePath for %v %v", key.Interface(), value.Interface())
}
if parentPath.isStringSlicePath() {
childPath = &gnmiPath{}
keyval, err := KeyValueAsString(key.Interface())
if err != nil {
return nil, fmt.Errorf("can't append path element key: %v", err)
}
// We copy the elements from the existing elementPath such that when updating
// it, then the elements are not modified when the paths are changed.
childPath.stringSlicePath = append(childPath.stringSlicePath, parentPath.stringSlicePath...)
childPath.stringSlicePath = append(childPath.stringSlicePath, keyval)
return childPath, nil
}
// Note: this is shallow copy for performance.
childPath = parentPath.Copy()
return appendgNMIPathElemKey(value, childPath)
}
// appendgNMIPathElemKey takes an input reflect.Value which must implement KeyHelperGoStruct
// and appends the keys from it to the last entry in the supplied mapPath, which must be a
// gNMI PathElem message.
func appendgNMIPathElemKey(v reflect.Value, p *gnmiPath) (*gnmiPath, error) {
if p == nil {
return nil, fmt.Errorf("nil path supplied")
}
if !p.isValid() {
return nil, fmt.Errorf("invalid structured path in supplied path: %v", p)
}
if p.isStringSlicePath() {
return nil, fmt.Errorf("invalid path type to append keys: %v", p)
}
if p.Len() == 0 {
return nil, fmt.Errorf("invalid path element path length, can't append keys to 0 length path: %v", p.pathElemPath)
}
np := p.Copy()
e, err := np.LastPathElem()
if err != nil {
return nil, err
}
newElem := proto.Clone(e).(*gnmipb.PathElem)
if !v.IsValid() || v.IsNil() {
return nil, fmt.Errorf("nil value received for element %v", p)
}
k, err := PathKeyFromStruct(v)
if err != nil {
return nil, fmt.Errorf("cannot extract keys: %v", err)
}
newElem.Key = k
if err := np.SetIndex(np.Len()-1, newElem); err != nil {
return nil, err
}
return np, nil
}
// keyHelperStruct makes sure ΛListKeyMap() is implemented such that the struct
// has the corresponding function to retrieve the list keys as a map.
type keyHelperGoKeyStruct interface {
// ΛListKeyMap defines a helper method that returns a map of the
// keys of a list element.
ΛListKeyMap() (map[string]any, error)
}
// PathKeyFromStruct returns a map[string]string which represents the keys for a YANG
// list element. The provided reflect.Value must implement the KeyHelperGoStruct interface,
// and hence be a struct which represents a list member within the schema.
func PathKeyFromStruct(v reflect.Value) (map[string]string, error) {
gs, ok := v.Interface().(keyHelperGoKeyStruct)
if !ok {
return nil, fmt.Errorf("cannot render to gNMI PathElem for structs that do not implement KeyHelperGoStruct, got: %T (%s)", v.Type().Name(), v.Interface())
}
km, err := gs.ΛListKeyMap()
if err != nil {
return nil, err
}
k, err := keyMapAsStrings(km)
if err != nil {
return nil, err
}
return k, nil
}
// keyMapAsStrings takes an input map[string]any, keyed by the name of
// a leaf, and with a value of the leaf's value, and returns it as a map[string]string
// as is required in the gNMI PathElem message. The ΛListKeyMap helper function on
// a generated KeyHelperGoStruct returns a map[string]any of the form of
// the input keys argument to this function.
func keyMapAsStrings(keys map[string]any) (map[string]string, error) {
nk := map[string]string{}
for kn, k := range keys {
v, err := KeyValueAsString(k)
if err != nil {
return nil, err
}
nk[kn] = v
}
return nk, nil
}
// KeyValueAsString returns a string representation of the any supplied. If the
// type provided cannot be represented as a string for use in a gNMI path, an error is
// returned.
func KeyValueAsString(v any) (string, error) {
kv := reflect.ValueOf(v)
if _, isEnum := v.(GoEnum); isEnum {
name, _, err := enumFieldToString(kv, false)
if err != nil {
return "", fmt.Errorf("cannot resolve enumerated type in key, got err: %v", err)
}
return name, nil
}
switch kv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprintf("%d", v), nil
case reflect.Float64:
return fmt.Sprintf("%g", v), nil
case reflect.String:
return fmt.Sprintf("%s", v), nil
case reflect.Bool:
return fmt.Sprintf("%t", v), nil
case reflect.Ptr:
iv, err := unionPtrValue(kv, false)
if err != nil {
return "", err
}
return KeyValueAsString(iv)
case reflect.Slice:
if kv.Type().Elem().Kind() == reflect.Uint8 {
return binaryBase64(kv.Bytes()), nil
}
return "", fmt.Errorf("cannot convert slice of type %v to a string for use in a key: %v", kv.Type().Elem().Kind(), v)
}
return "", fmt.Errorf("cannot convert type %v to a string for use in a key: %v", kv.Kind(), v)
}
// sliceToScalarArray takes an input slice of empty interfaces and converts it to
// a gNMI ScalarArray that can be populated as the leaflist_val field within a Notification
// message. Returns an error if the slice contains a type that cannot be mapped to
// a TypedValue message.
func sliceToScalarArray(v []any) (*gnmipb.ScalarArray, error) {
arr := &gnmipb.ScalarArray{}
for _, e := range v {
tv, err := value.FromScalar(e)
if err != nil {
return nil, err
}
arr.Element = append(arr.Element, tv)
}
return arr, nil
}
// addToNotification adds the given path value pair to the given notification,
// stripping the given prefix.
func addToNotification(pk *path, value any, n *gnmipb.Notification, pfx *gnmiPath) error {
path, err := pk.p.StripPrefix(pfx)
if err != nil {
return err
}
ppath, err := path.ToProto()
if err != nil {
return err
}
val, err := EncodeTypedValue(value, gnmipb.Encoding_JSON)
if err != nil {
return err
}
n.Update = append(n.Update, &gnmipb.Update{
Path: ppath,
Val: val,
})
return nil
}
// leavesToNotifications takes an input map of leaves, and outputs a slice of
// notifications that corresponds to the leaf update, the supplied timestamp is
// used in the set of notifications. If an error is encountered it is returned.
// TODO(robjs): Currently, we return only a single Notification for all but
// ordered lists, but this is likely to be suboptimal since it results in very
// large Notifications for particular structs. There should be some
// fragmentation of Updates across Notification messages in a future
// implementation. We return a slice to keep the API stable.
func leavesToNotifications(leaves map[*path]any, ts int64, pfx *gnmiPath) ([]*gnmipb.Notification, error) {
var notifs []*gnmipb.Notification
// Non-"telemetry-atomic" values.
n := &gnmipb.Notification{
Timestamp: ts,
}
p, err := pfx.ToProto()
if err != nil {
return nil, err
}
n.Prefix = p
for pk, v := range leaves {
// This is for handling "telemetry-atomic" subtrees that have
// leaves bundled and possibly in a certain order.
if pvs, ok := v.([]*pathval); ok {
// Check that the subtree path matches the prefix, and
// then provide the subtree path itself as the prefix.
subtreePfx := pk.p
if _, err := subtreePfx.StripPrefix(pfx); err != nil {
return nil, err
}
notif, err := createAtomicNotif(pvs, ts, subtreePfx)
if err != nil {
return nil, err
}
if notif != nil {
notifs = append(notifs, notif)
}
} else if err := addToNotification(pk, v, n, pfx); err != nil {
return nil, err
}
}
switch {
case len(n.Update) == 0 && len(notifs) == 0:
return []*gnmipb.Notification{n}, nil
case len(n.Update) == 0:
return notifs, nil
default:
return append([]*gnmipb.Notification{n}, notifs...), nil
}
}
// EncodeTypedValueOpt is an interface implemented by arguments to
// the EncodeTypedValueOpt function.
type EncodeTypedValueOpt interface {
// IsMarshal7951Arg is a market method.
IsEncodeTypedValueOpt()
}
// EncodeTypedValue encodes val into a gNMI TypedValue message, using the specified encoding
// type if the value is a struct.
func EncodeTypedValue(val any, enc gnmipb.Encoding, opts ...EncodeTypedValueOpt) (*gnmipb.TypedValue, error) {
jc := &RFC7951JSONConfig{}
for _, opt := range opts {
if cfg, ok := opt.(*RFC7951JSONConfig); ok {
jc = cfg
}
}
switch v := val.(type) {
case GoStruct, GoOrderedMap:
return marshalStructOrOrderedList(v, enc, jc)
case GoEnum:
en, err := EnumName(v)
if err != nil {
return nil, fmt.Errorf("cannot marshal enum, %v", err)
}
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_StringVal{en}}, nil
}
vv := reflect.ValueOf(val)
switch {
case util.IsValueNil(vv) || !vv.IsValid():
return nil, nil
case vv.Type().Kind() == reflect.Int64 && unionSingletonUnderlyingTypes[vv.Type().Name()] == nil:
// Invalid int64 that is not an enum or a simple union Int64 type.
return nil, fmt.Errorf("cannot represent field value %v as TypedValue", val)
case vv.Type().Name() == BinaryTypeName:
// This is a binary type which is defined as a []byte, so we encode it as the bytes.
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_BytesVal{vv.Bytes()}}, nil
case vv.Type().Name() == EmptyTypeName:
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_BoolVal{vv.Bool()}}, nil
case vv.Kind() == reflect.Slice:
sval, err := leaflistToSlice(vv, false)
if err != nil {
return nil, err
}
arr, err := sliceToScalarArray(sval)
if err != nil {
return nil, err
}
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_LeaflistVal{arr}}, nil
case util.IsValueStructPtr(vv):
nv, err := unwrapUnionInterfaceValue(vv, false)
if err != nil {
return nil, fmt.Errorf("cannot resolve union field value: %v", err)
}
vv = reflect.ValueOf(nv)
// Apart from binary, all other possible union subtypes are scalars or typedefs of scalars.
if vv.Type().Name() == BinaryTypeName {
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_BytesVal{vv.Bytes()}}, nil
}
case util.IsValuePtr(vv):
vv = vv.Elem()
if util.IsNilOrInvalidValue(vv) {
return nil, nil
}
default:
if underlyingType, ok := unionSingletonUnderlyingTypes[vv.Type().Name()]; ok {
if !vv.Type().ConvertibleTo(underlyingType) {
return nil, fmt.Errorf("ygot internal implementation bug: union type %q inconvertible to underlying type %q", vv.Type().Name(), underlyingType)
}
vv = vv.Convert(underlyingType)
}
}
return value.FromScalar(vv.Interface())
}
// marshalStructOrOrderedList encodes the struct/ordered list s according to
// the encoding specified by enc. It is returned as a TypedValue gNMI message.
func marshalStructOrOrderedList(s any, enc gnmipb.Encoding, cfg *RFC7951JSONConfig) (*gnmipb.TypedValue, error) {
if reflect.ValueOf(s).IsNil() {
return nil, nil
}
var (
j any
err error
encfn func(s string) *gnmipb.TypedValue
)
switch enc {
case gnmipb.Encoding_JSON:
j, err = jsonValue(reflect.ValueOf(s), "", jsonOutputConfig{jType: Internal})
encfn = func(s string) *gnmipb.TypedValue {
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_JsonVal{JsonVal: []byte(s)}}
}
case gnmipb.Encoding_JSON_IETF:
// We always prepend the module name when marshalling within a Notification.
cfg.AppendModuleName = true
j, err = jsonValue(reflect.ValueOf(s), "", jsonOutputConfig{jType: RFC7951, rfc7951Config: cfg})
encfn = func(s string) *gnmipb.TypedValue {
return &gnmipb.TypedValue{Value: &gnmipb.TypedValue_JsonIetfVal{JsonIetfVal: []byte(s)}}
}
default:
return nil, fmt.Errorf("invalid encoding %v", gnmipb.Encoding_name[int32(enc)])
}
if err != nil {
return nil, err
}
js, err := json.MarshalIndent(j, "", " ")
if err != nil {
return nil, fmt.Errorf("cannot encode JSON, %v", err)
}
return encfn(string(js)), nil
}
// leaflistToSlice takes a reflect.Value that represents a leaf list in the YANG schema
// (GoStruct) and outputs a slice of any that corresponds to its contents that
// should be used within a Notification. If prependModuleNameIref is set to true, then
// identity names are prepended with the name of the module that defines them.
func leaflistToSlice(val reflect.Value, prependModuleNameIref bool) ([]any, error) {
sval := []any{}
for i := 0; i < val.Len(); i++ {
e := val.Index(i)
// Handle mapping leaf-lists. There are two cases of leaf-lists
// within the YANG structs. The first is the simple case of having
// a single typed leaf-list - so mapping can be done solely based
// on the type of the elements of the slice. The second case is
// a leaf-list of union values, which means that there may be
// multiple types. This is represented as []any
switch e.Kind() {
case reflect.String:
sval = append(sval, e.String())
case reflect.Uint8:
sval = append(sval, uint8(e.Uint()))
case reflect.Uint16:
sval = append(sval, uint16(e.Uint()))
case reflect.Uint32:
sval = append(sval, uint32(e.Uint()))
case reflect.Uint64, reflect.Uint:
sval = append(sval, e.Uint())
case reflect.Int8:
sval = append(sval, int8(e.Int()))
case reflect.Int16:
sval = append(sval, int16(e.Int()))
case reflect.Int32:
sval = append(sval, int32(e.Int()))
case reflect.Int:
sval = append(sval, e.Int())
case reflect.Int64:
if _, ok := e.Interface().(GoEnum); ok {
name, _, err := enumFieldToString(e, prependModuleNameIref)
if err != nil {
return nil, err
}
sval = append(sval, name)
} else {
sval = append(sval, e.Int())
}
case reflect.Float32, reflect.Float64:
sval = append(sval, e.Float())
case reflect.Bool:
sval = append(sval, e.Bool())
case reflect.Interface:
// Occurs in two cases:
// 1) Where there is a leaflist of mixed types.
// 2) Where there is a leaflist of unions.
var err error
ev := e.Elem()