| 1 |
# utils/config.py |
| 2 |
import os |
| 3 |
import re |
| 4 |
import warnings |
| 5 |
|
| 6 |
# 3rd-party modules |
| 7 |
from lxml import etree |
| 8 |
|
| 9 |
# package modules |
| 10 |
from jnpr.junos.exception import * |
| 11 |
from jnpr.junos import jxml as JXML |
| 12 |
from jnpr.junos.utils.util import Util |
| 13 |
|
| 14 |
""" |
| 15 |
Configuration Utilities |
| 16 |
""" |
| 17 |
|
| 18 |
|
| 19 |
class Config(Util): |
| 20 |
""" |
| 21 |
Overview of Configuration Utilities. |
| 22 |
|
| 23 |
* :meth:`commit`: commit changes |
| 24 |
* :meth:`commit_check`: perform the commit check operation |
| 25 |
* :meth:`diff`: return the diff string between running and candidate config |
| 26 |
* :meth:`load`: load changes into the candidate config |
| 27 |
* :meth:`lock`: take an exclusive lock on the candidate config |
| 28 |
* :meth:`pdiff`: prints the diff string (debug/helper) |
| 29 |
* :meth:`rescue`: controls "rescue configuration" |
| 30 |
* :meth:`rollback`: perform the load rollback command |
| 31 |
* :meth:`unlock`: release the exclusive lock |
| 32 |
""" |
| 33 |
|
| 34 |
# ------------------------------------------------------------------------ |
| 35 |
# commit |
| 36 |
# ------------------------------------------------------------------------ |
| 37 |
def commit(self, **kvargs): |
| 38 |
""" |
| 39 |
Commit a configuration. |
| 40 |
|
| 41 |
:param str comment: If provided logs this comment with the commit. |
| 42 |
:param int confirm: If provided activates confirm safeguard with |
| 43 |
provided value as timeout (minutes). |
| 44 |
:param int timeout: If provided the command will wait for completion |
| 45 |
using the provided value as timeout (seconds). |
| 46 |
By default the device timeout is used. |
| 47 |
:param bool sync: On dual control plane systems, requests that |
| 48 |
the candidate configuration on one control plane be |
| 49 |
copied to the other control plane, checked for |
| 50 |
correct syntax, and committed on both Routing |
| 51 |
Engines. |
| 52 |
:param bool force_sync: On dual control plane systems, forces the |
| 53 |
candidate configuration on one control plane to |
| 54 |
be copied to the other control plane. |
| 55 |
:param bool full: When true requires all the daemons to check and |
| 56 |
evaluate the new configuration. |
| 57 |
:param bool detail: When true return commit detail as XML |
| 58 |
|
| 59 |
:param ignore_warning: A boolean, string or list of string. |
| 60 |
If the value is True, it will ignore all warnings regardless of the |
| 61 |
warning message. If the value is a string, it will ignore |
| 62 |
warning(s) if the message of each warning matches the string. If |
| 63 |
the value is a list of strings, ignore warning(s) if the message of |
| 64 |
each warning matches at least one of the strings in the list. |
| 65 |
|
| 66 |
For example:: |
| 67 |
|
| 68 |
cu.commit(ignore_warning=True) |
| 69 |
cu.commit(ignore_warning='Advertisement-interval is ' |
| 70 |
'less than four times') |
| 71 |
cu.commit(ignore_warning=['Advertisement-interval is ' |
| 72 |
'less than four times', |
| 73 |
'Chassis configuration for network ' |
| 74 |
'services has been changed.']) |
| 75 |
|
| 76 |
.. note:: |
| 77 |
When the value of ignore_warning is a string, or list of strings, |
| 78 |
the string is actually used as a case-insensitive regular |
| 79 |
expression pattern. If the string contains only alpha-numeric |
| 80 |
characters, as shown in the above examples, this results in a |
| 81 |
case-insensitive substring match. However, any regular expression |
| 82 |
pattern supported by the re library may be used for more |
| 83 |
complicated match conditions. |
| 84 |
|
| 85 |
:returns: |
| 86 |
* ``True`` when successful |
| 87 |
* Commit detail XML (when detail is True) |
| 88 |
|
| 89 |
:raises CommitError: When errors detected in candidate configuration. |
| 90 |
You can use the Exception errs variable |
| 91 |
to identify the specific problems |
| 92 |
|
| 93 |
.. warning:: |
| 94 |
If the function does not receive a reply prior to the timeout |
| 95 |
a RpcTimeoutError will be raised. It is possible the commit |
| 96 |
was successful. Manual verification may be required. |
| 97 |
""" |
| 98 |
rpc_args = {} |
| 99 |
|
| 100 |
# if a comment is provided, then include that in the RPC |
| 101 |
|
| 102 |
comment = kvargs.get("comment") |
| 103 |
if comment: |
| 104 |
rpc_args["log"] = comment |
| 105 |
|
| 106 |
# if confirm is provided, then setup the RPC args |
| 107 |
# so that Junos will either use the default confirm |
| 108 |
# timeout (confirm=True) or a specific timeout |
| 109 |
# (confirm=<minutes>) |
| 110 |
|
| 111 |
confirm = kvargs.get("confirm") |
| 112 |
if confirm: |
| 113 |
rpc_args["confirmed"] = True |
| 114 |
confirm_val = str(confirm) |
| 115 |
if "True" != confirm_val: |
| 116 |
rpc_args["confirm-timeout"] = confirm_val |
| 117 |
|
| 118 |
# if a timeout is provided, then include that in the RPC |
| 119 |
|
| 120 |
timeout = kvargs.get("timeout") |
| 121 |
if timeout: |
| 122 |
rpc_args["dev_timeout"] = timeout |
| 123 |
|
| 124 |
# Check for force_sync and sync |
| 125 |
if kvargs.get("force_sync"): |
| 126 |
rpc_args["synchronize"] = True |
| 127 |
rpc_args["force-synchronize"] = True |
| 128 |
elif kvargs.get("sync"): |
| 129 |
rpc_args["synchronize"] = True |
| 130 |
|
| 131 |
# Check for full |
| 132 |
if kvargs.get("full"): |
| 133 |
rpc_args["full"] = True |
| 134 |
|
| 135 |
# Check for ignore_warning |
| 136 |
ignore_warn = kvargs.get("ignore_warning") |
| 137 |
if ignore_warn: |
| 138 |
rpc_args["ignore_warning"] = ignore_warn |
| 139 |
|
| 140 |
rpc_varg = [] |
| 141 |
detail = kvargs.get("detail") |
| 142 |
if detail: |
| 143 |
rpc_varg = [{"detail": "detail"}] |
| 144 |
|
| 145 |
# dbl-splat the rpc_args since we want to pass key/value to metaexec |
| 146 |
# if there is a commit/check error, this will raise an execption |
| 147 |
|
| 148 |
try: |
| 149 |
rsp = self.rpc.commit_configuration(*rpc_varg, **rpc_args) |
| 150 |
except RpcTimeoutError: |
| 151 |
raise |
| 152 |
except RpcError as err: # jnpr.junos exception |
| 153 |
if err.rsp is not None and err.rsp.find("ok") is not None: |
| 154 |
# this means there are warnings, but no errors |
| 155 |
return True |
| 156 |
else: |
| 157 |
raise CommitError(cmd=err.cmd, rsp=err.rsp, errs=err.errs) |
| 158 |
except Exception as err: |
| 159 |
# so the ncclient gives us something I don't want. I'm going to |
| 160 |
# convert it and re-raise the commit error |
| 161 |
if hasattr(err, "xml") and isinstance(err.xml, etree._Element): |
| 162 |
raise CommitError(rsp=err.xml) |
| 163 |
else: |
| 164 |
raise |
| 165 |
|
| 166 |
if detail: |
| 167 |
return rsp |
| 168 |
else: |
| 169 |
return True |
| 170 |
|
| 171 |
# ------------------------------------------------------------------------- |
| 172 |
# commit check |
| 173 |
# ------------------------------------------------------------------------- |
| 174 |
|
| 175 |
def commit_check(self, **kvargs): |
| 176 |
""" |
| 177 |
Perform a commit check. If the commit check passes, this function |
| 178 |
will return ``True``. If the commit-check results in warnings, they |
| 179 |
are reported and available in the Exception errs. |
| 180 |
|
| 181 |
:param int timeout: If provided the command will wait for completion |
| 182 |
using the provided value as timeout (seconds). |
| 183 |
|
| 184 |
:returns: ``True`` if commit-check is successful (no errors) |
| 185 |
:raises CommitError: When errors detected in candidate configuration. |
| 186 |
You can use the Exception errs variable |
| 187 |
to identify the specific problems |
| 188 |
:raises RpcError: When underlying ncclient has an error |
| 189 |
""" |
| 190 |
rpc_args = {} |
| 191 |
|
| 192 |
# if a timeout is provided, then include that in the RPC |
| 193 |
|
| 194 |
timeout = kvargs.get("timeout") |
| 195 |
if timeout: |
| 196 |
rpc_args["dev_timeout"] = timeout |
| 197 |
|
| 198 |
try: |
| 199 |
self.rpc.commit_configuration(check=True, **rpc_args) |
| 200 |
except RpcTimeoutError: |
| 201 |
raise |
| 202 |
except RpcError as err: # jnpr.junos exception |
| 203 |
if err.rsp is not None and err.rsp.find("ok") is not None: |
| 204 |
# this means there is a warning, but no errors |
| 205 |
return True |
| 206 |
else: |
| 207 |
raise CommitError(cmd=err.cmd, rsp=err.rsp, errs=err.errs) |
| 208 |
except Exception as err: |
| 209 |
# :err: is from ncclient, so extract the XML data |
| 210 |
# and convert into dictionary |
| 211 |
if hasattr(err, "xml") and isinstance(err.xml, etree._Element): |
| 212 |
return JXML.rpc_error(err.xml) |
| 213 |
else: |
| 214 |
raise |
| 215 |
|
| 216 |
return True |
| 217 |
|
| 218 |
# ------------------------------------------------------------------------- |
| 219 |
# show | compare rollback <number|0*> |
| 220 |
# ------------------------------------------------------------------------- |
| 221 |
|
| 222 |
def diff(self, rb_id=0, ignore_warning=False, use_fast_diff=False): |
| 223 |
""" |
| 224 |
Retrieve a diff (patch-format) report of the candidate config against |
| 225 |
either the current active config, or a different rollback. |
| 226 |
|
| 227 |
:param int rb_id: rollback id [0..49] |
| 228 |
:param bool ignore_warning: Ignore any rpc-error with severity warning |
| 229 |
:param bool use_fast_diff: equivalent to "show | compare use-fast-diff" |
| 230 |
|
| 231 |
:returns: |
| 232 |
* ``None`` if there is no difference |
| 233 |
* ascii-text (str) if there is a difference |
| 234 |
""" |
| 235 |
|
| 236 |
if rb_id < 0 or rb_id > 49: |
| 237 |
raise ValueError("Invalid rollback #" + str(rb_id)) |
| 238 |
|
| 239 |
rpc_params = dict(compare="rollback", rollback=str(rb_id), format="text") |
| 240 |
if use_fast_diff: |
| 241 |
if rb_id > 0: |
| 242 |
raise ValueError("use_fast_diff can only be used with rb_id 0") |
| 243 |
rpc_params["use-fast-diff"] = "yes" |
| 244 |
try: |
| 245 |
rsp = self.rpc.get_configuration( |
| 246 |
rpc_params, |
| 247 |
ignore_warning=ignore_warning, |
| 248 |
) |
| 249 |
except RpcTimeoutError: |
| 250 |
raise |
| 251 |
except RpcError as err: |
| 252 |
if ( |
| 253 |
err.rpc_error["severity"] == "warning" |
| 254 |
and err.message == "mgd: statement must contain additional " |
| 255 |
"statements" |
| 256 |
): |
| 257 |
# Fix for Issue #655, JDM 15.1X53-D45 responses with |
| 258 |
# extraneous warning message |
| 259 |
return "Unable to parse diff from response!" |
| 260 |
else: |
| 261 |
raise |
| 262 |
|
| 263 |
# The output is expected to be an etree, it may have empty <configuration-output> tags |
| 264 |
# Adding a preventive check and displaying warning in case the value is bool. |
| 265 |
# This check is added for PR 1564189 (juniper internal) which has issue for certain junos releases. |
| 266 |
if isinstance(rsp, bool): |
| 267 |
warnings.warn( |
| 268 |
"diff shouldn't return boolean as a rpc-reply", |
| 269 |
RuntimeWarning, |
| 270 |
) |
| 271 |
return None |
| 272 |
|
| 273 |
diff_txt = rsp.find("configuration-output").text |
| 274 |
return None if diff_txt == "\n" else diff_txt |
| 275 |
|
| 276 |
def pdiff(self, rb_id=0, ignore_warning=False, use_fast_diff=False): |
| 277 |
""" |
| 278 |
Helper method that calls ``print`` on the diff (patch-format) between |
| 279 |
the current candidate and the provided rollback. |
| 280 |
|
| 281 |
:param int rb_id: the rollback id value [0-49] |
| 282 |
:param bool ignore_warning: Ignore any rpc-error with severity warning |
| 283 |
:param bool use_fast_diff: equivalent to "show | compare use-fast-diff" |
| 284 |
|
| 285 |
:returns: ``None`` |
| 286 |
""" |
| 287 |
print(self.diff(rb_id, ignore_warning, use_fast_diff)) |
| 288 |
|
| 289 |
# ------------------------------------------------------------------------- |
| 290 |
# helper on loading configs |
| 291 |
# ------------------------------------------------------------------------- |
| 292 |
|
| 293 |
def load(self, *vargs, **kvargs): |
| 294 |
""" |
| 295 |
Loads changes into the candidate configuration. Changes can be |
| 296 |
in the form of strings (text,set,xml, json), XML objects, and files. |
| 297 |
Files can be either static snippets of configuration or Jinja2 |
| 298 |
templates. When using Jinja2 Templates, this method will render |
| 299 |
variables into the templates and then load the resulting change; |
| 300 |
i.e. "template building". |
| 301 |
|
| 302 |
:param object vargs[0]: |
| 303 |
The content to load. If the contents is a string, the framework |
| 304 |
will attempt to automatically determine the format. If it is |
| 305 |
unable to determine the format then you must specify the |
| 306 |
**format** parameter. If the content is an XML object, then |
| 307 |
this method assumes you've structured it correctly; |
| 308 |
and if not an Exception will be raised. |
| 309 |
|
| 310 |
:param str path: |
| 311 |
Path to file of configuration on the local server. |
| 312 |
The path extension will be used to determine the format of |
| 313 |
the contents: |
| 314 |
|
| 315 |
* "conf","text","txt" is curly-text-style |
| 316 |
* "set" - ascii-text, set-style |
| 317 |
* "xml" - ascii-text, XML |
| 318 |
* "json" - ascii-text, json |
| 319 |
|
| 320 |
.. note:: The format can specifically set using **format**. |
| 321 |
|
| 322 |
:param str format: |
| 323 |
Determines the format of the contents. |
| 324 |
Supported options - text, set, xml, json |
| 325 |
|
| 326 |
If not provided, internally application will try to find out the format |
| 327 |
|
| 328 |
:param bool overwrite: |
| 329 |
Determines if the contents completely replace the existing |
| 330 |
configuration. Default is ``False``. |
| 331 |
|
| 332 |
.. note:: This option cannot be used if **format** is "set". |
| 333 |
|
| 334 |
:param bool merge: |
| 335 |
If set to ``True`` will set the load-config action to merge. |
| 336 |
the default load-config action is 'replace' |
| 337 |
|
| 338 |
:param bool update: |
| 339 |
If set to ``True`` Compare a complete loaded configuration against |
| 340 |
the candidate configuration. For each hierarchy level or |
| 341 |
configuration object that is different in the two configurations, |
| 342 |
the version in the loaded configuration replaces the version in the |
| 343 |
candidate configuration. When the configuration is later committed, |
| 344 |
only system processes that are affected by the changed configuration |
| 345 |
elements parse the new configuration. |
| 346 |
|
| 347 |
.. note:: This option cannot be used if **format** is "set". |
| 348 |
|
| 349 |
:param bool patch: |
| 350 |
If set to ``True`` will set the load-config action to load patch. |
| 351 |
|
| 352 |
:param str template_path: |
| 353 |
Similar to the **path** parameter, but this indicates that |
| 354 |
the file contents are ``Jinja2`` format and will require |
| 355 |
template-rendering. |
| 356 |
|
| 357 |
.. note:: This parameter is used in conjunction with |
| 358 |
**template_vars**. The template filename extension will |
| 359 |
be used to determine the format-style of the contents, |
| 360 |
or you can override using **format**. |
| 361 |
|
| 362 |
:param jinja2.Template template: |
| 363 |
A Jinja2 Template object. Same description as *template_path*, |
| 364 |
except this option you provide the actual Template, rather than |
| 365 |
a path to the template file. |
| 366 |
|
| 367 |
:param dict template_vars: |
| 368 |
Used in conjunction with the other template options. This parameter |
| 369 |
contains a dictionary of variables to render into the template. |
| 370 |
|
| 371 |
:param ignore_warning: A boolean, string or list of string. |
| 372 |
If the value is True, it will ignore all warnings regardless of the |
| 373 |
warning message. If the value is a string, it will ignore |
| 374 |
warning(s) if the message of each warning matches the string. If |
| 375 |
the value is a list of strings, ignore warning(s) if the message of |
| 376 |
each warning matches at least one of the strings in the list. |
| 377 |
|
| 378 |
For example:: |
| 379 |
|
| 380 |
cu.load(cnf, ignore_warning=True) |
| 381 |
cu.load(cnf, ignore_warning='statement not found') |
| 382 |
cu.load(cnf, ignore_warning=['statement not found', |
| 383 |
'statement has no contents; ignored') |
| 384 |
|
| 385 |
.. note:: |
| 386 |
When the value of ignore_warning is a string, or list of strings, |
| 387 |
the string is actually used as a case-insensitive regular |
| 388 |
expression pattern. If the string contains only alpha-numeric |
| 389 |
characters, as shown in the above examples, this results in a |
| 390 |
case-insensitive substring match. However, any regular expression |
| 391 |
pattern supported by the re library may be used for more |
| 392 |
complicated match conditions. |
| 393 |
|
| 394 |
:param str url: |
| 395 |
Specify the full pathname of the file that contains the configuration |
| 396 |
data to load. The value can be a local file path, an FTP location, or |
| 397 |
a Hypertext Transfer Protocol (HTTP). |
| 398 |
Refer `Doc page <https://www.juniper.net/documentation/en_US/junos/topics/reference/tag-summary/junos-xml-protocol-load-configuration.html>`_ |
| 399 |
for more details. |
| 400 |
|
| 401 |
For example:: |
| 402 |
|
| 403 |
cu.load(url="/var/home/user/golden.conf") |
| 404 |
cu.load(url="ftp://[email protected]/filename") |
| 405 |
cu.load(url="http://username:password@hostname/path/filename") |
| 406 |
cu.load(url="/var/home/user/golden.conf", overwrite=True) |
| 407 |
|
| 408 |
:returns: |
| 409 |
RPC-reply as XML object. |
| 410 |
|
| 411 |
:raises: ConfigLoadError: When errors detected while loading candidate |
| 412 |
configuration. You can use the Exception |
| 413 |
errs variable to identify the specific |
| 414 |
problems. |
| 415 |
""" |
| 416 |
rpc_xattrs = {} |
| 417 |
rpc_xattrs["format"] = "xml" # default to XML format |
| 418 |
rpc_xattrs["action"] = "replace" # replace is default action |
| 419 |
|
| 420 |
rpc_contents = None |
| 421 |
|
| 422 |
actions = filter( |
| 423 |
lambda item: kvargs.get(item, False), |
| 424 |
("overwrite", "merge", "update", "patch"), |
| 425 |
) |
| 426 |
if len(list(actions)) >= 2: |
| 427 |
raise ValueError("actions can be only one among %s" % ", ".join(actions)) |
| 428 |
|
| 429 |
# support the ability to completely replace the Junos configuration |
| 430 |
# note: this cannot be used if format='set', per Junos API. |
| 431 |
|
| 432 |
overwrite = kvargs.get("overwrite", False) |
| 433 |
if overwrite is True: |
| 434 |
rpc_xattrs["action"] = "override" |
| 435 |
if kvargs.get("update") is True: |
| 436 |
rpc_xattrs["action"] = "update" |
| 437 |
elif kvargs.get("merge") is True: |
| 438 |
del rpc_xattrs["action"] |
| 439 |
elif kvargs.get("patch") is True: |
| 440 |
rpc_xattrs["action"] = "patch" |
| 441 |
|
| 442 |
ignore_warning = kvargs.get("ignore_warning", False) |
| 443 |
|
| 444 |
# --------------------------------------------------------------------- |
| 445 |
# private helpers ... |
| 446 |
# --------------------------------------------------------------------- |
| 447 |
|
| 448 |
def _lformat_byext(path): |
| 449 |
"""determine the format style from the file extension""" |
| 450 |
ext = os.path.splitext(path)[1] |
| 451 |
if ext == ".xml": |
| 452 |
return "xml" |
| 453 |
if ext in [".conf", ".text", ".txt"]: |
| 454 |
return "text" |
| 455 |
if ext in [".set"]: |
| 456 |
return "set" |
| 457 |
if ext in [".json"]: |
| 458 |
return "json" |
| 459 |
raise ValueError("Unknown file contents from extension: %s" % ext) |
| 460 |
|
| 461 |
def _lset_format(kvargs, rpc_xattrs): |
| 462 |
"""setup the kvargs/rpc_xattrs""" |
| 463 |
# when format is given, setup the xml attrs appropriately |
| 464 |
if kvargs["format"] == "set": |
| 465 |
if overwrite is True or kvargs.get("update") is True: |
| 466 |
raise ValueError( |
| 467 |
"conflicting args, cannot use 'set' with '%s'" |
| 468 |
% ("overwrite" if overwrite is True else "update") |
| 469 |
) |
| 470 |
rpc_xattrs["action"] = "set" |
| 471 |
kvargs["format"] = "text" |
| 472 |
rpc_xattrs["format"] = kvargs["format"] |
| 473 |
|
| 474 |
def _lset_fromfile(path): |
| 475 |
"""setup the kvargs/rpc_xattrs based on path""" |
| 476 |
if "format" not in kvargs: |
| 477 |
# we use the extension to determine the format |
| 478 |
kvargs["format"] = _lformat_byext(path) |
| 479 |
_lset_format(kvargs, rpc_xattrs) |
| 480 |
|
| 481 |
def _lset_from_rexp(rpc): |
| 482 |
"""setup the kvargs/rpc_xattrs using string regular expression""" |
| 483 |
if re.search(r"^\s*<.*>$", rpc, re.MULTILINE): |
| 484 |
kvargs["format"] = "xml" |
| 485 |
elif re.search( |
| 486 |
r"^\s*(set|delete|rename|insert|activate|deactivate" |
| 487 |
r"|annotate|copy|protect|unprotect)\s", |
| 488 |
rpc, |
| 489 |
): |
| 490 |
kvargs["format"] = "set" |
| 491 |
elif re.search(r"^[a-z:]*\s*[\w-]+\s+\{", rpc, re.I) and re.search( |
| 492 |
r".*}\s*$", rpc |
| 493 |
): |
| 494 |
kvargs["format"] = "text" |
| 495 |
elif re.search(r"^\s*\{", rpc) and re.search(r".*}\s*$", rpc): |
| 496 |
kvargs["format"] = "json" |
| 497 |
|
| 498 |
def try_load(rpc_contents, rpc_xattrs, ignore_warning=ignore_warning): |
| 499 |
try: |
| 500 |
got = self.rpc.load_config( |
| 501 |
rpc_contents, ignore_warning=ignore_warning, **rpc_xattrs |
| 502 |
) |
| 503 |
except RpcTimeoutError as err: |
| 504 |
raise err |
| 505 |
except RpcError as err: |
| 506 |
raise ConfigLoadError(cmd=err.cmd, rsp=err.rsp, errs=err.errs) |
| 507 |
# Something unexpected happened - raise it up |
| 508 |
except Exception as err: |
| 509 |
raise |
| 510 |
|
| 511 |
return got |
| 512 |
|
| 513 |
# --------------------------------------------------------------------- |
| 514 |
# end-of: private helpers |
| 515 |
# --------------------------------------------------------------------- |
| 516 |
|
| 517 |
if "format" in kvargs: |
| 518 |
_lset_format(kvargs, rpc_xattrs) |
| 519 |
|
| 520 |
# --------------------------------------------------------------------- |
| 521 |
# if contents are provided as vargs[0], then process that as XML or str |
| 522 |
# --------------------------------------------------------------------- |
| 523 |
|
| 524 |
if len(vargs): |
| 525 |
# caller is providing the content directly. |
| 526 |
rpc_contents = vargs[0] |
| 527 |
if isinstance(rpc_contents, str): |
| 528 |
if "format" not in kvargs: |
| 529 |
_lset_from_rexp(rpc_contents) |
| 530 |
if "format" in kvargs: |
| 531 |
_lset_format(kvargs, rpc_xattrs) |
| 532 |
else: |
| 533 |
raise RuntimeError( |
| 534 |
"Not able to resolve the config format " |
| 535 |
"You must define the format of the contents " |
| 536 |
"explicitly to the function. Ex: format='set'" |
| 537 |
) |
| 538 |
if kvargs["format"] == "xml": |
| 539 |
# covert the XML string into XML structure |
| 540 |
rpc_contents = etree.XML(rpc_contents) |
| 541 |
|
| 542 |
# --------------------------------------------------------------------- |
| 543 |
# if path is provided, use the static-config file |
| 544 |
# --------------------------------------------------------------------- |
| 545 |
|
| 546 |
elif "path" in kvargs: |
| 547 |
# then this is a static-config file. load that as our rpc_contents |
| 548 |
try: |
| 549 |
# Explicitly request Python 3.x universal newline |
| 550 |
rpc_contents = open(kvargs["path"], "r", newline=None).read() |
| 551 |
except TypeError: |
| 552 |
# Fallback to Python 2.x universal newline |
| 553 |
rpc_contents = open(kvargs["path"], "rU").read() |
| 554 |
_lset_fromfile(kvargs["path"]) |
| 555 |
if rpc_xattrs["format"] == "xml": |
| 556 |
# covert the XML string into XML structure |
| 557 |
rpc_contents = etree.XML(rpc_contents) |
| 558 |
|
| 559 |
# --------------------------------------------------------------------- |
| 560 |
# if template_path is provided, then jinja2 load the template, and |
| 561 |
# render the results. if template_vars are provided, use those |
| 562 |
# in the render process. |
| 563 |
# --------------------------------------------------------------------- |
| 564 |
|
| 565 |
elif "template_path" in kvargs: |
| 566 |
path = kvargs["template_path"] |
| 567 |
template = self.dev.Template(path) |
| 568 |
rpc_contents = template.render(kvargs.get("template_vars", {})) |
| 569 |
_lset_fromfile(path) |
| 570 |
if rpc_xattrs["format"] == "xml": |
| 571 |
# covert the XML string into XML structure |
| 572 |
rpc_contents = etree.XML(rpc_contents) |
| 573 |
|
| 574 |
# --------------------------------------------------------------------- |
| 575 |
# if template is provided, then this is a pre-loaded jinja2 Template |
| 576 |
# object. Use the template.filename to determine the format style |
| 577 |
# --------------------------------------------------------------------- |
| 578 |
|
| 579 |
elif "template" in kvargs: |
| 580 |
template = kvargs["template"] |
| 581 |
path = template.filename |
| 582 |
rpc_contents = template.render(kvargs.get("template_vars", {})) |
| 583 |
_lset_fromfile(path) |
| 584 |
if rpc_xattrs["format"] == "xml": |
| 585 |
# covert the XML string into XML structure |
| 586 |
rpc_contents = etree.XML(rpc_contents) |
| 587 |
|
| 588 |
if rpc_contents is not None: |
| 589 |
return try_load(rpc_contents, rpc_xattrs, ignore_warning=ignore_warning) |
| 590 |
elif "url" in kvargs and rpc_contents is None: |
| 591 |
url = kvargs["url"] |
| 592 |
_lset_fromfile(url) |
| 593 |
rpc_xattrs["url"] = url |
| 594 |
return try_load(rpc_contents, rpc_xattrs, ignore_warning=ignore_warning) |
| 595 |
else: |
| 596 |
raise RuntimeError("Unhandled load request") |
| 597 |
|
| 598 |
# ------------------------------------------------------------------------- |
| 599 |
# config exclusive |
| 600 |
# ------------------------------------------------------------------------- |
| 601 |
|
| 602 |
def lock(self): |
| 603 |
""" |
| 604 |
Attempts an exclusive lock on the candidate configuration. This |
| 605 |
is a non-blocking call. |
| 606 |
|
| 607 |
:returns: |
| 608 |
``True`` always when successful |
| 609 |
|
| 610 |
:raises LockError: When the lock cannot be obtained |
| 611 |
""" |
| 612 |
try: |
| 613 |
self.rpc.lock_configuration() |
| 614 |
except Exception as err: |
| 615 |
if isinstance(err, RpcError): |
| 616 |
raise LockError(rsp=err.rsp) |
| 617 |
elif isinstance(err, ConnectClosedError): |
| 618 |
raise err |
| 619 |
else: |
| 620 |
# :err: is from ncclient |
| 621 |
raise LockError(rsp=JXML.remove_namespaces(err.xml)) |
| 622 |
|
| 623 |
return True |
| 624 |
|
| 625 |
# ------------------------------------------------------------------------- |
| 626 |
# releases the exclusive lock |
| 627 |
# ------------------------------------------------------------------------- |
| 628 |
|
| 629 |
def unlock(self): |
| 630 |
""" |
| 631 |
Unlocks the candidate configuration. |
| 632 |
|
| 633 |
:returns: |
| 634 |
``True`` always when successful |
| 635 |
|
| 636 |
:raises UnlockError: If you attempt to unlock a configuration |
| 637 |
when you do not own the lock |
| 638 |
""" |
| 639 |
try: |
| 640 |
self.rpc.unlock_configuration() |
| 641 |
except Exception as err: |
| 642 |
if isinstance(err, RpcError): |
| 643 |
raise UnlockError(rsp=err.rsp) |
| 644 |
elif isinstance(err, ConnectClosedError): |
| 645 |
raise err |
| 646 |
else: |
| 647 |
# :err: is from ncclient |
| 648 |
raise UnlockError(rsp=JXML.remove_namespaces(err.xml)) |
| 649 |
|
| 650 |
return True |
| 651 |
|
| 652 |
# ------------------------------------------------------------------------- |
| 653 |
# rollback <number|0*> |
| 654 |
# ------------------------------------------------------------------------- |
| 655 |
|
| 656 |
def rollback(self, rb_id=0, ignore_warning=False): |
| 657 |
""" |
| 658 |
Rollback the candidate config to either the last active or |
| 659 |
a specific rollback number. |
| 660 |
|
| 661 |
:param int rb_id: The rollback id value [0-49], defaults to ``0``. |
| 662 |
|
| 663 |
:param ignore_warning: A boolean, string or list of string. |
| 664 |
If the value is True, it will ignore all warnings regardless of the |
| 665 |
warning message. If the value is a string, it will ignore |
| 666 |
warning(s) if the message of each warning matches the string. If |
| 667 |
the value is a list of strings, ignore warning(s) if the message of |
| 668 |
each warning matches at least one of the strings in the list. |
| 669 |
|
| 670 |
:returns: |
| 671 |
``True`` always when successful |
| 672 |
|
| 673 |
:raises ValueError: When invalid rollback id is given |
| 674 |
""" |
| 675 |
|
| 676 |
if rb_id < 0 or rb_id > 49: |
| 677 |
raise ValueError("Invalid rollback #" + str(rb_id)) |
| 678 |
|
| 679 |
self.rpc.load_configuration( |
| 680 |
dict(compare="rollback", rollback=str(rb_id)), ignore_warning=ignore_warning |
| 681 |
) |
| 682 |
|
| 683 |
return True |
| 684 |
|
| 685 |
# ------------------------------------------------------------------------- |
| 686 |
# rescue configuration |
| 687 |
# ------------------------------------------------------------------------- |
| 688 |
|
| 689 |
def rescue(self, action, format="text"): |
| 690 |
""" |
| 691 |
Perform action on the "rescue configuration". |
| 692 |
|
| 693 |
:param str action: identifies the action as follows: |
| 694 |
|
| 695 |
* "get" - retrieves/returns the rescue configuration via **format** |
| 696 |
* "save" - saves current configuration as rescue |
| 697 |
* "delete" - removes the rescue configuration |
| 698 |
* "reload" - loads the rescue config as candidate (no-commit) |
| 699 |
|
| 700 |
:param str format: identifies the return format when **action** is |
| 701 |
"get": |
| 702 |
|
| 703 |
* "text" (default) - ascii-text format |
| 704 |
* "xml" - as XML object |
| 705 |
|
| 706 |
:return: |
| 707 |
|
| 708 |
* When **action** is 'get', then the contents of the rescue |
| 709 |
configuration is returned in the specified *format*. If there |
| 710 |
is no rescue configuration saved, then the return value is |
| 711 |
``None``. |
| 712 |
|
| 713 |
* ``True`` when **action** is "save". |
| 714 |
|
| 715 |
* ``True`` when **action** is "delete". |
| 716 |
|
| 717 |
.. note:: ``True`` regardless if a rescue configuration exists. |
| 718 |
|
| 719 |
* When **action** is 'reload', return is ``True`` if a rescue |
| 720 |
configuration exists, and ``False`` otherwise. |
| 721 |
|
| 722 |
.. note:: The rescue configuration is only loaded as the candidate, |
| 723 |
and not committed. You must commit to make the rescue |
| 724 |
configuration active. |
| 725 |
|
| 726 |
:raises ValueError: |
| 727 |
If **action** is not one of the above |
| 728 |
""" |
| 729 |
|
| 730 |
def _rescue_save(): |
| 731 |
""" |
| 732 |
Saves the current configuration as the rescue configuration |
| 733 |
""" |
| 734 |
self.rpc.request_save_rescue_configuration() |
| 735 |
return True |
| 736 |
|
| 737 |
def _rescue_delete(): |
| 738 |
""" |
| 739 |
Deletes the existing resuce configuration. |
| 740 |
""" |
| 741 |
# note that this will result in an "OK" regardless if |
| 742 |
# a rescue config exists or not. |
| 743 |
self.rpc.request_delete_rescue_configuration() |
| 744 |
return True |
| 745 |
|
| 746 |
def _rescue_get(): |
| 747 |
""" |
| 748 |
Retrieves the rescue configuration, returning it in |
| 749 |
either :format: 'text' or 'xml'. |
| 750 |
|
| 751 |
Returns either the 'text'/'xml' if the rescue config |
| 752 |
exists, or :None: otherwise |
| 753 |
""" |
| 754 |
try: |
| 755 |
got = self.rpc.get_rescue_information(format=format) |
| 756 |
return ( |
| 757 |
got.findtext("configuration-information/configuration-output") |
| 758 |
if "text" == format |
| 759 |
else got |
| 760 |
) |
| 761 |
except: |
| 762 |
return None |
| 763 |
|
| 764 |
def _rescue_reload(): |
| 765 |
""" |
| 766 |
Loads the rescue configuration as the active candidate. |
| 767 |
This action does *not* commit the configuration; use the |
| 768 |
:commit(): method for that purpose. |
| 769 |
|
| 770 |
Returns the XML response if the rescue configuration |
| 771 |
exists, or :False: otherwise |
| 772 |
""" |
| 773 |
try: |
| 774 |
return self.rpc.load_configuration({"rescue": "rescue"}) |
| 775 |
except: |
| 776 |
return False |
| 777 |
|
| 778 |
def _unsupported_action(): |
| 779 |
raise ValueError("unsupported action: {}".format(action)) |
| 780 |
|
| 781 |
result = { |
| 782 |
"get": _rescue_get, |
| 783 |
"save": _rescue_save, |
| 784 |
"delete": _rescue_delete, |
| 785 |
"reload": _rescue_reload, |
| 786 |
}.get(action, _unsupported_action)() |
| 787 |
|
| 788 |
return result |
| 789 |
|
| 790 |
def __init__(self, dev, mode=None, **kwargs): |
| 791 |
""" |
| 792 |
:param str mode: Can be used *only* when creating Config object using |
| 793 |
context manager |
| 794 |
|
| 795 |
* "private" - Work in private database |
| 796 |
* "dynamic" - Work in dynamic database |
| 797 |
* "batch" - Work in batch database |
| 798 |
* "exclusive" - Work with Locking the candidate configuration |
| 799 |
* "ephemeral" - Work in default/specified ephemeral instance |
| 800 |
|
| 801 |
:param str ephemeral_instance: ephemeral instance name |
| 802 |
|
| 803 |
.. code-block:: python |
| 804 |
|
| 805 |
# mode can be private/dynamic/exclusive/batch/ephemeral |
| 806 |
with Config(dev, mode='exclusive') as cu: |
| 807 |
cu.load('set system services netconf traceoptions file xyz', |
| 808 |
format='set') |
| 809 |
print cu.diff() |
| 810 |
cu.commit() |
| 811 |
|
| 812 |
.. warning:: |
| 813 |
Ephemeral databases are an advanced Junos feature which |
| 814 |
if used incorrectly can have serious negative impact on the operation |
| 815 |
of the Junos device. We recommend you consult JTAC and/or you Juniper |
| 816 |
account team before deploying the ephemeral database feature in your |
| 817 |
network. |
| 818 |
""" |
| 819 |
self.mode = mode |
| 820 |
if not kwargs.get("ephemeral_instance") and kwargs: |
| 821 |
raise ValueError("Unsupported argument provided to Config class") |
| 822 |
self.kwargs = kwargs |
| 823 |
|
| 824 |
Util.__init__(self, dev=dev) |
| 825 |
|
| 826 |
def __enter__(self): |
| 827 |
# defining separate functions for each mode so that can be |
| 828 |
# changed/edited as per the need of corresponding rpc call. |
| 829 |
def _open_configuration_private(): |
| 830 |
try: |
| 831 |
self.rpc.open_configuration(private=True) |
| 832 |
except (RpcTimeoutError, ConnectClosedError) as err: |
| 833 |
raise err |
| 834 |
except RpcError as err: |
| 835 |
if err.rpc_error["severity"] == "warning": |
| 836 |
if ( |
| 837 |
err.message != "uncommitted changes will be discarded " |
| 838 |
"on exit" |
| 839 |
): |
| 840 |
warnings.warn(err.message, RuntimeWarning) |
| 841 |
return True |
| 842 |
else: |
| 843 |
raise err |
| 844 |
|
| 845 |
def _open_configuration_dynamic(): |
| 846 |
try: |
| 847 |
self.rpc.open_configuration(dynamic=True) |
| 848 |
except RpcError as err: |
| 849 |
raise err |
| 850 |
return True |
| 851 |
|
| 852 |
def _open_configuration_batch(): |
| 853 |
try: |
| 854 |
self.rpc.open_configuration(batch=True) |
| 855 |
except (RpcTimeoutError, ConnectClosedError) as err: |
| 856 |
raise err |
| 857 |
except RpcError as err: |
| 858 |
if err.rpc_error["severity"] == "warning": |
| 859 |
if ( |
| 860 |
err.message != "uncommitted changes will be discarded " |
| 861 |
"on exit" |
| 862 |
): |
| 863 |
warnings.warn(err.message, RuntimeWarning) |
| 864 |
return True |
| 865 |
else: |
| 866 |
raise err |
| 867 |
|
| 868 |
def _open_configuration_exclusive(): |
| 869 |
return self.lock() |
| 870 |
|
| 871 |
def _open_configuration_ephemeral(**kwargs): |
| 872 |
self.rpc.open_configuration(**kwargs) |
| 873 |
return True |
| 874 |
|
| 875 |
def _unsupported_option(): |
| 876 |
if self.mode is not None: |
| 877 |
raise ValueError("unsupported action: {}".format(self.mode)) |
| 878 |
|
| 879 |
if self.kwargs.get("ephemeral_instance"): |
| 880 |
ephemeral_kwargs = {"ephemeral_instance": self.kwargs["ephemeral_instance"]} |
| 881 |
else: |
| 882 |
ephemeral_kwargs = {"ephemeral": True} |
| 883 |
|
| 884 |
{ |
| 885 |
"private": _open_configuration_private, |
| 886 |
"dynamic": _open_configuration_dynamic, |
| 887 |
"batch": _open_configuration_batch, |
| 888 |
"exclusive": _open_configuration_exclusive, |
| 889 |
"ephemeral": lambda: _open_configuration_ephemeral(**ephemeral_kwargs), |
| 890 |
}.get(self.mode, _unsupported_option)() |
| 891 |
return self |
| 892 |
|
| 893 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 894 |
if self.mode == "exclusive": |
| 895 |
self.unlock() |
| 896 |
elif self.mode is not None: |
| 897 |
self.rpc.close_configuration() |