| 1 |
# Copyright 2009 Shikhar Bhushan |
| 2 |
# Copyright 2014 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 |
import logging |
| 18 |
from threading import Thread, Lock, Event |
| 19 |
from queue import Queue, Empty |
| 20 |
|
| 21 |
try: |
| 22 |
import selectors |
| 23 |
except ImportError: |
| 24 |
import selectors2 as selectors |
| 25 |
|
| 26 |
import ncclient.transport |
| 27 |
from ncclient.xml_ import * |
| 28 |
from ncclient.capabilities import Capabilities |
| 29 |
from ncclient.logging_ import SessionLoggerAdapter |
| 30 |
from ncclient.transport.errors import TransportError, SessionError, SessionCloseError |
| 31 |
from ncclient.transport.notify import Notification |
| 32 |
|
| 33 |
logger = logging.getLogger('ncclient.transport.session') |
| 34 |
|
| 35 |
# v1.0: RFC 4742 |
| 36 |
MSG_DELIM = b"]]>]]>" |
| 37 |
# v1.1: RFC 6242 |
| 38 |
END_DELIM = b'\n##\n' |
| 39 |
|
| 40 |
TICK = 0.1 |
| 41 |
|
| 42 |
|
| 43 |
class NetconfBase: |
| 44 |
'''Netconf Base protocol version''' |
| 45 |
BASE_10 = 1 |
| 46 |
BASE_11 = 2 |
| 47 |
|
| 48 |
|
| 49 |
class Session(Thread): |
| 50 |
|
| 51 |
"Base class for use by transport protocol implementations." |
| 52 |
|
| 53 |
def __init__(self, capabilities): |
| 54 |
Thread.__init__(self, daemon=True, name='session') |
| 55 |
self._listeners = set() |
| 56 |
self._lock = Lock() |
| 57 |
self._q = Queue() |
| 58 |
self._notification_q = Queue() |
| 59 |
self._client_capabilities = capabilities |
| 60 |
self._server_capabilities = None # yet |
| 61 |
self._base = NetconfBase.BASE_10 |
| 62 |
self._id = None # session-id |
| 63 |
self._connected = False # to be set/cleared by subclass implementation |
| 64 |
self.logger = SessionLoggerAdapter(logger, {'session': self}) |
| 65 |
self.logger.debug('%r created: client_capabilities=%r', |
| 66 |
self, self._client_capabilities) |
| 67 |
self._device_handler = None # Should be set by child class |
| 68 |
|
| 69 |
def _dispatch_message(self, raw): |
| 70 |
try: |
| 71 |
root = parse_root(raw) |
| 72 |
except Exception as e: |
| 73 |
device_handled_raw=self._device_handler.handle_raw_dispatch(raw) |
| 74 |
if isinstance(device_handled_raw, str): |
| 75 |
root = parse_root(device_handled_raw) |
| 76 |
elif isinstance(device_handled_raw, Exception): |
| 77 |
self._dispatch_error(device_handled_raw) |
| 78 |
return |
| 79 |
else: |
| 80 |
self.logger.error('error parsing dispatch message: %s', e) |
| 81 |
return |
| 82 |
self.logger.debug('dispatching message to different listeners: %s', |
| 83 |
raw) |
| 84 |
with self._lock: |
| 85 |
listeners = list(self._listeners) |
| 86 |
for l in listeners: |
| 87 |
self.logger.debug('dispatching message to listener: %r', l) |
| 88 |
l.callback(root, raw) # no try-except; fail loudly if you must! |
| 89 |
|
| 90 |
def _dispatch_error(self, err): |
| 91 |
with self._lock: |
| 92 |
listeners = list(self._listeners) |
| 93 |
for l in listeners: |
| 94 |
self.logger.debug('dispatching error to %r', l) |
| 95 |
try: # here we can be more considerate with catching exceptions |
| 96 |
l.errback(err) |
| 97 |
except Exception as e: |
| 98 |
self.logger.warning('error dispatching to %r: %r', l, e) |
| 99 |
|
| 100 |
def _post_connect(self, timeout=60): |
| 101 |
"Greeting stuff" |
| 102 |
init_event = Event() |
| 103 |
error = [None] # so that err_cb can bind error[0]. just how it is. |
| 104 |
# callbacks |
| 105 |
def ok_cb(id, capabilities): |
| 106 |
self._id = id |
| 107 |
self._server_capabilities = capabilities |
| 108 |
init_event.set() |
| 109 |
def err_cb(err): |
| 110 |
error[0] = err |
| 111 |
init_event.set() |
| 112 |
self.add_listener(NotificationHandler(self._notification_q)) |
| 113 |
listener = HelloHandler(ok_cb, err_cb) |
| 114 |
self.add_listener(listener) |
| 115 |
self.send(HelloHandler.build(self._client_capabilities, self._device_handler)) |
| 116 |
self.logger.debug('starting main loop') |
| 117 |
self.start() |
| 118 |
# we expect server's hello message, if server doesn't responds in 60 seconds raise exception |
| 119 |
init_event.wait(timeout) |
| 120 |
if not init_event.is_set(): |
| 121 |
raise SessionError("Capability exchange timed out") |
| 122 |
# received hello message or an error happened |
| 123 |
self.remove_listener(listener) |
| 124 |
if error[0]: |
| 125 |
raise error[0] |
| 126 |
#if ':base:1.0' not in self.server_capabilities: |
| 127 |
# raise MissingCapabilityError(':base:1.0') |
| 128 |
if 'urn:ietf:params:netconf:base:1.1' in self._server_capabilities and 'urn:ietf:params:netconf:base:1.1' in self._client_capabilities: |
| 129 |
self.logger.debug("After 'hello' message selecting netconf:base:1.1 for encoding") |
| 130 |
self._base = NetconfBase.BASE_11 |
| 131 |
self.logger.info('initialized: session-id=%s | server_capabilities=%s', |
| 132 |
self._id, self._server_capabilities) |
| 133 |
|
| 134 |
def add_listener(self, listener): |
| 135 |
"""Register a listener that will be notified of incoming messages and |
| 136 |
errors. |
| 137 |
|
| 138 |
:type listener: :class:`SessionListener` |
| 139 |
""" |
| 140 |
self.logger.debug('installing listener %r', listener) |
| 141 |
if not isinstance(listener, SessionListener): |
| 142 |
raise SessionError("Listener must be a SessionListener type") |
| 143 |
with self._lock: |
| 144 |
self._listeners.add(listener) |
| 145 |
|
| 146 |
def remove_listener(self, listener): |
| 147 |
"""Unregister some listener; ignore if the listener was never |
| 148 |
registered. |
| 149 |
|
| 150 |
:type listener: :class:`SessionListener` |
| 151 |
""" |
| 152 |
self.logger.debug('discarding listener %r', listener) |
| 153 |
with self._lock: |
| 154 |
self._listeners.discard(listener) |
| 155 |
|
| 156 |
def get_listener_instance(self, cls): |
| 157 |
"""If a listener of the specified type is registered, returns the |
| 158 |
instance. |
| 159 |
|
| 160 |
:type cls: :class:`SessionListener` |
| 161 |
""" |
| 162 |
with self._lock: |
| 163 |
for listener in self._listeners: |
| 164 |
if isinstance(listener, cls): |
| 165 |
return listener |
| 166 |
|
| 167 |
def connect(self, *args, **kwds): # subclass implements |
| 168 |
raise NotImplementedError |
| 169 |
|
| 170 |
def _transport_read(self): |
| 171 |
""" |
| 172 |
Read data from underlying Transport layer, either SSH or TLS, as |
| 173 |
implemented in subclass. |
| 174 |
|
| 175 |
:return: Byte string read from Transport, or None if nothing was read. |
| 176 |
""" |
| 177 |
raise NotImplementedError |
| 178 |
|
| 179 |
def _transport_write(self, data): |
| 180 |
""" |
| 181 |
Write data into underlying Transport layer, either SSH or TLS, as |
| 182 |
implemented in subclass. |
| 183 |
|
| 184 |
:param data: Byte string to write. |
| 185 |
:return: Number of bytes sent, or 0 if the stream is closed. |
| 186 |
""" |
| 187 |
raise NotImplementedError |
| 188 |
|
| 189 |
def _transport_register(self, selector, event): |
| 190 |
""" |
| 191 |
Register the channel/socket of Transport layer for selection. |
| 192 |
Implemented in a subclass. |
| 193 |
|
| 194 |
:param selector: Selector to register with. |
| 195 |
:param event: Type of event for selection. |
| 196 |
""" |
| 197 |
raise NotImplementedError |
| 198 |
|
| 199 |
def _send_ready(self): |
| 200 |
""" |
| 201 |
Check if Transport layer is ready to send the data. Implemented |
| 202 |
in a subclass. |
| 203 |
|
| 204 |
:return: True if the layer is ready, False otherwise. |
| 205 |
""" |
| 206 |
raise NotImplementedError |
| 207 |
|
| 208 |
def run(self): |
| 209 |
q = self._q |
| 210 |
|
| 211 |
def start_delim(data_len): |
| 212 |
return b'\n#%i\n' % data_len |
| 213 |
|
| 214 |
try: |
| 215 |
s = selectors.DefaultSelector() |
| 216 |
self._transport_register(s, selectors.EVENT_READ) |
| 217 |
self.logger.debug('selector type = %s', s.__class__.__name__) |
| 218 |
while True: |
| 219 |
|
| 220 |
if not q.empty() and self._send_ready(): |
| 221 |
self.logger.debug("Sending message") |
| 222 |
data = q.get().encode() |
| 223 |
if self._base == NetconfBase.BASE_11: |
| 224 |
data = b"%s%s%s" % (start_delim(len(data)), data, END_DELIM) |
| 225 |
else: |
| 226 |
data = b"%s%s" % (data, MSG_DELIM) |
| 227 |
self.logger.info("Sending:\n%s", data) |
| 228 |
while data: |
| 229 |
n = self._transport_write(data) |
| 230 |
if n <= 0: |
| 231 |
raise SessionCloseError(self._buffer.getvalue(), data) |
| 232 |
data = data[n:] |
| 233 |
|
| 234 |
events = s.select(timeout=TICK) |
| 235 |
if events: |
| 236 |
data = self._transport_read() |
| 237 |
if data: |
| 238 |
try: |
| 239 |
self.parser.parse(data) |
| 240 |
except ncclient.transport.parser.SAXFilterXMLNotFoundError: |
| 241 |
self.logger.debug('switching from sax to dom parsing') |
| 242 |
self.parser = ncclient.transport.parser.DefaultXMLParser(self) |
| 243 |
self.parser.parse(data) |
| 244 |
elif self._closing.is_set(): |
| 245 |
# End of session, expected |
| 246 |
break |
| 247 |
else: |
| 248 |
# End of session, unexpected |
| 249 |
raise SessionCloseError(self._buffer.getvalue()) |
| 250 |
except Exception as e: |
| 251 |
self.logger.debug("Broke out of main loop, error=%r", e) |
| 252 |
self._dispatch_error(e) |
| 253 |
self.close() |
| 254 |
|
| 255 |
def send(self, message): |
| 256 |
"""Send the supplied *message* (xml string) to NETCONF server.""" |
| 257 |
if not self.connected: |
| 258 |
raise TransportError('Not connected to NETCONF server') |
| 259 |
self.logger.debug('queueing %s', message) |
| 260 |
self._q.put(message) |
| 261 |
|
| 262 |
def scp(self): |
| 263 |
raise NotImplementedError |
| 264 |
### Properties |
| 265 |
|
| 266 |
def take_notification(self, block, timeout): |
| 267 |
try: |
| 268 |
return self._notification_q.get(block, timeout) |
| 269 |
except Empty: |
| 270 |
return None |
| 271 |
|
| 272 |
@property |
| 273 |
def connected(self): |
| 274 |
"Connection status of the session." |
| 275 |
return self._connected |
| 276 |
|
| 277 |
@property |
| 278 |
def client_capabilities(self): |
| 279 |
"Client's :class:`Capabilities`" |
| 280 |
return self._client_capabilities |
| 281 |
|
| 282 |
@property |
| 283 |
def server_capabilities(self): |
| 284 |
"Server's :class:`Capabilities`" |
| 285 |
return self._server_capabilities |
| 286 |
|
| 287 |
@property |
| 288 |
def id(self): |
| 289 |
"""A string representing the `session-id`. If the session has not been initialized it will be `None`""" |
| 290 |
return self._id |
| 291 |
|
| 292 |
|
| 293 |
class SessionListener: |
| 294 |
|
| 295 |
"""Base class for :class:`Session` listeners, which are notified when a new |
| 296 |
NETCONF message is received or an error occurs. |
| 297 |
|
| 298 |
.. note:: |
| 299 |
Avoid time-intensive tasks in a callback's context. |
| 300 |
""" |
| 301 |
|
| 302 |
def callback(self, root, raw): |
| 303 |
"""Called when a new XML document is received. The *root* argument allows the callback to determine whether it wants to further process the document. |
| 304 |
|
| 305 |
Here, *root* is a tuple of *(tag, attributes)* where *tag* is the qualified name of the root element and *attributes* is a dictionary of its attributes (also qualified names). |
| 306 |
|
| 307 |
*raw* will contain the XML document as a string. |
| 308 |
""" |
| 309 |
raise NotImplementedError |
| 310 |
|
| 311 |
def errback(self, ex): |
| 312 |
"""Called when an error occurs. |
| 313 |
|
| 314 |
:type ex: :exc:`Exception` |
| 315 |
""" |
| 316 |
raise NotImplementedError |
| 317 |
|
| 318 |
|
| 319 |
class HelloHandler(SessionListener): |
| 320 |
|
| 321 |
def __init__(self, init_cb, error_cb): |
| 322 |
self._init_cb = init_cb |
| 323 |
self._error_cb = error_cb |
| 324 |
|
| 325 |
def callback(self, root, raw): |
| 326 |
tag, attrs = root |
| 327 |
if (tag == qualify("hello")) or (tag == "hello"): |
| 328 |
try: |
| 329 |
id, capabilities = HelloHandler.parse(raw) |
| 330 |
except Exception as e: |
| 331 |
self._error_cb(e) |
| 332 |
else: |
| 333 |
self._init_cb(id, capabilities) |
| 334 |
|
| 335 |
def errback(self, err): |
| 336 |
self._error_cb(err) |
| 337 |
|
| 338 |
@staticmethod |
| 339 |
def build(capabilities, device_handler): |
| 340 |
"Given a list of capability URI's returns <hello> message XML string" |
| 341 |
if device_handler: |
| 342 |
# This is used as kwargs dictionary for lxml's Element() function. |
| 343 |
# Therefore the arg-name ("nsmap") is used as key here. |
| 344 |
xml_namespace_kwargs = { "nsmap" : device_handler.get_xml_base_namespace_dict() } |
| 345 |
else: |
| 346 |
xml_namespace_kwargs = {} |
| 347 |
hello = new_ele("hello", **xml_namespace_kwargs) |
| 348 |
caps = sub_ele(hello, "capabilities") |
| 349 |
def fun(uri): sub_ele(caps, "capability").text = uri |
| 350 |
list(map(fun, capabilities)) |
| 351 |
return to_xml(hello) |
| 352 |
|
| 353 |
@staticmethod |
| 354 |
def parse(raw): |
| 355 |
"Returns tuple of (session-id (str), capabilities (Capabilities)" |
| 356 |
sid, capabilities = 0, [] |
| 357 |
root = to_ele(raw) |
| 358 |
for child in root.getchildren(): |
| 359 |
if child.tag == qualify("session-id") or child.tag == "session-id": |
| 360 |
sid = child.text |
| 361 |
elif child.tag == qualify("capabilities") or child.tag == "capabilities" : |
| 362 |
for cap in child.getchildren(): |
| 363 |
if cap.tag == qualify("capability") or cap.tag == "capability": |
| 364 |
capabilities.append(cap.text) |
| 365 |
return sid, Capabilities(capabilities) |
| 366 |
|
| 367 |
|
| 368 |
class NotificationHandler(SessionListener): |
| 369 |
def __init__(self, notification_q): |
| 370 |
self._notification_q = notification_q |
| 371 |
|
| 372 |
def callback(self, root, raw): |
| 373 |
tag, _ = root |
| 374 |
if tag == qualify('notification', NETCONF_NOTIFICATION_NS): |
| 375 |
self._notification_q.put(Notification(raw)) |
| 376 |
|
| 377 |
def errback(self, _): |
| 378 |
pass |