Debian Codegraph @

ncclient/operations/rpc.py

raw
1 # Copyright 2009 Shikhar Bhushan
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from threading import Event, Lock
16 from uuid import uuid4
17
18 from ncclient.xml_ import *
19 from ncclient.logging_ import SessionLoggerAdapter
20 from ncclient.transport import SessionListener
21 from ncclient.operations import util
22 from ncclient.operations.errors import OperationError, TimeoutExpiredError, MissingCapabilityError
23
24 import logging
25 logger = logging.getLogger("ncclient.operations.rpc")
26
27
28 class RPCError(OperationError):
29
30 "Represents an `rpc-error`. It is a type of :exc:`OperationError` and can be raised as such."
31
32 tag_to_attr = {
33 qualify("error-type"): "_type",
34 qualify("error-tag"): "_tag",
35 qualify("error-app-tag"): "_app_tag",
36 qualify("error-severity"): "_severity",
37 qualify("error-info"): "_info",
38 qualify("error-path"): "_path",
39 qualify("error-message"): "_message"
40 }
41
42 def __init__(self, raw, errs=None):
43 self._raw = raw
44 if errs is None:
45 # Single RPCError
46 self._errlist = None
47 for attr in RPCError.tag_to_attr.values():
48 setattr(self, attr, None)
49 for subele in raw:
50 attr = RPCError.tag_to_attr.get(subele.tag, None)
51 if attr is not None:
52 setattr(self, attr, subele.text if attr != "_info" else to_xml(subele) )
53 if self.message is not None:
54 OperationError.__init__(self, self.message)
55 else:
56 OperationError.__init__(self, self.to_dict())
57 else:
58 # Multiple errors returned. Errors is a list of RPCError objs
59 self._errlist = errs
60 errlist = []
61 for err in errs:
62 if err.severity:
63 errsev = err.severity
64 else:
65 errsev = 'undefined'
66 if err.message:
67 errmsg = err.message
68 else:
69 errmsg = 'not an error message in the reply. Enable debug'
70 errordict = {"severity": errsev, "message":errmsg}
71 errlist.append(errordict)
72 # We are interested in the severity and the message
73 self._severity = 'warning'
74 self._message = "\n".join(["%s: %s" %(err['severity'].strip(), err['message'].strip()) for err in errlist])
75 self.errors = errs
76 has_error = filter(lambda higherr: higherr['severity'] == 'error', errlist)
77 if has_error:
78 self._severity = 'error'
79 OperationError.__init__(self, self.message)
80
81 def to_dict(self):
82 return dict([ (attr[1:], getattr(self, attr)) for attr in RPCError.tag_to_attr.values() ])
83
84 @property
85 def xml(self):
86 "The `rpc-error` element as returned in XML. \
87 Multiple errors are returned as list of RPC errors"
88 return self._raw
89
90 @property
91 def type(self):
92 "The contents of the `error-type` element."
93 return self._type
94
95 @property
96 def tag(self):
97 "The contents of the `error-tag` element."
98 return self._tag
99
100 @property
101 def app_tag(self):
102 "The contents of the `error-app-tag` element."
103 return self._app_tag
104
105 @property
106 def severity(self):
107 "The contents of the `error-severity` element."
108 return self._severity
109
110 @property
111 def path(self):
112 "The contents of the `error-path` element if present or `None`."
113 return self._path
114
115 @property
116 def message(self):
117 "The contents of the `error-message` element if present or `None`."
118 return self._message
119
120 @property
121 def info(self):
122 "XML string or `None`; representing the `error-info` element."
123 return self._info
124
125 @property
126 def errlist(self):
127 "List of errors if this represents multiple errors, otherwise None."
128 return self._errlist
129
130
131 class RPCReply:
132
133 """Represents an *rpc-reply*. Only concerns itself with whether the operation was successful.
134
135 *raw*: the raw unparsed reply
136
137 *huge_tree*: parse XML with very deep trees and very long text content
138
139 .. note::
140 If the reply has not yet been parsed there is an implicit, one-time parsing overhead to
141 accessing some of the attributes defined by this class.
142 """
143
144 ERROR_CLS = RPCError
145 "Subclasses can specify a different error class, but it should be a subclass of `RPCError`."
146
147 def __init__(self, raw, huge_tree=False, parsing_error_transform=None):
148 self._raw = raw
149 self._parsing_error_transform = parsing_error_transform
150 self._parsed = False
151 self._root = None
152 self._errors = []
153 self._huge_tree = huge_tree
154
155 def __repr__(self):
156 return self._raw
157
158 def parse(self):
159 "Parses the *rpc-reply*."
160 if self._parsed: return
161 root = self._root = to_ele(self._raw, huge_tree=self._huge_tree) # The <rpc-reply> element
162 # Per RFC 4741 an <ok/> tag is sent when there are no errors or warnings
163 ok = root.find(qualify("ok"))
164 if ok is None:
165 # Create RPCError objects from <rpc-error> elements
166 error = root.find('.//'+qualify('rpc-error'))
167 if error is not None:
168 for err in root.getiterator(error.tag):
169 # Process a particular <rpc-error>
170 self._errors.append(self.ERROR_CLS(err))
171 try:
172 self._parsing_hook(root)
173 except Exception as e:
174 if self._parsing_error_transform is None:
175 # re-raise as we have no workaround
176 raise e
177
178 # Apply device specific workaround and try again
179 self._parsing_error_transform(root)
180 self._parsing_hook(root)
181
182 self._parsed = True
183
184 def _parsing_hook(self, root):
185 "No-op by default. Gets passed the *root* element for the reply."
186 pass
187
188 def set_parsing_error_transform(self, transform_function):
189 self._parsing_error_transform = transform_function
190
191 @property
192 def xml(self):
193 "*rpc-reply* element as returned."
194 return self._raw
195
196 @property
197 def ok(self):
198 "Boolean value indicating if there were no errors."
199 self.parse()
200 return not self.errors # empty list => false
201
202 @property
203 def error(self):
204 "Returns the first :class:`RPCError` and `None` if there were no errors."
205 self.parse()
206 if self._errors:
207 return self._errors[0]
208 else:
209 return None
210
211 @property
212 def errors(self):
213 "List of `RPCError` objects. Will be empty if there were no *rpc-error* elements in reply."
214 self.parse()
215 return self._errors
216
217
218 class RPCReplyListener(SessionListener): # internal use
219
220 creation_lock = Lock()
221
222 # one instance per session -- maybe there is a better way??
223 def __new__(cls, session, device_handler):
224 with RPCReplyListener.creation_lock:
225 instance = session.get_listener_instance(cls)
226 if instance is None:
227 instance = object.__new__(cls)
228 instance._lock = Lock()
229 instance._id2rpc = {}
230 instance._device_handler = device_handler
231 #instance._pipelined = session.can_pipeline
232 session.add_listener(instance)
233 instance.logger = SessionLoggerAdapter(logger,
234 {'session': session})
235 return instance
236
237 def register(self, id, rpc):
238 with self._lock:
239 self._id2rpc[id] = rpc
240
241 def callback(self, root, raw):
242 tag, attrs = root
243 if self._device_handler.perform_qualify_check():
244 if tag != qualify("rpc-reply"):
245 return
246 if "message-id" not in attrs:
247 # required attribute so raise OperationError
248 raise OperationError("Could not find 'message-id' attribute in <rpc-reply>")
249 else:
250 id = attrs["message-id"] # get the msgid
251 with self._lock:
252 try:
253 rpc = self._id2rpc[id] # the corresponding rpc
254 self.logger.debug("Delivering to %r", rpc)
255 rpc.deliver_reply(raw)
256 except KeyError:
257 raise OperationError("Unknown 'message-id': %s" % id)
258 # no catching other exceptions, fail loudly if must
259 else:
260 # if no error delivering, can del the reference to the RPC
261 del self._id2rpc[id]
262
263 def errback(self, err):
264 try:
265 for rpc in self._id2rpc.values():
266 rpc.deliver_error(err)
267 finally:
268 self._id2rpc.clear()
269
270
271 class RaiseMode:
272 """
273 Define how errors indicated by RPC should be handled.
274
275 Note that any error_filters defined in the device handler will still be
276 applied, even if ERRORS or ALL is defined: If the filter matches, an exception
277 will NOT be raised.
278
279 """
280 NONE = 0
281 "Don't attempt to raise any type of `rpc-error` as :exc:`RPCError`."
282
283 ERRORS = 1
284 "Raise only when the `error-type` indicates it is an honest-to-god error."
285
286 ALL = 2
287 "Don't look at the `error-type`, always raise."
288
289
290 class RPC:
291
292 """Base class for all operations, directly corresponding to *rpc* requests. Handles making the request, and taking delivery of the reply."""
293
294 DEPENDS = []
295 """Subclasses can specify their dependencies on capabilities as a list of URI's or abbreviated names, e.g. ':writable-running'. These are verified at the time of instantiation. If the capability is not available, :exc:`MissingCapabilityError` is raised."""
296
297 REPLY_CLS = RPCReply
298 "By default :class:`RPCReply`. Subclasses can specify a :class:`RPCReply` subclass."
299
300
301 def __init__(self, session, device_handler, async_mode=False, timeout=30, raise_mode=RaiseMode.NONE, huge_tree=False):
302 """
303 *session* is the :class:`~ncclient.transport.Session` instance
304
305 *device_handler" is the :class:`~ncclient.devices.*.*DeviceHandler` instance
306
307 *async* specifies whether the request is to be made asynchronously, see :attr:`is_async`
308
309 *timeout* is the timeout for a synchronous request, see :attr:`timeout`
310
311 *raise_mode* specifies the exception raising mode, see :attr:`raise_mode`
312
313 *huge_tree* parse xml with huge_tree support (e.g. for large text config retrieval), see :attr:`huge_tree`
314 """
315 self._session = session
316 try:
317 for cap in self.DEPENDS:
318 self._assert(cap)
319 except AttributeError:
320 pass
321 self._async = async_mode
322 self._timeout = timeout
323 self._raise_mode = raise_mode
324 self._huge_tree = huge_tree
325 self._id = uuid4().urn # Keeps things simple instead of having a class attr with running ID that has to be locked
326 self._listener = RPCReplyListener(session, device_handler)
327 self._listener.register(self._id, self)
328 self._reply = None
329 self._error = None
330 self._event = Event()
331 self._device_handler = device_handler
332 self.logger = SessionLoggerAdapter(logger, {'session': session})
333
334
335 def _wrap(self, subele):
336 # internal use
337 ele = new_ele("rpc", {"message-id": self._id},
338 **self._device_handler.get_xml_extra_prefix_kwargs())
339 ele.append(subele)
340 return to_xml(ele)
341
342 def _request(self, op):
343 """Implementations of :meth:`request` call this method to send the request and process the reply.
344
345 In synchronous mode, blocks until the reply is received and returns :class:`RPCReply`. Depending on the :attr:`raise_mode` a `rpc-error` element in the reply may lead to an :exc:`RPCError` exception.
346
347 In asynchronous mode, returns immediately, returning `self`. The :attr:`event` attribute will be set when the reply has been received (see :attr:`reply`) or an error occured (see :attr:`error`).
348
349 *op* is the operation to be requested as an :class:`~xml.etree.ElementTree.Element`
350 """
351 self.logger.info('Requesting %r', self.__class__.__name__)
352 req = self._wrap(op)
353 self._session.send(req)
354 if self._async:
355 self.logger.debug('Async request, returning %r', self)
356 return self
357 else:
358 self.logger.debug('Sync request, will wait for timeout=%r', self._timeout)
359 self._event.wait(self._timeout)
360 if self._event.is_set():
361 if self._error:
362 # Error that prevented reply delivery
363 raise self._error
364 self._reply.parse()
365 if self._reply.error is not None and not self._device_handler.is_rpc_error_exempt(self._reply.error.message):
366 # <rpc-error>'s [ RPCError ]
367
368 if self._raise_mode == RaiseMode.ALL or (self._raise_mode == RaiseMode.ERRORS and self._reply.error.severity == "error"):
369 errlist = []
370 errors = self._reply.errors
371 if len(errors) > 1:
372 raise RPCError(to_ele(self._reply._raw), errs=errors)
373 else:
374 raise self._reply.error
375 if self._device_handler.transform_reply():
376 return NCElement(self._reply, self._device_handler.transform_reply(), huge_tree=self._huge_tree)
377 else:
378 return self._reply
379 else:
380 raise TimeoutExpiredError('ncclient timed out while waiting for an rpc reply.')
381
382 def request(self):
383 """Subclasses must implement this method. Typically only the request needs to be built as an
384 :class:`~xml.etree.ElementTree.Element` and everything else can be handed off to
385 :meth:`_request`."""
386 pass
387
388 def _assert(self, capability):
389 """Subclasses can use this method to verify that a capability is available with the NETCONF
390 server, before making a request that requires it. A :exc:`MissingCapabilityError` will be
391 raised if the capability is not available."""
392 if capability not in self._session.server_capabilities:
393 raise MissingCapabilityError('Server does not support [%s]' % capability)
394
395 def deliver_reply(self, raw):
396 # internal use
397 self._reply = self.REPLY_CLS(raw, huge_tree=self._huge_tree)
398
399 # Set the reply_parsing_error transform outside the constructor, to keep compatibility for
400 # third party reply classes outside of ncclient
401 self._reply.set_parsing_error_transform(
402 self._device_handler.reply_parsing_error_transform(self.REPLY_CLS)
403 )
404
405 self._event.set()
406
407 def deliver_error(self, err):
408 # internal use
409 self._error = err
410 self._event.set()
411
412 @property
413 def reply(self):
414 ":class:`RPCReply` element if reply has been received or `None`"
415 return self._reply
416
417 @property
418 def error(self):
419 """:exc:`Exception` type if an error occured or `None`.
420
421 .. note::
422 This represents an error which prevented a reply from being received. An *rpc-error*
423 does not fall in that category -- see `RPCReply` for that.
424 """
425 return self._error
426
427 @property
428 def id(self):
429 "The *message-id* for this RPC."
430 return self._id
431
432 @property
433 def session(self):
434 "The `~ncclient.transport.Session` object associated with this RPC."
435 return self._session
436
437 @property
438 def event(self):
439 """:class:`~threading.Event` that is set when reply has been received or when an error preventing
440 delivery of the reply occurs.
441 """
442 return self._event
443
444 def __set_async(self, async_mode=True):
445 self._async = async_mode
446 if async_mode and not self._session.can_pipeline:
447 raise UserWarning('Asynchronous mode not supported for this device/session')
448
449 def __set_raise_mode(self, mode):
450 assert(mode in (RaiseMode.NONE, RaiseMode.ERRORS, RaiseMode.ALL))
451 self._raise_mode = mode
452
453 def __set_timeout(self, timeout):
454 self._timeout = timeout
455
456 raise_mode = property(fget=lambda self: self._raise_mode, fset=__set_raise_mode)
457 """Depending on this exception raising mode, an `rpc-error` in the reply may be raised as an :exc:`RPCError` exception. Valid values are the constants defined in :class:`RaiseMode`. """
458
459 is_async = property(fget=lambda self: self._async, fset=__set_async)
460 """Specifies whether this RPC will be / was requested asynchronously. By default RPC's are synchronous."""
461
462 timeout = property(fget=lambda self: self._timeout, fset=__set_timeout)
463 """Timeout in seconds for synchronous waiting defining how long the RPC request will block on a reply before raising :exc:`TimeoutExpiredError`.
464
465 Irrelevant for asynchronous usage.
466 """
467
468 @property
469 def huge_tree(self):
470 """Whether `huge_tree` support for XML parsing of RPC replies is enabled (default=False)"""
471 return self._huge_tree
472
473 @huge_tree.setter
474 def huge_tree(self, x):
475 self._huge_tree = x
476
477 class GenericRPC(RPC):
478 """Generic rpc commands wrapper"""
479 REPLY_CLS = RPCReply
480 """See :class:`RPCReply`."""
481
482 def request(self, rpc_command, source=None, filter=None, config=None, target=None, format=None):
483 """
484 *rpc_command* specifies rpc command to be dispatched either in plain text or in xml element format (depending on command)
485
486 *target* name of the configuration datastore being edited
487
488 *source* name of the configuration datastore being queried
489
490 *config* is the configuration, which must be rooted in the `config` element. It can be specified either as a string or an :class:`~xml.etree.ElementTree.Element`.
491
492 *filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
493
494 :seealso: :ref:`filter_params`
495
496 Examples of usage::
497
498 m.rpc('rpc_command')
499
500 or dispatch element like ::
501
502 rpc_command = new_ele('get-xnm-information')
503 sub_ele(rpc_command, 'type').text = "xml-schema"
504 m.rpc(rpc_command)
505 """
506
507 if etree.iselement(rpc_command):
508 node = rpc_command
509 else:
510 node = new_ele(rpc_command)
511 if target is not None:
512 node.append(util.datastore_or_url("target", target, self._assert))
513 if source is not None:
514 node.append(util.datastore_or_url("source", source, self._assert))
515 if filter is not None:
516 node.append(util.build_filter(filter))
517 if config is not None:
518 node.append(validated_element(config, ("config", qualify("config"))))
519
520 return self._request(node)