Debian Codegraph @

lib/jnpr/junos/factory/optable.py

raw
1 from copy import deepcopy
2 import logging
3
4 # 3rd-party
5 from lxml import etree
6 from lxml.builder import E
7
8 # local
9 from jnpr.junos.factory.table import Table
10 from jnpr.junos.jxml import remove_namespaces, remove_namespaces_and_spaces
11 from jnpr.junos.decorators import checkSAXParserDecorator
12
13 logger = logging.getLogger("jnpr.junos.factory.optable")
14
15
16 class OpTable(Table):
17 # -------------------------------------------------------------------------
18 # PUBLIC METHODS
19 # -------------------------------------------------------------------------
20
21 @checkSAXParserDecorator
22 def get(self, *vargs, **kvargs):
23 r"""
24 Retrieve the XML table data from the Device instance and
25 returns back the Table instance - for call-chaining purposes.
26
27 If the Table was created with a :path: rather than a Device,
28 then this method will load the XML from that file. In this
29 case, the \*vargs, and \**kvargs are not used.
30
31 ALIAS: __call__
32
33 :vargs:
34 [0] is the table :arg_key: value. This is used so that
35 the caller can retrieve just one item from the table without
36 having to know the Junos RPC argument.
37
38 :kvargs:
39 these are the name/value pairs relating to the specific Junos
40 XML command attached to the table. For example, if the RPC
41 is 'get-route-information', there are parameters such as
42 'table' and 'destination'. Any valid RPC argument can be
43 passed to :kvargs: to further filter the results of the :get():
44 operation. neato!
45
46 NOTES:
47 If you need to create a 'stub' for unit-testing
48 purposes, you want to create a subclass of your table and
49 overload this methods.
50 """
51 self._clearkeys()
52
53 if self._path is not None:
54 # for loading from local file-path
55 self.xml = remove_namespaces(etree.parse(self._path).getroot())
56 return self
57
58 if self._lxml is not None:
59 return self
60
61 argkey = vargs[0] if len(vargs) else None
62
63 rpc_args = {}
64
65 if self._use_filter:
66 try:
67 filter_xml = generate_sax_parser_input(self)
68 rpc_args["filter_xml"] = filter_xml
69 except Exception as ex:
70 logger.debug("Not able to create SAX parser input due to " "'%s'" % ex)
71 self.D.transform = lambda: remove_namespaces_and_spaces
72
73 self.D.transform = lambda: remove_namespaces_and_spaces
74 rpc_args.update(self.GET_ARGS) # copy default args
75 # saltstack get_table pass args as named keyword
76 if "args" in kvargs and isinstance(kvargs["args"], dict):
77 rpc_args.update(kvargs.pop("args"))
78 rpc_args.update(kvargs) # copy caller provided args
79
80 if hasattr(self, "GET_KEY") and argkey is not None:
81 rpc_args.update({self.GET_KEY: argkey})
82
83 # execute the Junos RPC to retrieve the table
84 self.xml = getattr(self.RPC, self.GET_RPC)(**rpc_args)
85
86 # returning self for call-chaining purposes, yo!
87 return self
88
89
90 def generate_sax_parser_input(obj):
91 """
92 Used to generate xml object from Table/view to be used in SAX parsing
93 Args:
94 obj: self object which contains table/view details
95
96 Returns: lxml etree object to be used as sax parser input
97
98 """
99 item_tags = []
100 if "/" in obj.ITEM_XPATH:
101 item_tags = obj.ITEM_XPATH.split("/")
102 parser_ingest = E(item_tags.pop(-1), E(obj.ITEM_NAME_XPATH))
103 else:
104 parser_ingest = E(obj.ITEM_XPATH, E(obj.ITEM_NAME_XPATH))
105 local_field_dict = deepcopy(obj.VIEW.FIELDS)
106 # first make element out of group fields
107 if obj.VIEW.GROUPS:
108 for group, group_xpath in obj.VIEW.GROUPS.items():
109 # need to pop out group items so that it wont be reused with fields
110 group_field_dict = {
111 k: local_field_dict.pop(k)
112 for k, v in obj.VIEW.FIELDS.items()
113 if v.get("group") == group
114 }
115 group_ele = E(group_xpath)
116 for key, val in group_field_dict.items():
117 group_ele.append(E(val.get("xpath")))
118 parser_ingest.append(group_ele)
119 for i, item in enumerate(local_field_dict.items()):
120 # i is the index and item will be taple of field key and value
121 field_dict = item[1]
122 if "table" in field_dict:
123 # handle nested table/view
124 child_table = field_dict.get("table")
125 parser_ingest.insert(i + 1, generate_sax_parser_input(child_table))
126 else:
127 xpath = field_dict.get("xpath")
128 # xpath can be multi level, for ex traffic-statistics/input-pps
129 # going in reverse order, for fields example.
130 # split xpath in 2 part, search for first part xpath, if exists, append later
131 # else continue, and finally add full xpath to parent
132 # min-delay: probe-test-global-results/probe-test-generic-results/probe-test-rtt/probe-summary-results/min-delay
133 # max-delay: probe-test-global-results/probe-test-generic-results/probe-test-rtt/probe-summary-results/max-delay
134 # avg-delay: probe-test-global-results/probe-test-generic-results/probe-test-rtt/probe-summary-results/avg-delay
135 # positive-rtt-jitter: probe-test-global-results/probe-test-generic-results/probe-test-positive-round-trip-jitter/probe-summary-results/avg-delay
136 # loss-percentage: probe-test-global-results/probe-test-generic-results/loss-percentage
137 # current-min-delay: probe-last-test-results/probe-test-generic-results/probe-test-rtt/probe-summary-results/min-delay
138 # current-max-delay: probe-last-test-results/probe-test-generic-results/probe-test-rtt/probe-summary-results/max-delay
139 # current-avg-delay: probe-last-test-results/probe-test-generic-results/probe-test-rtt/probe-summary-results/avg-delay
140 # current-positive-rtt-jitter: probe-last-test-results/probe-test-generic-results/probe-test-positive-round-trip-jitter/probe-summary-results/avg-delay
141 # current-loss-percentage: probe-last-test-results/probe-test-generic-results/loss-percentage
142 if "/" in xpath:
143 tags = xpath.split("/")
144 tags_len = len(tags)
145 local_elem_to_add = E(tags[-1])
146 for i in range(tags_len, 0, -1):
147 xpath = "/".join(tags[:i])
148 local_obj = parser_ingest
149 elem_exists = local_obj.xpath(xpath)
150 if elem_exists:
151 xpath_exists = elem_exists[0]
152 xpath_exists.insert(1, local_elem_to_add)
153 break
154 if local_elem_to_add.tag != tags[i - 1]:
155 local_elem_to_add = E(tags[i - 1], local_elem_to_add)
156 else:
157 parser_ingest.insert(1, local_elem_to_add)
158 else:
159 parser_ingest.insert(i + 1, E(xpath))
160 # cases where item is something like
161 # item: task-memory-malloc-usage-report/task-malloc-list/task-malloc
162 # created filter from last item task-malloc
163 # Now add all the tags if present
164 for item_tag in item_tags[::-1]:
165 parser_ingest = E(item_tag, parser_ingest)
166 logger.debug("Generated filter XML is: %s" % etree.tostring(parser_ingest))
167
168 return parser_ingest