Debian Codegraph @

lib/jnpr/junos/rpcmeta.py

raw
1 import re
2 import sys
3 from lxml import etree
4 from lxml.builder import E
5 from jnpr.junos import jxml as JXML
6
7
8 class _RpcMetaExec(object):
9 # -----------------------------------------------------------------------
10 # CONSTRUCTOR
11 # -----------------------------------------------------------------------
12
13 def __init__(self, junos):
14 """
15 ~PRIVATE CLASS~
16 creates an RPC meta-executor object bound to the provided
17 ez-netconf :junos: object
18 """
19 self._junos = junos
20
21 # -----------------------------------------------------------------------
22 # get_config
23 # -----------------------------------------------------------------------
24
25 def get_config(
26 self,
27 filter_xml=None,
28 options={},
29 model=None,
30 namespace=None,
31 remove_ns=True,
32 **kwargs
33 ):
34 """
35 retrieve configuration from the Junos device
36
37 .. code-block:: python
38
39 dev.rpc.get_config()
40 dev.rpc.get_config(filter_xml='<system><services/></system>')
41 dev.rpc.get_config(filter_xml='system/services')
42 dev.rpc.get_config(
43 filter_xml=etree.XML('<system><services/></system>'),
44 options={'format': 'json'})
45 # to fetch junos as well as yang model configs
46 dev.rpc.get_config(model=True)
47 # openconfig yang example
48 dev.rpc.get_config(filter_xml='bgp', model='openconfig')
49 dev.rpc.get_config(filter_xml='<bgp><neighbors></neighbors></bgp>',
50 model='openconfig')
51 # custom yang example
52 dev.rpc.get_config(filter_xml='l2vpn', model='custom',
53 namespace="http://yang.juniper.net/customyang/l2vpn")
54 # ietf yang example
55 dev.rpc.get_config(filter_xml='interfaces', model='ietf')
56 # ietf-softwire yang example
57 dev.rpc.get_config(filter_xml='softwire-config', model='ietf',
58 namespace="urn:ietf:params:xml:ns:yang:ietf-softwire",
59 options={'format': 'json'})
60
61
62 :filter_xml: fully XML formatted tag which defines what to retrieve,
63 when omitted the entire configuration is returned;
64 the following returns the device host-name configured
65 with "set system host-name"
66
67 .. code-block:: python
68
69 config = dev.rpc.get_config(filter_xml=etree.XML('''
70 <configuration>
71 <system>
72 <host-name/>
73 </system>
74 </configuration>'''))
75
76 :options: is a dictionary of XML attributes to set within the
77 <get-configuration> RPC; the following returns the device
78 host-name either configured with "set system host-name"
79 and if unconfigured, the value inherited from
80 apply-group re0|re1, typical for multi-RE systems
81
82 .. code-block:: python
83
84 config = dev.rpc.get_config(filter_xml=etree.XML('''
85 <configuration>
86 <system>
87 <host-name/>
88 </system>
89 </configuration>'''),
90 options={'database':'committed','inherit':'inherit'})
91
92 :param str model: Can provide yang model openconfig/custom/ietf. When
93 model is True and filter_xml is None, xml is enclosed under
94 <data> so that we get junos as well as other model
95 configurations
96
97 :param str namespace: User can have their own defined namespace in the
98 custom yang models, In such cases they need to provide that
99 namespace so that it can be used to fetch yang modeled configs
100
101 :param bool remove_ns: remove namespaces, if value assigned is False,
102 function will return xml with namespaces. The same xml
103 returned can be loaded back to devices. This comes handy in
104 case of yang based configs
105
106 .. code-block:: python
107
108 dev.rpc.get_config(filter_xml='bgp', model='openconfig',
109 remove_ns=False)
110 """
111
112 nmspaces = {
113 "openconfig": "http://openconfig.net/yang/",
114 "ietf": "urn:ietf:params:xml:ns:yang:ietf-",
115 }
116
117 rpc = E("get-configuration", options)
118
119 if filter_xml is not None:
120 if not isinstance(filter_xml, etree._Element):
121 if re.search("^<.*>$", filter_xml):
122 filter_xml = etree.XML(filter_xml)
123 else:
124 filter_data = None
125 for tag in filter_xml.split("/")[::-1]:
126 filter_data = (
127 E(tag) if filter_data is None else E(tag, filter_data)
128 )
129 filter_xml = filter_data
130 # wrap the provided filter with toplevel <configuration> if
131 # it does not already have one (not in case of yang model config)
132 if (
133 filter_xml.tag != "configuration"
134 and model is None
135 and namespace is None
136 ):
137 etree.SubElement(rpc, "configuration").append(filter_xml)
138 else:
139 if model is not None or namespace is not None:
140 if model == "custom" and namespace is None:
141 raise AttributeError(
142 'For "custom" model, ' 'explicitly provide "namespace"'
143 )
144 ns = namespace or (nmspaces.get(model.lower()) + filter_xml.tag)
145 filter_xml.attrib["xmlns"] = ns
146 rpc.append(filter_xml)
147 transform = self._junos.transform
148 if remove_ns is False:
149 self._junos.transform = lambda: JXML.strip_namespaces_prefix
150 try:
151 response = self._junos.execute(rpc, **kwargs)
152 finally:
153 self._junos.transform = transform
154 # in case of model provided top level should be data
155 # return response
156 if model and filter_xml is None and options.get("format") != "json":
157 response = response.getparent()
158 response.tag = "data"
159 return response
160
161 # -----------------------------------------------------------------------
162 # get
163 # -----------------------------------------------------------------------
164
165 def get(self, filter_select=None, ignore_warning=False, **kwargs):
166 """
167 Retrieve running configuration and device state information using
168 <get> rpc
169
170 .. code-block:: python
171
172 dev.rpc.get()
173 dev.rpc.get(ignore_warning=True)
174 dev.rpc.get(filter_select='bgp') or dev.rpc.get('bgp')
175 dev.rpc.get(filter_select='bgp/neighbors')
176 dev.rpc.get("/bgp/neighbors/neighbor[neighbor-address='10.10.0.1']"
177 "/timers/state/hold-time")
178 dev.rpc.get('mpls', ignore_warning=True)
179
180 :param str filter_select:
181 The select attribute will be treated as an XPath expression and
182 used to filter the returned data.
183
184 :param ignore_warning: A boolean, string or list of string.
185 If the value is True, it will ignore all warnings regardless of the
186 warning message. If the value is a string, it will ignore
187 warning(s) if the message of each warning matches the string. If
188 the value is a list of strings, ignore warning(s) if the message of
189 each warning matches at least one of the strings in the list.
190
191 For example::
192
193 dev.rpc.get(ignore_warning=True)
194 dev.rpc.get(ignore_warning='vrrp subsystem not running')
195 dev.rpc.get(ignore_warning=['vrrp subsystem not running',
196 'statement not found'])
197
198 .. note::
199 When the value of ignore_warning is a string, or list of strings,
200 the string is actually used as a case-insensitive regular
201 expression pattern. If the string contains only alpha-numeric
202 characters, as shown in the above examples, this results in a
203 case-insensitive substring match. However, any regular expression
204 pattern supported by the re library may be used for more
205 complicated match conditions.
206
207 :returns: xml object
208 """
209 # junos only support filter type to be xpath
210 filter_params = {"type": "xpath"}
211 if filter_select is not None:
212 filter_params["source"] = filter_select
213 rpc = E("get", E("filter", filter_params))
214 return self._junos.execute(rpc, ignore_warning=ignore_warning, **kwargs)
215
216 # -----------------------------------------------------------------------
217 # load_config
218 # -----------------------------------------------------------------------
219
220 def load_config(self, contents, ignore_warning=False, **options):
221 """
222 loads :contents: onto the Junos device, does not commit the change.
223
224 :param ignore_warning: A boolean, string or list of string.
225 If the value is True, it will ignore all warnings regardless of the
226 warning message. If the value is a string, it will ignore
227 warning(s) if the message of each warning matches the string. If
228 the value is a list of strings, ignore warning(s) if the message of
229 each warning matches at least one of the strings in the list.
230
231 For example::
232
233 dev.rpc.load_config(cnf, ignore_warning=True)
234 dev.rpc.load_config(cnf,
235 ignore_warning='vrrp subsystem not running')
236 dev.rpc.load_config(cnf,
237 ignore_warning=['vrrp subsystem not running',
238 'statement not found'])
239 dev.rpc.load_config(cnf, ignore_warning='statement not found')
240
241 .. note::
242 When the value of ignore_warning is a string, or list of strings,
243 the string is actually used as a case-insensitive regular
244 expression pattern. If the string contains only alpha-numeric
245 characters, as shown in the above examples, this results in a
246 case-insensitive substring match. However, any regular expression
247 pattern supported by the re library may be used for more
248 complicated match conditions.
249
250 :options: is a dictionary of XML attributes to set within the
251 <load-configuration> RPC.
252
253 The :contents: are interpreted by the :options: as follows:
254
255 format='text' and action='set', then :contents: is a string containing
256 a series of "set" commands
257
258 format='text', then :contents: is a string containing Junos
259 configuration in curly-brace/text format
260
261 format='json', then :contents: is a string containing Junos
262 configuration in json format
263
264 url='path', then :contents: is a None
265
266 <otherwise> :contents: is XML structure
267 """
268 rpc = E("load-configuration", options)
269
270 if contents is None and "url" in options:
271 pass
272 elif ("action" in options) and (options["action"] == "set"):
273 rpc.append(E("configuration-set", contents))
274 elif ("action" in options) and (options["action"] == "patch"):
275 rpc.append(E("configuration-patch", contents))
276 elif ("format" in options) and (options["format"] == "text"):
277 rpc.append(E("configuration-text", contents))
278 elif ("format" in options) and (options["format"] == "json"):
279 rpc.append(E("configuration-json", contents))
280 else:
281 # otherwise, it's just XML Element
282 if contents.tag != "configuration":
283 etree.SubElement(rpc, "configuration").append(contents)
284 else:
285 rpc.append(contents)
286
287 return self._junos.execute(rpc, ignore_warning=ignore_warning)
288
289 # -----------------------------------------------------------------------
290 # cli
291 # -----------------------------------------------------------------------
292
293 def cli(self, command, format="text", normalize=False):
294 rpc = E("command", command)
295 if format.lower() in ["text", "json"]:
296 rpc.attrib["format"] = format
297 return self._junos.execute(rpc, normalize=normalize)
298
299 # -----------------------------------------------------------------------
300 # method missing
301 # -----------------------------------------------------------------------
302
303 def __getattr__(self, rpc_cmd_name):
304 """
305 metaprograms a function to execute the :rpc_cmd_name:
306
307 the caller will be passing (*vargs, **kvargs) on
308 execution of the meta function; these are the specific
309 rpc command arguments(**kvargs) and options bound
310 as XML attributes (*vargs)
311 """
312
313 rpc_cmd = re.sub("_", "-", rpc_cmd_name)
314
315 def _exec_rpc(*vargs, **kvargs):
316 # create the rpc as XML command
317 rpc = etree.Element(rpc_cmd)
318
319 # Gather decorator keywords into dec_args and remove from kvargs
320 dec_arg_keywords = [
321 "dev_timeout",
322 "normalize",
323 "ignore_warning",
324 "filter_xml",
325 ]
326 dec_args = {}
327 for keyword in dec_arg_keywords:
328 if keyword in kvargs:
329 dec_args[keyword] = kvargs.pop(keyword)
330
331 # kvargs are the command parameter/values
332 if kvargs:
333 for arg_name, arg_value in kvargs.items():
334 arg_name = re.sub("_", "-", arg_name)
335 if not isinstance(arg_value, (tuple, list)):
336 arg_value = [arg_value]
337 for a in arg_value:
338 if not isinstance(
339 a,
340 (bool, str, unicode) if sys.version < "3" else (bool, str),
341 ):
342 raise TypeError(
343 "The value %s for argument %s"
344 " is of %s. Argument "
345 "values must be a string, "
346 "boolean, or list/tuple of "
347 "strings and booleans." % (a, arg_name, str(type(a)))
348 )
349 if a is not False:
350 arg = etree.SubElement(rpc, arg_name)
351 if not isinstance(a, bool):
352 arg.text = a
353
354 # vargs[0] is a dict, command options like format='text'
355 if vargs:
356 for k, v in vargs[0].items():
357 if v is not True:
358 rpc.attrib[k] = v
359
360 # now invoke the command against the
361 # associated :junos: device and return
362 # the results per :junos:execute()
363 return self._junos.execute(rpc, **dec_args)
364
365 # metabind help() and the function name to the :rpc_cmd_name:
366 # provided by the caller ... that's about all we can do, yo!
367
368 _exec_rpc.__doc__ = rpc_cmd
369 _exec_rpc.__name__ = rpc_cmd_name
370
371 # return the metafunction that the caller will in-turn invoke
372 return _exec_rpc
373
374 # -----------------------------------------------------------------------
375 # callable
376 # -----------------------------------------------------------------------
377
378 def __call__(self, rpc_cmd, **kvargs):
379 """
380 callable will execute the provided :rpc_cmd: against the
381 attached :junos: object and return the RPC response per
382 :junos:execute()
383
384 kvargs is simply passed 'as-is' to :junos:execute()
385 """
386 return self._junos.execute(rpc_cmd, **kvargs)