Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
abstract,
default_dir,
copy_to_standby=False):
''' Save current configuration to a checkpoint file '''
if method == 'checkpoint' or method == 'config_replace':
# Create unique filename
self.to_url = self.__class__.__name__ + time.ctime().\
replace(' ', '_').\
replace(':', '_')
# Save configuration
self.create_checkpoint_file(device=device, file=self.to_url)
# Instantiate a filetransferutils instance for JunOS device
self.filetransfer = FileUtils.from_device(device)
# Verify checkpoint file exists
if self.to_url in self.filetransfer.dir(target=self.to_url,
device=device):
log.info("Successfully created checkpoint/file '{}'".
format(self.to_url))
else:
raise Exception("Unable to create checkpoint/file '{}'".
format(self.to_url))
# Return filename generated to caller
return self.to_url
else:
raise NotImplementedError("save configuration using method '{}'".
format(method))
except Exception as e:
log.error(e)
if i == iteration - 1:
raise Exception(
'Unable to load override configuration')
else:
log.info('Load override configuration failed:\n'
'sleeping {} seconds and retrying...'.
format(interval))
time.sleep(interval)
else:
log.info('Load override configuration passed')
break
# Instantiate a filetransferutils instance for JunOS device
self.filetransfer = FileUtils.from_device(device)
# Compare restored configuration to details in file
if compare:
log.info("Comparing current configuration with load override file")
exclude_failed = False
# Keys to exclude
exclude = r'(.*Last changed.*)|(.*Last commit.*)|(.*1c1.*)|(.*\-.*)'
if compare_exclude:
if isinstance(compare_exclude, str):
exclude += '|{}'.format(compare_exclude)
else:
for item in compare_exclude:
exclude += '|{}'.format(compare_exclude)
"""Prepare the device for ISSU:
1. Check currect image version and upgrade image version
2. Copy upgrade image to standby RP
Raises:
Unicon errors
Exception
Example:
>>> _prepare_issu(steps=steps, upgrade_image='someimage')
"""
# Init
device = self.device
filetransfer = FileUtils.from_device(device)
if not device.filetransfer_attributes['protocol']:
raise Exception("Unable to continue ISSU process, file transfer "
"'protocol' is missing. Check the testbed yaml file and the "
"provided arguments.")
for disk in ['harddisk:', 'stby-harddisk:']:
# Check for space on RP and SRP
logger.info("Verify '{}' has enough space".format(disk))
try:
self.check_disk_space(device=device, disk=disk,
image=upgrade_image)
except Exception as e:
raise Exception("FAIL: Device '{}' does not have enough space -"
" skipping ISSU".format(disk))
required_space ('int'): required total disk space (Optional)
directory ('str'): directory to check file size (Optional)
timeout('int'): timeout in seconds (Optional, default 300)
fu_session ('obj'): existing FileUtils object to reuse (Optional)
Returns:
True if enough space, False otherwise
"""
if fu_session:
return _verify_enough_server_disk_space(device, protocol, server=server,
directory=directory,
required_space=required_space,
timeout=timeout,
fu_session=fu_session)
else:
with FileUtils(testbed=device.testbed) as fu:
return _verify_enough_server_disk_space(device, protocol, server=server,
directory=directory,
required_space=required_space,
timeout=timeout,
fu_session=fu)
servers = self.device.testbed.servers
# Check if there is a self.protocol server
if self.protocol not in servers:
raise Exception("'{p}' server missing in the testbed "
"yaml file".format(p=self.protocol))
# Find ip
ip = servers[self.protocol]['address']
port = servers[self.protocol].get('custom', {}).get('port', 22)
local_file = os.path.join(self.local_dir,
os.path.basename(self.pcap_file))
# Create directory if doesnt exists
os.makedirs(self.local_dir, exist_ok=True)
with FileUtils(testbed=self.device.testbed) as futils:
futils.get_child(self.protocol)
futils.children[self.protocol].SSH_DEFAULT_PORT = port
futils.copyfile(
source = '{p}://{i}/{path}'.format(p=self.protocol, i=ip,
path=self.pcap_file),
destination = self.local_dir)
return output
12. Execute 'issu commitversion' to complete ISSU process
13. Reload the device and then reconnect to it
14. Verify device is now booted with ISSU upgrade image
Raises:
Unicon errors
Exception
Example:
>>> _perform_issu(steps=steps, upgrade_image='someimage')
"""
# Init
device = self.device
lookup = Lookup.from_device(device)
filetransfer = FileUtils.from_device(device)
image_name = basename(upgrade_image)
# ======================================================================
# Get standby RP
# ======================================================================
with steps.start("Get standby RP information", continue_=True) as step:
platform_dict = lookup.parser.show_platform.\
ShowPlatform(device=device).parse()
# Standby RP
rs = R(['slot', '(?P.*)', 'rp', '(?P.*)', 'state', 'ok, standby'])
ret = find([platform_dict], rs, filter_=False, all_keys=True)
if not ret:
raise Exception("Device '{}' does not have standby RP - cannot "
"perform ISSU".format(device.name))
standby_rp = ret[0][1][1]
srp = re.search('(?P(\d))', standby_rp).groupdict()['srp']
expected_images=expected_num_images):
log.error(banner("*** Terminating Genie Clean ***"))
section.failed("Incorrect number of images provided. Please "
"provide {} expected image(s) under destination"
".path in clean yaml file.\n".format(
expected_num_images), goto=['exit'])
else:
step.passed("Correct number of images provided")
# Init
success_copy_ha = False
files_to_copy = {}
unknown_size = False
# Establish FileUtils session for all FileUtils operations
file_utils = FileUtils(testbed=device.testbed)
# Execute 'dir' before copying image files
log.info(banner("Executing 'dir {}' before copying image files".\
format(destination_act)))
dir_before = device.execute('dir {}'.format(destination_act))
# Loop over all image files provided by user
for file in image_files:
# Get filesize of image files on remote server
with steps.start("Get filesize of '{}' on remote server '{}'".\
format(file, server)) as step:
try:
file_size = device.api.get_file_size_from_server(
server=server,
path=file,
protocol=protocol,
except (KeyError, AttributeError):
log.error(banner("*** Terminating Genie Clean ***"))
section.failed("Server '{}' was provided in the clean yaml file "
"but doesn't exist in the testbed file".\
format(server_from), goto=['exit'])
try:
# Connect to the server
server_from_obj.connect()
except Exception as e:
log.error(banner("*** Terminating Genie Clean ***"))
section.failed('Failed to connect to {} due to {}'.\
format(server_from_obj.name, str(e)), goto=['exit'])
# establish a FileUtils session for all FileUtils operations
fu = FileUtils(testbed=device.testbed)
files_to_copy = {}
with steps.start("Collecting file info on origin and '{d}' "
"before copy".format(d=destination_hostname or dest_dir)) as step:
file_size = -1
for file in origin_path:
with step.start("Collecting '{f}' info".format(f=file)) as substep:
# file to copy is remote
if server_from:
try:
log.info(
"Getting size of the file '{}' from file server '{}'".format(
file, server_from))
file_size = device.api.get_file_size_from_server(server=server_from,
path=file,
protocol=protocol,
Raises:
Exception
"""
if fu_session:
_copy_to_server(protocol,
server,
local_path,
remote_path,
timeout=timeout,
fu_session=fu_session,
quiet=quiet)
else:
with FileUtils(testbed=testbed) as fu:
_copy_to_server(protocol,
server,
local_path,
remote_path,
timeout=timeout,
fu_session=fu,
quiet=quiet)
size ('int'): expected file size in bytes, if not provided will only check
file existence with name (Optional)
timeout('int'): timeout in seconds (Optional)
fu_session ('obj'): existing FileUtils object to reuse (Optional)
max_tries ('int;): max number of attempts (Optional)
Returns:
True if enough space, false otherwise
"""
# global session
if fu_session:
return _verify_file_exists_on_server(device, protocol, file, server=server, size=size,
timeout=timeout, fu_session=fu_session, max_tries=max_tries)
# no global session, establish a local one
else:
with FileUtils(testbed=device.testbed) as fu:
return _verify_file_exists_on_server(device, protocol, file, server=server, size=size,
timeout=timeout, fu_session=fu, max_tries=max_tries)