Debian Codegraph @

ncclient/manager.py

raw
1 # Copyright 2009 Shikhar Bhushan
2 # Copyright 2011 Leonidas Poulopoulos
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 """
17 This module is a thin layer of abstraction around the library.
18 It exposes all core functionality.
19 """
20
21 from ncclient import operations
22 from ncclient import transport
23 import socket
24 import logging
25 import functools
26
27 from ncclient.xml_ import *
28
29 logger = logging.getLogger('ncclient.manager')
30
31 OPERATIONS = {
32 "get": operations.Get,
33 "get_config": operations.GetConfig,
34 "get_schema": operations.GetSchema,
35 "dispatch": operations.Dispatch,
36 "edit_config": operations.EditConfig,
37 "copy_config": operations.CopyConfig,
38 "validate": operations.Validate,
39 "commit": operations.Commit,
40 "discard_changes": operations.DiscardChanges,
41 "cancel_commit": operations.CancelCommit,
42 "delete_config": operations.DeleteConfig,
43 "lock": operations.Lock,
44 "unlock": operations.Unlock,
45 "create_subscription": operations.CreateSubscription,
46 "close_session": operations.CloseSession,
47 "kill_session": operations.KillSession,
48 "poweroff_machine": operations.PoweroffMachine,
49 "reboot_machine": operations.RebootMachine,
50 "rpc": operations.GenericRPC,
51 }
52
53 """
54 Dictionary of base method names and corresponding :class:`~ncclient.operations.RPC`
55 subclasses. It is used to lookup operations, e.g. `get_config` is mapped to
56 :class:`~ncclient.operations.GetConfig`. It is thus possible to add additional
57 operations to the :class:`Manager` API.
58 """
59
60
61 def make_device_handler(device_params, ignore_errors=None):
62 """
63 Create a device handler object that provides device specific parameters and
64 functions, which are called in various places throughout our code.
65
66 If no device_params are defined or the "name" in the parameter dict is not
67 known then a default handler will be returned.
68
69 """
70 if device_params is None:
71 device_params = {}
72
73 handler = device_params.get('handler', None)
74 if handler:
75 return handler(device_params, ignore_errors)
76
77 device_name = device_params.get("name", "default")
78 # Attempt to import device handler class. All device handlers are
79 # in a module called "ncclient.devices.<devicename>" and in a class named
80 # "<devicename>DeviceHandler", with the first letter capitalized.
81 class_name = "%sDeviceHandler" % device_name.capitalize()
82 devices_module_name = "ncclient.devices.%s" % device_name
83 dev_module_obj = __import__(devices_module_name)
84 handler_module_obj = getattr(getattr(dev_module_obj, "devices"), device_name)
85 class_obj = getattr(handler_module_obj, class_name)
86 handler_obj = class_obj(device_params, ignore_errors)
87 return handler_obj
88
89
90 def _extract_device_params(kwds):
91 device_params = kwds.pop("device_params", None)
92
93 return device_params
94
95 def _extract_errors_params(kwds):
96 errors_params = kwds.pop("errors_params", {})
97 return (
98 errors_params.get("ignore_errors", []),
99 errors_params.get("raise_mode", operations.RaiseMode.ALL)
100 )
101
102 def _extract_manager_params(kwds):
103 manager_params = kwds.pop("manager_params", {})
104
105 # To maintain backward compatibility
106 if 'timeout' not in manager_params and 'timeout' in kwds:
107 manager_params['timeout'] = kwds['timeout']
108 return manager_params
109
110 def _extract_nc_params(kwds):
111 nc_params = kwds.pop("nc_params", {})
112
113 return nc_params
114
115 def connect_ssh(*args, **kwds):
116 """Initialize a :class:`Manager` over the SSH transport.
117 For documentation of arguments see :meth:`ncclient.transport.SSHSession.connect`.
118
119 The underlying :class:`ncclient.transport.SSHSession` is created with
120 :data:`CAPABILITIES`. All the provided arguments are passed directly to its
121 implementation of :meth:`~ncclient.transport.SSHSession.connect`.
122
123 To customize the :class:`Manager`, add a `manager_params` dictionary in connection
124 parameters (e.g. `manager_params={'timeout': 60}` for a bigger RPC timeout parameter)
125
126 To invoke advanced vendor related operation add
127 `device_params={'name': '<vendor_alias>'}` in connection parameters. For the time,
128 'junos' and 'nexus' are supported for Juniper and Cisco Nexus respectively.
129
130 A custom device handler can be provided with
131 `device_params={'handler':<handler class>}` in connection parameters.
132
133 To specify errors to be be ignored in the RPC reply add
134 `errors_params={'ignore_errors': ['error pattern to ignore']}` in connection parameters.
135
136 To control the error raising mode add `raise_mode` in the `errors_params`
137 (e.g. `errors_params={'raise_mode': 0}` for ignoring all RPC errors)
138 See :class:`ncclient.operations.rpc.RaiseMode` for valid values of `raise_mode`
139
140 """
141 # Extract device/manager/netconf parameter dictionaries, if they were passed into this function.
142 # Remove them from kwds (which should keep only session.connect() parameters).
143 device_params = _extract_device_params(kwds)
144 manager_params = _extract_manager_params(kwds)
145 nc_params = _extract_nc_params(kwds)
146 ignore_errors, raise_mode = _extract_errors_params(kwds)
147 manager_params["raise_mode"] = raise_mode
148
149 device_handler = make_device_handler(device_params, ignore_errors)
150 device_handler.add_additional_ssh_connect_params(kwds)
151 device_handler.add_additional_netconf_params(nc_params)
152 session = transport.SSHSession(device_handler)
153
154 try:
155 session.connect(*args, **kwds)
156 except Exception as ex:
157 if session.transport:
158 session.close()
159 raise
160 return Manager(session, device_handler, **manager_params)
161
162
163 def connect_tls(*args, **kwargs):
164 """Initialize a :class:`Manager` over the TLS transport."""
165 device_params = _extract_device_params(kwargs)
166 manager_params = _extract_manager_params(kwargs)
167 nc_params = _extract_nc_params(kwargs)
168 ignore_errors, raise_mode = _extract_errors_params(kwargs)
169 manager_params["raise_mode"] = raise_mode
170
171 device_handler = make_device_handler(device_params, ignore_errors)
172 device_handler.add_additional_netconf_params(nc_params)
173 session = transport.TLSSession(device_handler)
174
175 session.connect(*args, **kwargs)
176
177 return Manager(session, device_handler, **manager_params)
178
179 def connect_uds(*args, **kwargs):
180 """Initialize a :class:`Manager` over the Unix Socket transport."""
181 device_params = _extract_device_params(kwargs)
182 manager_params = _extract_manager_params(kwargs)
183 nc_params = _extract_nc_params(kwargs)
184 ignore_errors, raise_mode = _extract_errors_params(kwargs)
185 manager_params["raise_mode"] = raise_mode
186
187 device_handler = make_device_handler(device_params, ignore_errors)
188 device_handler.add_additional_netconf_params(nc_params)
189 session = transport.UnixSocketSession(device_handler)
190
191 session.connect(*args, **kwargs)
192
193 return Manager(session, device_handler, **manager_params)
194
195 def connect_ioproc(*args, **kwds):
196 device_params = _extract_device_params(kwds)
197 manager_params = _extract_manager_params(kwds)
198 ignore_errors, raise_mode = _extract_errors_params(kwds)
199 manager_params["raise_mode"] = raise_mode
200
201 if device_params:
202 import_string = 'ncclient.transport.third_party.'
203 import_string += device_params['name'] + '.ioproc'
204 third_party_import = __import__(import_string, fromlist=['IOProc'])
205
206 device_handler = make_device_handler(device_params, ignore_errors)
207
208 session = third_party_import.IOProc(device_handler)
209 session.connect()
210
211 return Manager(session, device_handler, **manager_params)
212
213
214 def connect(*args, **kwds):
215 if "host" in kwds:
216 host = kwds["host"]
217 device_params = kwds.get('device_params', {})
218 if host == 'localhost' and device_params.get('name') == 'junos' \
219 and device_params.get('local'):
220 return connect_ioproc(*args, **kwds)
221 else:
222 return connect_ssh(*args, **kwds)
223
224 def call_home(*args, **kwds):
225 host = kwds["host"]
226 port = kwds.get("port",4334)
227 srv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
228 srv_socket.bind((host, port))
229 srv_socket.settimeout(kwds.get("timeout", 10))
230 srv_socket.listen()
231
232 sock, remote_host = srv_socket.accept()
233 logger.info('Callhome connection initiated from remote host {0}'.format(remote_host))
234 kwds['sock'] = sock
235 return connect_ssh(*args, **kwds)
236
237 class Manager:
238
239 """
240 For details on the expected behavior of the operations and their
241 parameters refer to :rfc:`6241`.
242
243 Manager instances are also context managers so you can use it like this::
244
245 with manager.connect("host") as m:
246 # do your stuff
247
248 ... or like this::
249
250 m = manager.connect("host")
251 try:
252 # do your stuff
253 finally:
254 m.close_session()
255 """
256
257 # __metaclass__ = OpExecutor
258
259
260 HUGE_TREE_DEFAULT = False
261 """Default for `huge_tree` support for XML parsing of RPC replies (defaults to False)"""
262
263 def __init__(self, session, device_handler, timeout=30, raise_mode=operations.RaiseMode.ALL):
264 self._session = session
265 self._async_mode = False
266 self._timeout = timeout
267 self._raise_mode = raise_mode
268 self._huge_tree = self.HUGE_TREE_DEFAULT
269 self._device_handler = device_handler
270 self._vendor_operations = {}
271 if device_handler:
272 self._vendor_operations.update(device_handler.add_additional_operations())
273
274 def __enter__(self):
275 return self
276
277 def __exit__(self, *args):
278 self.close_session()
279 return False
280
281 def __set_timeout(self, timeout):
282 self._timeout = timeout
283
284 def __set_async_mode(self, mode):
285 self._async_mode = mode
286
287 def __set_raise_mode(self, mode):
288 assert(mode in (operations.RaiseMode.NONE, operations.RaiseMode.ERRORS, operations.RaiseMode.ALL))
289 self._raise_mode = mode
290
291 def execute(self, cls, *args, **kwds):
292 return cls(self._session,
293 device_handler=self._device_handler,
294 async_mode=self._async_mode,
295 timeout=self._timeout,
296 raise_mode=self._raise_mode,
297 huge_tree=self._huge_tree).request(*args, **kwds)
298
299 def locked(self, target):
300 """Returns a context manager for a lock on a datastore, where
301 *target* is the name of the configuration datastore to lock, e.g.::
302
303 with m.locked("running"):
304 # do your stuff
305
306 ... instead of::
307
308 m.lock("running")
309 try:
310 # do your stuff
311 finally:
312 m.unlock("running")
313 """
314 return operations.LockContext(self._session, self._device_handler, target)
315
316 def scp(self):
317 return self._session.scp()
318
319 def session(self):
320 raise NotImplementedError
321
322 def __getattr__(self, method):
323 if method in self._vendor_operations:
324 return functools.partial(self.execute, self._vendor_operations[method])
325 elif method in OPERATIONS:
326 return functools.partial(self.execute, OPERATIONS[method])
327 else:
328 """Parse args/kwargs correctly in order to build XML element"""
329 def _missing(*args, **kwargs):
330 m = method.replace('_', '-')
331 root = new_ele(m)
332 if args:
333 for arg in args:
334 sub_ele(root, arg)
335 r = self.rpc(root)
336 return r
337 return _missing
338
339 def take_notification(self, block=True, timeout=None):
340 """Attempt to retrieve one notification from the queue of received
341 notifications.
342
343 If block is True, the call will wait until a notification is
344 received.
345
346 If timeout is a number greater than 0, the call will wait that
347 many seconds to receive a notification before timing out.
348
349 If there is no notification available when block is False or
350 when the timeout has elapse, None will be returned.
351
352 Otherwise a :class:`~ncclient.operations.notify.Notification`
353 object will be returned.
354 """
355 return self._session.take_notification(block, timeout)
356
357 @property
358 def client_capabilities(self):
359 """:class:`~ncclient.capabilities.Capabilities` object representing
360 the client's capabilities."""
361 return self._session._client_capabilities
362
363 @property
364 def server_capabilities(self):
365 """:class:`~ncclient.capabilities.Capabilities` object representing
366 the server's capabilities."""
367 return self._session._server_capabilities
368
369 @property
370 def channel_id(self):
371 return self._session._channel_id
372
373 @property
374 def channel_name(self):
375 return self._session._channel_name
376
377 @property
378 def session_id(self):
379 """`session-id` assigned by the NETCONF server."""
380 return self._session.id
381
382 @property
383 def connected(self):
384 """Whether currently connected to the NETCONF server."""
385 return self._session.connected
386
387 async_mode = property(fget=lambda self: self._async_mode,
388 fset=__set_async_mode)
389 """Specify whether operations are executed asynchronously (`True`) or
390 synchronously (`False`) (the default)."""
391
392 timeout = property(fget=lambda self: self._timeout, fset=__set_timeout)
393 """Specify the timeout for synchronous RPC requests."""
394
395 raise_mode = property(fget=lambda self: self._raise_mode,
396 fset=__set_raise_mode)
397 """Specify which errors are raised as :exc:`~ncclient.operations.RPCError`
398 exceptions. Valid values are the constants defined in
399 :class:`~ncclient.operations.RaiseMode`.
400 The default value is :attr:`~ncclient.operations.RaiseMode.ALL`."""
401
402 @property
403 def huge_tree(self):
404 """Whether `huge_tree` support for XML parsing of RPC replies is enabled (default=False)
405 The default value is configurable through :attr:`~ncclient.manager.Manager.HUGE_TREE_DEFAULT`"""
406 return self._huge_tree
407
408 @huge_tree.setter
409 def huge_tree(self, x):
410 self._huge_tree = x