| 1 |
# stdlib |
| 2 |
from __future__ import print_function |
| 3 |
import hashlib |
| 4 |
import re |
| 5 |
from os import path |
| 6 |
import sys |
| 7 |
|
| 8 |
try: |
| 9 |
# Python 3.x |
| 10 |
from urllib.parse import urlparse |
| 11 |
except ImportError: |
| 12 |
# Python 2.x |
| 13 |
from urlparse import urlparse |
| 14 |
|
| 15 |
# 3rd-party modules |
| 16 |
from lxml.builder import E |
| 17 |
from lxml import etree |
| 18 |
|
| 19 |
# local modules |
| 20 |
from jnpr.junos.decorators import timeoutDecorator |
| 21 |
from jnpr.junos.utils.util import Util |
| 22 |
from jnpr.junos.utils.scp import SCP |
| 23 |
from jnpr.junos.utils.ftp import FTP |
| 24 |
from jnpr.junos.utils.start_shell import StartShell |
| 25 |
from jnpr.junos.exception import SwRollbackError, RpcTimeoutError, RpcError |
| 26 |
from ncclient.xml_ import NCElement |
| 27 |
from jnpr.junos import jxml as JXML |
| 28 |
|
| 29 |
""" |
| 30 |
Software Installation Utilities |
| 31 |
""" |
| 32 |
|
| 33 |
__all__ = ["SW"] |
| 34 |
|
| 35 |
|
| 36 |
def _hashfile(afile, hasher, blocksize=65536): |
| 37 |
buf = afile.read(blocksize) |
| 38 |
while len(buf) > 0: |
| 39 |
hasher.update(buf) |
| 40 |
buf = afile.read(blocksize) |
| 41 |
return hasher.hexdigest() |
| 42 |
|
| 43 |
|
| 44 |
class SW(Util): |
| 45 |
""" |
| 46 |
Software Utility class, used to perform a software upgrade and |
| 47 |
associated functions. These methods have been tested on |
| 48 |
*simple deployments*. Refer to **install** for restricted |
| 49 |
use-cases for software upgrades. |
| 50 |
|
| 51 |
**Primary methods:** |
| 52 |
* :meth:`install`: perform the entire software installation process |
| 53 |
* :meth:`reboot`: reboots the system for the new image to take effect |
| 54 |
* :meth:`poweroff`: shutdown the system |
| 55 |
|
| 56 |
**Helpers:** (Useful as standalone as well) |
| 57 |
* :meth:`put`: SCP put package file onto Junos device |
| 58 |
* :meth:`pkgadd`: performs the 'request' operation to install the package |
| 59 |
* :meth:`validate`: performs the 'request' to validate the package |
| 60 |
|
| 61 |
**Miscellaneous:** |
| 62 |
* rollback: same as 'request software rollback' |
| 63 |
* inventory: (property) provides file info for current and rollback |
| 64 |
images on the device |
| 65 |
""" |
| 66 |
|
| 67 |
def __init__(self, dev): |
| 68 |
Util.__init__(self, dev) |
| 69 |
self._dev = dev |
| 70 |
self._RE_list = [] |
| 71 |
if "junos_info" in dev.facts and dev.facts["junos_info"] is not None: |
| 72 |
self._RE_list = list(dev.facts["junos_info"].keys()) |
| 73 |
else: |
| 74 |
self._RE_list = [x for x in dev.facts.keys() if x.startswith("version_RE")] |
| 75 |
self._multi_RE = bool(dev.facts.get("2RE")) |
| 76 |
# Branch SRX in an SRX cluster doesn't really support multi_RE |
| 77 |
# functionality for SW. |
| 78 |
if ( |
| 79 |
dev.facts.get("personality", "") == "SRX_BRANCH" |
| 80 |
and dev.facts.get("srx_cluster") is True |
| 81 |
): |
| 82 |
self._multi_RE = False |
| 83 |
self._multi_VC = bool( |
| 84 |
self._multi_RE is True |
| 85 |
and dev.facts.get("vc_capable") is True |
| 86 |
and dev.facts.get("vc_mode") != "Disabled" |
| 87 |
) |
| 88 |
self._multi_VC_nsync = bool( |
| 89 |
self._multi_RE is False |
| 90 |
and dev.facts.get("vc_capable") is True |
| 91 |
and dev.facts.get("vc_mode") != "Disabled" |
| 92 |
) |
| 93 |
self._mixed_VC = bool(dev.facts.get("vc_mode") == "Mixed") |
| 94 |
# The devices which currently support single-RE ISSU, communicate with |
| 95 |
# the new Junos VM using internal IP 128.0.0.63. |
| 96 |
# Therefore, the 'localre' value in the 'current_re' fact can currently |
| 97 |
# be used to check for this capability. |
| 98 |
# {master: 0} |
| 99 |
# user @ s0 > file show / etc / hosts.junos | match localre |
| 100 |
# 128.0.0.63 localre |
| 101 |
self._single_re_issu = bool( |
| 102 |
"current_re" in dev.facts and "localre" in dev.facts["current_re"] |
| 103 |
) |
| 104 |
self.log = lambda report: None |
| 105 |
|
| 106 |
# ----------------------------------------------------------------------- |
| 107 |
# CLASS METHODS |
| 108 |
# ----------------------------------------------------------------------- |
| 109 |
|
| 110 |
@classmethod |
| 111 |
def local_sha256(cls, package): |
| 112 |
r""" |
| 113 |
Computes the SHA-256 value on the package file. |
| 114 |
|
| 115 |
:param str package: |
| 116 |
File-path to the package (\*.tgz) file on the local server |
| 117 |
|
| 118 |
:returns: SHA-256 checksum (str) |
| 119 |
:raises IOError: when **package** file does not exist |
| 120 |
""" |
| 121 |
return _hashfile(open(package, "rb"), hashlib.sha256()) |
| 122 |
|
| 123 |
@classmethod |
| 124 |
def local_md5(cls, package): |
| 125 |
r""" |
| 126 |
Computes the MD5 checksum value on the local package file. |
| 127 |
|
| 128 |
:param str package: |
| 129 |
File-path to the package (\*.tgz) file on the local server |
| 130 |
|
| 131 |
:returns: MD5 checksum (str) |
| 132 |
:raises IOError: when **package** file does not exist |
| 133 |
""" |
| 134 |
return _hashfile(open(package, "rb"), hashlib.md5()) |
| 135 |
|
| 136 |
@classmethod |
| 137 |
def local_sha1(cls, package): |
| 138 |
r""" |
| 139 |
Computes the SHA1 checksum value on the local package file. |
| 140 |
|
| 141 |
:param str package: |
| 142 |
File-path to the package (\*.tgz) file on the local server |
| 143 |
|
| 144 |
:returns: SHA1 checksum (str) |
| 145 |
:raises IOError: when **package** file does not exist |
| 146 |
""" |
| 147 |
return _hashfile(open(package, "rb"), hashlib.sha1()) |
| 148 |
|
| 149 |
@classmethod |
| 150 |
def local_checksum(cls, package, algorithm="md5"): |
| 151 |
r""" |
| 152 |
Computes the checksum value on the local package file. |
| 153 |
|
| 154 |
:param str package: |
| 155 |
File-path to the package (\*.tgz) file on the local server |
| 156 |
:param str algorithm: |
| 157 |
The algorithm to use for computing the checksum. Valid values are: |
| 158 |
'md5', 'sha1', and 'sha256'. Defaults to 'md5'. |
| 159 |
|
| 160 |
:returns: checksum (str) |
| 161 |
:raises IOError: when **package** file does not exist |
| 162 |
""" |
| 163 |
if algorithm == "md5": |
| 164 |
return cls.local_md5(package) |
| 165 |
elif algorithm == "sha1": |
| 166 |
return cls.local_sha1(package) |
| 167 |
elif algorithm == "sha256": |
| 168 |
return cls.local_sha256(package) |
| 169 |
else: |
| 170 |
raise ValueError("Unknown checksum algorithm: %s" % (algorithm)) |
| 171 |
|
| 172 |
@classmethod |
| 173 |
def progress(cls, dev, report): |
| 174 |
"""simple progress report function""" |
| 175 |
print(dev.hostname + ": " + report) |
| 176 |
|
| 177 |
# ------------------------------------------------------------------------- |
| 178 |
# put - Copy the image onto the device |
| 179 |
# ------------------------------------------------------------------------- |
| 180 |
|
| 181 |
def put(self, package, remote_path="/var/tmp", progress=None): |
| 182 |
""" |
| 183 |
SCP or FTP 'put' the package file from the local server to the remote |
| 184 |
device. |
| 185 |
|
| 186 |
:param str package: |
| 187 |
File path to the package file on the local file system |
| 188 |
|
| 189 |
:param str remote_path: |
| 190 |
The directory on the device where the package will be copied to. |
| 191 |
|
| 192 |
:param func progress: |
| 193 |
Callback function to indicate progress. If set to ``True`` |
| 194 |
uses :meth:`scp._scp_progress` for basic reporting by default. |
| 195 |
See that class method for details. |
| 196 |
""" |
| 197 |
# execute FTP when connection mode if telnet |
| 198 |
if hasattr(self._dev, "_mode") and self._dev._mode == "telnet": |
| 199 |
with FTP(self._dev) as ftp: |
| 200 |
ftp.put(package, remote_path) |
| 201 |
else: |
| 202 |
# execute the secure-copy with the Python SCP module |
| 203 |
with SCP(self._dev, progress=progress) as scp: |
| 204 |
scp.put(package, remote_path) |
| 205 |
|
| 206 |
# ------------------------------------------------------------------------- |
| 207 |
# pkgadd - used to perform the 'request system software add ...' |
| 208 |
# ------------------------------------------------------------------------- |
| 209 |
|
| 210 |
def pkgadd(self, remote_package, vmhost=False, **kvargs): |
| 211 |
""" |
| 212 |
Issue the RPC equivalent of the 'request system software add' command |
| 213 |
or the 'request vmhost software add' command on the package. |
| 214 |
If vhmhost=False, the <request-package-add> RPC is used and the |
| 215 |
The "no-validate" options is set. If you want to validate |
| 216 |
the image, do that using the specific :meth:`validate` method. |
| 217 |
If vmhost=True, the <request-vmhost-package-add> RPC is used. |
| 218 |
|
| 219 |
If you want to reboot the device, invoke the :meth:`reboot` method |
| 220 |
after installing the software rather than passing the ``reboot=True`` |
| 221 |
parameter. |
| 222 |
|
| 223 |
:param str remote_package: |
| 224 |
The file-path to the install package on the remote (Junos) device. |
| 225 |
|
| 226 |
|
| 227 |
:param bool vhmhost: |
| 228 |
(Optional) A boolean indicating if this is a software update of the |
| 229 |
vhmhost. The default is ``vmhost=False``. |
| 230 |
|
| 231 |
:param dict kvargs: |
| 232 |
Any additional parameters to the 'request' command can |
| 233 |
be passed within **kvargs**, following the RPC syntax |
| 234 |
methodology (dash-2-underscore,etc.) |
| 235 |
|
| 236 |
.. warning:: Refer to the restrictions listed in :meth:`install`. |
| 237 |
""" |
| 238 |
|
| 239 |
if vmhost is False: |
| 240 |
if isinstance(remote_package, (list, tuple)) and self._mixed_VC: |
| 241 |
args = dict(no_validate=True, set=remote_package) |
| 242 |
else: |
| 243 |
args = dict(no_validate=True, package_name=remote_package) |
| 244 |
args.update(kvargs) |
| 245 |
rsp = self.rpc.request_package_add(**args) |
| 246 |
else: |
| 247 |
rsp = self.rpc.request_vmhost_package_add( |
| 248 |
package_name=remote_package, **kvargs |
| 249 |
) |
| 250 |
|
| 251 |
return self._parse_pkgadd_response(rsp) |
| 252 |
|
| 253 |
# ------------------------------------------------------------------------- |
| 254 |
# pkgaddNSSU - used to perform NSSU upgrade |
| 255 |
# ------------------------------------------------------------------------- |
| 256 |
|
| 257 |
def pkgaddNSSU(self, remote_package, **kvargs): |
| 258 |
""" |
| 259 |
Issue the 'request system software nonstop-upgrade' command on the |
| 260 |
package. |
| 261 |
|
| 262 |
:param str remote_package: |
| 263 |
The file-path to the install package on the remote (Junos) device. |
| 264 |
""" |
| 265 |
|
| 266 |
rsp = self.rpc.request_package_nonstop_upgrade( |
| 267 |
package_name=remote_package, **kvargs |
| 268 |
) |
| 269 |
return self._parse_pkgadd_response(rsp) |
| 270 |
|
| 271 |
# ------------------------------------------------------------------------- |
| 272 |
# pkgaddISSU - used to perform ISSU upgrade |
| 273 |
# ------------------------------------------------------------------------- |
| 274 |
|
| 275 |
def pkgaddISSU(self, remote_package, vmhost=False, **kvargs): |
| 276 |
""" |
| 277 |
Issue the RPC equivalent of the |
| 278 |
'request system software in-service-upgrade' command |
| 279 |
or the 'request vmhost software in-service-upgrade' command on the |
| 280 |
package. If vhmhost=False, the <request-package-in-service-upgrade> |
| 281 |
RPC is used. If vmhost=True, the |
| 282 |
<request-vmhost-package-in-service-upgrade> RPC is used. |
| 283 |
|
| 284 |
:param str remote_package: |
| 285 |
The file-path to the install package on the remote (Junos) device. |
| 286 |
|
| 287 |
|
| 288 |
:param bool vmhost: |
| 289 |
(Optional) A boolean indicating if this is a software update of the |
| 290 |
vhmhost. The default is ``vmhost=False``. |
| 291 |
""" |
| 292 |
|
| 293 |
if vmhost is False: |
| 294 |
rsp = self.rpc.request_package_in_service_upgrade( |
| 295 |
package_name=remote_package, **kvargs |
| 296 |
) |
| 297 |
else: |
| 298 |
rsp = self.rpc.request_vmhost_package_in_service_upgrade( |
| 299 |
package_name=remote_package, **kvargs |
| 300 |
) |
| 301 |
return self._parse_pkgadd_response(rsp) |
| 302 |
|
| 303 |
def _parse_pkgadd_response(self, rsp): |
| 304 |
got = rsp.getparent() |
| 305 |
output_msg = "\n".join( |
| 306 |
[i.text for i in got.findall("output") if i.text is not None] |
| 307 |
) |
| 308 |
package_result = got.findtext("package-result") |
| 309 |
if package_result is None: |
| 310 |
# <package-result> is not present |
| 311 |
if "ERROR:" in output_msg and ( |
| 312 |
("is not found" in output_msg) or ("no such file" in output_msg) |
| 313 |
): |
| 314 |
# MX80 output with non-existent package looks like: |
| 315 |
# <output> |
| 316 |
# ERROR: package: /var/tmp/nonexistent.tgz is not found or empty |
| 317 |
# </output> |
| 318 |
package_result = "1" |
| 319 |
else: |
| 320 |
# Not a known specific error in the output. Assume success. |
| 321 |
# That is, assume <package-result>0</package-result> |
| 322 |
self.log( |
| 323 |
"software pkgadd response is missing package-result " |
| 324 |
"element. Assuming success." |
| 325 |
) |
| 326 |
package_result = "0" |
| 327 |
rc = int(package_result.strip()) |
| 328 |
self.log("software pkgadd package-result: %s\nOutput: %s" % (rc, output_msg)) |
| 329 |
return rc == 0, output_msg |
| 330 |
|
| 331 |
# ------------------------------------------------------------------------- |
| 332 |
# validate - perform 'request' operation to validate the package |
| 333 |
# ------------------------------------------------------------------------- |
| 334 |
|
| 335 |
def validate(self, remote_package, issu=False, nssu=False, **kwargs): |
| 336 |
""" |
| 337 |
Issues the 'request' operation to validate the package against the |
| 338 |
config. |
| 339 |
|
| 340 |
:returns: |
| 341 |
* ``True`` if validation passes. i.e return code (rc) value is 0 |
| 342 |
* * ``False`` otherwise |
| 343 |
""" |
| 344 |
if nssu and not self._issu_nssu_requirement_validation(): |
| 345 |
return False |
| 346 |
if issu: |
| 347 |
if not self._issu_requirement_validation(): |
| 348 |
return False |
| 349 |
rsp = self.rpc.check_in_service_upgrade( |
| 350 |
package_name=remote_package, **kwargs |
| 351 |
).getparent() |
| 352 |
else: |
| 353 |
rsp = self.rpc.request_package_validate( |
| 354 |
package_name=remote_package, **kwargs |
| 355 |
).getparent() |
| 356 |
rc = int(rsp.findtext("package-result")) |
| 357 |
output_msg = "\n".join( |
| 358 |
[i.text for i in rsp.findall("output") if i.text is not None] |
| 359 |
) |
| 360 |
self.log("software validate package-result: %s\nOutput: %s" % (rc, output_msg)) |
| 361 |
return 0 == rc |
| 362 |
|
| 363 |
def _issu_requirement_validation(self): |
| 364 |
""" |
| 365 |
Checks: |
| 366 |
* The master Routing Engine and backup Routing Engine must be |
| 367 |
running the same software version before you can perform a |
| 368 |
unified ISSU. |
| 369 |
* Check GRES is enabled |
| 370 |
* Check NSR is enabled |
| 371 |
* Check commit synchronize is enabled |
| 372 |
* Verify that NSR is configured on the master Routing Engine |
| 373 |
by using the "show task replication" command. |
| 374 |
* Verify that GRES is enabled on the backup Routing Engine |
| 375 |
by using the show system switchover command. |
| 376 |
|
| 377 |
:returns: |
| 378 |
* ``True`` if validation passes. |
| 379 |
* * ``False`` otherwise |
| 380 |
""" |
| 381 |
self.log( |
| 382 |
"ISSU requirement validation: The master Routing Engine and\n" |
| 383 |
"backup Routing engine must be running the same software\n" |
| 384 |
"version before you can perform a unified ISSU." |
| 385 |
) |
| 386 |
if not ( |
| 387 |
self._dev.facts["2RE"] |
| 388 |
and self._dev.facts["version_RE0"] == self._dev.facts["version_RE1"] |
| 389 |
): |
| 390 |
self.log( |
| 391 |
"Requirement FAILED: The master Routing Engine (%s) and\n" |
| 392 |
"backup Routing Engine (%s) must be running the same\n" |
| 393 |
"software version before it can perform a unified ISSU" |
| 394 |
% (self._dev.facts["version_RE0"], self._dev.facts["version_RE1"]) |
| 395 |
) |
| 396 |
return False |
| 397 |
if not self._issu_nssu_requirement_validation(): |
| 398 |
return False |
| 399 |
self.log( |
| 400 |
"Verify that GRES is enabled on the backup Routing Engine\n" |
| 401 |
'by using the command "show system switchover"' |
| 402 |
) |
| 403 |
output = "" |
| 404 |
try: |
| 405 |
op = self._dev.rpc.request_shell_execute( |
| 406 |
routing_engine="backup", command="cli show system switchover" |
| 407 |
) |
| 408 |
if op.findtext(".//switchover-state", default="").lower() == "on": |
| 409 |
self.log("Graceful switchover status is On") |
| 410 |
return True |
| 411 |
output = op.findtext(".//output", default="") |
| 412 |
except RpcError: |
| 413 |
# request-shell-execute rpc is not available for <14.1 |
| 414 |
with StartShell(self._dev) as ss: |
| 415 |
ss.run("cli", "> ", timeout=5) |
| 416 |
if ss.run("request routing-engine " "login other-routing-engine")[0]: |
| 417 |
# depending on user permission, prompt will go to either |
| 418 |
# cli or shell, below line of code prompt will finally end |
| 419 |
# up in cli mode |
| 420 |
ss.run("cli", "> ", timeout=5) |
| 421 |
data = ss.run("show system switchover", "> ", timeout=5) |
| 422 |
output = data[1] |
| 423 |
ss.run("exit") |
| 424 |
else: |
| 425 |
self.log( |
| 426 |
"Requirement FAILED: Not able run " '"show system switchover"' |
| 427 |
) |
| 428 |
return False |
| 429 |
gres_status = re.search(r"Graceful switchover: (\w+)", output, re.I) |
| 430 |
if not (gres_status is not None and gres_status.group(1).lower() == "on"): |
| 431 |
self.log("Requirement FAILED: Graceful switchover status " "is not On") |
| 432 |
return False |
| 433 |
self.log("Graceful switchover status is On") |
| 434 |
return True |
| 435 |
|
| 436 |
def _issu_nssu_requirement_validation(self): |
| 437 |
""" |
| 438 |
Checks: |
| 439 |
* Check GRES is enabled |
| 440 |
* Check NSR is enabled |
| 441 |
* Check commit synchronize is enabled |
| 442 |
* Verify that NSR is configured on the master Routing Engine |
| 443 |
by using the "show task replication" command. |
| 444 |
|
| 445 |
:returns: |
| 446 |
* ``True`` if validation passes. |
| 447 |
* * ``False`` otherwise |
| 448 |
""" |
| 449 |
self.log("Checking GRES configuration") |
| 450 |
conf = self._dev.rpc.get_config( |
| 451 |
filter_xml=etree.XML( |
| 452 |
""" |
| 453 |
<configuration> |
| 454 |
<chassis> |
| 455 |
<redundancy> |
| 456 |
<graceful-switchover/> |
| 457 |
</redundancy> |
| 458 |
</chassis> |
| 459 |
</configuration>""" |
| 460 |
), |
| 461 |
options={ |
| 462 |
"database": "committed", |
| 463 |
"inherit": "inherit", |
| 464 |
"commit-scripts": "apply", |
| 465 |
}, |
| 466 |
) |
| 467 |
if conf.find("chassis/redundancy/graceful-switchover") is None: |
| 468 |
self.log("Requirement FAILED: GRES is not Enabled " "in configuration") |
| 469 |
return False |
| 470 |
self.log("Checking commit synchronize configuration") |
| 471 |
conf = self._dev.rpc.get_config( |
| 472 |
filter_xml=etree.XML( |
| 473 |
""" |
| 474 |
<configuration> |
| 475 |
<system> |
| 476 |
<commit> |
| 477 |
<synchronize/> |
| 478 |
</commit> |
| 479 |
</system> |
| 480 |
</configuration>""" |
| 481 |
), |
| 482 |
options={ |
| 483 |
"database": "committed", |
| 484 |
"inherit": "inherit", |
| 485 |
"commit-scripts": "apply", |
| 486 |
}, |
| 487 |
) |
| 488 |
if conf.find("system/commit/synchronize") is None: |
| 489 |
self.log( |
| 490 |
"Requirement FAILED: commit synchronize is not " |
| 491 |
"Enabled in configuration" |
| 492 |
) |
| 493 |
return False |
| 494 |
self.log("Checking NSR configuration") |
| 495 |
conf = self._dev.rpc.get_config( |
| 496 |
filter_xml=etree.XML( |
| 497 |
""" |
| 498 |
<configuration> |
| 499 |
<routing-options> |
| 500 |
<nonstop-routing/> |
| 501 |
</routing-options> |
| 502 |
</configuration> |
| 503 |
""" |
| 504 |
), |
| 505 |
options={ |
| 506 |
"database": "committed", |
| 507 |
"inherit": "inherit", |
| 508 |
"commit-scripts": "apply", |
| 509 |
}, |
| 510 |
) |
| 511 |
if conf.find("routing-options/nonstop-routing") is None: |
| 512 |
self.log("Requirement FAILED: NSR is not Enabled in configuration") |
| 513 |
return False |
| 514 |
self.log( |
| 515 |
"Verifying that GRES status on the current Routing Engine " |
| 516 |
'is Enabled by using the "show task replication" command.' |
| 517 |
) |
| 518 |
op = self._dev.rpc.get_routing_task_replication_state() |
| 519 |
if not ( |
| 520 |
op.findtext("task-gres-state") == "Enabled" |
| 521 |
and op.findtext("task-re-mode") == "Master" |
| 522 |
): |
| 523 |
self.log( |
| 524 |
"Requirement FAILED: Either Stateful Replication is not " |
| 525 |
"Enabled or RE mode\nis not Master" |
| 526 |
) |
| 527 |
return False |
| 528 |
return True |
| 529 |
|
| 530 |
def remote_checksum(self, remote_package, timeout=300, algorithm="md5"): |
| 531 |
""" |
| 532 |
Computes a checksum of the remote_package file on the remote device. |
| 533 |
|
| 534 |
:param str remote_package: |
| 535 |
The file-path on the remote Junos device |
| 536 |
:param int timeout: |
| 537 |
The amount of time (seconds) before declaring an RPC timeout. |
| 538 |
The default RPC timeout is generally around 30 seconds. So this |
| 539 |
:timeout: value will be used in the context of the checksum process. |
| 540 |
Defaults to 5 minutes (5*60=300) |
| 541 |
:param str algorithm: |
| 542 |
The algorithm to use for computing the checksum. Valid values are: |
| 543 |
'md5', 'sha1', and 'sha256'. Defaults to 'md5'. |
| 544 |
|
| 545 |
:returns: |
| 546 |
* The checksum string |
| 547 |
* ``None`` when the **remote_package** is not found. |
| 548 |
|
| 549 |
:raises RpcError: RPC errors other than **remote_package** not found. |
| 550 |
""" |
| 551 |
kwargs = {"path": remote_package, "dev_timeout": timeout, "normalize": True} |
| 552 |
try: |
| 553 |
if algorithm == "md5": |
| 554 |
rsp = self.rpc.get_checksum_information(**kwargs) |
| 555 |
elif algorithm == "sha1": |
| 556 |
rsp = self.rpc.get_sha1_checksum_information(**kwargs) |
| 557 |
elif algorithm == "sha256": |
| 558 |
rsp = self.rpc.get_sha256_checksum_information(**kwargs) |
| 559 |
else: |
| 560 |
raise ValueError("Unknown checksum algorithm: %s" % (algorithm)) |
| 561 |
return rsp.findtext(".//checksum") |
| 562 |
except RpcError as e: |
| 563 |
if "No such file or directory" in getattr(e, "message", ""): |
| 564 |
return None |
| 565 |
else: |
| 566 |
raise |
| 567 |
|
| 568 |
# ------------------------------------------------------------------------- |
| 569 |
# safe_copy - copies the package and performs checksum |
| 570 |
# ------------------------------------------------------------------------- |
| 571 |
|
| 572 |
def safe_copy( |
| 573 |
self, |
| 574 |
package, |
| 575 |
remote_path="/var/tmp", |
| 576 |
progress=None, |
| 577 |
cleanfs=True, |
| 578 |
cleanfs_timeout=300, |
| 579 |
checksum=None, |
| 580 |
checksum_timeout=300, |
| 581 |
checksum_algorithm="md5", |
| 582 |
force_copy=False, |
| 583 |
): |
| 584 |
""" |
| 585 |
Copy the install package safely to the remote device. By default |
| 586 |
this means to clean the filesystem to make space, perform the |
| 587 |
secure-copy, and then verify the checksum. |
| 588 |
|
| 589 |
:param str package: |
| 590 |
file-path to package on local filesystem |
| 591 |
:param str remote_path: |
| 592 |
file-path to directory on remote device |
| 593 |
:param func progress: |
| 594 |
call-back function for progress updates. If set to ``True`` uses |
| 595 |
:meth:`sw.progress` for basic reporting by default. |
| 596 |
:param bool cleanfs: |
| 597 |
When ``True`` (default) perform a |
| 598 |
"request system storage cleanup" on the device. |
| 599 |
:param int cleanfs_timeout: |
| 600 |
Number of seconds (default 300) to wait for the |
| 601 |
"request system storage cleanup" to complete. |
| 602 |
:param str checksum: |
| 603 |
This is the checksum string as computed on the local system. |
| 604 |
This value will be used to compare the checksum on the |
| 605 |
remote Junos device. |
| 606 |
:param int checksum_timeout: |
| 607 |
Number of seconds (default 300) to wait for the calculation of the |
| 608 |
checksum on the remote Junos device. |
| 609 |
:param str checksum_algorithm: |
| 610 |
The algorithm to use for computing the checksum. Valid values are: |
| 611 |
'md5', 'sha1', and 'sha256'. Defaults to 'md5'. |
| 612 |
:param bool force_copy: |
| 613 |
When ``True`` perform the copy even if the package is already |
| 614 |
present at the remote_path on the device. When ``False`` (default) |
| 615 |
if the package is already present at the remote_path, and the local |
| 616 |
checksum matches the remote checksum, then skip the copy to |
| 617 |
optimize time. |
| 618 |
|
| 619 |
:returns: |
| 620 |
* ``True`` when the copy was successful |
| 621 |
* ``False`` otherwise |
| 622 |
""" |
| 623 |
|
| 624 |
def _progress(report): |
| 625 |
if progress is True: |
| 626 |
self.progress(self._dev, report) |
| 627 |
elif callable(progress): |
| 628 |
progress(self._dev, report) |
| 629 |
|
| 630 |
if checksum is None: |
| 631 |
_progress("computing checksum on local package: %s" % (package)) |
| 632 |
try: |
| 633 |
checksum = SW.local_checksum(package, algorithm=checksum_algorithm) |
| 634 |
except IOError: |
| 635 |
_progress( |
| 636 |
"error computing checksum on local package: %s. " |
| 637 |
"Ensure the local package exists." % (package) |
| 638 |
) |
| 639 |
return False |
| 640 |
|
| 641 |
if checksum is None: |
| 642 |
_progress( |
| 643 |
"Unable to calculate the checksum on local package: %s." % (package) |
| 644 |
) |
| 645 |
return False |
| 646 |
|
| 647 |
if cleanfs is True: |
| 648 |
_progress("cleaning filesystem ...") |
| 649 |
try: |
| 650 |
self.rpc.request_system_storage_cleanup(dev_timeout=cleanfs_timeout) |
| 651 |
except RpcError as err: |
| 652 |
_progress("Problem cleaning filesystem: %s" % (str(err))) |
| 653 |
return False |
| 654 |
|
| 655 |
# Calculate the remote package name. |
| 656 |
remote_package = remote_path + "/" + path.basename(package) |
| 657 |
|
| 658 |
remote_checksum = None |
| 659 |
# Check to see if the package file already exists on the remote |
| 660 |
# device by trying to get the checksum. |
| 661 |
if force_copy is False: |
| 662 |
_progress( |
| 663 |
"before copy, computing checksum on remote package: %s" % remote_package |
| 664 |
) |
| 665 |
remote_checksum = self.remote_checksum( |
| 666 |
remote_package, timeout=checksum_timeout, algorithm=checksum_algorithm |
| 667 |
) |
| 668 |
|
| 669 |
if remote_checksum != checksum: |
| 670 |
# Need to copy the file. |
| 671 |
self.put(package, remote_path=remote_path, progress=progress) |
| 672 |
|
| 673 |
# Now validate checksum of the recently copied file. |
| 674 |
_progress( |
| 675 |
"after copy, computing checksum on remote package: %s" % remote_package |
| 676 |
) |
| 677 |
remote_checksum = self.remote_checksum( |
| 678 |
remote_package, timeout=checksum_timeout, algorithm=checksum_algorithm |
| 679 |
) |
| 680 |
|
| 681 |
if remote_checksum != checksum: |
| 682 |
_progress("checksum check failed.") |
| 683 |
return False |
| 684 |
|
| 685 |
_progress("checksum check passed.") |
| 686 |
return True |
| 687 |
|
| 688 |
# ------------------------------------------------------------------------- |
| 689 |
# install - complete installation process, but not reboot |
| 690 |
# ------------------------------------------------------------------------- |
| 691 |
|
| 692 |
def install( |
| 693 |
self, |
| 694 |
package=None, |
| 695 |
pkg_set=None, |
| 696 |
remote_path="/var/tmp", |
| 697 |
progress=None, |
| 698 |
validate=False, |
| 699 |
checksum=None, |
| 700 |
cleanfs=True, |
| 701 |
no_copy=False, |
| 702 |
issu=False, |
| 703 |
nssu=False, |
| 704 |
timeout=1800, |
| 705 |
cleanfs_timeout=300, |
| 706 |
checksum_timeout=300, |
| 707 |
checksum_algorithm="md5", |
| 708 |
force_copy=False, |
| 709 |
all_re=True, |
| 710 |
member_id=None, |
| 711 |
vmhost=False, |
| 712 |
**kwargs |
| 713 |
): |
| 714 |
""" |
| 715 |
Performs the complete installation of the **package** that includes the |
| 716 |
following steps: |
| 717 |
|
| 718 |
1. If :package: is a URL, or :no_copy: is True, skip to step 8. |
| 719 |
2. computes the checksum of :package: or :pgk_set: on the local host |
| 720 |
if :checksum: was not provided. |
| 721 |
3. performs a storage cleanup on the remote Junos device if :cleanfs: |
| 722 |
is ``True`` |
| 723 |
4. Attempts to compute the checksum of the :package: filename in the |
| 724 |
:remote_path: directory of the remote Junos device if the |
| 725 |
:force_copy: argument is ``False`` |
| 726 |
5. SCP or FTP copies the :package: file from the local host to the |
| 727 |
:remote_path: directory on the remote Junos device under any of the |
| 728 |
following conditions: |
| 729 |
|
| 730 |
a) The :force_copy: argument is ``True`` |
| 731 |
b) The :package: filename doesn't already exist in the |
| 732 |
:remote_path: directory of the remote Junos device. |
| 733 |
c) The checksum computed in step 2 does not match the checksum |
| 734 |
computed in step 4. |
| 735 |
6. If step 5 was executed, computes the checksum of the :package: |
| 736 |
filename in the :remote_path: directory of the remote Junos device. |
| 737 |
7. Validates the checksum computed in step 2 matches the checksum |
| 738 |
computed in step 6. |
| 739 |
8. validates the package if :validate: is True |
| 740 |
9. installs the package |
| 741 |
|
| 742 |
.. warning:: This process has been validated on the following |
| 743 |
deployments. |
| 744 |
|
| 745 |
Tested: |
| 746 |
|
| 747 |
* Single RE devices (EX, QFX, MX, SRX). |
| 748 |
* MX dual-RE |
| 749 |
* EX virtual-chassis when all same HW model |
| 750 |
* QFX virtual-chassis when all same HW model |
| 751 |
* QFX/EX mixed virtual-chassis |
| 752 |
* Mixed mode VC |
| 753 |
|
| 754 |
Known Restrictions: |
| 755 |
|
| 756 |
* SRX cluster |
| 757 |
* MX virtual-chassis |
| 758 |
|
| 759 |
You can get a progress report on this process by providing a |
| 760 |
**progress** callback. |
| 761 |
|
| 762 |
.. note:: You will need to invoke the :meth:`reboot` method explicitly |
| 763 |
to reboot the device. |
| 764 |
|
| 765 |
:param str package: |
| 766 |
Either the full file path to the install package tarball on the local |
| 767 |
(PyEZ host's) filesystem OR a URL (from the target device's |
| 768 |
perspcective) from which the device retrieves installed. When the |
| 769 |
value is a URL, then the :no_copy: and :remote_path: values are |
| 770 |
unused. The acceptable formats for a URL value may be found at: |
| 771 |
https://www.juniper.net/documentation/en_US/junos/topics/concept/junos-software-formats-filenames-urls.html |
| 772 |
|
| 773 |
:param list pkg_set: |
| 774 |
A list/tuple of :package: values which will be installed on a mixed |
| 775 |
VC setup. |
| 776 |
|
| 777 |
:param str remote_path: |
| 778 |
If the value of :package: or :pkg_set: is a file path on the local |
| 779 |
(PyEZ host's) filesystem, then the image is copied from the local |
| 780 |
filesystem to the :remote_path: directory on the target Junos |
| 781 |
device. The default is ``/var/tmp``. If the value of :package: or |
| 782 |
:pkg_set: is a URL, then the value of :remote_path: is unused. |
| 783 |
|
| 784 |
:param func progress: |
| 785 |
If provided, this is a callback function with a function prototype |
| 786 |
given the Device instance and the report string:: |
| 787 |
|
| 788 |
def myprogress(dev, report): |
| 789 |
print "host: %s, report: %s" % (dev.hostname, report) |
| 790 |
|
| 791 |
If set to ``True``, it uses :meth:`sw.progress` |
| 792 |
for basic reporting by default. |
| 793 |
|
| 794 |
:param bool validate: |
| 795 |
When ``True`` this method will perform a config validation against |
| 796 |
the new image |
| 797 |
|
| 798 |
:param str checksum: |
| 799 |
hexdigest of the package file. If this is not provided, then this |
| 800 |
method will perform the calculation. If you are planning on using the |
| 801 |
same image for multiple updates, you should consider using the |
| 802 |
:meth:`local_checksum` method to pre calculate this value and then |
| 803 |
provide to this method. |
| 804 |
|
| 805 |
:param bool cleanfs: |
| 806 |
When ``True`` will perform a 'storage cleanup' before copying the |
| 807 |
file to the device. Default is ``True``. |
| 808 |
|
| 809 |
:param bool no_copy: |
| 810 |
When the value of :package: or :pkg_set is not a URL, and the value |
| 811 |
of :no_copy: is ``True`` the software package will not be copied to |
| 812 |
the device and is presumed to already exist on the :remote_path: |
| 813 |
directory of the target Junos device. When the value of :no_copy: is |
| 814 |
``False`` (the default), then the package is copied from the local |
| 815 |
PyEZ host to the :remote_path: directory of the target Junos device. |
| 816 |
If the value of :package: or :pkg_set: is a URL, then the value of |
| 817 |
:no_copy: is unused. |
| 818 |
|
| 819 |
:param bool issu: |
| 820 |
(Optional) When ``True`` allows unified in-service software upgrade |
| 821 |
(ISSU) feature enables you to upgrade between two different Junos OS |
| 822 |
releases with no disruption on the control plane and with minimal |
| 823 |
disruption of traffic. |
| 824 |
|
| 825 |
:param bool nssu: |
| 826 |
(Optional) When ``True`` allows nonstop software upgrade (NSSU) |
| 827 |
enables you to upgrade the software running on a Juniper Networks |
| 828 |
EX Series Virtual Chassis or a Juniper Networks EX Series Ethernet |
| 829 |
Switch with redundant Routing Engines with a single command and |
| 830 |
minimal disruption to network traffic. |
| 831 |
|
| 832 |
:param int timeout: |
| 833 |
(Optional) The amount of time (seconds) to wait for the |
| 834 |
:package: installation to complete before declaring an RPC |
| 835 |
timeout. This argument was added since most of the time the |
| 836 |
"package add" RPC takes a significant amount of time. The default |
| 837 |
RPC timeout is 30 seconds. So this :timeout: value will be |
| 838 |
used in the context of the SW installation process. Defaults to |
| 839 |
30 minutes (30*60=1800) |
| 840 |
|
| 841 |
:param int cleanfs_timeout: |
| 842 |
(Optional) Number of seconds (default 300) to wait for the |
| 843 |
"request system storage cleanup" to complete. |
| 844 |
|
| 845 |
:param int checksum_timeout: |
| 846 |
(Optional) Number of seconds (default 300) to wait for the |
| 847 |
calculation of the checksum on the remote Junos device. |
| 848 |
:param str checksum_algorithm: |
| 849 |
(Optional) The algorithm to use for computing the checksum. |
| 850 |
Valid values are: 'md5', 'sha1', and 'sha256'. Defaults to 'md5'. |
| 851 |
|
| 852 |
:param bool force_copy: |
| 853 |
(Optional) When ``True`` perform the copy even if :package: is |
| 854 |
already present at the :remote_path: directory on the remote Junos |
| 855 |
device. When ``False`` (default) if the :package: is already present |
| 856 |
at the :remote_path:, AND the local checksum matches the remote |
| 857 |
checksum, then skip the copy to optimize time. |
| 858 |
|
| 859 |
:param bool all_re: |
| 860 |
(Optional) When ``True`` (default) install the package on |
| 861 |
all Routing Engines of the Junos device. When ``False`` perform |
| 862 |
the software install only on the current Routing Engine. |
| 863 |
|
| 864 |
:param bool vmhost: |
| 865 |
(Optional) A boolean indicating if this is a software update of the |
| 866 |
vhmhost. The default is ``vmhost=False``. |
| 867 |
|
| 868 |
:param kwargs **kwargs: |
| 869 |
(Optional) Additional keyword arguments are passed through to the |
| 870 |
"package add" RPC. |
| 871 |
|
| 872 |
:returns: tuple(<status>, <msg>) |
| 873 |
* status : ``True`` when the installation is successful and ``False`` otherwise |
| 874 |
* msg : msg received as response or error message created |
| 875 |
""" |
| 876 |
if issu is True and nssu is True: |
| 877 |
raise TypeError("install function can either take issu or nssu not both") |
| 878 |
elif (issu is True or nssu is True) and ( |
| 879 |
self._multi_RE is not True and self._single_re_issu is not True |
| 880 |
): |
| 881 |
raise TypeError("ISSU/NSSU requires Multi RE setup") |
| 882 |
|
| 883 |
def _progress(report): |
| 884 |
if progress is True: |
| 885 |
self.progress(self._dev, report) |
| 886 |
elif callable(progress): |
| 887 |
progress(self._dev, report) |
| 888 |
|
| 889 |
self.log = _progress |
| 890 |
|
| 891 |
# --------------------------------------------------------------------- |
| 892 |
# Before doing anything, Do check if any pending install exists. |
| 893 |
# --------------------------------------------------------------------- |
| 894 |
try: |
| 895 |
pending_install = self._dev.rpc.request_package_checks_pending_install() |
| 896 |
msg = pending_install.text |
| 897 |
if ( |
| 898 |
msg |
| 899 |
and msg.strip() != "" |
| 900 |
and pending_install.getparent().findtext("package-result").strip() |
| 901 |
== "1" |
| 902 |
): |
| 903 |
_progress(msg) |
| 904 |
return False |
| 905 |
except RpcError: |
| 906 |
_progress( |
| 907 |
"request-package-checks-pending-install rpc is not " |
| 908 |
"supported on given device" |
| 909 |
) |
| 910 |
except Exception as ex: |
| 911 |
_progress("check pending install failed with exception: %s" % ex) |
| 912 |
# Continue with software installation |
| 913 |
|
| 914 |
# --------------------------------------------------------------------- |
| 915 |
# perform a 'safe-copy' of the image to the remote device |
| 916 |
# --------------------------------------------------------------------- |
| 917 |
|
| 918 |
if package is None and pkg_set is None: |
| 919 |
raise TypeError( |
| 920 |
"install() requires either the package or pkg_set argument." |
| 921 |
) |
| 922 |
|
| 923 |
remote_pkg_set = [] |
| 924 |
if (sys.version < "3" and isinstance(package, (str, unicode))) or isinstance( |
| 925 |
package, str |
| 926 |
): |
| 927 |
pkg_set = [package] |
| 928 |
if isinstance(pkg_set, (list, tuple)) and len(pkg_set) > 0: |
| 929 |
remote_urls = ["ftp", "scp", "http", "https", "tftp", "sftp"] |
| 930 |
for pkg in pkg_set: |
| 931 |
parsed_url = urlparse(pkg) |
| 932 |
if parsed_url.scheme not in remote_urls: |
| 933 |
if no_copy is False: |
| 934 |
# To disable cleanfs after 1st iteration |
| 935 |
cleanfs = cleanfs and pkg_set.index(pkg) == 0 |
| 936 |
copy_ok = self.safe_copy( |
| 937 |
pkg, |
| 938 |
remote_path=remote_path, |
| 939 |
progress=progress, |
| 940 |
cleanfs=cleanfs, |
| 941 |
checksum=checksum, |
| 942 |
cleanfs_timeout=cleanfs_timeout, |
| 943 |
checksum_timeout=checksum_timeout, |
| 944 |
checksum_algorithm=checksum_algorithm, |
| 945 |
force_copy=force_copy, |
| 946 |
) |
| 947 |
if copy_ok is False: |
| 948 |
return False, "Package %s couldn't be copied" % pkg |
| 949 |
pkg = remote_path + "/" + path.basename(pkg) |
| 950 |
|
| 951 |
remote_pkg_set.append(pkg) |
| 952 |
else: |
| 953 |
raise ValueError("proper value for either package or pkg_set is missing") |
| 954 |
# --------------------------------------------------------------------- |
| 955 |
# at this point, the file exists on the remote device |
| 956 |
# or will be loaded directly from a URL. |
| 957 |
# --------------------------------------------------------------------- |
| 958 |
|
| 959 |
if len(remote_pkg_set) == 1: |
| 960 |
remote_package = remote_pkg_set[0] |
| 961 |
# validate can't be used in the case of a Mixed VC |
| 962 |
# With vmhost=True, validate is handled in the package add. |
| 963 |
if validate is True: |
| 964 |
if self._mixed_VC is False and vmhost is not True: |
| 965 |
_progress( |
| 966 |
"validating software against current config," |
| 967 |
" please be patient ..." |
| 968 |
) |
| 969 |
try: |
| 970 |
v_ok = self.validate( |
| 971 |
remote_package, issu, nssu, dev_timeout=timeout |
| 972 |
) |
| 973 |
except RpcError as e: |
| 974 |
if "syntax error" in getattr(e, "message", ""): |
| 975 |
v_ok = True |
| 976 |
else: |
| 977 |
raise |
| 978 |
|
| 979 |
if v_ok is not True: |
| 980 |
return v_ok, "Package validation failed" |
| 981 |
else: |
| 982 |
if vmhost is True: |
| 983 |
# Need to pass the no_validate option via kwargs. |
| 984 |
kwargs.update({"no_validate": True}) |
| 985 |
|
| 986 |
if issu is True: |
| 987 |
if validate is False: # To Check validation is False |
| 988 |
# Need to pass the no_validate option via kwargs |
| 989 |
kwargs.update({"no_validate": True}) |
| 990 |
_progress("ISSU: installing software ... please be patient ...") |
| 991 |
return self.pkgaddISSU( |
| 992 |
remote_package, vmhost=vmhost, dev_timeout=timeout, **kwargs |
| 993 |
) |
| 994 |
elif nssu is True: |
| 995 |
if validate is False: |
| 996 |
# Need to pass the no_validate option via kwargs |
| 997 |
kwargs.update({"no_validate": True}) |
| 998 |
_progress("NSSU: installing software ... please be patient ...") |
| 999 |
return self.pkgaddNSSU(remote_package, dev_timeout=timeout, **kwargs) |
| 1000 |
elif member_id is not None: |
| 1001 |
ok = True, "" |
| 1002 |
if self._multi_VC_nsync is True or self._multi_VC is True: |
| 1003 |
vc_members = [ |
| 1004 |
re.search(r"(\d+)", x).group(1) |
| 1005 |
for x in self._RE_list |
| 1006 |
if re.search(r"(\d+)", x) |
| 1007 |
] |
| 1008 |
vc_members.remove(self.dev.facts["vc_master"]) |
| 1009 |
vc_members.insert(len(vc_members), self.dev.facts["vc_master"]) |
| 1010 |
for vc_id in vc_members: |
| 1011 |
if vc_id in member_id: |
| 1012 |
_progress( |
| 1013 |
"installing software on VC member: {} ... please " |
| 1014 |
"be patient ...".format(vc_id) |
| 1015 |
) |
| 1016 |
bool_ret, msg = self.pkgadd( |
| 1017 |
remote_package, |
| 1018 |
vmhost=vmhost, |
| 1019 |
member=vc_id, |
| 1020 |
dev_timeout=timeout, |
| 1021 |
**kwargs |
| 1022 |
) |
| 1023 |
ok = ok[0] and bool_ret, ok[1] + "\n" + msg |
| 1024 |
return ok |
| 1025 |
elif self._multi_RE is False or all_re is False: |
| 1026 |
# simple case of single RE upgrade. |
| 1027 |
_progress("installing software ... please be patient ...") |
| 1028 |
add_ok = self.pkgadd( |
| 1029 |
remote_package, vmhost=vmhost, dev_timeout=timeout, **kwargs |
| 1030 |
) |
| 1031 |
return add_ok |
| 1032 |
else: |
| 1033 |
# we need to update multiple devices |
| 1034 |
if self._multi_VC is True: |
| 1035 |
ok = True, "" |
| 1036 |
# extract the VC number out of the _RE_list |
| 1037 |
vc_members = [ |
| 1038 |
re.search(r"(\d+)", x).group(1) |
| 1039 |
for x in self._RE_list |
| 1040 |
if re.search(r"(\d+)", x) |
| 1041 |
] |
| 1042 |
if self.dev.facts["vc_master"] in vc_members: |
| 1043 |
vc_members.remove(self.dev.facts["vc_master"]) |
| 1044 |
vc_members.insert(len(vc_members), self.dev.facts["vc_master"]) |
| 1045 |
for vc_id in vc_members: |
| 1046 |
_progress( |
| 1047 |
"installing software on VC member: {} ... please " |
| 1048 |
"be patient ...".format(vc_id) |
| 1049 |
) |
| 1050 |
bool_ret, msg = self.pkgadd( |
| 1051 |
remote_package, |
| 1052 |
vmhost=vmhost, |
| 1053 |
member=vc_id, |
| 1054 |
dev_timeout=timeout, |
| 1055 |
**kwargs |
| 1056 |
) |
| 1057 |
ok = ok[0] and bool_ret, ok[1] + "\n" + msg |
| 1058 |
return ok |
| 1059 |
else: |
| 1060 |
# For Dual RE device re0/re1 is not required |
| 1061 |
if self._dev.facts["_is_linux"]: |
| 1062 |
_progress("installing software ... please be patient ...") |
| 1063 |
ok = self.pkgadd( |
| 1064 |
remote_package, vmhost=vmhost, dev_timeout=timeout, **kwargs |
| 1065 |
) |
| 1066 |
else: |
| 1067 |
# then this is a device with two RE that supports the "re0" |
| 1068 |
# and "re1" options to the command (M, MX tested only) |
| 1069 |
_progress( |
| 1070 |
"installing software on RE0 ... please be patient ..." |
| 1071 |
) |
| 1072 |
ok = self.pkgadd( |
| 1073 |
remote_package, |
| 1074 |
vmhost=vmhost, |
| 1075 |
re0=True, |
| 1076 |
dev_timeout=timeout, |
| 1077 |
**kwargs |
| 1078 |
) |
| 1079 |
_progress( |
| 1080 |
"installing software on RE1 ... please be patient ..." |
| 1081 |
) |
| 1082 |
bool_ret, msg = self.pkgadd( |
| 1083 |
remote_package, |
| 1084 |
vmhost=vmhost, |
| 1085 |
re1=True, |
| 1086 |
dev_timeout=timeout, |
| 1087 |
**kwargs |
| 1088 |
) |
| 1089 |
ok = ok[0] and bool_ret, ok[1] + "\n" + msg |
| 1090 |
return ok |
| 1091 |
|
| 1092 |
elif len(remote_pkg_set) > 1 and self._mixed_VC: |
| 1093 |
_progress("installing software ... please be patient ...") |
| 1094 |
add_ok = self.pkgadd( |
| 1095 |
remote_pkg_set, vmhost=vmhost, dev_timeout=timeout, **kwargs |
| 1096 |
) |
| 1097 |
return add_ok |
| 1098 |
|
| 1099 |
def _system_operation( |
| 1100 |
self, |
| 1101 |
cmd, |
| 1102 |
in_min=0, |
| 1103 |
at=None, |
| 1104 |
all_re=True, |
| 1105 |
other_re=False, |
| 1106 |
vmhost=False, |
| 1107 |
member_id=None, |
| 1108 |
): |
| 1109 |
""" |
| 1110 |
Send the rpc for actions like shutdown, reboot, halt with optional |
| 1111 |
delay (in minutes) or at a specified date and time. |
| 1112 |
|
| 1113 |
:param int in_min: time (minutes) before rebooting/shutting down the device. |
| 1114 |
|
| 1115 |
:param str at: date and time the reboot should take place. The |
| 1116 |
string must match the junos cli reboot/poweroff/halt syntax |
| 1117 |
|
| 1118 |
:param bool all_re: In case of dual re or VC setup, function by default |
| 1119 |
will reboot/shutdown all. If all is False will only reboot/shutdown connected device |
| 1120 |
|
| 1121 |
:param str on_node: In case of linux based device, function will by default |
| 1122 |
reboot the whole device. If any specific node is mentioned, |
| 1123 |
reboot will be performed on mentioned node |
| 1124 |
|
| 1125 |
:param str other_re: If the system has dual Routing Engines and this option is C(true), |
| 1126 |
then the action is performed on the other REs in the system. |
| 1127 |
|
| 1128 |
:param bool vmhost: |
| 1129 |
(Optional) A boolean indicating to run 'request vmhost reboot'. |
| 1130 |
The default is ``vmhost=False``. |
| 1131 |
|
| 1132 |
:param list member_id: |
| 1133 |
(optional) install software on the specified members ids of VC. |
| 1134 |
The default is ``member_id=None``. |
| 1135 |
|
| 1136 |
:returns: |
| 1137 |
* rpc response message (string) if command successful |
| 1138 |
|
| 1139 |
:raises RpcError: when command is not successful. |
| 1140 |
""" |
| 1141 |
if other_re is True: |
| 1142 |
if self._dev.facts["2RE"]: |
| 1143 |
cmd.append(E("other-routing-engine")) |
| 1144 |
elif all_re is True: |
| 1145 |
if self._multi_RE is True and vmhost is True: |
| 1146 |
cmd.append(E("routing-engine", "both")) |
| 1147 |
elif self._multi_RE is True and self._multi_VC is False: |
| 1148 |
cmd.append(E("both-routing-engines")) |
| 1149 |
elif self._mixed_VC is True: |
| 1150 |
cmd.append(E("all-members")) |
| 1151 |
elif ( |
| 1152 |
self._multi_VC_nsync is True or self._multi_VC is True |
| 1153 |
) and member_id is not None: |
| 1154 |
cmd.append(E("member", str(member_id))) |
| 1155 |
if in_min >= 0 and at is None: |
| 1156 |
if vmhost is not True: |
| 1157 |
cmd.append(E("in", str(in_min))) |
| 1158 |
elif at is not None: |
| 1159 |
cmd.append(E("at", str(at))) |
| 1160 |
try: |
| 1161 |
rsp = self.rpc(cmd, ignore_warning=True, normalize=True) |
| 1162 |
if self._dev.facts["_is_linux"]: |
| 1163 |
got = rsp.text |
| 1164 |
else: |
| 1165 |
got = rsp.getparent().findtext(".//request-reboot-status") |
| 1166 |
if got is None: |
| 1167 |
# On some platforms stopping/rebooting |
| 1168 |
# REs produces <output> messages and |
| 1169 |
# <request-reboot-status> messages. |
| 1170 |
output_msg = "\n".join( |
| 1171 |
[ |
| 1172 |
i.text |
| 1173 |
for i in rsp.getparent().xpath("//output") |
| 1174 |
if i.text is not None |
| 1175 |
] |
| 1176 |
) |
| 1177 |
if output_msg != "": |
| 1178 |
got = output_msg |
| 1179 |
return got |
| 1180 |
except Exception as err: |
| 1181 |
raise err |
| 1182 |
|
| 1183 |
# ------------------------------------------------------------------------- |
| 1184 |
# reboot - system reboot |
| 1185 |
# ------------------------------------------------------------------------- |
| 1186 |
def reboot( |
| 1187 |
self, |
| 1188 |
in_min=0, |
| 1189 |
at=None, |
| 1190 |
all_re=True, |
| 1191 |
on_node=None, |
| 1192 |
vmhost=False, |
| 1193 |
other_re=False, |
| 1194 |
member_id=None, |
| 1195 |
): |
| 1196 |
""" |
| 1197 |
Perform a system reboot, with optional delay (in minutes) or at |
| 1198 |
a specified date and time. |
| 1199 |
|
| 1200 |
If the device is equipped with dual-RE, then both RE will be |
| 1201 |
rebooted. This code also handles EX/QFX VC. |
| 1202 |
|
| 1203 |
:param int in_min: time (minutes) before rebooting the device. |
| 1204 |
|
| 1205 |
:param str at: date and time the reboot should take place. The |
| 1206 |
string must match the junos cli reboot syntax |
| 1207 |
|
| 1208 |
:param bool all_re: In case of dual re or VC setup, function by default |
| 1209 |
will reboot all. If all is False will only reboot connected device |
| 1210 |
|
| 1211 |
:param str on_node: In case of linux based device, function will by default |
| 1212 |
reboot the whole device. If any specific node is mentioned, |
| 1213 |
reboot will be performed on mentioned node |
| 1214 |
|
| 1215 |
:param bool vmhost: |
| 1216 |
(Optional) A boolean indicating to run 'request vmhost reboot'. |
| 1217 |
The default is ``vmhost=False``. |
| 1218 |
|
| 1219 |
:param str other_re: If the system has dual Routing Engines and this option is C(true), |
| 1220 |
then the action is performed on the other REs in the system. |
| 1221 |
|
| 1222 |
:param list member_id: |
| 1223 |
(optional) install software on the specified members ids of VC. |
| 1224 |
The default is ``member_id=None``. |
| 1225 |
|
| 1226 |
:returns: |
| 1227 |
* reboot message (string) if command successful |
| 1228 |
""" |
| 1229 |
|
| 1230 |
if ( |
| 1231 |
self._multi_VC_nsync is True or self._multi_VC is True |
| 1232 |
) and member_id is not None: |
| 1233 |
vc_members = [ |
| 1234 |
re.search(r"(\d+)", x).group(1) |
| 1235 |
for x in self._RE_list |
| 1236 |
if re.search(r"(\d+)", x) |
| 1237 |
] |
| 1238 |
vc_members.remove(self.dev.facts["vc_master"]) |
| 1239 |
vc_members.insert(len(vc_members), self.dev.facts["vc_master"]) |
| 1240 |
|
| 1241 |
if self._dev.facts["_is_linux"]: |
| 1242 |
if on_node is None: |
| 1243 |
cmd = E("request-system-reboot") |
| 1244 |
else: |
| 1245 |
cmd = E("request-node-reboot") |
| 1246 |
cmd.append(E("node", on_node)) |
| 1247 |
elif vmhost is True: |
| 1248 |
cmd = E("request-vmhost-reboot") |
| 1249 |
else: |
| 1250 |
cmd = E("request-reboot") |
| 1251 |
|
| 1252 |
try: |
| 1253 |
if member_id is not None: |
| 1254 |
for m_id in member_id: |
| 1255 |
if m_id in vc_members: |
| 1256 |
return self._system_operation( |
| 1257 |
cmd, in_min, at, all_re, other_re, vmhost, member_id=m_id |
| 1258 |
) |
| 1259 |
else: |
| 1260 |
return self._system_operation(cmd, in_min, at, all_re, other_re, vmhost) |
| 1261 |
except RpcTimeoutError as err: |
| 1262 |
raise err |
| 1263 |
except Exception as err: |
| 1264 |
raise err |
| 1265 |
|
| 1266 |
# ------------------------------------------------------------------------- |
| 1267 |
# poweroff - system shutdown |
| 1268 |
# ------------------------------------------------------------------------- |
| 1269 |
def poweroff( |
| 1270 |
self, in_min=0, at=None, on_node=None, all_re=True, other_re=False, vmhost=False |
| 1271 |
): |
| 1272 |
""" |
| 1273 |
Perform a system shutdown, with optional delay (in minutes) . |
| 1274 |
|
| 1275 |
If the device is equipped with dual-RE, then both RE will be |
| 1276 |
shut down. This code also handles EX/QFX VC. |
| 1277 |
|
| 1278 |
:param int in_min: time (minutes) before shutting down the device. |
| 1279 |
|
| 1280 |
:param str at: date and time the poweroff should take place. The |
| 1281 |
string must match the junos cli poweroff syntax |
| 1282 |
|
| 1283 |
:param str on_node: In case of linux based device, function will by default |
| 1284 |
shutdown the whole device. If any specific node is mentioned, |
| 1285 |
shutdown will be performed on mentioned node |
| 1286 |
|
| 1287 |
:param bool all_re: In case of dual re or VC setup, function by default |
| 1288 |
will shutdown all. If all is False will only shutdown connected device |
| 1289 |
|
| 1290 |
:param str other_re: If the system has dual Routing Engines and this option is C(true), |
| 1291 |
then the action is performed on the other REs in the system. |
| 1292 |
|
| 1293 |
:param str vmhost: If the device is vmhost device then the shutdown will be performed on the device |
| 1294 |
|
| 1295 |
:returns: |
| 1296 |
* power-off message (string) if command successful |
| 1297 |
|
| 1298 |
:raises RpcError: when command is not successful. |
| 1299 |
|
| 1300 |
.. todo:: need to better handle the exception event. |
| 1301 |
""" |
| 1302 |
if self._dev.facts["_is_linux"]: |
| 1303 |
if on_node is None: |
| 1304 |
cmd = E("request-shutdown-power-off") |
| 1305 |
else: |
| 1306 |
cmd = E("request-node-power-off") |
| 1307 |
cmd.append(E("node", on_node)) |
| 1308 |
elif vmhost is True: |
| 1309 |
cmd = E("request-vmhost-poweroff") |
| 1310 |
all_re = False |
| 1311 |
else: |
| 1312 |
cmd = E("request-power-off") |
| 1313 |
try: |
| 1314 |
return self._system_operation(cmd, in_min, at, all_re, other_re, vmhost) |
| 1315 |
except Exception as err: |
| 1316 |
if err.rsp.findtext(".//error-severity") != "warning": |
| 1317 |
raise err |
| 1318 |
|
| 1319 |
# ------------------------------------------------------------------------- |
| 1320 |
# halt - system halt |
| 1321 |
# ------------------------------------------------------------------------- |
| 1322 |
def halt(self, in_min=0, at=None, all_re=True, other_re=False): |
| 1323 |
""" |
| 1324 |
Perform a system halt, with optional delay (in minutes) or at |
| 1325 |
a specified date and time. |
| 1326 |
|
| 1327 |
:param int in_min: time (minutes) before halting the device. |
| 1328 |
|
| 1329 |
:param str at: date and time the halt should take place. The |
| 1330 |
string must match the junos cli reboot syntax |
| 1331 |
|
| 1332 |
:param bool all_re: In case of dual re or VC setup, function by default |
| 1333 |
will halt all. If all is False will only halt connected device |
| 1334 |
|
| 1335 |
:param str other_re: If the system has dual Routing Engines and this option is C(true), |
| 1336 |
then the action is performed on the other REs in the system. |
| 1337 |
|
| 1338 |
:returns: |
| 1339 |
* rpc response message (string) if command successful |
| 1340 |
""" |
| 1341 |
if self._dev.facts["_is_linux"]: |
| 1342 |
cmd = E("request-shutdown-halt") |
| 1343 |
else: |
| 1344 |
cmd = E("request-halt") |
| 1345 |
|
| 1346 |
try: |
| 1347 |
return self._system_operation( |
| 1348 |
cmd, in_min, at, all_re, other_re, vmhost=False |
| 1349 |
) |
| 1350 |
except Exception as err: |
| 1351 |
raise err |
| 1352 |
|
| 1353 |
def zeroize(self, all_re=False, media=None): |
| 1354 |
""" |
| 1355 |
Restore the system (configuration, log files, etc.) to a |
| 1356 |
factory default state. This is the equivalent of the |
| 1357 |
C(request system zeroize) CLI command. |
| 1358 |
|
| 1359 |
:param bool all_re: In case of dual re or VC setup, function by default |
| 1360 |
will halt all. If all is False will only halt connected device |
| 1361 |
|
| 1362 |
:param str media: Overwrite media when performing the zeroize operation. |
| 1363 |
|
| 1364 |
:returns: |
| 1365 |
* rpc response message (string) if command successful |
| 1366 |
""" |
| 1367 |
cmd = E("request-system-zeroize") |
| 1368 |
if all_re is False: |
| 1369 |
if self._dev.facts["2RE"]: |
| 1370 |
cmd = E("local") |
| 1371 |
if media is True: |
| 1372 |
cmd = E("media") |
| 1373 |
|
| 1374 |
# initialize an empty output message |
| 1375 |
output_msg = "" |
| 1376 |
|
| 1377 |
try: |
| 1378 |
# For zeroize we don't get a response similar to reboot, shutdown. |
| 1379 |
# The response may come as a warning message only. |
| 1380 |
# Code is added here to extract the warning message and append it. |
| 1381 |
# Don't pass ignore warning true and handle the warning here. |
| 1382 |
rsp = self.rpc(cmd, normalize=True) |
| 1383 |
except RpcError as ex: |
| 1384 |
if hasattr(ex, "xml"): |
| 1385 |
if hasattr(ex, "errs"): |
| 1386 |
errors = ex.errs |
| 1387 |
else: |
| 1388 |
errors = [ex] |
| 1389 |
for err in errors: |
| 1390 |
if err.get("severity", "") != "warning": |
| 1391 |
# Not a warning (probably an error). |
| 1392 |
raise ex |
| 1393 |
output_msg += err.get("message", "") + "\n" |
| 1394 |
rsp = ex.xml.getroottree().getroot() |
| 1395 |
# 1) A normal response has been run through the XSLT |
| 1396 |
# transformation, but ex.xml has not. Do that now. |
| 1397 |
encode = None if sys.version < "3" else "unicode" |
| 1398 |
rsp = NCElement( |
| 1399 |
etree.tostring(rsp, encoding=encode), self._dev.transform() |
| 1400 |
)._NCElement__doc |
| 1401 |
# 2) Now remove all of the <rpc-error> elements from |
| 1402 |
# the response. We've already confirmed they are all warnings |
| 1403 |
rsp = etree.fromstring(str(JXML.strip_rpc_error_transform(rsp))) |
| 1404 |
else: |
| 1405 |
# ignore_warning was false, or an RPCError which doesn't have |
| 1406 |
# an XML attribute. Raise it up for the caller to deal with. |
| 1407 |
raise ex |
| 1408 |
except Exception as err: |
| 1409 |
raise err |
| 1410 |
|
| 1411 |
# safety check added in case the rpc-reply for zeroize doesn't have message |
| 1412 |
# This scenario is not expected. |
| 1413 |
if isinstance(rsp, bool): |
| 1414 |
return "zeroize initiated with no message" |
| 1415 |
|
| 1416 |
output_msg += "\n".join( |
| 1417 |
[i.text for i in rsp.xpath("//message") if i.text is not None] |
| 1418 |
) |
| 1419 |
return output_msg |
| 1420 |
|
| 1421 |
# ------------------------------------------------------------------------- |
| 1422 |
# rollback - clears the install request |
| 1423 |
# ------------------------------------------------------------------------- |
| 1424 |
|
| 1425 |
def rollback(self): |
| 1426 |
""" |
| 1427 |
Issues the 'request' command to do the rollback and returns the string |
| 1428 |
output of the results. |
| 1429 |
|
| 1430 |
:returns: |
| 1431 |
Rollback results (str) |
| 1432 |
""" |
| 1433 |
rsp = self.rpc.request_package_rollback() |
| 1434 |
fail_list = ["Cannot rollback", "rollback aborted"] |
| 1435 |
multi = rsp.xpath("//multi-routing-engine-item") |
| 1436 |
if multi: |
| 1437 |
rsp = {} |
| 1438 |
for x in multi: |
| 1439 |
re = x.findtext("re-name") |
| 1440 |
output = x.findtext("output") |
| 1441 |
if any(x in output for x in fail_list): |
| 1442 |
raise SwRollbackError(re=re, rsp=output) |
| 1443 |
else: |
| 1444 |
rsp[re] = output |
| 1445 |
return str(rsp) |
| 1446 |
else: |
| 1447 |
output = rsp.xpath("//output")[0].text |
| 1448 |
if any(x in output for x in fail_list): |
| 1449 |
raise SwRollbackError(rsp=output) |
| 1450 |
else: |
| 1451 |
return output |
| 1452 |
|
| 1453 |
# ------------------------------------------------------------------------- |
| 1454 |
# inventory - file info on current and rollback packages |
| 1455 |
# ------------------------------------------------------------------------- |
| 1456 |
|
| 1457 |
@property |
| 1458 |
def inventory(self): |
| 1459 |
""" |
| 1460 |
Returns dictionary of file listing information for current and rollback |
| 1461 |
Junos install packages. This information comes from the /packages |
| 1462 |
directory. |
| 1463 |
|
| 1464 |
.. warning:: Experimental method; may not work on all platforms. If |
| 1465 |
you find this not working, please report issue. |
| 1466 |
""" |
| 1467 |
from jnpr.junos.utils.fs import FS |
| 1468 |
|
| 1469 |
fs = FS(self.dev) |
| 1470 |
pkgs = fs.ls("/packages") |
| 1471 |
return dict( |
| 1472 |
current=pkgs["files"].get("junos"), rollback=pkgs["files"].get("junos.old") |
| 1473 |
) |