/
cvl_semantics.go
1767 lines (1504 loc) · 54.4 KB
/
cvl_semantics.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 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. //
// //
// 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 cvl
import (
"encoding/json"
"encoding/xml"
"fmt"
"regexp"
"strings"
cmn "github.com/Azure/sonic-mgmt-common/cvl/common"
"github.com/Azure/sonic-mgmt-common/cvl/internal/yparser"
"github.com/antchfx/jsonquery"
"github.com/antchfx/xmlquery"
"github.com/antchfx/xpath"
"github.com/google/go-cmp/cmp"
//lint:ignore ST1001 This is safe to dot import for util package
. "github.com/Azure/sonic-mgmt-common/cvl/internal/util"
)
// YValidator YANG Validator used for external semantic
// validation including custom/platform validation
type YValidator struct {
root *xmlquery.Node //Top evel root for data
current *xmlquery.Node //Current position
//operation string //Edit operation
}
type DepDataCallBack func(ctxt interface{}, redisKeys []string, redisKeyFilter, keyNames, pred, fields, count string) string
type DepDataCountCallBack func(ctxt interface{}, redisKeyFilter, keyNames, pred, field string) float64
var depDataCb DepDataCallBack = func(ctxt interface{}, redisKeys []string, redisKeyFilter, keyNames, pred, fields, count string) string {
c := ctxt.(*CVL)
return c.addDepYangData(redisKeys, redisKeyFilter, keyNames, pred, fields, 0)
}
var depDataCountCb DepDataCountCallBack = func(ctxt interface{}, redisKeyFilter, keyNames, pred, field string) float64 {
if pred != "" {
pred = "return (" + pred + ")"
}
c := ctxt.(*CVL)
s := cmn.Search{Pattern: redisKeyFilter, Predicate: pred, KeyNames: strings.Split(keyNames, "|"), WithField: field}
redisEntries, err := c.dbAccess.Count(s).Result()
count := float64(0)
if (err == nil) && (redisEntries > 0) {
count = float64(redisEntries)
}
if IsTraceAllowed(TRACE_SEMANTIC) {
TRACE_LOG(TRACE_SEMANTIC, "depDataCountCb() with redisKeyFilter=%s, keyNames= %s, predicate=%s, fields=%s, returned = %v", redisKeyFilter, keyNames, pred, field, count)
}
return count
}
// Generate leaf/leaf-list YANG data
func (c *CVL) generateYangLeafData(tableName string, jsonNode *jsonquery.Node,
parent *xmlquery.Node) CVLRetCode {
//Traverse fields
for jsonFieldNode := jsonNode.FirstChild; jsonFieldNode != nil; jsonFieldNode = jsonFieldNode.NextSibling {
//Add fields as leaf to the list
if jsonFieldNode.Type == jsonquery.ElementNode &&
jsonFieldNode.FirstChild != nil &&
jsonFieldNode.FirstChild.Type == jsonquery.TextNode {
if len(modelInfo.tableInfo[tableName].mapLeaf) == 2 { //mapping should have two leaf always
//Values should be stored inside another list as map table
listNode := c.addYangNode(tableName, parent, tableName, "") //Add the list to the top node
c.addYangNode(tableName,
listNode, modelInfo.tableInfo[tableName].mapLeaf[0],
jsonFieldNode.Data)
c.addYangNode(tableName,
listNode, modelInfo.tableInfo[tableName].mapLeaf[1],
jsonFieldNode.FirstChild.Data)
} else {
//check if it is hash-ref, then need to add only key from "TABLE|k1"
hashRefMatch := reHashRef.FindStringSubmatch(jsonFieldNode.FirstChild.Data)
if len(hashRefMatch) == 3 {
c.addYangNode(tableName,
parent, jsonFieldNode.Data,
hashRefMatch[2]) //take hashref key value
} else {
c.addYangNode(tableName,
parent, jsonFieldNode.Data,
jsonFieldNode.FirstChild.Data)
}
}
} else if jsonFieldNode.Type == jsonquery.ElementNode &&
jsonFieldNode.FirstChild != nil &&
jsonFieldNode.FirstChild.Type == jsonquery.ElementNode {
//Array data e.g. VLAN members@ or 'ports@'
for arrayNode := jsonFieldNode.FirstChild; arrayNode != nil; arrayNode = arrayNode.NextSibling {
node := c.addYangNode(tableName,
parent, jsonFieldNode.Data,
arrayNode.FirstChild.Data)
//mark these nodes as leaf-list
addAttrNode(node, "leaf-list", "")
}
}
}
//Add all the default nodes required for must and when exps evaluation
for nodeName, valStr := range modelInfo.tableInfo[tableName].dfltLeafVal {
//Check if default node is already present in data
var child *xmlquery.Node
for child = parent.FirstChild; child != nil; child = child.NextSibling {
if child.Data == nodeName {
break
}
}
if child != nil {
//node is already present, skip adding it
continue
}
valArr := strings.Split(valStr, ",")
for idx := 0; idx < len(valArr); idx++ {
node := c.addYangNode(tableName,
parent, nodeName, valArr[idx])
//mark these nodes as leaf-list
if len(valArr) > 1 {
addAttrNode(node, "leaf-list", "")
}
}
}
return CVL_SUCCESS
}
// Add attribute YANG node
func addAttrNode(n *xmlquery.Node, key, val string) {
var attr xml.Attr = xml.Attr{
Name: xml.Name{Local: key},
Value: val,
}
n.Attr = append(n.Attr, attr)
}
func getAttrNodeVal(node *xmlquery.Node, name string) string {
if node == nil {
return ""
}
if len(node.Attr) == 0 {
return ""
}
for idx := 0; idx < len(node.Attr); idx++ {
if node.Attr[idx].Name.Local == name {
return node.Attr[idx].Value
}
}
return ""
}
// Add YANG node with or without parent, with or without value
func (c *CVL) addYangNode(tableName string, parent *xmlquery.Node,
name string, value string) *xmlquery.Node {
//Create the node
node := &xmlquery.Node{Parent: parent, Data: name,
Type: xmlquery.ElementNode}
//Set prefix from parent
if parent != nil {
node.Prefix = parent.Prefix
}
if value != "" {
//Create the value node
textNode := &xmlquery.Node{Data: value, Type: xmlquery.TextNode}
node.FirstChild = textNode
node.LastChild = textNode
}
if parent == nil {
//Creating top node
return node
}
if parent.FirstChild == nil {
//Create as first child
parent.FirstChild = node
parent.LastChild = node
} else {
//Append as sibling
tmp := parent.LastChild
tmp.NextSibling = node
node.PrevSibling = tmp
parent.LastChild = node
}
return node
}
// Generate YANG list data along with top container,
// table container.
// If needed, stores the list pointer against each request table/key
// in requestCahce so that YANG data can be reached
// directly on given table/key
func (c *CVL) generateYangListData(jsonNode *jsonquery.Node,
storeInReqCache bool) (*xmlquery.Node, CVLErrorInfo) {
var cvlErrObj CVLErrorInfo
tableName := jsonNode.Data
origTableName := tableName
c.batchLeaf = nil
c.batchLeaf = make([]*yparser.YParserLeafValue, 0)
//Every Redis table is mapped as list within a container,
//E.g. ACL_RULE is mapped as
// container ACL_RULE { list ACL_RULE_LIST {} }
var topNode *xmlquery.Node
var listConatinerNode *xmlquery.Node
topNodesAdded := false
//Traverse each key instance
keyPresent := false
for jsonNode = jsonNode.FirstChild; jsonNode != nil; jsonNode = jsonNode.NextSibling {
//store the redis key
redisKey := jsonNode.Data
//Mark at least one key is present
keyPresent = true
//For each field check if is key
//If it is key, create list as child of top container
// Get all key name/value pairs
if yangListName := getRedisTblToYangList(origTableName, redisKey); yangListName != "" {
tableName = yangListName
}
if _, exists := modelInfo.tableInfo[tableName]; !exists {
CVL_LOG(WARNING, "Failed to find schema details for table %s", origTableName)
cvlErrObj.ErrCode = CVL_SYNTAX_ERROR
cvlErrObj.TableName = origTableName
cvlErrObj.Msg = "Schema details not found"
return nil, cvlErrObj
}
if !topNodesAdded {
// Add top most container e.g. 'container sonic-acl {...}'
topNode = c.addYangNode(origTableName, nil, modelInfo.tableInfo[tableName].modelName, "")
//topNode.Prefix = modelInfo.modelNs[modelInfo.tableInfo[tableName].modelName].prefix
topNode.Prefix = modelInfo.tableInfo[tableName].modelName
topNode.NamespaceURI = modelInfo.modelNs[modelInfo.tableInfo[tableName].modelName].ns
//Add the container node for each list
//e.g. 'container ACL_TABLE { list ACL_TABLE_LIST ...}
listConatinerNode = c.addYangNode(origTableName, topNode, origTableName, "")
topNodesAdded = true
}
keyValuePair := getRedisToYangKeys(tableName, redisKey)
keyCompCount := len(keyValuePair)
totalKeyComb := 1
var keyIndices []int
//Find number of all key combinations
//Each key can have one or more key values, which results in nk1 * nk2 * nk2 combinations
idx := 0
for i := range keyValuePair {
totalKeyComb = totalKeyComb * len(keyValuePair[i].values)
keyIndices = append(keyIndices, 0)
}
for ; totalKeyComb > 0; totalKeyComb-- {
//Get the YANG list name from Redis table name
//Ideally they are same except when one Redis table is split
//into multiple YANG lists
//Add table i.e. create list element
listNode := c.addYangNode(tableName, listConatinerNode, tableName+"_LIST", "") //Add the list to the top node
addAttrNode(listNode, "key", redisKey)
if storeInReqCache {
//store the list pointer in requestCache against the table/key
reqCache, exists := c.requestCache[tableName][redisKey]
if exists {
//Store same list instance in all requests under same table/key
for idx := 0; idx < len(reqCache); idx++ {
//Save the YANG data tree for using it later
reqCache[idx].YangData = listNode
}
}
}
//For each key combination
//Add keys as leaf to the list
for idx = 0; idx < keyCompCount; idx++ {
c.addYangNode(tableName, listNode, keyValuePair[idx].key,
keyValuePair[idx].values[keyIndices[idx]])
}
//Get all fields under the key field and add them as children of the list
c.generateYangLeafData(tableName, jsonNode, listNode)
//Check which key elements left after current key element
var next int = keyCompCount - 1
for (next > 0) && ((keyIndices[next] + 1) >= len(keyValuePair[next].values)) {
next--
}
//No more combination possible
if next < 0 {
break
}
keyIndices[next]++
//Reset indices for all other key elements
for idx = next + 1; idx < keyCompCount; idx++ {
keyIndices[idx] = 0
}
}
}
if !keyPresent {
return nil, cvlErrObj
}
return topNode, cvlErrObj
}
// Append given children to destNode
func (c *CVL) appendSubtree(dest, src *xmlquery.Node) CVLRetCode {
if dest == nil || src == nil {
return CVL_FAILURE
}
var lastSibling *xmlquery.Node = nil
for srcNode := src; srcNode != nil; srcNode = srcNode.NextSibling {
//set parent for all nodes
srcNode.Parent = dest
lastSibling = srcNode
}
if dest.LastChild == nil {
//No sibling in dest yet
dest.FirstChild = src
dest.LastChild = lastSibling
} else {
//Append to the last sibling
dest.LastChild.NextSibling = src
src.PrevSibling = dest.LastChild
dest.LastChild = lastSibling
}
return CVL_SUCCESS
}
// Return subtree after detaching from parent
func (c *CVL) detachSubtree(parent *xmlquery.Node) *xmlquery.Node {
child := parent.FirstChild
if child != nil {
//set children to nil
parent.FirstChild = nil
parent.LastChild = nil
} else {
//No children
return nil
}
//Detach all children from parent
for node := child; node != nil; node = node.NextSibling {
node.Parent = nil
}
return child
}
// Detach a node from its parent
func (c *CVL) detachNode(node *xmlquery.Node) CVLRetCode {
if node == nil {
return CVL_FAILURE
}
//get the parent node
parent := node.Parent
if parent == nil {
//Already detached node
return CVL_SUCCESS
}
//adjust siblings
if parent.FirstChild == node && parent.LastChild == node {
//this is the only node
parent.FirstChild = nil
parent.LastChild = nil
} else if parent.FirstChild == node {
//first child, set new first child
parent.FirstChild = node.NextSibling
node.NextSibling.PrevSibling = nil
} else {
node.PrevSibling.NextSibling = node.NextSibling
if node.NextSibling != nil {
//if remaining sibling
node.NextSibling.PrevSibling = node.PrevSibling
} else {
//this is last child getting detached,
//so set lastChild as node's prevSibling
parent.LastChild = node.PrevSibling
}
}
//detach from parent and siblings
node.Parent = nil
node.PrevSibling = nil
node.NextSibling = nil
return CVL_SUCCESS
}
// Delete all leaf-list nodes in destination
// Leaf-list should be replaced from source
// destination
func (c *CVL) deleteDestLeafList(dest *xmlquery.Node) {
TRACE_LOG(TRACE_CACHE, "Updating leaf-list by "+
"removing and then adding leaf-list")
//find start and end of dest leaf list
leafListName := dest.Data
for node := dest; node != nil; {
tmpNextNode := node.NextSibling
if node.Data == leafListName {
c.detachNode(node)
node = tmpNextNode
continue
} else {
//no more leaflist node
break
}
}
}
// deleteLeafNodes removes specified child nodes from an xml node topNode
func (c *CVL) deleteLeafNodes(topNode *xmlquery.Node, cfgData map[string]string) {
for node := topNode.FirstChild; node != nil; {
if _, found := cfgData[getNodeName(node)]; found {
tmpNode := node.NextSibling
c.detachNode(node)
node = tmpNode
} else {
node = node.NextSibling
}
}
}
// Check if the given list src node already exists in dest node
func (c *CVL) checkIfListNodeExists(dest, src *xmlquery.Node) *xmlquery.Node {
if (dest == nil) || (src == nil) {
return nil
}
tableName := getYangListToRedisTbl(src.Data)
redisKey := getAttrNodeVal(src, "key")
if tableName == "" || redisKey == "" {
return nil
}
entry, exists := c.requestCache[tableName][redisKey]
if !exists || (len(entry) == 0) {
return nil
}
//CREATE/UPDATE/DELETE request for same table/key points to
//same yang list in request cache
yangList := entry[0].YangData
if yangList == nil || yangList.Parent == nil {
//Source node does not exist in destination
return nil
}
if dest.Parent == yangList.Parent {
//Same parent means yang list already exists in destination tree
return yangList
}
return nil
}
// Merge YANG data recursively from dest to src
// Leaf-list is always replaced and appeneded at
// the end of list's children
func (c *CVL) mergeYangData(dest, src *xmlquery.Node) CVLRetCode {
if (dest == nil) || (src == nil) {
return CVL_FAILURE
}
TRACE_LOG((TRACE_SYNTAX | TRACE_SEMANTIC),
"Merging YANG data %s %s", dest.Data, src.Data)
if (dest.Type == xmlquery.TextNode) && (src.Type == xmlquery.TextNode) {
//handle leaf node by updating value
dest.Data = src.Data
return CVL_SUCCESS
}
srcNode := src
destLeafListDeleted := make(map[string]bool)
for srcNode != nil {
//Find all source nodes and attach to the matching destination node
ret := CVL_FAILURE
//TRACE_LOG((TRACE_SYNTAX | TRACE_SEMANTIC), "MergeData : src loop\n")
destLoop:
destNode := dest
for ; destNode != nil; destNode = destNode.NextSibling {
//TRACE_LOG((TRACE_SYNTAX | TRACE_SEMANTIC), "MergeData : dest loop\n")
if destNode.Data != srcNode.Data {
//Can proceed to subtree only if current node name matches
continue
}
if strings.HasSuffix(destNode.Data, "_LIST") {
//Check if src list node already exists in destination
tmpNode := c.checkIfListNodeExists(destNode, srcNode)
if tmpNode != nil {
destNode = tmpNode
} else {
destNode = tmpNode
break
}
//find exact match for list instance
//check with key value, stored in attribute
/*if (len(destNode.Attr) == 0) || (len(srcNode.Attr) == 0) ||
(destNode.Attr[0].Value != srcNode.Attr[0].Value) {
//move to next list
continue
}*/
} else if (len(destNode.Attr) > 0) && (len(srcNode.Attr) > 0) &&
(destNode.Attr[0].Name.Local == "leaf-list") &&
(srcNode.Attr[0].Name.Local == "leaf-list") { // attribute has type
delFlag, exists := destLeafListDeleted[srcNode.Data]
if !exists || !delFlag {
//Replace all leaf-list nodes from destination first
c.deleteDestLeafList(destNode)
destLeafListDeleted[srcNode.Data] = true
//Note that 'dest' still points to list keys
//even though all leaf-list might have been deleted
//as we never delete key while merging
goto destLoop
} else {
//if all dest leaflist deleted,
//just break to add all leaflist
destNode = nil
break
}
}
//Go to their children
ret = c.mergeYangData(destNode.FirstChild, srcNode.FirstChild)
//Node matched break now
break
} //dest node loop
if ret == CVL_FAILURE {
if destNode == nil {
//destNode == nil -> node not found
//detach srcNode and append to dest
tmpNextSrcNode := srcNode.NextSibling
if CVL_SUCCESS == c.detachNode(srcNode) {
if (len(srcNode.Attr) > 0) &&
(srcNode.Attr[0].Name.Local == "leaf-list") {
//set the flag so that we don't delete leaf-list
//from destNode further
destLeafListDeleted[srcNode.Data] = true
}
c.appendSubtree(dest.Parent, srcNode)
}
srcNode = tmpNextSrcNode
continue
} else {
//subtree merge failure ,, append subtree
subTree := c.detachSubtree(srcNode)
if subTree != nil {
c.appendSubtree(destNode, subTree)
}
}
}
srcNode = srcNode.NextSibling
} //src node loop
return CVL_SUCCESS
}
func (c *CVL) findYangList(tableName string, redisKey string) *xmlquery.Node {
origCurrent := c.yv.current
tmpCurrent := c.moveToYangList(tableName, redisKey)
c.yv.current = origCurrent
return tmpCurrent
}
// Locate YANG list instance in root for given table name and key
func (c *CVL) moveToYangList(tableName string, redisKey string) *xmlquery.Node {
var nodeTbl *xmlquery.Node = nil
redisTableName := getYangListToRedisTbl(tableName)
modelName := modelInfo.tableInfo[tableName].modelName
//move to the model first
for node := c.yv.root.FirstChild; node != nil; node = node.NextSibling {
if node.Data != modelName {
continue
}
//Move to container
for nodeTbl = node.FirstChild; nodeTbl != nil; nodeTbl = nodeTbl.NextSibling {
if nodeTbl.Data == redisTableName {
break
}
}
break
}
if nodeTbl == nil {
TRACE_LOG(TRACE_SEMANTIC, "YANG data for table %s, key %s is not present in YANG tree",
tableName, redisKey)
return nil
}
//Move to list
listName := tableName + "_LIST"
for nodeList := nodeTbl.FirstChild; nodeList != nil; nodeList = nodeList.NextSibling {
if nodeList.Data != listName {
continue
}
c.yv.current = nodeList
//if no key specified or no other instance exists,
//just return the first list instance
if redisKey == "" || nodeList.NextSibling == nil {
return c.yv.current
}
for ; nodeList != nil; nodeList = nodeList.NextSibling {
if len(nodeList.Attr) > 0 {
if cmn.KeyMatch(nodeList.Attr[0].Value, redisKey) {
c.yv.current = nodeList
return nodeList
}
}
}
if nodeList == nil {
break
}
}
CVL_LOG(WARNING, "No list entry matched, unable to find YANG data for table %s, key %s",
tableName, redisKey)
return nil
}
// Set operation node value based on operation in request received
func (c *CVL) setOperation(op cmn.CVLOperation) {
var node *xmlquery.Node
for node = c.yv.root.FirstChild; node != nil; node = node.NextSibling {
if node.Data == "operation" {
break
}
}
//Add the operation container
if node == nil {
node = c.addYangNode("", c.yv.root, "operation", "")
node.Prefix = "sonic-common" //"cmn"
//modelInfo.modelNs["sonic-common"].prefix
node.NamespaceURI = modelInfo.modelNs["sonic-common"].ns
}
opNode := node.FirstChild
if opNode == nil {
node.Prefix = "sonic-common" //"cmn"
opNode = c.addYangNode("", node, "operation", "NONE")
}
switch op {
case cmn.OP_CREATE:
opNode.FirstChild.Data = "CREATE"
case cmn.OP_UPDATE:
opNode.FirstChild.Data = "UPDATE"
case cmn.OP_DELETE:
opNode.FirstChild.Data = "DELETE"
default:
opNode.FirstChild.Data = "NONE"
}
}
// Add given YANG data buffer to Yang Validator
// redisKeys - Set of redis keys
// redisKeyFilter - Redis key filter in glob style pattern
// keyNames - Names of all keys separated by "|"
// predicate - Condition on keys/fields
// fields - Fields to retrieve, separated by "|"
// Return "," separated list of leaf nodes if only one leaf is requested
// One leaf is used as xpath query result in other nested xpath
func (c *CVL) addDepYangData(redisKeys []string, redisKeyFilter,
keyNames, predicate, fields string, count int) string {
var v interface{}
tmpPredicate := ""
//Get filtered Redis data based on lua script
//filter derived from Xpath predicate
if predicate != "" {
tmpPredicate = "return (" + predicate + ")"
}
s := cmn.Search{Pattern: redisKeyFilter, Predicate: tmpPredicate, KeyNames: strings.Split(keyNames, "|"), WithField: fields, Limit: count}
cfgData, err := c.dbAccess.Lookup(s).Result()
singleLeaf := "" //leaf data for single leaf
if IsTraceAllowed(TRACE_SEMANTIC) {
TRACE_LOG(TRACE_SEMANTIC, "addDepYangData() with redisKeyFilter=%s, "+
"predicate=%s, fields=%s, returned cfgData = %s, err=%v",
redisKeyFilter, predicate, fields, cfgData, err)
}
if len(cfgData) == 0 {
return ""
}
// If dependent data is already being added for semantic evaluation, don't
// add again. This prevents adding same data multiple times and reduce size
// of xml generated for semantic evaluation by xpath engine.
if _, ok := c.depDataCache[cfgData]; ok {
return ""
}
c.depDataCache[cfgData] = nil
//Parse the JSON map received from lua script
b := []byte(cfgData)
if err := json.Unmarshal(b, &v); err != nil {
return ""
}
var dataMap map[string]interface{} = v.(map[string]interface{})
dataTop, _ := jsonquery.ParseJsonMap(&dataMap)
for jsonNode := dataTop.FirstChild; jsonNode != nil; jsonNode = jsonNode.NextSibling {
//Generate YANG data for Yang Validator from Redis JSON
topYangNode, _ := c.generateYangListData(jsonNode, false)
if topYangNode == nil {
continue
}
if (topYangNode.FirstChild != nil) &&
(topYangNode.FirstChild.FirstChild != nil) {
//Add attribute mentioning that data is from db
addAttrNode(topYangNode.FirstChild.FirstChild, "db", "")
}
//Build single leaf data requested
singleLeaf = ""
for redisKey := topYangNode.FirstChild.FirstChild; redisKey != nil; redisKey = redisKey.NextSibling {
for field := redisKey.FirstChild; field != nil; field = field.NextSibling {
if field.Data == fields && field.FirstChild != nil {
//Single field requested
singleLeaf = singleLeaf + field.FirstChild.Data + ","
break
}
}
}
//Merge with main YANG data cache
doc := &xmlquery.Node{Type: xmlquery.DocumentNode}
doc.FirstChild = topYangNode
doc.LastChild = topYangNode
topYangNode.Parent = doc
if c.mergeYangData(c.yv.root, doc) != CVL_SUCCESS {
continue
}
}
//remove last comma in case mulitple values returned
if singleLeaf != "" {
return singleLeaf[:len(singleLeaf)-1]
}
return ""
}
// Add all other table data for validating all 'must' exp for tableName
// One entry is needed for incremental loading of must tables
func (c *CVL) addYangDataForMustExp(op cmn.CVLOperation, tableName string, oneEntry bool) CVLRetCode {
if modelInfo.tableInfo[tableName].mustExpr == nil {
return CVL_SUCCESS
}
defer c.clearTmpDbCache()
for mustTblName, mustOp := range modelInfo.tableInfo[tableName].tablesForMustExp {
//First check if must expression should be executed for the given operation
if (mustOp != cmn.OP_NONE) && ((mustOp & op) == cmn.OP_NONE) {
//must to be excuted for particular operation, but current operation
//is not the same one
continue
}
//If one entry is needed and it is already availale in c.yv.root cache
//just ignore and continue
if oneEntry {
node := c.moveToYangList(mustTblName, "")
if node != nil {
//One entry exists, continue
continue
}
}
redisTblName := getYangListToRedisTbl(mustTblName) //1 yang to N Redis table case
tableKeys, err := c.dbAccess.Keys(redisTblName +
modelInfo.tableInfo[mustTblName].redisKeyDelim + "*").Result()
if err != nil {
return CVL_FAILURE
}
if len(tableKeys) == 0 {
//No dependent data for mustTable available
continue
}
c.clearTmpDbCache()
//fill all keys; TBD Optimize based on predicate in Xpath
tablePrefixLen := len(redisTblName + modelInfo.tableInfo[mustTblName].redisKeyDelim)
for _, tableKey := range tableKeys {
tableKey = tableKey[tablePrefixLen:] //remove table prefix
tmpKeyArr := strings.Split(tableKey, modelInfo.tableInfo[mustTblName].redisKeyDelim)
if len(tmpKeyArr) != len(modelInfo.tableInfo[mustTblName].keys) {
//Number of keys should be same as in YANG list keys
//Need to check this for one Redis table to many YANG list case
continue
}
if c.tmpDbCache[redisTblName] == nil {
c.tmpDbCache[redisTblName] = map[string]interface{}{tableKey: nil}
} else {
tblMap := c.tmpDbCache[redisTblName]
tblMap.(map[string]interface{})[tableKey] = nil
c.tmpDbCache[redisTblName] = tblMap
}
//Load only one entry
if oneEntry {
TRACE_LOG(TRACE_SEMANTIC, "addYangDataForMustExp(): Adding one entry table %s, key %s",
redisTblName, tableKey)
break
}
}
if c.tmpDbCache[redisTblName] == nil {
//No entry present in DB
continue
}
//fetch using pipeline
c.fetchTableDataToTmpCache(redisTblName, c.tmpDbCache[redisTblName].(map[string]interface{}))
data, err := jsonquery.ParseJsonMap(&c.tmpDbCache)
if err != nil {
return CVL_FAILURE
}
//Build yang tree for each table and cache it
for jsonNode := data.FirstChild; jsonNode != nil; jsonNode = jsonNode.NextSibling {
//Visit each top level list in a loop for creating table data
topYangNode, _ := c.generateYangListData(jsonNode, false)
if topYangNode == nil {
//No entry found, check next entry
continue
}
if (topYangNode.FirstChild != nil) &&
(topYangNode.FirstChild.FirstChild != nil) {
//Add attribute mentioning that data is from db
addAttrNode(topYangNode.FirstChild.FirstChild, "db", "")
}
//Create full document by adding document node
doc := &xmlquery.Node{Type: xmlquery.DocumentNode}
doc.FirstChild = topYangNode
doc.LastChild = topYangNode
topYangNode.Parent = doc
if c.mergeYangData(c.yv.root, doc) != CVL_SUCCESS {
return CVL_INTERNAL_UNKNOWN
}
}
}
return CVL_SUCCESS
}
// Compile all must expression and save the expression tree
func compileMustExps() {
reMultiPred := regexp.MustCompile(`\][ ]*\[`)
for _, tInfo := range modelInfo.tableInfo {
if tInfo.mustExpr == nil {
continue
}
// Replace multiple predicate using 'and' expressiona
// xpath engine not accepting multiple predicates
for _, mustExprArr := range tInfo.mustExpr {
for _, mustExpr := range mustExprArr {
mustExpr.exprTree = xpath.MustCompile(
reMultiPred.ReplaceAllString(mustExpr.expr, " and "))
}
}
}
}
// Compile all when expression and save the expression tree
func compileWhenExps() {
reMultiPred := regexp.MustCompile(`\][ ]*\[`)
for _, tInfo := range modelInfo.tableInfo {
if tInfo.whenExpr == nil {
continue
}
// Replace multiple predicate using 'and' expressiona
// xpath engine not accepting multiple predicates
for _, whenExprArr := range tInfo.whenExpr {
for _, whenExpr := range whenExprArr {
whenExpr.exprTree = xpath.MustCompile(
reMultiPred.ReplaceAllString(whenExpr.expr, " and "))
//Store all YANG list used in the expression
whenExpr.yangListNames = getYangListNamesInExpr(whenExpr.expr)
}
}
}
}
func compileLeafRefPath() {
reMultiPred := regexp.MustCompile(`\][ ]*\[`)
for _, tInfo := range modelInfo.tableInfo {
if len(tInfo.leafRef) == 0 { //no leafref
continue
}
//for nodeName, leafRefArr := range tInfo.leafRef {
for _, leafRefArr := range tInfo.leafRef {
for _, leafRefArrItem := range leafRefArr {
if leafRefArrItem.path == "non-leafref" {
//Leaf type has at-least one non-learef data type