-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaseclasses.py
More file actions
3192 lines (2884 loc) · 115 KB
/
baseclasses.py
File metadata and controls
3192 lines (2884 loc) · 115 KB
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 2018 5G Exchange (5GEx) Project
# Copyright 2016-2017 Ericsson Hungary Ltd.
#
# 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.
# Yang baseclasses for the pyang plugin (PNC) developed at Ericsson Hungary Ltd.
__author__ = "5GEx Consortium, Robert Szabo, Balazs Miriszlai, Akos Recse, Raphael Vicente Rosa"
__copyright__ = "Copyright 2018 5G Exchange (5GEx) Project, Copyright 2016-2017 Ericsson Hungary Ltd."
__credits__ = "Robert Szabo, Raphael Vicente Rosa, David Jocha, Janos Elek, Balazs Miriszlai, Akos Recse"
__license__ = "Apache License, Version 2.0"
__version_text__ = "yang/baseclasses/v5bis"
__version__ = "2017-06-26"
from xml.dom.minidom import parseString
import xml.etree.ElementTree as ET
import copy
from decimal import *
from collections import OrderedDict, Iterable
import StringIO
import os
import sys
import string
import logging
import json
import re
logger = logging.getLogger("baseclss")
__EDIT_OPERATION_TYPE_ENUMERATION__ = ( # see https://tools.ietf.org/html/rfc6241#section-7.2
"merge", # default operation
"replace",
"create",
"delete",
"remove"
)
DEFAULT = object()
__IGNORED_ATTRIBUTES__ = ("_parent", "_tag", "_sorted_children", "_referred", "_key_attributes", "_sh")
__EQ_IGNORED_ATTRIBUTES__ = ("_parent", "_sorted_children", "_referred", "_key_attributes", "_floating")
__YANG_COPY_ATTRIBUTES__ = ("_tag", "_sorted_children", "_operation", "_attributes", "_floating")
__REDUCE_ATTRIBUTES__ = ("")
class PathUtils:
@staticmethod
def path_to_list(path):
_list = list()
_remaining = path
while '[' in _remaining:
_begin, _remaining = _remaining.split('[', 1)
_mid, _remaining = _remaining.split(']', 1)
_p = _begin.split('/')
if len(_list) > 0:
_p.pop(0)
_list.extend(_p)
_list[-1] += '[' + _mid + ']'
if _remaining is None:
break
if _remaining is not None:
_p = _remaining.split('/')
if len(_list) > 0:
_p.pop(0)
_list.extend(_p)
return _list
@staticmethod
def add(_from, _to):
if _to[0] == '/': # absolute path
return _to
p1 = PathUtils.path_to_list(_from)
p2 = PathUtils.path_to_list(_to)
l = p2.pop(0)
while l == "..":
p1.pop()
l = p2.pop(0)
p1.append(l)
p1 += p2
return '/'.join(p1)
@staticmethod
def diff(_from, _to):
if _to[0] != '/': # relative path
return _to
p1 = PathUtils.path_to_list(_from)
p2 = PathUtils.path_to_list(_to)
l1 = p1.pop(0)
l2 = p2.pop(0)
try:
while l1 == l2:
l1 = p1.pop(0)
l2 = p2.pop(0)
p2.insert(0, l2)
p2.insert(0, '..') # the paths divereged but both exist to this level
except:
pass # catch exection that one of the path did not exist at this level, it is not a problem
while len(p1)>0:
p2.insert(0, "..")
p1.pop(0)
return '/'.join(p2)
@staticmethod
def match_path_regexp(path, path_regexp):
p = PathUtils.path_to_list(path)
_filter = PathUtils.path_to_list(path_regexp)
try:
while re.match(_filter[0], p[0]) is not None:
p.pop(0)
_filter.pop(0)
finally:
if len(_filter)>0:
return None
@staticmethod
def remove_id_from_path(path):
'''
Returns with a simple type path by removing ids from the given path.
Example:
/virtualizer/nodes/node[id=1]/ports/port[id=2] => /virtualizer/nodes/node/ports/port
'''
id_regex = re.compile('\[(.*?)\]')
return re.sub(id_regex, '', path)
@staticmethod
def split_tag_and_key_values(tag_with_key_values):
if (tag_with_key_values.find("[") > 0) and (tag_with_key_values.find("]") > 0):
tag = tag_with_key_values[0: tag_with_key_values.find("[")]
key_values = tag_with_key_values[tag_with_key_values.find("[") + 1: tag_with_key_values.rfind("]")]
kv = key_values.split("=")
return tag, kv
return tag_with_key_values, None
@staticmethod
def split_path_segment_to_key_value_dict(path_segment):
if (path_segment.find("[") > 0) and (path_segment.find("]") > 0):
tag = path_segment[0: path_segment.find("[")]
keystring = path_segment[path_segment.find("[") + 1: path_segment.rfind("]")]
keys = dict(item.split("=") for item in keystring.split(","))
return tag, keys
return path_segment, None
@staticmethod
def merge_tag_and_keyst_to_path_segment(tag, keys):
if keys is None:
return tag
return tag + '[' + ','.join(['%s=%s' % (key, value) for (key, value) in keys.items()]) + ']'
@staticmethod
def get_key_values_by_tag(path, tag):
p = path.split("/")
t = tag.split("/")
for i in range(1, len(p)+1):
_tag, _kv = PathUtils.split_tag_and_key_values(p[-i])
if (_tag == t[-1]) and (_kv is not None):
match = True
for j in range(1, min(len(p)+1-i,len(t))):
__tag, __kv = PathUtils.split_tag_and_key_values(p[-i-j])
if __tag != t[-1-j]:
match = False
break
if match:
return _kv[1]
return None
@staticmethod
def has_tags(path, tags, at=None):
"""
Check if path has tags (without key and values)
:param path: string, path
:param tags: pattern to check for
:param at: int, position to check for (can be negative)
:return: boolean, True if match; False otherwise
"""
p = path.split("/")
_path = ""
for i in range(0, len(p)):
l = p[i]
if (l.find("[") > 0) and (l.find("]") > 0):
attrib = l[0: l.find("[")]
_path= _path + "/" + attrib
else:
_path= _path + l
p = path.split('/')
if at is not None:
if len(p) > abs(at):
return p[at] == path
return False
return path in p
class YangJson:
@classmethod
def elem_to_dict(cls, elem):
d = OrderedDict()
tag = elem.tag
for subelement in elem:
sub_tag = subelement.tag
sub_value = cls.elem_to_dict(subelement)
value = sub_value[sub_tag]
if sub_tag in d.keys():
if type(d[sub_tag]) is list:
d[sub_tag].append(value)
else:
d[sub_tag] = [d[sub_tag], value]
else:
d[sub_tag] = value
if d:
if elem.text:
d['text'] = elem.text
if elem.attrib:
d['attributes'] = elem.attrib
if elem.tail:
d['tail'] = elem.tail
else:
if elem.text:
d = elem.text or None
return {tag: d}
@classmethod
def dict_to_elem(cls, input_dict):
dict_tag = input_dict.keys()[0]
dict_value = input_dict[dict_tag]
sub_nodes = []
text = None
tail = None
attributes = None
if type(dict_value) is dict:
for key, value in dict_value.items():
if key == 'text':
text = value
elif key == 'tail':
tail = value
elif key == 'attributes':
attributes = value
elif type(value) is list:
list_sub_nodes = map(lambda sub_node: {key: sub_node}, value)
list_sub_nodes = map(cls.dict_to_elem, list_sub_nodes)
sub_nodes.extend(list_sub_nodes)
else:
sub_node = cls.dict_to_elem({key: value})
sub_nodes.append(sub_node)
else:
text = dict_value
node = ET.Element(dict_tag)
node.text = text
node.tail = tail
for sub_node in sub_nodes:
node.append(sub_node)
if attributes:
node.attrib = attributes
return node
@classmethod
def from_json(cls, _json):
_dict = json.loads(_json)
_elem = cls.dict_to_elem(_dict)
return _elem
@classmethod
def to_json(cls, _elem, ordered=True):
_dict = cls.elem_to_dict(_elem)
_json = json.dumps(_dict, indent=4, sort_keys=ordered)
return _json
# Custom Exceptions
class YangCopyDifferentParent(Exception):
pass
class Yang(object):
"""
Class defining the root attributes and methods for all Virtualizer classes
"""
def __init__(self, tag, parent=None):
self._parent = parent
self._tag = tag
self._operation = None
self._referred = [] # to hold leafref references for backward search
self._sorted_children = [] # to hold children Yang list
self._attributes = ['_operation']
# self._leaf_attributes = list()
self._floating = False # get_path() will not return initial '/', i.e., only relative path is returned
def format(self, **kwargs):
for c in self._sorted_children:
if self.__dict__[c] is not None:
self.__dict__[c].format(**kwargs)
# def __setattr__(self, key, value):
# """
# Calls set_value() for Leaf types so that they behave like string, int etc...
# :param key: string, attribute name
# :param value: value of arbitrary type
# :return: -
# """
# if (value is not None) and (key in self.__dict__) and issubclass(type(self.__dict__[key]),
# Leaf) and not issubclass(type(value), Yang):
# self.__dict__[key].set_value(value)
# else:
# self.__dict__[key] = value
def match_tags(self, tags):
if tags is None:
return True
if type(tags) in [] in (list, tuple):
return self._tag in tags
return self._tag == tags
def path_filter(self, path_filter, reference=None):
def check_attrib(base, offset, attrib_path, value):
try:
a = base.walk_path(offset)
a = a.walk_path(attrib_path)
if value is not None:
return a.get_value() == value
return True
except:
return False
if path_filter is None:
return True # empty filter matches everything
path = self.get_path()
m = re.match(path_filter['path'], path)
if m is not None:
a_path = path_filter.get('attrib', None)
if a_path is not None:
if check_attrib(self, m.group(0), a_path, path_filter.get('value', None)):
return True
if reference is not None:
return check_attrib(reference, m.group(0), a_path, path_filter.get('value', None))
return False
return True
else:
return False
def get_next(self, children=None, operation=None, tags=None, _called_from_parent_=False, reference= None, path_filter=None):
"""
Returns the next Yang element followed by the one called for. It can be used for in-depth traversar of the yang tree.
:param children: Yang (for up level call to hand over the callee children)
:return: Yang
"""
i = 0
if operation is None:
operation = (None,) + __EDIT_OPERATION_TYPE_ENUMERATION__
if len(self._sorted_children) > 0:
if children is None:
while i < len(self._sorted_children):
if (self.__dict__[self._sorted_children[i]] is not None) and \
(self.__dict__[self._sorted_children[i]].is_initialized()):
if self.__dict__[self._sorted_children[i]].has_operation(operation) and self.__dict__[self._sorted_children[i]].match_tags(tags) and self.__dict__[self._sorted_children[i]].path_filter(path_filter, reference=reference):
return self.__dict__[self._sorted_children[i]]
else:
res = self.__dict__[self._sorted_children[i]].get_next(operation=operation, tags=tags, _called_from_parent_=True, reference=reference, path_filter=path_filter)
if res is not None:
return res
i += 1
else:
while i < len(self._sorted_children):
i += 1
if self.__dict__[self._sorted_children[i - 1]] == children:
break
while i < len(self._sorted_children):
if (self.__dict__[self._sorted_children[i]] is not None) and \
(self.__dict__[self._sorted_children[i]].is_initialized()):
if self.__dict__[self._sorted_children[i]].has_operation(operation) and self.__dict__[self._sorted_children[i]].match_tags(tags) and self.__dict__[self._sorted_children[i]].path_filter(path_filter, reference=reference):
return self.__dict__[self._sorted_children[i]]
else:
res = self.__dict__[self._sorted_children[i]].get_next(operation=operation, tags=tags, _called_from_parent_=True, reference=reference, path_filter=path_filter)
if res is not None:
return res
i += 1
# go to parent
if (self._parent is not None) and (not _called_from_parent_):
return self._parent.get_next(self, operation=operation, tags=tags, reference=reference, path_filter=path_filter)
return None
def get_attr(self, attrib, v=None, default=DEFAULT):
if hasattr(self, attrib):
return self.__dict__[attrib]
if (v is not None) and isinstance(v, Yang):
_v = v.walk_path(self.get_path())
if hasattr(_v, attrib):
return _v.__dict__[attrib]
if default is not DEFAULT:
# default return is given
return default
raise ValueError("Attrib={attrib} cannot be found in self={self} and other={v}".format(
self=self.get_as_text(), v=v.get_as_text()))
def has_attr_with_value(self, attrib, value, ignore_case=True):
if hasattr(self, attrib):
if ignore_case and (self.__dict_[attrib].get_as_text().lower() == value.lower()):
return True
return self.__dict_[attrib].get_as_text() == value
return False
def has_attrs_with_regex(self, av_list):
try:
if len(av_list) == 0: # for list entries
return self
if len(av_list) == 1 and type(av_list[0]) in (list, tuple):
return self.has_attrs_with_regex(av_list[0])
if type(av_list) is tuple:
av_list = list(av_list)
if type(av_list[0]) is list:
l = av_list.pop(0)
attr = l[0]
elif type(av_list[0]) is tuple:
l = av_list.pop(0)
if self.has_attrs_with_regex(l):
return self.has_attrs_with_regex(av_list)
elif (len(av_list) == 2) and (isinstance(av_list[1], basestring)): # attrib and value check
l = list(av_list)
av_list = ()
attr = l[0]
else:
l = av_list.pop(0)
attr = l
_return = True
if hasattr(self, attr):
if self.__dict__[attr].is_initialized():
if type(l) in (list, tuple):
if type(l[1]) in (list, tuple):
_return = self.__dict__[attr].has_attrs_with_regex(l[1]) # recursive structure call
if _return and len(av_list) > 0:
return _return and self.has_attrs_with_regex(av_list)
else:
return _return
else:
if re.match(l[1], self.__dict__[attr].get_as_text()) is not None:
if len(av_list) > 0:
return self.has_attrs_with_regex(av_list)
else:
return True
else:
if (type(av_list) in (list, tuple)) and (len(av_list)>0):
return self.__dict__[attr].has_attrs_with_regex(av_list)
else:
return True
return False
except:
return False
def has_attrs_with_values(self, av_list, ignore_case=True):
try:
if len(av_list) == 0: # for list entries
return self
if len(av_list) == 1 and type(av_list[0]) in (list, tuple):
return self.has_attrs_with_values(av_list[0], ignore_case)
if type(av_list) is tuple:
av_list = list(av_list)
if type(av_list[0]) is list:
l = av_list.pop(0)
attr = l[0]
elif type(av_list[0]) is tuple:
l = av_list.pop(0)
if self.has_attrs_with_values(l, ignore_case):
return self.has_attrs_with_values(av_list, ignore_case)
elif (len(av_list) == 2) and (isinstance(av_list[1], basestring)): # attrib and value check
l = list(av_list)
av_list = ()
attr = l[0]
else:
l = av_list.pop(0)
attr = l
_return = True
if hasattr(self, attr):
if self.__dict__[attr].is_initialized():
if type(l) in (list, tuple):
if type(l[1]) in (list, tuple):
_return = self.__dict__[attr].has_attrs_with_values(l[1], ignore_case) # recursive structure call
if _return and len(av_list) > 0:
return _return and self.has_attrs_with_values(av_list, ignore_case)
else:
return _return
else:
if ignore_case and (self.__dict__[attr].get_as_text().lower() == l[1].lower()):
if len(av_list) > 0:
return self.has_attrs_with_values(av_list, ignore_case)
else:
return _return
if self.__dict__[attr].get_as_text() == l[1]:
if len(av_list) > 0:
return self.has_attrs_with_values(av_list, ignore_case)
else:
return True
else:
if (type(av_list) in (list, tuple)) and (len(av_list)>0):
return self.__dict__[attr].has_attrs_with_values(av_list, ignore_case)
else:
return True
return False
except:
return False
def get_parent(self, level=1, tag=None):
"""
Returns the parent in the class subtree.
:param level: number of recursive parent calls or number of tag match to iterate
:param tag: look for specific tag; if level is also used then levelth match of the tag
:return: Yang
"""
if tag is not None:
if self._tag == tag:
return self._parent.get_parent(level=level-1, tag=tag) if level > 1 else self # return self if no more level but matcing tag; otherwise continue
return self._parent.get_parent(level=level, tag=tag)
if level > 1:
return self._parent.get_parent(level=level-1) if self._parent is not None else None
return self._parent
def set_parent(self, parent):
"""
Set the parent to point to the next node up in the Yang class instance tree
:param parent: Yang
:return: -
"""
self._parent = parent
def get_tag(self):
"""
Returns the YANG tag for the class.
:return: string
"""
return self._tag
def set_tag(self, tag):
"""
Set the YANG tag for the class
:param tag: string
:return: -
"""
self._tag = tag
def et(self):
return self._et(None, False, True)
def json(self, ordered=True):
velem = self._et(None, False, ordered=True)
vjson = YangJson.to_json(velem, ordered=True)
return vjson
def xml(self, ordered=True):
"""
Dump the class subtree as XML string
:param ordered: boolean -- defines alaphabetic ordering (True) or the one that was read
:return: string
"""
root = self._et(None, False, ordered)
xmlstr = ET.tostring(root, encoding="utf8", method="xml")
dom = parseString(xmlstr)
return dom.toprettyxml()
def get_as_text(self, ordered=True):
"""
Dump the class subtree as TEXT string
:return: string
"""
root = self._et(None, False, ordered)
return ET.tostring(root, encoding="utf8", method="html")
def html(self, ordered=True, header="", tailer=""):
"""
Dump the class subtree as HTML pretty formatted string
:return: string
"""
def indent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
root = self._et(None, False, ordered)
indent(root)
output = StringIO.StringIO()
if not isinstance(root, ET.ElementTree):
root = ET.ElementTree(root)
root.write(output)
if output.buflist[-1] == '\n':
output.buflist.pop()
html = header + output.getvalue() + tailer
output.close()
return html
def write_to_file(self, outfilename, format="html", ordered=True):
"""
Writes Yang tree to a file; path is created on demand
:param outfilename: string
:param format: string ("html", "xml", "text"), default is "html"
:return: -
"""
if not os.path.exists(os.path.dirname(outfilename)):
os.makedirs(os.path.dirname(outfilename))
text = self.html(ordered=ordered)
if format == "text":
text = self.get_as_text(ordered=ordered)
elif format == "xml":
text = self.xml(ordered=ordered)
with open(outfilename, 'w') as outfile:
outfile.writelines(text)
def update_parent(self):
for k, v in self.__dict__.items():
if k not in __IGNORED_ATTRIBUTES__:
if isinstance(v, Yang):
v.set_parent(self)
v.update_parent()
def reduce(self, reference, ignores=None):
"""
Delete instances which equivalently exist in the reference tree.
The call is recursive, a node is removed if and only if all of its children are removed.
:param reference: Yang
:param ignores: tuple of attribute names not to use during the compare operation
:return: True if object to be removed otherwise False
"""
_reduce = True
_ignores = list(__IGNORED_ATTRIBUTES__)
if ignores is not None:
if type(ignores) is tuple:
_ignores.extend(ignores)
else:
_ignores.append(ignores)
for k in self._sorted_children:
if k not in _ignores:
v = getattr(self, k)
vv = getattr(reference, k)
if self.has_operation(('delete', 'remove')):
if v is not None:
v.clear_data()
elif type(v) == type(vv):
if v.reduce(vv):
v.clear_data()
else:
_reduce = False
else:
_reduce = False
if self.has_operation(reference.get_operation()):
self.set_operation(None, recursive=None, force=True)
else:
_reduce = False
# _reduce &= self.has_operation(reference.get_operation())
return _reduce
def _diff(self, source, ignores=None):
"""
Delete instances which equivalently exist in the reference tree.
The call is recursive, a node is removed if and only if all of its children are removed.
:param reference: Yang
:param ignores: tuple of attribute names not to use during the compare operation
:return: True if object to be removed otherwise False
"""
_ignores = list(__IGNORED_ATTRIBUTES__)
if ignores is not None:
if type(ignores) is tuple:
_ignores.extend(ignores)
else:
_ignores.append(ignores)
for k, v in self.__dict__.items():
if type(self._parent) is ListYang: # todo: move this outside
if k == self.keys():
_ignores.append(k)
if k not in _ignores:
if isinstance(v, Yang):
if k in source.__dict__.keys():
if type(v) == type(source.__dict__[k]):
v._diff(source.__dict__[k])
if v.is_initialized() is False:
v.delete()
else:
v.set_operation("create", recursive=False, force=False)
for k, v in source.__dict__.items():
if k not in _ignores:
if isinstance(v, Yang):
if k not in self.__dict__.keys():
self.__dict__[k] = v.empty_copy()
self.__dict__[k].set_operation("delete", recursive=False, force=True)
def clear_subtree(self, ignores=None):
"""
Removes children recursively
:param ignores: list of attributes to be ignored (e.g., keys)
:return:
"""
_ignores = list(__IGNORED_ATTRIBUTES__)
if ignores is not None:
if type(ignores) is tuple:
_ignores.extend(ignores)
else:
_ignores.append(ignores)
for k, v in self.__dict__.items():
if type(self._parent) is ListYang:
if k == self.keys():
_ignores.append(k)
if k not in _ignores:
if isinstance(v, Yang):
v.delete()
def get_path(self, path_cache=None, drop=0):
"""
Returns the complete path (since the root) of the instance of Yang
:param: -
:return: string
"""
if drop > 0:
if self._parent is None:
raise ValueError("get_path cannot drop {drop} tails at {path}".format(drop=drop, path=self.get_path(path_cache=path_cache)))
return self._parent.get_path(path_cache=path_cache, drop=drop-1)
try:
return path_cache[self] # if object is already in the cache
except:
pass
if self._parent is not None:
p = self._parent.get_path(path_cache=path_cache) + "/" + self.get_tag()
elif not self._floating:
p = "/" + self.get_tag()
else:
p = self.get_tag()
if (path_cache is not None) and (not self._floating):
path_cache[self] = p
return p
def has_path(self, path, at=None):
"""
Check if path is in the object's path
:param path: string, pattern to check for
:param at: int, position to check for (can be negative)
:return: boolean, True if match; False otherwise
"""
p = PathUtils.path_to_list(self.get_path())
if at is not None:
if len(p) > abs(at):
return p[at] == path
return False
return path in p
def create_from_path(self, path):
"""
Create yang tree from path
:param path: string, path to create
:return: Yang, Yang object at the source instance's / path's path
"""
if path == "" or len(path) == 0:
return self
if type(path) in (list, tuple):
p = path
else:
p = PathUtils.path_to_list(path)
if len(p) < 1:
return self
if p[0] == "": # absolute path
if self.get_parent() is not None:
return self.get_parent().create_from_path(p)
p.pop(0)
return self.create_from_path(p)
l = p.pop(0)
if l == "..":
return self.get_parent().create_from_path(p)
elif l == self._tag:
return self.create_from_path(p)
elif (l.find("[") > 0) and (l.find("]") > 0):
attrib = l[0: l.find("[")]
keystring = l[l.find("[") + 1: l.rfind("]")]
keys = dict(item.split("=") for item in keystring.split(","))
if self._tag == attrib: # listed yang, with match
if self.match_keys(**keys):
return self.create_from_path(p)
else:
raise ValueError("Error: cannot create path at this entry, check configurations!!!\n{}\nfor path: {}".format(self, path))
try:
return self.__dict__[attrib][keys].create_from_path(p)
except:
# key does not exist
_yang = self.__dict__[attrib]._type(**keys)
self.__dict__[attrib].add(_yang)
return self.__dict__[attrib][keys].create_from_path(p)
else:
try:
return self.__dict__[l].create_from_path(p)
except:
logger.exception("Fixme: how to create class object")
raise ValueError("Fixme: how to create class object")
raise ValueError("create_from_path: no conditions matched ")
def create_path(self, source, path=None, target_copy_type=None):
"""
Create yang tree from source for non-existing objects along the path
:param source: Yang, used to initialize the yang tree as needed
:param path: string, path to create; if None then source's path is used
:return: Yang, Yang object at the source instance's / path's path
"""
try:
if path is None:
path = source.get_path()
if type(path) in (list, tuple):
p = path
else:
p = PathUtils.path_to_list(path)
if len(p) < 1:
return self
_copy_type = "empty"
if len(p) == 1:
_copy_type = target_copy_type
l = p.pop(0)
if l == "": # absolute path
if self.get_parent() is not None:
return self.get_parent().create_path(source, path=path, target_copy_type=target_copy_type)
elif self.get_tag() == PathUtils.split_tag_and_key_values(p[0])[0]:
p.pop(0)
return self.create_path(source, path=p, target_copy_type=target_copy_type)
_p = PathUtils.path_to_list(self.get_path())
# if p[0] == _p[1]:
p.pop(0)
return self.create_path(source, path=p, target_copy_type=target_copy_type)
# raise ValueError("Root tag not found in walk_path()")
if l == "..":
return self.get_parent().create_path(source, path=p, target_copy_type=target_copy_type)
elif (l.find("[") > 0) and (l.find("]") > 0):
attrib = l[0: l.find("[")]
keystring = l[l.find("[") + 1: l.rfind("]")]
key = list()
keyvalues = keystring.split(",")
for kv in keyvalues:
v = kv.split("=")
key.append(v[1])
if len(key) == 1:
key = key[0]
if not (key in self.__dict__[attrib].keys()):
_yang = source.walk_path(self.get_path()).__dict__[attrib][key]
self.__dict__[attrib].add(_yang.copy(_copy_type))
return getattr(self, attrib)[key].create_path(source, path=p, target_copy_type=target_copy_type)
else:
if (not (l in self.__dict__.keys())) or (getattr(self, l) is None):
_yang = getattr(source.walk_path(self.get_path()), l)
self.__dict__[l] = _yang.copy(_copy_type)
self.__dict__[l].set_parent(self)
return getattr(self, l).create_path(source, path=p, target_copy_type=target_copy_type)
raise ValueError("Root tag not found in walk_path()")
except Exception as e:
try:
logger.error("CreatePath: attrib={} path={} at\n{}".format(l, '/'.join(p),self))
except:
pass
finally:
raise e
def walk_path(self, path, reference=None):
"""
Follows the specified path to return the instance the path points to (handles relative and absolute paths)
:param path: string
:return: attribute instance of Yang
"""
if type(path) is Leafref:
return self.walk_path(path.data)
if type(path) in (list, tuple):
p = path
else:
p = PathUtils.path_to_list(path)
if len(p) < 1:
return self
l = p.pop(0)
if l == "": # absolute path
if self.get_parent() is not None:
return self.get_parent().walk_path(path, reference)
if len(p) == 0:
return self
if self.get_tag() == PathUtils.split_tag_and_key_values(p[0])[0]:
p.pop(0)
return self.walk_path(p, reference)
_p = PathUtils.path_to_list(self.get_path())
if p[0] == _p[1]:
p.pop(0)
return self.walk_path(p, reference)
# entry not in the current tree, let's try the reference tree
if reference is not None:
try:
yng = reference.walk_path(self.get_path(), reference=None)
return yng.walk_path(p, reference=None)
except:
# path does not exist in the reference tree raise exception
raise ValueError("in walk_path(): Root tag not found neither in the current nor in the reference tree")
# raise ValueError("Root tag not found in walk_path()")
if l == "..":
return self.get_parent().walk_path(p, reference)
else:
if (l.find("[") > 0) and (l.find("]") > 0):
attrib = l[0: l.find("[")]
keystring = l[l.find("[") + 1: l.rfind("]")]
key = list()
keyvalues = keystring.split(",")
for kv in keyvalues:
v = kv.split("=")
key.append(v[1])
if len(key) == 1:
if key[0] in self.__dict__[attrib].keys():
return getattr(self, attrib)[key[0]].walk_path(p, reference)
elif reference is not None:
yng = reference.walk_path(self.get_path(), reference=None)
p.insert(0, l)
return yng.walk_path(p, reference=None)
elif key in self.__dict__[attrib].keys():
return getattr(self, attrib)[key].walk_path(p, reference)
else:
if (l in self.__dict__.keys()) and (getattr(self, l) is not None):
return getattr(self, l).walk_path(p, reference)
elif reference is not None:
path = self.get_path()
yng = reference.walk_path(path, reference=None)
p.insert(0, l)
return yng.walk_path(p, reference=None)
raise ValueError("Path does not exist from {f} to {t}; yang tree={y}".format(f=self.get_path(), t=l+"/"+"/".join(p), y=self.html()))
def get_rel_path(self, target):
"""
Returns the relative path from self to the target
:param target: instance of Yang
:return: string
"""
src = self.get_path()
dst = target.get_path()
s = PathUtils.path_to_list(src)
d = PathUtils.path_to_list(dst)
if s[0] != d[0]:
return dst
i = 1
ret = list()
while s[i] == d[i]:
i += 1
for j in range(i, len(s)):
ret.insert(0, "..")
for j in range(i, len(d)):
ret.append(d[j])
return '/'.join(ret)
@classmethod
def parse(cls, parent=None, root=None):
"""
Class method to create virtualizer from XML string
:param parent: Yang
:param root: ElementTree
:return: class instance of Yang
"""
temp = cls(root.tag, parent=parent)
temp._parse(parent, root)
return temp
@classmethod
def parse_from_file(cls, filename):
try:
tree = ET.parse(filename)
return cls.parse(root=tree.getroot())
except ET.ParseError as e:
raise Exception('XML file ParseError: %s' % e.message)
@classmethod
def parse_from_text(cls, text):
try:
if text == "":
raise ValueError("Empty file")
tree = ET.ElementTree(ET.fromstring(text))
return cls.parse(root=tree.getroot())
except ET.ParseError as e: