| 1 |
# |
| 2 |
# (c) 2017 Red Hat Inc. |
| 3 |
# |
| 4 |
# This file is part of Ansible |
| 5 |
# |
| 6 |
# Ansible is free software: you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# Ansible is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
# |
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
from abc import abstractmethod |
| 22 |
from functools import wraps |
| 23 |
|
| 24 |
from ansible.errors import AnsibleError |
| 25 |
from ansible.plugins import AnsiblePlugin |
| 26 |
from ansible.module_utils.common.text.converters import to_native |
| 27 |
from ansible.module_utils.basic import missing_required_lib |
| 28 |
|
| 29 |
try: |
| 30 |
from ncclient.operations import RPCError |
| 31 |
from ncclient.xml_ import to_xml, to_ele, NCElement |
| 32 |
HAS_NCCLIENT = True |
| 33 |
NCCLIENT_IMP_ERR = None |
| 34 |
# paramiko and gssapi are incompatible and raise AttributeError not ImportError |
| 35 |
# When running in FIPS mode, cryptography raises InternalError |
| 36 |
# https://bugzilla.redhat.com/show_bug.cgi?id=1778939 |
| 37 |
except Exception as err: |
| 38 |
HAS_NCCLIENT = False |
| 39 |
NCCLIENT_IMP_ERR = err |
| 40 |
|
| 41 |
try: |
| 42 |
from lxml.etree import Element, SubElement, tostring, fromstring |
| 43 |
except ImportError: |
| 44 |
from xml.etree.ElementTree import Element, SubElement, tostring, fromstring |
| 45 |
|
| 46 |
|
| 47 |
def ensure_ncclient(func): |
| 48 |
@wraps(func) |
| 49 |
def wrapped(self, *args, **kwargs): |
| 50 |
if not HAS_NCCLIENT: |
| 51 |
raise AnsibleError("%s: %s" % (missing_required_lib('ncclient'), to_native(NCCLIENT_IMP_ERR))) |
| 52 |
return func(self, *args, **kwargs) |
| 53 |
return wrapped |
| 54 |
|
| 55 |
|
| 56 |
class NetconfBase(AnsiblePlugin): |
| 57 |
""" |
| 58 |
A base class for implementing Netconf connections |
| 59 |
|
| 60 |
.. note:: Unlike most of Ansible, nearly all strings in |
| 61 |
:class:`TerminalBase` plugins are byte strings. This is because of |
| 62 |
how close to the underlying platform these plugins operate. Remember |
| 63 |
to mark literal strings as byte string (``b"string"``) and to use |
| 64 |
:func:`~ansible.module_utils.common.text.converters.to_bytes` and |
| 65 |
:func:`~ansible.module_utils.common.text.converters.to_text` to avoid unexpected |
| 66 |
problems. |
| 67 |
|
| 68 |
List of supported rpc's: |
| 69 |
:get: Retrieves running configuration and device state information |
| 70 |
:get_config: Retrieves the specified configuration from the device |
| 71 |
:edit_config: Loads the specified commands into the remote device |
| 72 |
:commit: Load configuration from candidate to running |
| 73 |
:discard_changes: Discard changes to candidate datastore |
| 74 |
:validate: Validate the contents of the specified configuration. |
| 75 |
:lock: Allows the client to lock the configuration system of a device. |
| 76 |
:unlock: Release a configuration lock, previously obtained with the lock operation. |
| 77 |
:copy_config: create or replace an entire configuration datastore with the contents of another complete |
| 78 |
configuration datastore. |
| 79 |
:get-schema: Retrieves the required schema from the device |
| 80 |
:get_capabilities: Retrieves device information and supported rpc methods |
| 81 |
|
| 82 |
For JUNOS: |
| 83 |
:execute_rpc: RPC to be execute on remote device |
| 84 |
:load_configuration: Loads given configuration on device |
| 85 |
|
| 86 |
Note: rpc support depends on the capabilities of remote device. |
| 87 |
|
| 88 |
:returns: Returns output received from remote device as byte string |
| 89 |
Note: the 'result' or 'error' from response should to be converted to object |
| 90 |
of ElementTree using 'fromstring' to parse output as xml doc |
| 91 |
|
| 92 |
'get_capabilities()' returns 'result' as a json string. |
| 93 |
|
| 94 |
Usage: |
| 95 |
from ansible.module_utils.connection import Connection |
| 96 |
|
| 97 |
conn = Connection() |
| 98 |
data = conn.execute_rpc(rpc) |
| 99 |
reply = fromstring(reply) |
| 100 |
|
| 101 |
data = conn.get_capabilities() |
| 102 |
json.loads(data) |
| 103 |
|
| 104 |
conn.load_configuration(config=[''set system ntp server 1.1.1.1''], action='set', format='text') |
| 105 |
""" |
| 106 |
|
| 107 |
__rpc__ = ['rpc', 'get_config', 'get', 'edit_config', 'validate', 'copy_config', 'dispatch', 'lock', 'unlock', |
| 108 |
'discard_changes', 'commit', 'get_schema', 'delete_config', 'get_device_operations'] |
| 109 |
|
| 110 |
def __init__(self, connection): |
| 111 |
super(NetconfBase, self).__init__() |
| 112 |
self._connection = connection |
| 113 |
|
| 114 |
@property |
| 115 |
def m(self): |
| 116 |
return self._connection.manager |
| 117 |
|
| 118 |
def rpc(self, name): |
| 119 |
""" |
| 120 |
RPC to be execute on remote device |
| 121 |
:param name: Name of rpc in string format |
| 122 |
:return: Received rpc response from remote host |
| 123 |
""" |
| 124 |
try: |
| 125 |
obj = to_ele(name) |
| 126 |
resp = self.m.rpc(obj) |
| 127 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 128 |
except RPCError as exc: |
| 129 |
msg = exc.xml |
| 130 |
raise Exception(to_xml(msg)) |
| 131 |
|
| 132 |
def get_config(self, source=None, filter=None): |
| 133 |
""" |
| 134 |
Retrieve all or part of a specified configuration |
| 135 |
(by default entire configuration is retrieved). |
| 136 |
:param source: Name of the configuration datastore being queried, defaults to running datastore |
| 137 |
:param filter: This argument specifies the portion of the configuration data to retrieve |
| 138 |
:return: Returns xml string containing the RPC response received from remote host |
| 139 |
""" |
| 140 |
if isinstance(filter, list): |
| 141 |
filter = tuple(filter) |
| 142 |
|
| 143 |
if not source: |
| 144 |
source = 'running' |
| 145 |
resp = self.m.get_config(source=source, filter=filter) |
| 146 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 147 |
|
| 148 |
def get(self, filter=None, with_defaults=None): |
| 149 |
""" |
| 150 |
Retrieve device configuration and state information. |
| 151 |
:param filter: This argument specifies the portion of the state data to retrieve |
| 152 |
(by default entire state data is retrieved) |
| 153 |
:param with_defaults: defines an explicit method of retrieving default values |
| 154 |
from the configuration |
| 155 |
:return: Returns xml string containing the RPC response received from remote host |
| 156 |
""" |
| 157 |
if isinstance(filter, list): |
| 158 |
filter = tuple(filter) |
| 159 |
resp = self.m.get(filter=filter, with_defaults=with_defaults) |
| 160 |
response = resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 161 |
return response |
| 162 |
|
| 163 |
def edit_config(self, config=None, format='xml', target='candidate', default_operation=None, test_option=None, error_option=None): |
| 164 |
""" |
| 165 |
Loads all or part of the specified *config* to the *target* configuration datastore. |
| 166 |
:param config: Is the configuration, which must be rooted in the `config` element. |
| 167 |
It can be specified either as a string or an :class:`~xml.etree.ElementTree.Element`. |
| 168 |
:param format: The format of configuration eg. xml, text |
| 169 |
:param target: Is the name of the configuration datastore being edited |
| 170 |
:param default_operation: If specified must be one of { `"merge"`, `"replace"`, or `"none"` } |
| 171 |
:param test_option: If specified must be one of { `"test_then_set"`, `"set"` } |
| 172 |
:param error_option: If specified must be one of { `"stop-on-error"`, `"continue-on-error"`, `"rollback-on-error"` } |
| 173 |
The `"rollback-on-error"` *error_option* depends on the `:rollback-on-error` capability. |
| 174 |
:return: Returns xml string containing the RPC response received from remote host |
| 175 |
""" |
| 176 |
if config is None: |
| 177 |
raise ValueError('config value must be provided') |
| 178 |
resp = self.m.edit_config(config, format=format, target=target, default_operation=default_operation, test_option=test_option, |
| 179 |
error_option=error_option) |
| 180 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 181 |
|
| 182 |
def validate(self, source='candidate'): |
| 183 |
""" |
| 184 |
Validate the contents of the specified configuration. |
| 185 |
:param source: Is the name of the configuration datastore being validated or `config` element |
| 186 |
containing the configuration subtree to be validated |
| 187 |
:return: Returns xml string containing the RPC response received from remote host |
| 188 |
""" |
| 189 |
resp = self.m.validate(source=source) |
| 190 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 191 |
|
| 192 |
def copy_config(self, source, target): |
| 193 |
""" |
| 194 |
Create or replace an entire configuration datastore with the contents of another complete configuration datastore. |
| 195 |
:param source: Is the name of the configuration datastore to use as the source of the copy operation or `config` |
| 196 |
element containing the configuration subtree to copy |
| 197 |
:param target: Is the name of the configuration datastore to use as the destination of the copy operation |
| 198 |
:return: Returns xml string containing the RPC response received from remote host |
| 199 |
""" |
| 200 |
resp = self.m.copy_config(source, target) |
| 201 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 202 |
|
| 203 |
def dispatch(self, rpc_command=None, source=None, filter=None): |
| 204 |
""" |
| 205 |
Execute rpc on the remote device eg. dispatch('clear-arp-table') |
| 206 |
:param rpc_command: specifies rpc command to be dispatched either in plain text or in xml element format (depending on command) |
| 207 |
:param source: name of the configuration datastore being queried |
| 208 |
:param filter: specifies the portion of the configuration to retrieve (by default entire configuration is retrieved) |
| 209 |
:return: Returns xml string containing the RPC response received from remote host |
| 210 |
""" |
| 211 |
if rpc_command is None: |
| 212 |
raise ValueError('rpc_command value must be provided') |
| 213 |
|
| 214 |
resp = self.m.dispatch(fromstring(rpc_command), source=source, filter=filter) |
| 215 |
|
| 216 |
if isinstance(resp, NCElement): |
| 217 |
# In case xml reply is transformed or namespace is removed in |
| 218 |
# ncclient device specific handler return modified xml response |
| 219 |
result = resp.data_xml |
| 220 |
elif hasattr(resp, 'data_ele') and resp.data_ele: |
| 221 |
# if data node is present in xml response return the xml string |
| 222 |
# with data node as root |
| 223 |
result = resp.data_xml |
| 224 |
else: |
| 225 |
# return raw xml string received from host with rpc-reply as the root node |
| 226 |
result = resp.xml |
| 227 |
|
| 228 |
return result |
| 229 |
|
| 230 |
def lock(self, target="candidate"): |
| 231 |
""" |
| 232 |
Allows the client to lock the configuration system of a device. |
| 233 |
:param target: is the name of the configuration datastore to lock, |
| 234 |
defaults to candidate datastore |
| 235 |
:return: Returns xml string containing the RPC response received from remote host |
| 236 |
""" |
| 237 |
resp = self.m.lock(target=target) |
| 238 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 239 |
|
| 240 |
def unlock(self, target="candidate"): |
| 241 |
""" |
| 242 |
Release a configuration lock, previously obtained with the lock operation. |
| 243 |
:param target: is the name of the configuration datastore to unlock, |
| 244 |
defaults to candidate datastore |
| 245 |
:return: Returns xml string containing the RPC response received from remote host |
| 246 |
""" |
| 247 |
resp = self.m.unlock(target=target) |
| 248 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 249 |
|
| 250 |
def discard_changes(self): |
| 251 |
""" |
| 252 |
Revert the candidate configuration to the currently running configuration. |
| 253 |
Any uncommitted changes are discarded. |
| 254 |
:return: Returns xml string containing the RPC response received from remote host |
| 255 |
""" |
| 256 |
resp = self.m.discard_changes() |
| 257 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 258 |
|
| 259 |
def commit(self, confirmed=False, timeout=None, persist=None): |
| 260 |
""" |
| 261 |
Commit the candidate configuration as the device's new current configuration. |
| 262 |
Depends on the `:candidate` capability. |
| 263 |
A confirmed commit (i.e. if *confirmed* is `True`) is reverted if there is no |
| 264 |
followup commit within the *timeout* interval. If no timeout is specified the |
| 265 |
confirm timeout defaults to 600 seconds (10 minutes). |
| 266 |
A confirming commit may have the *confirmed* parameter but this is not required. |
| 267 |
Depends on the `:confirmed-commit` capability. |
| 268 |
:param confirmed: whether this is a confirmed commit |
| 269 |
:param timeout: specifies the confirm timeout in seconds |
| 270 |
:param persist: make the confirmed commit survive a session termination, |
| 271 |
and set a token on the ongoing confirmed commit |
| 272 |
:return: Returns xml string containing the RPC response received from remote host |
| 273 |
""" |
| 274 |
resp = self.m.commit(confirmed=confirmed, timeout=timeout, persist=persist) |
| 275 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 276 |
|
| 277 |
def get_schema(self, identifier=None, version=None, format=None): |
| 278 |
""" |
| 279 |
Retrieve a named schema, with optional revision and type. |
| 280 |
:param identifier: name of the schema to be retrieved |
| 281 |
:param version: version of schema to get |
| 282 |
:param format: format of the schema to be retrieved, yang is the default |
| 283 |
:return: Returns xml string containing the RPC response received from remote host |
| 284 |
""" |
| 285 |
resp = self.m.get_schema(identifier, version=version, format=format) |
| 286 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 287 |
|
| 288 |
def delete_config(self, target): |
| 289 |
""" |
| 290 |
delete a configuration datastore |
| 291 |
:param target: specifies the name or URL of configuration datastore to delete |
| 292 |
:return: Returns xml string containing the RPC response received from remote host |
| 293 |
""" |
| 294 |
resp = self.m.delete_config(target) |
| 295 |
return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml |
| 296 |
|
| 297 |
def locked(self, target): |
| 298 |
return self.m.locked(target) |
| 299 |
|
| 300 |
@abstractmethod |
| 301 |
def get_capabilities(self): |
| 302 |
""" |
| 303 |
Retrieves device information and supported |
| 304 |
rpc methods by device platform and return result |
| 305 |
as a string |
| 306 |
:return: Netconf session capability |
| 307 |
""" |
| 308 |
pass |
| 309 |
|
| 310 |
@staticmethod |
| 311 |
def guess_network_os(obj): |
| 312 |
""" |
| 313 |
Identifies the operating system of network device. |
| 314 |
:param obj: ncclient manager connection instance |
| 315 |
:return: The name of network operating system. |
| 316 |
""" |
| 317 |
pass |
| 318 |
|
| 319 |
def get_base_rpc(self): |
| 320 |
""" |
| 321 |
Returns list of base rpc method supported by remote device |
| 322 |
:return: List of RPC supported |
| 323 |
""" |
| 324 |
return self.__rpc__ |
| 325 |
|
| 326 |
def put_file(self, source, destination): |
| 327 |
""" |
| 328 |
Copies file to remote host |
| 329 |
:param source: Source location of file |
| 330 |
:param destination: Destination file path |
| 331 |
:return: Returns xml string containing the RPC response received from remote host |
| 332 |
""" |
| 333 |
pass |
| 334 |
|
| 335 |
def fetch_file(self, source, destination): |
| 336 |
""" |
| 337 |
Fetch file from remote host |
| 338 |
:param source: Source location of file |
| 339 |
:param destination: Source location of file |
| 340 |
:return: Returns xml string containing the RPC response received from remote host |
| 341 |
""" |
| 342 |
pass |
| 343 |
|
| 344 |
def get_device_operations(self, server_capabilities): |
| 345 |
""" |
| 346 |
Retrieve remote host capability from Netconf server hello message. |
| 347 |
:param server_capabilities: Server capabilities received during Netconf session initialization |
| 348 |
:return: Remote host capabilities in dictionary format |
| 349 |
""" |
| 350 |
operations = {} |
| 351 |
capabilities = '\n'.join(server_capabilities) |
| 352 |
operations['supports_commit'] = ':candidate' in capabilities |
| 353 |
operations['supports_defaults'] = ':with-defaults' in capabilities |
| 354 |
operations['supports_confirm_commit'] = ':confirmed-commit' in capabilities |
| 355 |
operations['supports_startup'] = ':startup' in capabilities |
| 356 |
operations['supports_xpath'] = ':xpath' in capabilities |
| 357 |
operations['supports_writable_running'] = ':writable-running' in capabilities |
| 358 |
operations['supports_validate'] = ':validate' in capabilities |
| 359 |
|
| 360 |
operations['lock_datastore'] = [] |
| 361 |
if operations['supports_writable_running']: |
| 362 |
operations['lock_datastore'].append('running') |
| 363 |
|
| 364 |
if operations['supports_commit']: |
| 365 |
operations['lock_datastore'].append('candidate') |
| 366 |
|
| 367 |
if operations['supports_startup']: |
| 368 |
operations['lock_datastore'].append('startup') |
| 369 |
|
| 370 |
operations['supports_lock'] = bool(operations['lock_datastore']) |
| 371 |
|
| 372 |
return operations |
| 373 |
|
| 374 |
# TODO Restore .xml, when ncclient supports it for all platforms |