code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
speed = set()
smart_resource = _get_attribute_value_of(system_obj, 'smart_storage')
if smart_resource is not None:
speed.update(_get_attribute_value_of(
smart_resource, 'drive_rotational_speed_rpm', default=set()))
storage_resource = _get_attribute_value_of(system_obj, 'storages')
if storage_resource is not None:
speed.update(_get_attribute_value_of(
storage_resource, 'drive_rotational_speed_rpm', default=set()))
return speed | def get_drive_rotational_speed_rpm(system_obj) | Gets the set of rotational speed rpms of the disks.
:param system_obj: The HPESystem object.
:returns the set of rotational speed rpms of the HDD devices. | 2.665745 | 2.63101 | 1.013202 |
target_raid_config = node.get('target_raid_config', {}).copy()
return hpssa_manager.create_configuration(
raid_config=target_raid_config) | def create_configuration(self, node, ports) | Create RAID configuration on the bare metal.
This method creates the desired RAID configuration as read from
node['target_raid_config'].
:param node: A dictionary of the node object
:param ports: A list of dictionaries containing information of ports
for the node
:returns: The current RAID configuration of the below format.
raid_config = {
'logical_disks': [{
'size_gb': 100,
'raid_level': 1,
'physical_disks': [
'5I:0:1',
'5I:0:2'],
'controller': 'Smart array controller'
},
]
} | 7.562334 | 5.360153 | 1.410843 |
result = {}
result['Disk Erase Status'] = hpssa_manager.erase_devices()
result.update(super(ProliantHardwareManager,
self).erase_devices(node, port))
return result | def erase_devices(self, node, port) | Erase the drives on the bare metal.
This method erase all the drives which supports sanitize and the drives
which are not part of any logical volume on the bare metal. It calls
generic erase method after the success of Sanitize disk erase.
:param node: A dictionary of the node object.
:param port: A list of dictionaries containing information of ports
for the node.
:raises exception.HPSSAOperationError, if there is a failure on the
erase operation on the controllers.
:returns: The dictionary of controllers with the drives and erase
status for each drive. | 10.771968 | 8.888921 | 1.211842 |
self.model = model
if 'G7' in self.model:
self.MEMORY_SIZE_TAG = "MEMORY_SIZE"
self.MEMORY_SIZE_NOT_PRESENT_TAG = "Not Installed"
self.NIC_INFORMATION_TAG = "NIC_INFOMATION"
else:
self.MEMORY_SIZE_TAG = "TOTAL_MEMORY_SIZE"
self.MEMORY_SIZE_NOT_PRESENT_TAG = "N/A"
self.NIC_INFORMATION_TAG = "NIC_INFORMATION" | def init_model_based_tags(self, model) | Initializing the model based memory and NIC information tags.
It should be called just after instantiating a RIBCL object.
ribcl = ribcl.RIBCLOperations(host, login, password, timeout,
port, cacert=cacert)
model = ribcl.get_product_name()
ribcl.init_model_based_tags(model)
Again, model attribute is also set here on the RIBCL object.
:param model: the model string | 4.290567 | 3.12448 | 1.37321 |
if self.port:
urlstr = 'https://%s:%d/ribcl' % (self.host, self.port)
else:
urlstr = 'https://%s/ribcl' % (self.host)
xml = self._serialize_xml(root)
headers = {"Content-length": str(len(xml))}
if extra_headers:
headers.update(extra_headers)
kwargs = {'headers': headers, 'data': xml}
if self.cacert is not None:
kwargs['verify'] = self.cacert
else:
kwargs['verify'] = False
try:
LOG.debug(self._("POST %(url)s with request data: "
"%(request_data)s"),
{'url': urlstr,
'request_data': MaskedRequestData(kwargs)})
response = requests.post(urlstr, **kwargs)
response.raise_for_status()
except Exception as e:
LOG.debug(self._("Unable to connect to iLO. %s"), e)
raise exception.IloConnectionError(e)
return response.text | def _request_ilo(self, root, extra_headers=None) | Send RIBCL XML data to iLO.
This function sends the XML request to the ILO and
receives the output from ILO.
:raises: IloConnectionError() if unable to send the request. | 2.652437 | 2.561337 | 1.035568 |
root = etree.Element('RIBCL', VERSION="2.0")
login = etree.SubElement(
root, 'LOGIN', USER_LOGIN=self.login, PASSWORD=self.password)
tagname = etree.SubElement(login, tag_name, MODE=mode)
subelements = subelements or {}
etree.SubElement(tagname, cmdname)
if six.PY2:
root_iterator = root.getiterator(cmdname)
else:
root_iterator = root.iter(cmdname)
for cmd in root_iterator:
for key, value in subelements.items():
cmd.set(key, value)
return root | def _create_dynamic_xml(self, cmdname, tag_name, mode, subelements=None) | Create RIBCL XML to send to iLO.
This function creates the dynamic xml required to be sent
to the ILO for all the APIs.
:param cmdname: the API which needs to be implemented.
:param tag_name: the tag info under which ILO has defined
the particular API.
:param mode: 'read' or 'write'
:param subelements: dictionary containing subelements of the
particular API tree.
:returns: the etree.Element for the root of the RIBCL XML | 3.439774 | 3.320865 | 1.035807 |
if hasattr(etree, 'tostringlist'):
if six.PY3:
xml_content_list = [
x.decode("utf-8") for x in etree.tostringlist(root)]
else:
xml_content_list = etree.tostringlist(root)
xml = '\r\n'.join(xml_content_list) + '\r\n'
else:
if six.PY3:
xml_content = etree.tostring(root).decode("utf-8")
else:
xml_content = etree.tostring(root)
xml = xml_content + '\r\n'
return xml | def _serialize_xml(self, root) | Serialize XML data into string
It serializes the dynamic xml created and converts
it to a string. This is done before sending the
xml to the ILO.
:param root: root of the dynamic xml. | 2.107857 | 2.2135 | 0.952273 |
count = 0
xml_dict = {}
resp_message = None
xml_start_pos = []
for m in re.finditer(r"\<\?xml", xml_response):
xml_start_pos.append(m.start())
while count < len(xml_start_pos):
if (count == len(xml_start_pos) - 1):
result = xml_response[xml_start_pos[count]:]
else:
start = xml_start_pos[count]
end = xml_start_pos[count + 1]
result = xml_response[start:end]
result = result.strip()
message = etree.fromstring(result)
resp = self._validate_message(message)
if hasattr(resp, 'tag'):
xml_dict = self._elementtree_to_dict(resp)
elif resp is not None:
resp_message = resp
count = count + 1
if xml_dict:
return xml_dict
elif resp_message is not None:
return resp_message | def _parse_output(self, xml_response) | Parse the response XML from iLO.
This function parses the output received from ILO.
As the output contains multiple XMLs, it extracts
one xml at a time and loops over till all the xmls
in the response are exhausted.
It returns the data to APIs either in dictionary
format or as the string.
It creates the dictionary only if the Ilo response
contains the data under the requested RIBCL command.
If the Ilo response contains only the string,
then the string is returned back. | 2.536025 | 2.455789 | 1.032672 |
node = {}
text = getattr(element, 'text')
if text is not None:
text = text.strip()
if len(text) != 0:
node['text'] = text
node.update(element.items()) # element's attributes
child_nodes = {}
for child in element: # element's children
child_nodes.setdefault(child.tag, []).append(
self._elementtree_to_dict(child))
# convert all single-element lists into non-lists
for key, value in child_nodes.items():
if len(value) == 1:
child_nodes[key] = value[0]
node.update(child_nodes.items())
return node | def _elementtree_to_dict(self, element) | Convert XML elementtree to dictionary.
Converts the actual response from the ILO for an API
to the dictionary. | 2.431446 | 2.560642 | 0.949545 |
if message.tag != 'RIBCL':
# the true case shall be unreachable for response
# XML from Ilo as all messages are tagged with RIBCL
# but still raise an exception if any invalid
# XML response is returned by Ilo. Set status to some
# arbitary non-zero value.
status = -1
raise exception.IloClientInternalError(message, status)
for child in message:
if child.tag != 'RESPONSE':
return message
status = int(child.get('STATUS'), 16)
msg = child.get('MESSAGE')
if status == 0 and msg != 'No error':
return msg
if status != 0:
if 'syntax error' in msg or 'Feature not supported' in msg:
for cmd in BOOT_MODE_CMDS:
if cmd in msg:
platform = self.get_product_name()
msg = ("%(cmd)s is not supported on %(platform)s" %
{'cmd': cmd, 'platform': platform})
LOG.debug(self._("Got invalid response with "
"message: '%(message)s'"),
{'message': msg})
raise (exception.IloCommandNotSupportedError
(msg, status))
else:
LOG.debug(self._("Got invalid response with "
"message: '%(message)s'"),
{'message': msg})
raise exception.IloClientInternalError(msg, status)
if (status in exception.IloLoginFailError.statuses or
msg in exception.IloLoginFailError.messages):
LOG.debug(self._("Got invalid response with "
"message: '%(message)s'"),
{'message': msg})
raise exception.IloLoginFailError(msg, status)
LOG.debug(self._("Got invalid response with "
"message: '%(message)s'"),
{'message': msg})
raise exception.IloError(msg, status) | def _validate_message(self, message) | Validate XML response from iLO.
This function validates the XML response to see
if the exit status is 0 or not in the response.
If the status is non-zero it raises exception. | 3.90523 | 3.588061 | 1.088396 |
xml = self._create_dynamic_xml(
create_command, tag_info, mode, dic)
d = self._request_ilo(xml)
data = self._parse_output(d)
LOG.debug(self._("Received response data: %s"), data)
return data | def _execute_command(self, create_command, tag_info, mode, dic={}) | Execute a command on the iLO.
Common infrastructure used by all APIs to send/get
response from ILO. | 6.179465 | 5.293906 | 1.167279 |
data = self._execute_command('GET_ALL_LICENSES', 'RIB_INFO', 'read')
d = {}
for key, val in data['GET_ALL_LICENSES']['LICENSE'].items():
if isinstance(val, dict):
d[key] = data['GET_ALL_LICENSES']['LICENSE'][key]['VALUE']
return d | def get_all_licenses(self) | Retrieve license type, key, installation date, etc. | 5.171616 | 4.589346 | 1.126874 |
dic = {'DEVICE': device.upper()}
data = self._execute_command(
'GET_VM_STATUS', 'RIB_INFO', 'read', dic)
return data['GET_VM_STATUS'] | def get_vm_status(self, device='FLOPPY') | Returns the virtual media drive status. | 8.7918 | 8.33034 | 1.055395 |
if power.upper() in POWER_STATE:
dic = {'HOST_POWER': POWER_STATE[power.upper()]}
data = self._execute_command(
'SET_HOST_POWER', 'SERVER_INFO', 'write', dic)
return data
else:
raise exception.IloInvalidInputError(
"Invalid input. The expected input is ON or OFF.") | def set_host_power(self, power) | Toggle the power button of server.
:param power: 'ON' or 'OFF' | 5.834716 | 6.124362 | 0.952706 |
dic = {'value': value}
data = self._execute_command(
'SET_ONE_TIME_BOOT', 'SERVER_INFO', 'write', dic)
return data | def set_one_time_boot(self, value) | Configures a single boot from a specific device.
:param value: specific device to which the boot option is set | 8.308424 | 11.130939 | 0.746426 |
dic = {
'DEVICE': device.upper(),
'IMAGE_URL': url,
}
data = self._execute_command(
'INSERT_VIRTUAL_MEDIA', 'RIB_INFO', 'write', dic)
return data | def insert_virtual_media(self, url, device='FLOPPY') | Notifies iLO of the location of a virtual media diskette image. | 7.456283 | 6.945449 | 1.073549 |
vm_status = self.get_vm_status(device=device)
if vm_status['IMAGE_INSERTED'] == 'NO':
return
dic = {'DEVICE': device.upper()}
self._execute_command(
'EJECT_VIRTUAL_MEDIA', 'RIB_INFO', 'write', dic) | def eject_virtual_media(self, device='FLOPPY') | Ejects the Virtual Media image if one is inserted. | 7.366001 | 6.471495 | 1.138222 |
dic = {'DEVICE': device.upper()}
xml = self._create_dynamic_xml(
'SET_VM_STATUS', 'RIB_INFO', 'write', dic)
if six.PY2:
child_iterator = xml.getiterator()
else:
child_iterator = xml.iter()
for child in child_iterator:
if child.tag == 'SET_VM_STATUS':
etree.SubElement(child, 'VM_BOOT_OPTION',
VALUE=boot_option.upper())
etree.SubElement(child, 'VM_WRITE_PROTECT',
VALUE=write_protect.upper())
d = self._request_ilo(xml)
data = self._parse_output(d)
return data | def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES') | Sets the Virtual Media drive status
It also allows the boot options for booting from the virtual media. | 3.651653 | 3.7729 | 0.967864 |
data = self._execute_command(
'GET_SUPPORTED_BOOT_MODE', 'SERVER_INFO', 'read')
supported_boot_mode = (
data['GET_SUPPORTED_BOOT_MODE']['SUPPORTED_BOOT_MODE']['VALUE'])
return mappings.GET_SUPPORTED_BOOT_MODE_RIBCL_MAP.get(
supported_boot_mode) | def get_supported_boot_mode(self) | Retrieves the supported boot mode.
:returns: any one of the following proliantutils.ilo.constants:
SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY,
SUPPORTED_BOOT_MODE_UEFI_ONLY,
SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI | 5.674537 | 5.862619 | 0.967918 |
dic = {'value': value}
data = self._execute_command(
'SET_PENDING_BOOT_MODE', 'SERVER_INFO', 'write', dic)
return data | def set_pending_boot_mode(self, value) | Configures the boot mode of the system from a specific boot mode. | 8.198041 | 8.932975 | 0.917728 |
result = self._get_persistent_boot()
boot_mode = self._check_boot_mode(result)
if boot_mode == 'bios':
return result[0]['value']
value = result[0]['DESCRIPTION']
if 'HP iLO Virtual USB CD' in value:
return 'CDROM'
elif 'NIC' in value or 'PXE' in value:
return 'NETWORK'
elif common.isDisk(value):
return 'HDD'
else:
return None | def get_persistent_boot_device(self) | Get the current persistent boot device set for the host. | 5.719588 | 5.554293 | 1.02976 |
xml = self._create_dynamic_xml(
'SET_PERSISTENT_BOOT', 'SERVER_INFO', 'write')
if six.PY2:
child_iterator = xml.getiterator()
else:
child_iterator = xml.iter()
for child in child_iterator:
for val in values:
if child.tag == 'SET_PERSISTENT_BOOT':
etree.SubElement(child, 'DEVICE', VALUE=val)
d = self._request_ilo(xml)
data = self._parse_output(d)
return data | def _set_persistent_boot(self, values=[]) | Configures a boot from a specific device. | 4.73408 | 4.490385 | 1.05427 |
urlstr = 'https://%s/xmldata?item=all' % (self.host)
kwargs = {}
if self.cacert is not None:
kwargs['verify'] = self.cacert
else:
kwargs['verify'] = False
try:
response = requests.get(urlstr, **kwargs)
response.raise_for_status()
except Exception as e:
raise IloConnectionError(e)
return response.text | def _request_host(self) | Request host info from the server. | 3.430484 | 3.235267 | 1.06034 |
xml = self._request_host()
root = etree.fromstring(xml)
data = self._elementtree_to_dict(root)
return data['HSI']['SPN']['text'], data['HSI']['cUUID']['text'] | def get_host_uuid(self) | Request host UUID of the server.
:returns: the host UUID of the server
:raises: IloConnectionError if failed connecting to the iLO. | 8.559541 | 10.18975 | 0.840015 |
if not data or data and "GET_EMBEDDED_HEALTH_DATA" not in data:
data = self._execute_command(
'GET_EMBEDDED_HEALTH', 'SERVER_INFO', 'read')
return data | def get_host_health_data(self, data=None) | Request host health data of the server.
:param: the data to retrieve from the server, defaults to None.
:returns: the dictionary containing the embedded health data.
:raises: IloConnectionError if failed connecting to the iLO.
:raises: IloError, on an error from iLO. | 8.388124 | 8.18226 | 1.02516 |
data = self.get_host_health_data(data)
d = (data['GET_EMBEDDED_HEALTH_DATA']['POWER_SUPPLIES']['SUPPLY'])
if not isinstance(d, list):
d = [d]
return d | def get_host_health_power_supplies(self, data=None) | Request the health power supply information.
:param: the data to retrieve from the server, defaults to None.
:returns: the dictionary containing the power supply information.
:raises: IloConnectionError if failed connecting to the iLO.
:raises: IloError, on an error from iLO. | 4.943375 | 5.798186 | 0.852573 |
data = self.get_host_health_data(data)
d = data['GET_EMBEDDED_HEALTH_DATA']['TEMPERATURE']['TEMP']
if not isinstance(d, list):
d = [d]
return d | def get_host_health_temperature_sensors(self, data=None) | Get the health Temp Sensor report.
:param: the data to retrieve from the server, defaults to None.
:returns: the dictionary containing the temperature sensors
information.
:raises: IloConnectionError if failed connecting to the iLO.
:raises: IloError, on an error from iLO. | 4.917251 | 5.584698 | 0.880487 |
data = self.get_host_health_data(data)
d = data['GET_EMBEDDED_HEALTH_DATA']['FANS']['FAN']
if not isinstance(d, list):
d = [d]
return d | def get_host_health_fan_sensors(self, data=None) | Get the health Fan Sensor Report.
:param: the data to retrieve from the server, defaults to None.
:returns: the dictionary containing the fan sensor information.
:raises: IloConnectionError if failed connecting to the iLO.
:raises: IloError, on an error from iLO. | 4.964323 | 5.71892 | 0.868052 |
dic = {'USER_LOGIN': self.login}
root = self._create_dynamic_xml(
'MOD_USER', 'USER_INFO', 'write', dic)
element = root.find('LOGIN/USER_INFO/MOD_USER')
etree.SubElement(element, 'PASSWORD', VALUE=password)
d = self._request_ilo(root)
self._parse_output(d) | def reset_ilo_credential(self, password) | Resets the iLO password.
:param password: The password to be set.
:raises: IloError, if account not found or on an error from iLO. | 7.924766 | 8.245378 | 0.961116 |
data = self.get_host_health_data()
properties = {
'memory_mb': self._parse_memory_embedded_health(data)
}
cpus, cpu_arch = self._parse_processor_embedded_health(data)
properties['cpus'] = cpus
properties['cpu_arch'] = cpu_arch
properties['local_gb'] = self._parse_storage_embedded_health(data)
macs = self._parse_nics_embedded_health(data)
return_value = {'properties': properties, 'macs': macs}
return return_value | def get_essential_properties(self) | Gets essential scheduling properties as required by ironic
:returns: a dictionary of server properties like memory size,
disk size, number of cpus, cpu arch, port numbers
and mac addresses.
:raises:IloError if iLO returns an error in command execution. | 3.758863 | 3.016068 | 1.246279 |
capabilities = {}
data = self.get_host_health_data()
ilo_firmware = self._get_ilo_firmware_version(data)
if ilo_firmware:
capabilities.update(ilo_firmware)
rom_firmware = self._get_rom_firmware_version(data)
if rom_firmware:
capabilities.update(rom_firmware)
capabilities.update({'server_model': self.get_product_name()})
capabilities.update(self._get_number_of_gpu_devices_connected(data))
boot_modes = common.get_supported_boot_modes(
self.get_supported_boot_mode())
capabilities.update({
'boot_mode_bios': boot_modes.boot_mode_bios,
'boot_mode_uefi': boot_modes.boot_mode_uefi})
return capabilities | def get_server_capabilities(self) | Gets server properties which can be used for scheduling
:returns: a dictionary of hardware properties like firmware
versions, server model.
:raises: IloError, if iLO returns an error in command execution. | 3.154894 | 3.087809 | 1.021726 |
memory_mb = 0
memory = self._get_memory_details_value_based_on_model(data)
if memory is None:
msg = "Unable to get memory data. Error: Data missing"
raise exception.IloError(msg)
total_memory_size = 0
for memory_item in memory:
memsize = memory_item[self.MEMORY_SIZE_TAG]["VALUE"]
if memsize != self.MEMORY_SIZE_NOT_PRESENT_TAG:
memory_bytes = (
strutils.string_to_bytes(
memsize.replace(' ', ''), return_int=True))
memory_mb = int(memory_bytes / (1024 * 1024))
total_memory_size = total_memory_size + memory_mb
return total_memory_size | def _parse_memory_embedded_health(self, data) | Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: memory size in MB.
:raises IloError, if unable to get the memory details. | 4.404214 | 4.084002 | 1.078407 |
processor = self.get_value_as_list((data['GET_EMBEDDED_HEALTH_DATA']
['PROCESSORS']), 'PROCESSOR')
if processor is None:
msg = "Unable to get cpu data. Error: Data missing"
raise exception.IloError(msg)
cpus = 0
for proc in processor:
for val in proc.values():
processor_detail = val['VALUE']
proc_core_threads = processor_detail.split('; ')
for x in proc_core_threads:
if "thread" in x:
v = x.split()
try:
cpus = cpus + int(v[0])
except ValueError:
msg = ("Unable to get cpu data. "
"The Value %s returned couldn't be "
"manipulated to get number of "
"actual processors" % processor_detail)
raise exception.IloError(msg)
cpu_arch = 'x86_64'
return cpus, cpu_arch | def _parse_processor_embedded_health(self, data) | Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: processor details like cpu arch and number of cpus. | 4.875863 | 4.737054 | 1.029303 |
local_gb = 0
storage = self.get_value_as_list(data['GET_EMBEDDED_HEALTH_DATA'],
'STORAGE')
if storage is None:
# We dont raise exception because this dictionary
# is available only when RAID is configured.
# If we raise error here then we will always fail
# inspection where this module is consumed. Hence
# as a workaround just return 0.
return local_gb
minimum = local_gb
for item in storage:
cntlr = self.get_value_as_list(item, 'CONTROLLER')
if cntlr is None:
continue
for s in cntlr:
drive = self.get_value_as_list(s, 'LOGICAL_DRIVE')
if drive is None:
continue
for item in drive:
for key, val in item.items():
if key == 'CAPACITY':
capacity = val['VALUE']
local_bytes = (strutils.string_to_bytes(
capacity.replace(' ', ''),
return_int=True))
local_gb = int(local_bytes / (1024 * 1024 * 1024))
if minimum >= local_gb or minimum == 0:
minimum = local_gb
# Return disk size 1 less than the actual disk size. This prevents
# the deploy to fail from Nova when root_gb is same as local_gb
# in Ironic. When the disk size is used as root_device hints,
# then it should be given as the actual size i.e.
# ironic (node.properties['local_gb'] + 1) else root device
# hint will fail.
if minimum:
minimum = minimum - 1
return minimum | def _parse_storage_embedded_health(self, data) | Gets the storage data from get_embedded_health
Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: disk size in GB. | 6.33976 | 6.153241 | 1.030312 |
if key not in dictionary:
return None
value = dictionary[key]
if not isinstance(value, list):
return [value]
else:
return value | def get_value_as_list(self, dictionary, key) | Helper function to check and convert a value to list.
Helper function to check and convert a value to json list.
This helps the ribcl data to be generalized across the servers.
:param dictionary: a dictionary to check in if key is present.
:param key: key to be checked if thats present in the given dictionary.
:returns the data converted to a list. | 2.276989 | 2.757364 | 0.825785 |
nic_data = self.get_value_as_list((data['GET_EMBEDDED_HEALTH_DATA']
[self.NIC_INFORMATION_TAG]), 'NIC')
if nic_data is None:
msg = "Unable to get NIC details. Data missing"
raise exception.IloError(msg)
nic_dict = {}
for item in nic_data:
try:
port = item['NETWORK_PORT']['VALUE']
mac = item['MAC_ADDRESS']['VALUE']
self._update_nic_data_from_nic_info_based_on_model(nic_dict,
item, port,
mac)
except KeyError:
msg = "Unable to get NIC details. Data missing"
raise exception.IloError(msg)
return nic_dict | def _parse_nics_embedded_health(self, data) | Gets the NIC details from get_embedded_health data
Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: a dictionary of port numbers and their corresponding
mac addresses.
:raises IloError, if unable to get NIC data. | 4.087231 | 3.788505 | 1.078851 |
firmware = self.get_value_as_list(data['GET_EMBEDDED_HEALTH_DATA'],
'FIRMWARE_INFORMATION')
if firmware is None:
return None
return dict((y['FIRMWARE_NAME']['VALUE'],
y['FIRMWARE_VERSION']['VALUE'])
for x in firmware for y in x.values()) | def _get_firmware_embedded_health(self, data) | Parse the get_host_health_data() for server capabilities
:param data: the output returned by get_host_health_data()
:returns: a dictionary of firmware name and firmware version. | 4.983593 | 5.270848 | 0.945501 |
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
try:
rom_firmware_version = (
firmware_details['HP ProLiant System ROM'])
return {'rom_firmware_version': rom_firmware_version}
except KeyError:
return None | def _get_rom_firmware_version(self, data) | Gets the rom firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: a dictionary of rom firmware version. | 6.594201 | 6.102642 | 1.080548 |
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
try:
return {'ilo_firmware_version': firmware_details['iLO']}
except KeyError:
return None | def _get_ilo_firmware_version(self, data) | Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: a dictionary of iLO firmware version. | 6.32544 | 6.486026 | 0.975241 |
data = self.get_host_health_data()
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
ilo_version_str = firmware_details.get('iLO', None)
return common.get_major_minor(ilo_version_str) | def get_ilo_firmware_version_as_major_minor(self) | Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<minor>" or None. | 5.364063 | 4.556322 | 1.177279 |
temp = self.get_value_as_list((data['GET_EMBEDDED_HEALTH_DATA']
['TEMPERATURE']), 'TEMP')
count = 0
if temp is None:
return {'pci_gpu_devices': count}
for key in temp:
for name, value in key.items():
if name == 'LABEL' and 'GPU' in value['VALUE']:
count = count + 1
return {'pci_gpu_devices': count} | def _get_number_of_gpu_devices_connected(self, data) | Gets the number of GPU devices connected to the server
Parse the get_host_health_data() and get the count of
number of GPU devices connected to the server.
:param data: the output returned by get_host_health_data()
:returns: a dictionary of rom firmware version. | 6.137943 | 5.822724 | 1.054136 |
root = self._create_dynamic_xml('LICENSE', 'RIB_INFO', 'write')
element = root.find('LOGIN/RIB_INFO/LICENSE')
etree.SubElement(element, 'ACTIVATE', KEY=key)
d = self._request_ilo(root)
self._parse_output(d) | def activate_license(self, key) | Activates iLO license.
:param key: iLO license key.
:raises: IloError, on an error from iLO. | 9.105442 | 10.069827 | 0.90423 |
fw_img_processor = firmware_controller.FirmwareImageUploader(filename)
LOG.debug(self._('Uploading firmware file: %s ...'), filename)
cookie = fw_img_processor.upload_file_to((self.host, self.port),
self.timeout)
LOG.debug(self._('Uploading firmware file: %s ... done'), filename)
root = self._get_firmware_update_xml_for_file_and_component(
filename, component_type)
element = root.find('LOGIN/RIB_INFO')
etree.SubElement(element, 'TPM_ENABLED', VALUE='Yes')
extra_headers = {'Cookie': cookie}
LOG.debug(self._('Flashing firmware file: %s ...'), filename)
d = self._request_ilo(root, extra_headers=extra_headers)
# wait till the firmware update completes.
common.wait_for_ribcl_firmware_update_to_complete(self)
self._parse_output(d)
LOG.info(self._('Flashing firmware file: %s ... done'), filename) | def update_firmware(self, filename, component_type) | Updates the given firmware on the server for the given component.
:param filename: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of component to be applied to.
:raises: InvalidInputError, if the validation of the input fails
:raises: IloError, on an error from iLO
:raises: IloConnectionError, if not able to reach iLO.
:raises: IloCommandNotSupportedError, if the command is
not supported on the server | 5.528215 | 5.669003 | 0.975165 |
if component == 'ilo':
cmd_name = 'UPDATE_RIB_FIRMWARE'
else:
# Note(deray): Not explicitly checking for all other supported
# devices (components), as those checks have already happened
# in the invoking methods and may seem redundant here.
cmd_name = 'UPDATE_FIRMWARE'
fwlen = os.path.getsize(filename)
root = self._create_dynamic_xml(cmd_name,
'RIB_INFO',
'write',
subelements={
'IMAGE_LOCATION': filename,
'IMAGE_LENGTH': str(fwlen)
})
return root | def _get_firmware_update_xml_for_file_and_component(
self, filename, component) | Creates the dynamic xml for flashing the device firmware via iLO.
This method creates the dynamic xml for flashing the firmware, based
on the component type so passed.
:param filename: location of the raw firmware file.
:param component_type: Type of component to be applied to.
:returns: the etree.Element for the root of the RIBCL XML
for flashing the device (component) firmware. | 9.745834 | 8.581233 | 1.135715 |
if 'G7' in self.model:
nic_dict[port] = mac
else:
location = item['LOCATION']['VALUE']
if location == 'Embedded':
nic_dict[port] = mac | def _update_nic_data_from_nic_info_based_on_model(self, nic_dict, item,
port, mac) | This method updates with port number and corresponding mac
:param nic_dict: dictionary contains port number and corresponding mac
:param item: dictionary containing nic details
:param port: Port number
:param mac: mac-address | 7.938344 | 7.939477 | 0.999857 |
try:
gzipper = gzip.GzipFile(fileobj=six.BytesIO(response.text))
LOG.debug(self._("Received compressed response for "
"url %(url)s."), {'url': url})
uncompressed_string = (gzipper.read().decode('UTF-8'))
response_body = json.loads(uncompressed_string)
except Exception as e:
LOG.debug(
self._("Error occurred while decompressing body. "
"Got invalid response '%(response)s' for "
"url %(url)s: %(error)s"),
{'url': url, 'response': response.text, 'error': e})
raise exception.IloError(e)
return response_body | def _get_response_body_from_gzipped_content(self, url, response) | Get the response body from gzipped content
Try to decode as gzip (we should check the headers for
Content-Encoding=gzip)
if response.headers['content-encoding'] == "gzip":
...
:param url: the url for which response was sent
:type url: str
:param response: response content object, probably gzipped
:type response: object
:returns: returns response body
:raises IloError: if the content is **not** gzipped | 3.156085 | 3.229539 | 0.977256 |
return self._rest_op('PATCH', suburi, request_headers, request_body) | def _rest_patch(self, suburi, request_headers, request_body) | REST PATCH operation.
HTTP response codes could be 500, 404, 202 etc. | 3.881354 | 3.862851 | 1.00479 |
return self._rest_op('PUT', suburi, request_headers, request_body) | def _rest_put(self, suburi, request_headers, request_body) | REST PUT operation.
HTTP response codes could be 500, 404, 202 etc. | 3.772044 | 3.892285 | 0.969108 |
return self._rest_op('POST', suburi, request_headers, request_body) | def _rest_post(self, suburi, request_headers, request_body) | REST POST operation.
The response body after the operation could be the new resource, or
ExtendedError, or it could be empty. | 3.886469 | 4.15526 | 0.935313 |
'''
Method that looks through the self.cycles and returns the
nearest cycle:
Parameters
----------
cycNum : int
int of the cycle desired cycle.
'''
cycNum=int(cycNum)
i=0
while i < len(self.cycles):
if cycNum < int(self.cycles[i]):
break
i+=1
if i ==0:
return self.cycles[i]
elif i == len(self.cycles):
return self.cycles[i-1]
lower=int(self.cycles[i-1])
higher=int(self.cycles[i])
if higher- cycNum >= cycNum-lower:
return self.cycles[i-1]
else:
return self.cycles[i] | def findCycle(self, cycNum) | Method that looks through the self.cycles and returns the
nearest cycle:
Parameters
----------
cycNum : int
int of the cycle desired cycle. | 3.024165 | 2.025982 | 1.492691 |
while isinstance(array, list) == True or \
isinstance(array, np.ndarray) == True:
try:
if len(array) == 1:
array = array[0]
else:
break
except:
break
return array | def red_dim(self, array) | This function reduces the dimensions of an array until it is
no longer of length 1. | 3.278645 | 2.996941 | 1.093997 |
'''
This method returns a zero-front padded string
It makes out of str(45) -> '0045' if 999 < max_num < 10000. This is
meant to work for reasonable integers (maybe less than 10^6).
Parameters
----------
number : integer
number that the string should represent.
max_num : integer
max number of cycle list, implies how many 0s have be padded
'''
cnum = str(number)
clen = len(cnum)
cmax = int(log10(max_num)) + 1
return (cmax - clen)*'0' + cnum | def _padding_model_number(number, max_num) | This method returns a zero-front padded string
It makes out of str(45) -> '0045' if 999 < max_num < 10000. This is
meant to work for reasonable integers (maybe less than 10^6).
Parameters
----------
number : integer
number that the string should represent.
max_num : integer
max number of cycle list, implies how many 0s have be padded | 9.840409 | 1.844188 | 5.335904 |
tmpX=[]
tmpY=[]
for i in range(len(x)):
if sparse == 1:
return x,y
if (i%sparse)==0:
tmpX.append(x[i])
tmpY.append(y[i])
return tmpX, tmpY | def _sparse(self, x, y, sparse) | Method that removes every non sparse th element.
For example:
if this argument was 5, This method would plot the 0th, 5th,
10th ... elements.
Parameters
----------
x : list
list of x values, of length j.
y : list
list of y values, of length j.
sparse : integer
Argument that skips every so many data points. | 3.509481 | 3.185797 | 1.101602 |
'''
Method for removing the title and/or xlabel and/or Ylabel.
Parameters
----------
Title : boolean, optional
Boolean of if title will be cleared. The default is True.
xlabel : boolean, optional
Boolean of if xlabel will be cleared. The default is True.
ylabel : boolean, optional
Boolean of if ylabel will be cleared. The default is True.
'''
if title:
pyl.title('')
if xlabel:
pyl.xlabel('')
if ylabel:
pyl.ylabel('') | def _clear(self, title=True, xlabel=True, ylabel=True) | Method for removing the title and/or xlabel and/or Ylabel.
Parameters
----------
Title : boolean, optional
Boolean of if title will be cleared. The default is True.
xlabel : boolean, optional
Boolean of if xlabel will be cleared. The default is True.
ylabel : boolean, optional
Boolean of if ylabel will be cleared. The default is True. | 2.483356 | 1.53976 | 1.61282 |
''' reverse xrange'''
xmax,xmin=pyl.xlim()
pyl.xlim(xmin,xmax) | def _xlimrev(self) | reverse xrange | 18.911362 | 14.039189 | 1.347041 |
'''
Create title string
Private method that creates a title string for a cycle plot
out of a list of title_items that are cycle attributes and can
be obtained with self.get
Parameters
----------
title_items : list
A list of cycle attributes.
cycle : scalar
The cycle for which the title string should be created.
Returns
-------
title_string: string
Title string that can be used to decorate plot.
'''
title_string=[]
form_str='%4.1F'
for item in title_items:
num=self.get(item,fname=cycle)
if num > 999 or num < 0.1:
num=log10(num)
prefix='log '
else:
prefix=''
title_string.append(prefix+item+'='+form_str%num)
tt=''
for thing in title_string:
tt = tt+thing+", "
return tt.rstrip(', ') | def _do_title_string(self,title_items,cycle) | Create title string
Private method that creates a title string for a cycle plot
out of a list of title_items that are cycle attributes and can
be obtained with self.get
Parameters
----------
title_items : list
A list of cycle attributes.
cycle : scalar
The cycle for which the title string should be created.
Returns
-------
title_string: string
Title string that can be used to decorate plot. | 5.373291 | 2.628676 | 2.044106 |
'''
create a movie with mass fractions vs mass coordinate between
xlim1 and xlim2, ylim1 and ylim2. Only works with instances of
se.
Parameters
----------
ini : integer
Initial model i.e. cycle.
end : integer
Final model i.e. cycle.
delta : integer
Sparsity factor of the frames.
what_specie : list
Array with species in the plot.
xlim1, xlim2 : integer or float
Mass coordinate range.
ylim1, ylim2 : integer or float
Mass fraction coordinate range.
symbol : list, optional
Array indicating which symbol you want to use. Must be of
the same len of what_specie array. The default is None.
'''
plotType=self._classTest()
if plotType=='se':
for i in range(ini,end+1,delta):
step = int(i)
#print step
if symbol==None:
symbol_dummy = '-'
for j in range(len(what_specie)):
self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy)
else:
for j in range(len(what_specie)):
symbol_dummy = symbol[j]
self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy)
#
filename = str('%03d' % step)+'_test.png'
pl.savefig(filename, dpi=400)
print('wrote file ', filename)
#
pl.clf()
else:
print('This method is not supported for '+str(self.__class__))
return | def plotprofMulti(self, ini, end, delta, what_specie, xlim1, xlim2,
ylim1, ylim2, symbol=None) | create a movie with mass fractions vs mass coordinate between
xlim1 and xlim2, ylim1 and ylim2. Only works with instances of
se.
Parameters
----------
ini : integer
Initial model i.e. cycle.
end : integer
Final model i.e. cycle.
delta : integer
Sparsity factor of the frames.
what_specie : list
Array with species in the plot.
xlim1, xlim2 : integer or float
Mass coordinate range.
ylim1, ylim2 : integer or float
Mass fraction coordinate range.
symbol : list, optional
Array indicating which symbol you want to use. Must be of
the same len of what_specie array. The default is None. | 3.779237 | 1.957654 | 1.930493 |
'''
Plot one species for cycle between xlim1 and xlim2 Only works
with instances of se and mesa _profile.
Parameters
----------
species : list
Which species to plot.
keystring : string or integer
Label that appears in the plot or in the case of se, a
cycle.
xlim1, xlim2 : integer or float
Mass coordinate range.
ylim1, ylim2 : integer or float
Mass fraction coordinate range.
symbol : string, optional
Which symbol you want to use. If None symbol is set to '-'.
The default is None.
show : boolean, optional
Show the ploted graph. The default is False.
'''
plotType=self._classTest()
if plotType=='se':
#tot_mass=self.se.get(keystring,'total_mass')
tot_mass=self.se.get('mini')
age=self.se.get(keystring,'age')
mass=self.se.get(keystring,'mass')
Xspecies=self.se.get(keystring,'iso_massf',species)
mod=keystring
elif plotType=='mesa_profile':
tot_mass=self.header_attr['star_mass']
age=self.header_attr['star_age']
mass=self.get('mass')
mod=self.header_attr['model_number']
Xspecies=self.get(species)
else:
print('This method is not supported for '+str(self.__class__))
return
if symbol == None:
symbol = '-'
x,y=self._logarithm(Xspecies,mass,True,False,10)
#print x
pl.plot(y,x,symbol,label=str(species))
pl.xlim(xlim1,xlim2)
pl.ylim(ylim1,ylim2)
pl.legend()
pl.xlabel('$Mass$ $coordinate$', fontsize=20)
pl.ylabel('$X_{i}$', fontsize=20)
#pl.title('Mass='+str(tot_mass)+', Time='+str(age)+' years, cycle='+str(mod))
pl.title('Mass='+str(tot_mass)+', cycle='+str(mod))
if show:
pl.show() | def plot_prof_1(self, species, keystring, xlim1, xlim2, ylim1,
ylim2, symbol=None, show=False) | Plot one species for cycle between xlim1 and xlim2 Only works
with instances of se and mesa _profile.
Parameters
----------
species : list
Which species to plot.
keystring : string or integer
Label that appears in the plot or in the case of se, a
cycle.
xlim1, xlim2 : integer or float
Mass coordinate range.
ylim1, ylim2 : integer or float
Mass fraction coordinate range.
symbol : string, optional
Which symbol you want to use. If None symbol is set to '-'.
The default is None.
show : boolean, optional
Show the ploted graph. The default is False. | 4.619211 | 2.592564 | 1.781715 |
'''
Plot density as a function of either mass coordiate or radius.
Parameters
----------
ixaxis : string
'mass' or 'radius'
The default value is 'mass'
ifig : integer or string
The figure label
The default value is None
colour : string
What colour the line should be
The default value is None
label : string
Label for the line
The default value is None
fname : integer
What cycle to plot from (if SE output)
The default value is None
'''
pT=self._classTest()
# Class-specific things:
if pT is 'mesa_profile':
x = self.get(ixaxis)
if ixaxis is 'radius':
x = x*ast.rsun_cm
y = self.get('logRho')
elif pT is 'se':
if fname is None:
raise IOError("Please provide the cycle number fname")
x = self.se.get(fname,ixaxis)
y = np.log10(self.se.get(fname,'rho'))
else:
raise IOError("Sorry. the density_profile method is not available \
for this class")
# Plot-specific things:
if ixaxis is 'radius':
x = np.log10(x)
xlab='$\log_{10}(r\,/\,{\\rm cm})$'
else:
xlab='${\\rm Mass}\,/\,M_\odot$'
if ifig is not None:
pl.figure(ifig)
if label is not None:
if colour is not None:
pl.plot(x,y,color=colour,label=label)
else:
pl.plot(x,y,label=label)
pl.legend(loc='best').draw_frame(False)
else:
if colour is not None:
pl.plot(x,y,color=colour)
else:
pl.plot(x,y)
pl.xlabel(xlab)
pl.ylabel('$\log_{10}(\\rho\,/\,{\\rm g\,cm}^{-3})$') | def density_profile(self,ixaxis='mass',ifig=None,colour=None,label=None,fname=None) | Plot density as a function of either mass coordiate or radius.
Parameters
----------
ixaxis : string
'mass' or 'radius'
The default value is 'mass'
ifig : integer or string
The figure label
The default value is None
colour : string
What colour the line should be
The default value is None
label : string
Label for the line
The default value is None
fname : integer
What cycle to plot from (if SE output)
The default value is None | 3.387454 | 2.456065 | 1.37922 |
return system.HPESystem(self._conn, identity,
redfish_version=self.redfish_version) | def get_system(self, identity) | Given the identity return a HPESystem object
:param identity: The identity of the System resource
:returns: The System object | 11.598439 | 7.710362 | 1.504267 |
return manager.HPEManager(self._conn, identity,
redfish_version=self.redfish_version) | def get_manager(self, identity) | Given the identity return a HPEManager object
:param identity: The identity of the Manager resource
:returns: The Manager object | 8.736199 | 5.711481 | 1.529586 |
update_service_url = utils.get_subresource_path_by(self,
'UpdateService')
return (update_service.
HPEUpdateService(self._conn, update_service_url,
redfish_version=self.redfish_version)) | def get_update_service(self) | Return a HPEUpdateService object
:returns: The UpdateService object | 6.690945 | 5.901145 | 1.133838 |
account_service_url = utils.get_subresource_path_by(self,
'AccountService')
return (account_service.
HPEAccountService(self._conn, account_service_url,
redfish_version=self.redfish_version)) | def get_account_service(self) | Return a HPEAccountService object | 6.520498 | 4.798119 | 1.35897 |
cmd = ' --c ' + ' --c '.join(components) if components else ''
try:
if SUM_LOCATION in sum_file_path:
location = os.path.join(mount_point, 'packages')
# NOTE: 'launch_sum.sh' binary is part of SPP ISO and it is
# available in the SPP mount point (eg:'/mount/launch_sum.sh').
# 'launch_sum.sh' binary calls the 'smartupdate' binary by passing
# the arguments.
processutils.execute('./launch_sum.sh', '--s', '--romonly',
'--use_location', location, cmd,
cwd=mount_point)
else:
processutils.execute(sum_file_path, '--s', '--romonly', cmd)
except processutils.ProcessExecutionError as e:
result = _parse_sum_ouput(e.exit_code)
if result:
return result
else:
raise exception.SUMOperationError(reason=str(e)) | def _execute_sum(sum_file_path, mount_point, components=None) | Executes the SUM based firmware update command.
This method executes the SUM based firmware update command to update the
components specified, if not, it performs update on all the firmware
components on th server.
:param sum_file_path: A string with the path to the SUM binary to be
executed
:param components: A list of components to be updated. If it is None, all
the firmware components are updated.
:param mount_point: Location in which SPP iso is mounted.
:returns: A string with the statistics of the updated/failed components.
:raises: SUMOperationError, when the SUM based firmware update operation
on the node fails. | 6.837348 | 5.636552 | 1.213037 |
with io.BytesIO() as fp:
with tarfile.open(fileobj=fp, mode='w:gz') as tar:
for f in OUTPUT_FILES:
if os.path.isfile(f):
tar.add(f)
fp.seek(0)
return base64.encode_as_bytes(fp.getvalue()) | def _get_log_file_data_as_encoded_content() | Gzip and base64 encode files and BytesIO buffers.
This method gets the log files created by SUM based
firmware update and tar zip the files.
:returns: A gzipped and base64 encoded string as text. | 2.50043 | 2.556416 | 0.9781 |
if exit_code == 3:
return "Summary: %s" % EXIT_CODE_TO_STRING.get(exit_code)
if exit_code in (0, 1, 253):
if os.path.exists(OUTPUT_FILES[0]):
with open(OUTPUT_FILES[0], 'r') as f:
output_data = f.read()
ret_data = output_data[(output_data.find('Deployed Components:') +
len('Deployed Components:')):
output_data.find('Exit status:')]
failed = 0
success = 0
for line in re.split('\n\n', ret_data):
if line:
if 'Success' not in line:
failed += 1
else:
success += 1
return {
'Summary': (
"%(return_string)s Status of updated components: Total: "
"%(total)s Success: %(success)s Failed: %(failed)s." %
{'return_string': EXIT_CODE_TO_STRING.get(exit_code),
'total': (success + failed), 'success': success,
'failed': failed}),
'Log Data': _get_log_file_data_as_encoded_content()
}
return "UPDATE STATUS: UNKNOWN" | def _parse_sum_ouput(exit_code) | Parse the SUM output log file.
This method parses through the SUM log file in the
default location to return the SUM update status. Sample return
string:
"Summary: The installation of the component failed. Status of updated
components: Total: 5 Success: 4 Failed: 1"
:param exit_code: A integer returned by the SUM after command execution.
:returns: A string with the statistics of the updated/failed
components and 'None' when the exit_code is not 0, 1, 3 or 253. | 3.91045 | 3.245452 | 1.204902 |
sum_update_iso = node['clean_step']['args'].get('url')
# Validates the http image reference for SUM update ISO.
try:
utils.validate_href(sum_update_iso)
except exception.ImageRefValidationFailed as e:
raise exception.SUMOperationError(reason=e)
# Ejects the CDROM device in the iLO and inserts the SUM update ISO
# to the CDROM device.
info = node.get('driver_info')
ilo_object = client.IloClient(info.get('ilo_address'),
info.get('ilo_username'),
info.get('ilo_password'))
ilo_object.eject_virtual_media('CDROM')
ilo_object.insert_virtual_media(sum_update_iso, 'CDROM')
# Waits for the OS to detect the disk and update the label file. SPP ISO
# is identified by matching its label.
time.sleep(WAIT_TIME_DISK_LABEL_TO_BE_VISIBLE)
vmedia_device_dir = "/dev/disk/by-label/"
for file in os.listdir(vmedia_device_dir):
if fnmatch.fnmatch(file, 'SPP*'):
vmedia_device_file = os.path.join(vmedia_device_dir, file)
if not os.path.exists(vmedia_device_file):
msg = "Unable to find the virtual media device for SUM"
raise exception.SUMOperationError(reason=msg)
# Validates the SPP ISO image for any file corruption using the checksum
# of the ISO file.
expected_checksum = node['clean_step']['args'].get('checksum')
try:
utils.verify_image_checksum(vmedia_device_file, expected_checksum)
except exception.ImageRefValidationFailed as e:
raise exception.SUMOperationError(reason=e)
# Mounts SPP ISO on a temporary directory.
vmedia_mount_point = tempfile.mkdtemp()
try:
try:
processutils.execute("mount", vmedia_device_file,
vmedia_mount_point)
except processutils.ProcessExecutionError as e:
msg = ("Unable to mount virtual media device %(device)s: "
"%(error)s" % {'device': vmedia_device_file, 'error': e})
raise exception.SUMOperationError(reason=msg)
# Executes the SUM based firmware update by passing the 'smartupdate'
# executable path if exists else 'hpsum' executable path and the
# components specified (if any).
sum_file_path = os.path.join(vmedia_mount_point, SUM_LOCATION)
if not os.path.exists(sum_file_path):
sum_file_path = os.path.join(vmedia_mount_point, HPSUM_LOCATION)
components = node['clean_step']['args'].get('components')
result = _execute_sum(sum_file_path, vmedia_mount_point,
components=components)
processutils.trycmd("umount", vmedia_mount_point)
finally:
shutil.rmtree(vmedia_mount_point, ignore_errors=True)
return result | def update_firmware(node) | Performs SUM based firmware update on the node.
This method performs SUM firmware update by mounting the
SPP ISO on the node. It performs firmware update on all or
some of the firmware components.
:param node: A node object of type dict.
:returns: Operation Status string.
:raises: SUMOperationError, when the vmedia device is not found or
when the mount operation fails or when the image validation fails.
:raises: IloConnectionError, when the iLO connection fails.
:raises: IloError, when vmedia eject or insert operation fails. | 3.312321 | 2.966204 | 1.116687 |
'''Return a string with markup tags converted to ansi-escape sequences.'''
tags, results = [], []
text = self.re_tag.sub(lambda m: self.sub_tag(m, tags, results), text)
if self.strict and tags:
markup = "%s%s%s" % (self.tag_sep[0], tags.pop(0), self.tag_sep[1])
raise MismatchedTag('opening tag "%s" has no corresponding closing tag' % markup)
if self.always_reset:
if not text.endswith(Style.RESET_ALL):
text += Style.RESET_ALL
return text | def parse(self, text) | Return a string with markup tags converted to ansi-escape sequences. | 4.987657 | 3.991637 | 1.249527 |
'''Wrapper around builtins.print() that runs parse() on all arguments first.'''
args = (self.parse(str(i)) for i in args)
builtins.print(*args, **kwargs) | def ansiprint(self, *args, **kwargs) | Wrapper around builtins.print() that runs parse() on all arguments first. | 7.949535 | 2.960116 | 2.685549 |
'''Return string with markup tags removed.'''
tags, results = [], []
return self.re_tag.sub(lambda m: self.clear_tag(m, tags, results), text) | def strip(self, text) | Return string with markup tags removed. | 8.602107 | 6.739853 | 1.276305 |
'''
Returns a generator to list the shares under the specified account.
The generator will lazily follow the continuation tokens returned by
the service and stop when all shares have been returned or num_results
is reached.
If num_results is specified and the account has more than that number of
shares, the generator will have a populated next_marker field once it
finishes. This marker can be used to create a new generator if more
results are desired.
:param str prefix:
Filters the results to return only shares whose names
begin with the specified prefix.
:param int num_results:
Specifies the maximum number of shares to return.
:param bool include_metadata:
Specifies that share metadata be returned in the response.
:param str marker:
An opaque continuation token. This value can be retrieved from the
next_marker field of a previous generator object if num_results was
specified and that generator has finished enumerating results. If
specified, this generator will begin returning results from the point
where the previous generator stopped.
:param int timeout:
The timeout parameter is expressed in seconds.
'''
include = 'metadata' if include_metadata else None
operation_context = _OperationContext(location_lock=True)
kwargs = {'prefix': prefix, 'marker': marker, 'max_results': num_results,
'include': include, 'timeout': timeout, '_context': operation_context}
resp = self._list_shares(**kwargs)
return ListGenerator(resp, self._list_shares, (), kwargs) | def list_shares(self, prefix=None, marker=None, num_results=None,
include_metadata=False, timeout=None) | Returns a generator to list the shares under the specified account.
The generator will lazily follow the continuation tokens returned by
the service and stop when all shares have been returned or num_results
is reached.
If num_results is specified and the account has more than that number of
shares, the generator will have a populated next_marker field once it
finishes. This marker can be used to create a new generator if more
results are desired.
:param str prefix:
Filters the results to return only shares whose names
begin with the specified prefix.
:param int num_results:
Specifies the maximum number of shares to return.
:param bool include_metadata:
Specifies that share metadata be returned in the response.
:param str marker:
An opaque continuation token. This value can be retrieved from the
next_marker field of a previous generator object if num_results was
specified and that generator has finished enumerating results. If
specified, this generator will begin returning results from the point
where the previous generator stopped.
:param int timeout:
The timeout parameter is expressed in seconds. | 2.951639 | 1.593764 | 1.851993 |
'''
Returns a generator to list the directories and files under the specified share.
The generator will lazily follow the continuation tokens returned by
the service and stop when all directories and files have been returned or
num_results is reached.
If num_results is specified and the share has more than that number of
files and directories, the generator will have a populated next_marker
field once it finishes. This marker can be used to create a new generator
if more results are desired.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param int num_results:
Specifies the maximum number of files to return,
including all directory elements. If the request does not specify
num_results or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting num_results to a value less than
or equal to zero results in error response code 400 (Bad Request).
:param str marker:
An opaque continuation token. This value can be retrieved from the
next_marker field of a previous generator object if num_results was
specified and that generator has finished enumerating results. If
specified, this generator will begin returning results from the point
where the previous generator stopped.
:param int timeout:
The timeout parameter is expressed in seconds.
:param str prefix:
List only the files and/or directories with the given prefix.
'''
operation_context = _OperationContext(location_lock=True)
args = (share_name, directory_name)
kwargs = {'marker': marker, 'max_results': num_results, 'timeout': timeout,
'_context': operation_context, 'prefix': prefix}
resp = self._list_directories_and_files(*args, **kwargs)
return ListGenerator(resp, self._list_directories_and_files, args, kwargs) | def list_directories_and_files(self, share_name, directory_name=None,
num_results=None, marker=None, timeout=None,
prefix=None) | Returns a generator to list the directories and files under the specified share.
The generator will lazily follow the continuation tokens returned by
the service and stop when all directories and files have been returned or
num_results is reached.
If num_results is specified and the share has more than that number of
files and directories, the generator will have a populated next_marker
field once it finishes. This marker can be used to create a new generator
if more results are desired.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param int num_results:
Specifies the maximum number of files to return,
including all directory elements. If the request does not specify
num_results or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting num_results to a value less than
or equal to zero results in error response code 400 (Bad Request).
:param str marker:
An opaque continuation token. This value can be retrieved from the
next_marker field of a previous generator object if num_results was
specified and that generator has finished enumerating results. If
specified, this generator will begin returning results from the point
where the previous generator stopped.
:param int timeout:
The timeout parameter is expressed in seconds.
:param str prefix:
List only the files and/or directories with the given prefix. | 2.447509 | 1.372512 | 1.783234 |
'''
Downloads a file's content, metadata, and properties. You can specify a
range if you don't need to download the file in its entirety. If no range
is specified, the full file will be downloaded.
See get_file_to_* for high level functions that handle the download
of large files with automatic chunking and progress notifications.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_name:
Name of existing file.
:param int start_range:
Start of byte range to use for downloading a section of the file.
If no end_range is given, all bytes after the start_range will be downloaded.
The start_range and end_range params are inclusive.
Ex: start_range=0, end_range=511 will download first 512 bytes of file.
:param int end_range:
End of byte range to use for downloading a section of the file.
If end_range is given, start_range must be provided.
The start_range and end_range params are inclusive.
Ex: start_range=0, end_range=511 will download first 512 bytes of file.
:param bool validate_content:
When this is set to True and specified together with the Range header,
the service returns the MD5 hash for the range, as long as the range
is less than or equal to 4 MB in size.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A File with content, properties, and metadata.
:rtype: :class:`~azure.storage.file.models.File`
'''
_validate_not_none('share_name', share_name)
_validate_not_none('file_name', file_name)
request = HTTPRequest()
request.method = 'GET'
request.host_locations = self._get_host_locations()
request.path = _get_path(share_name, directory_name, file_name)
request.query = { 'timeout': _int_to_str(timeout)}
_validate_and_format_range_headers(
request,
start_range,
end_range,
start_range_required=False,
end_range_required=False,
check_content_md5=validate_content)
return self._perform_request(request, _parse_file,
[file_name, validate_content],
operation_context=_context) | def _get_file(self, share_name, directory_name, file_name,
start_range=None, end_range=None, validate_content=False,
timeout=None, _context=None) | Downloads a file's content, metadata, and properties. You can specify a
range if you don't need to download the file in its entirety. If no range
is specified, the full file will be downloaded.
See get_file_to_* for high level functions that handle the download
of large files with automatic chunking and progress notifications.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_name:
Name of existing file.
:param int start_range:
Start of byte range to use for downloading a section of the file.
If no end_range is given, all bytes after the start_range will be downloaded.
The start_range and end_range params are inclusive.
Ex: start_range=0, end_range=511 will download first 512 bytes of file.
:param int end_range:
End of byte range to use for downloading a section of the file.
If end_range is given, start_range must be provided.
The start_range and end_range params are inclusive.
Ex: start_range=0, end_range=511 will download first 512 bytes of file.
:param bool validate_content:
When this is set to True and specified together with the Range header,
the service returns the MD5 hash for the range, as long as the range
is less than or equal to 4 MB in size.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A File with content, properties, and metadata.
:rtype: :class:`~azure.storage.file.models.File` | 2.220941 | 1.327228 | 1.673368 |
fw_img_extractor = firmware_controller.get_fw_extractor(
compact_firmware_file)
LOG.debug('Extracting firmware file: %s ...', compact_firmware_file)
raw_fw_file_path, is_extracted = fw_img_extractor.extract()
# Note(deray): Need to check if this processing is for RIS or RIBCL
# based systems. For Gen9 machines (RIS based) the firmware file needs
# to be on a http store, and hence requires the upload to happen for the
# firmware file.
to_upload = False
m = re.search('Gen(\d+)', ilo_object.model)
if int(m.group(1)) > 8:
to_upload = True
LOG.debug('Extracting firmware file: %s ... done', compact_firmware_file)
msg = ('Firmware file %(fw_file)s is %(msg)s. Need hosting (on an http '
'store): %(yes_or_no)s' %
{'fw_file': compact_firmware_file,
'msg': ('extracted. Extracted file: %s' % raw_fw_file_path
if is_extracted else 'already in raw format'),
'yes_or_no': 'Yes' if to_upload else 'No'})
LOG.info(msg)
return raw_fw_file_path, to_upload, is_extracted | def process_firmware_image(compact_firmware_file, ilo_object) | Processes the firmware file.
Processing the firmware file entails extracting the firmware file from its
compact format. Along with the raw (extracted) firmware file, this method
also sends out information of whether or not the extracted firmware file
a) needs to be uploaded to http store
b) is extracted in reality or the file was already in raw format
:param compact_firmware_file: firmware file to extract from
:param ilo_object: ilo client object (ribcl/ris object)
:raises: InvalidInputError, for unsupported file types or raw firmware
file not found from compact format.
:raises: ImageExtractionFailed, for extraction related issues
:returns: core(raw) firmware file
:returns: to_upload, boolean to indicate whether to upload or not
:returns: is_extracted, boolean to indicate firmware image is actually
extracted or not. | 5.100309 | 4.181728 | 1.219665 |
algorithms = (hashlib.algorithms_guaranteed if six.PY3
else hashlib.algorithms)
if hash_algo_name not in algorithms:
msg = ("Unsupported/Invalid hash name '%s' provided."
% hash_algo_name)
raise exception.InvalidInputError(msg)
return getattr(hashlib, hash_algo_name)() | def _get_hash_object(hash_algo_name) | Create a hash object based on given algorithm.
:param hash_algo_name: name of the hashing algorithm.
:raises: InvalidInputError, on unsupported or invalid input.
:returns: a hash object based on the given named algorithm. | 3.635267 | 3.580494 | 1.015298 |
checksum = _get_hash_object(hash_algo)
for chunk in iter(lambda: file_like_object.read(32768), b''):
checksum.update(chunk)
return checksum.hexdigest() | def hash_file(file_like_object, hash_algo='md5') | Generate a hash for the contents of a file.
It returns a hash of the file object as a string of double length,
containing only hexadecimal digits. It supports all the algorithms
hashlib does.
:param file_like_object: file like object whose hash to be calculated.
:param hash_algo: name of the hashing strategy, default being 'md5'.
:raises: InvalidInputError, on unsupported or invalid input.
:returns: a condensed digest of the bytes of contents. | 2.182552 | 3.148225 | 0.693264 |
try:
with open(image_location, 'rb') as fd:
actual_checksum = hash_file(fd)
except IOError as e:
raise exception.ImageRefValidationFailed(image_href=image_location,
reason=e)
if actual_checksum != expected_checksum:
msg = ('Error verifying image checksum. Image %(image)s failed to '
'verify against checksum %(checksum)s. Actual checksum is: '
'%(actual_checksum)s' %
{'image': image_location, 'checksum': expected_checksum,
'actual_checksum': actual_checksum})
raise exception.ImageRefValidationFailed(image_href=image_location,
reason=msg) | def verify_image_checksum(image_location, expected_checksum) | Verifies checksum (md5) of image file against the expected one.
This method generates the checksum of the image file on the fly and
verifies it against the expected checksum provided as argument.
:param image_location: location of image file whose checksum is verified.
:param expected_checksum: checksum to be checked against
:raises: ImageRefValidationFailed, if invalid file path or
verification fails. | 2.115086 | 2.173891 | 0.972949 |
try:
response = requests.head(image_href)
if response.status_code != http_client.OK:
raise exception.ImageRefValidationFailed(
image_href=image_href,
reason=("Got HTTP code %s instead of 200 in response to "
"HEAD request." % response.status_code))
except requests.RequestException as e:
raise exception.ImageRefValidationFailed(image_href=image_href,
reason=e)
return response | def validate_href(image_href) | Validate HTTP image reference.
:param image_href: Image reference.
:raises: exception.ImageRefValidationFailed if HEAD request failed or
returned response code not equal to 200.
:returns: Response to HEAD request. | 2.536392 | 2.167432 | 1.170229 |
if not settings or not filter_to_be_applied:
return settings
return {k: settings[k] for k in filter_to_be_applied if k in settings} | def apply_bios_properties_filter(settings, filter_to_be_applied) | Applies the filter to return the dict of filtered BIOS properties.
:param settings: dict of BIOS settings on which filter to be applied.
:param filter_to_be_applied: list of keys to be applied as filter.
:returns: A dictionary of filtered BIOS settings. | 2.511521 | 2.796616 | 0.898057 |
'''
Constructs an insert or replace entity request.
'''
_validate_entity(entity, key_encryption_key is not None)
_validate_encryption_required(require_encryption, key_encryption_key)
request = HTTPRequest()
request.method = 'PUT'
request.headers = {
_DEFAULT_CONTENT_TYPE_HEADER[0]: _DEFAULT_CONTENT_TYPE_HEADER[1],
_DEFAULT_ACCEPT_HEADER[0]: _DEFAULT_ACCEPT_HEADER[1],
}
if(key_encryption_key):
entity = _encrypt_entity(entity, key_encryption_key, encryption_resolver)
request.body = _get_request_body(_convert_entity_to_json(entity))
return request | def _insert_or_replace_entity(entity, require_encryption=False,
key_encryption_key=None, encryption_resolver=None) | Constructs an insert or replace entity request. | 2.838491 | 2.603298 | 1.090344 |
return account.HPEAccountCollection(
self._conn, utils.get_subresource_path_by(self, 'Accounts'),
redfish_version=self.redfish_version) | def accounts(self) | Property to provide instance of HPEAccountCollection | 6.978064 | 4.143032 | 1.684289 |
data = {
'Password': password,
}
self._conn.patch(self.path, data=data) | def update_credentials(self, password) | Update credentials of a redfish system
:param password: password to be updated | 6.630672 | 6.743817 | 0.983222 |
members = self.get_members()
for member in members:
if member.username == username:
return member | def get_member_details(self, username) | Returns the HPEAccount object
:param username: username of account
:returns: HPEAccount object if criterion matches, None otherwise | 2.99292 | 3.062894 | 0.977154 |
get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x]
if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None)
return list(map(get_mapped_media, media_types)) | def _get_media(media_types) | Helper method to map the media types. | 4.780879 | 4.32884 | 1.104425 |
action = eval("self._hpe_actions." + action_type + "_vmedia")
if not action:
if action_type == "insert":
action_path = '#HpeiLOVirtualMedia.InsertVirtualMedia'
else:
action_path = '#HpeiLOVirtualMedia.EjectVirtualMedia'
raise exception.MissingAttributeError(
attribute=action_path,
resource=self._path)
return action | def _get_action_element(self, action_type) | Helper method to return the action object. | 7.135648 | 6.5615 | 1.087503 |
try:
super(VirtualMedia, self).insert_media(url, write_protected=True)
except sushy_exceptions.SushyError:
target_uri = self._get_action_element('insert').target_uri
data = {'Image': url}
self._conn.post(target_uri, data=data) | def insert_media(self, url) | Inserts Virtual Media to the device
:param url: URL to image.
:raises: SushyError, on an error from iLO. | 6.307893 | 4.920237 | 1.28203 |
try:
super(VirtualMedia, self).eject_media()
except sushy_exceptions.SushyError:
target_uri = self._get_action_element('eject').target_uri
self._conn.post(target_uri, data={}) | def eject_media(self) | Ejects Virtual Media.
:raises: SushyError, on an error from iLO. | 5.301198 | 4.753006 | 1.115336 |
data = {
"Oem": {
"Hpe": {
"BootOnNextServerReset": boot_on_next_reset
}
}
}
self._conn.patch(self.path, data=data) | def set_vm_status(self, boot_on_next_reset) | Set the Virtual Media drive status.
:param boot_on_next_reset: boolean value
:raises: SushyError, on an error from iLO. | 3.369936 | 3.932054 | 0.857042 |
for vmedia_device in self.get_members():
if device in vmedia_device.media_types:
return vmedia_device | def get_member_device(self, device) | Returns the given virtual media device object.
:param device: virtual media device to be queried
:returns virtual media device object. | 6.549922 | 5.469475 | 1.197541 |
'''
Constructs a get entity request.
'''
_validate_not_none('partition_key', partition_key)
_validate_not_none('row_key', row_key)
_validate_not_none('accept', accept)
request = HTTPRequest()
request.method = 'GET'
request.headers = [('Accept', _to_str(accept))]
request.query = [('$select', _to_str(select))]
return request | def _get_entity(partition_key, row_key, select, accept) | Constructs a get entity request. | 2.803297 | 2.430746 | 1.153266 |
'''
Constructs an insert entity request.
'''
_validate_entity(entity)
request = HTTPRequest()
request.method = 'POST'
request.headers = [_DEFAULT_CONTENT_TYPE_HEADER,
_DEFAULT_PREFER_HEADER,
_DEFAULT_ACCEPT_HEADER]
request.body = _get_request_body(_convert_entity_to_json(entity))
return request | def _insert_entity(entity) | Constructs an insert entity request. | 4.584749 | 3.819018 | 1.200505 |
'''
Constructs a merge entity request.
'''
_validate_not_none('if_match', if_match)
_validate_entity(entity)
request = HTTPRequest()
request.method = 'MERGE'
request.headers = [_DEFAULT_CONTENT_TYPE_HEADER,
_DEFAULT_ACCEPT_HEADER,
('If-Match', _to_str(if_match))]
request.body = _get_request_body(_convert_entity_to_json(entity))
return request | def _merge_entity(entity, if_match) | Constructs a merge entity request. | 3.573145 | 3.343229 | 1.068771 |
'''
Constructs a delete entity request.
'''
_validate_not_none('if_match', if_match)
_validate_not_none('partition_key', partition_key)
_validate_not_none('row_key', row_key)
request = HTTPRequest()
request.method = 'DELETE'
request.headers = [_DEFAULT_ACCEPT_HEADER,
('If-Match', _to_str(if_match))]
return request | def _delete_entity(partition_key, row_key, if_match) | Constructs a delete entity request. | 3.357746 | 3.255615 | 1.031371 |
'''
Constructs an insert or replace entity request.
'''
_validate_entity(entity)
request = HTTPRequest()
request.method = 'PUT'
request.headers = [_DEFAULT_CONTENT_TYPE_HEADER,
_DEFAULT_ACCEPT_HEADER]
request.body = _get_request_body(_convert_entity_to_json(entity))
return request | def _insert_or_replace_entity(entity) | Constructs an insert or replace entity request. | 4.5424 | 3.732467 | 1.216997 |
if six.PY3:
executable_abs = shutil.which(executable_name)
else:
import distutils.spawn
executable_abs = distutils.spawn.find_executable(executable_name)
return executable_abs | def find_executable(executable_name) | Tries to find executable in PATH environment
It uses ``shutil.which`` method in Python3 and
``distutils.spawn.find_executable`` method in Python2.7 to find the
absolute path to the 'name' executable.
:param executable_name: name of the executable
:returns: Returns the absolute path to the executable or None if not found. | 2.625575 | 2.978308 | 0.881566 |
@six.wraps(func)
def wrapper(self, filename, component_type):
component_type = component_type and component_type.lower()
if (component_type not in SUPPORTED_FIRMWARE_UPDATE_COMPONENTS):
msg = ("Got invalid component type for firmware update: "
"``update_firmware`` is not supported on %(component)s" %
{'component': component_type})
LOG.error(self._(msg)) # noqa
raise exception.InvalidInputError(msg)
return func(self, filename, component_type)
return wrapper | def check_firmware_update_component(func) | Checks the firmware update component. | 3.887834 | 3.874903 | 1.003337 |
fw_img_extractor = FirmwareImageExtractor(fw_file)
extension = fw_img_extractor.fw_file_ext.lower()
if extension == '.scexe':
# assign _do_extract attribute to refer to _extract_scexe_file
fw_img_extractor._do_extract = types.MethodType(
_extract_scexe_file, fw_img_extractor)
elif extension == '.rpm':
# assign _do_extract attribute to refer to _extract_rpm_file
fw_img_extractor._do_extract = types.MethodType(
_extract_rpm_file, fw_img_extractor)
elif extension in RAW_FIRMWARE_EXTNS:
# Note(deray): Assigning ``extract`` attribute to return
# 1. the firmware file itself
# 2. boolean (False) to indicate firmware file is not extracted
def dummy_extract(self):
return fw_img_extractor.fw_file, False
fw_img_extractor.extract = types.MethodType(
dummy_extract, fw_img_extractor)
else:
raise exception.InvalidInputError(
'Unexpected compact firmware file type: %s' % fw_file)
return fw_img_extractor | def get_fw_extractor(fw_file) | Gets the firmware extractor object fine-tuned for specified type
:param fw_file: compact firmware file to be extracted from
:raises: InvalidInputError, for unsupported file types
:returns: FirmwareImageExtractor object | 3.842394 | 3.89383 | 0.98679 |
# Command to extract the smart component file.
unpack_cmd = '--unpack=' + extract_path
# os.path.isfile(target_file)
cmd = [target_file, unpack_cmd]
out, err = utils.trycmd(*cmd) | def _extract_scexe_file(self, target_file, extract_path) | Extracts the scexe file.
:param target_file: the firmware file to be extracted from
:param extract_path: the path where extraction is supposed to happen | 8.97923 | 11.35624 | 0.790687 |
if not os.path.exists(extract_path):
os.makedirs(extract_path)
os.chdir(extract_path)
if find_executable('rpm2cpio') is None:
raise exception.ImageExtractionFailed(
image_ref=target_file, reason='Command `rpm2cpio` not found.')
if find_executable('cpio') is None:
raise exception.ImageExtractionFailed(
image_ref=target_file, reason='Command `cpio` not found.')
try:
rpm2cpio = subprocess.Popen('rpm2cpio ' + target_file,
shell=True,
stdout=subprocess.PIPE)
cpio = subprocess.Popen('cpio -idm', shell=True,
stdin=rpm2cpio.stdout)
out, err = cpio.communicate()
except (OSError, ValueError) as e:
raise exception.ImageExtractionFailed(
image_ref=target_file,
reason='Unexpected error in extracting file. ' + str(e)) | def _extract_rpm_file(self, target_file, extract_path) | Extracts the rpm file.
:param target_file: the firmware file to be extracted from
:param extract_path: the path where extraction is supposed to happen
:raises: ImageExtractionFailed, if any issue with extraction | 2.089199 | 1.994543 | 1.047457 |
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
file_name, file_ext = os.path.splitext(os.path.basename(filename))
if file_ext in RAW_FIRMWARE_EXTNS:
# return filename
return os.path.join(dirpath, filename) | def _get_firmware_file(path) | Gets the raw firmware file
Gets the raw firmware file from the extracted directory structure
:param path: the directory structure to search for
:returns: the raw firmware file with the complete path | 2.651539 | 2.780048 | 0.953774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.