sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def align(aligner, reads): ''' Test if reads can get aligned to the lambda genome, if not: write to stdout ''' i = 0 for record in SeqIO.parse(reads, "fastq"): try: next(aligner.map(str(record.seq))) i += 1 except StopIteration: print(record.format("fastq"), end='') sys.stderr.write("NanoLyse: removed {} reads.\n".format(i))
Test if reads can get aligned to the lambda genome, if not: write to stdout
entailment
def _convert_json_response_to_entities(response, property_resolver, require_encryption, key_encryption_key, key_resolver): ''' Converts the response to tables class. ''' if response is None or response.body is None: return None entities = _list() entities.next_marker = _get_continuation_from_response_headers(response) root = loads(response.body.decode('utf-8')) if 'value' in root: for entity in root['value']: entity = _decrypt_and_deserialize_entity(entity, property_resolver, require_encryption, key_encryption_key, key_resolver) entities.append(entity) else: entities.append(_convert_json_to_entity(entity, property_resolver)) return entities
Converts the response to tables class.
entailment
def _exec_ipmitool(driver_info, command): """Execute the ipmitool command. This uses the lanplus interface to communicate with the BMC device driver. :param driver_info: the ipmitool parameters for accessing a node. :param command: the ipmitool command to be executed. """ ipmi_cmd = ("ipmitool -H %(address)s" " -I lanplus -U %(user)s -P %(passwd)s %(cmd)s" % {'address': driver_info['address'], 'user': driver_info['username'], 'passwd': driver_info['password'], 'cmd': command}) out = None try: out = subprocess.check_output(ipmi_cmd, shell=True) except Exception: pass return out
Execute the ipmitool command. This uses the lanplus interface to communicate with the BMC device driver. :param driver_info: the ipmitool parameters for accessing a node. :param command: the ipmitool command to be executed.
entailment
def get_nic_capacity(driver_info, ilo_fw): """Gets the FRU data to see if it is NIC data Gets the FRU data in loop from 0-255 FRU Ids and check if the returned data is NIC data. Couldn't find any easy way to detect if it is NIC data. We should't be hardcoding the FRU Id. :param driver_info: Contains the access credentials to access the BMC. :param ilo_fw: a tuple containing major and minor versions of firmware :returns: the max capacity supported by the NIC adapter. """ i = 0x0 value = None ilo_fw_rev = get_ilo_version(ilo_fw) or DEFAULT_FW_REV # Note(vmud213): iLO firmware versions >= 2.3 support reading the FRU # information in a single call instead of iterating over each FRU id. if ilo_fw_rev < MIN_SUGGESTED_FW_REV: for i in range(0xff): # Note(vmud213): We can discard FRU ID's between 0x6e and 0xee # as they don't contain any NIC related information if (i < 0x6e) or (i > 0xee): cmd = "fru print %s" % hex(i) out = _exec_ipmitool(driver_info, cmd) if out and 'port' in out and 'Adapter' in out: value = _parse_ipmi_nic_capacity(out) if value is not None: break else: continue else: cmd = "fru print" out = _exec_ipmitool(driver_info, cmd) if out: for line in out.split('\n'): if line and 'port' in line and 'Adapter' in line: value = _parse_ipmi_nic_capacity(line) if value is not None: break return value
Gets the FRU data to see if it is NIC data Gets the FRU data in loop from 0-255 FRU Ids and check if the returned data is NIC data. Couldn't find any easy way to detect if it is NIC data. We should't be hardcoding the FRU Id. :param driver_info: Contains the access credentials to access the BMC. :param ilo_fw: a tuple containing major and minor versions of firmware :returns: the max capacity supported by the NIC adapter.
entailment
def _parse_ipmi_nic_capacity(nic_out): """Parse the FRU output for NIC capacity Parses the FRU output. Seraches for the key "Product Name" in FRU output and greps for maximum speed supported by the NIC adapter. :param nic_out: the FRU output for NIC adapter. :returns: the max capacity supported by the NIC adapter. """ if (("Device not present" in nic_out) or ("Unknown FRU header" in nic_out) or not nic_out): return None capacity = None product_name = None data = nic_out.split('\n') for item in data: fields = item.split(':') if len(fields) > 1: first_field = fields[0].strip() if first_field == "Product Name": # Join the string back if the Product Name had some # ':' by any chance product_name = ':'.join(fields[1:]) break if product_name: product_name_array = product_name.split(' ') for item in product_name_array: if 'Gb' in item: capacity_int = item.strip('Gb') if capacity_int.isdigit(): capacity = item return capacity
Parse the FRU output for NIC capacity Parses the FRU output. Seraches for the key "Product Name" in FRU output and greps for maximum speed supported by the NIC adapter. :param nic_out: the FRU output for NIC adapter. :returns: the max capacity supported by the NIC adapter.
entailment
def _extract_encryption_metadata(entity, require_encryption, key_encryption_key, key_resolver): ''' Extracts the encryption metadata from the given entity, setting them to be utf-8 strings. If no encryption metadata is present, will return None for all return values unless require_encryption is true, in which case the method will throw. :param entity: The entity being retrieved and decrypted. Could be a dict or an entity object. :param bool require_encryption: If set, will enforce that the retrieved entity is encrypted and decrypt it. :param object key_encryption_key: The user-provided key-encryption-key. Must implement the following methods: unwrap_key(key, algorithm)--returns the unwrapped form of the specified symmetric key using the string-specified algorithm. get_kid()--returns a string key id for this key-encryption-key. :param function key_resolver(kid): The user-provided key resolver. Uses the kid string to return a key-encryption-key implementing the interface defined above. :returns: a tuple containing the entity iv, the list of encrypted properties, the entity cek, and whether the entity was encrypted using JavaV1. :rtype: tuple (bytes[], list, bytes[], bool) ''' _validate_not_none('entity', entity) try: encrypted_properties_list = _decode_base64_to_bytes(entity['_ClientEncryptionMetadata2']) encryption_data = entity['_ClientEncryptionMetadata1'] encryption_data = _dict_to_encryption_data(loads(encryption_data)) except Exception as e: # Message did not have properly formatted encryption metadata. if require_encryption: raise ValueError(_ERROR_ENTITY_NOT_ENCRYPTED) else: return (None,None,None,None) if not(encryption_data.encryption_agent.encryption_algorithm == _EncryptionAlgorithm.AES_CBC_256): raise ValueError(_ERROR_UNSUPPORTED_ENCRYPTION_ALGORITHM) content_encryption_key = _validate_and_unwrap_cek(encryption_data, key_encryption_key, key_resolver) # Special check for compatibility with Java V1 encryption protocol. isJavaV1 = (encryption_data.key_wrapping_metadata is None) or \ ((encryption_data.encryption_agent.protocol == _ENCRYPTION_PROTOCOL_V1) and \ 'EncryptionLibrary' in encryption_data.key_wrapping_metadata and \ 'Java' in encryption_data.key_wrapping_metadata['EncryptionLibrary']) metadataIV = _generate_property_iv(encryption_data.content_encryption_IV, entity['PartitionKey'], entity['RowKey'], '_ClientEncryptionMetadata2', isJavaV1) cipher = _generate_AES_CBC_cipher(content_encryption_key, metadataIV) # Decrypt the data. decryptor = cipher.decryptor() encrypted_properties_list = decryptor.update(encrypted_properties_list) + decryptor.finalize() # Unpad the data. unpadder = PKCS7(128).unpadder() encrypted_properties_list = unpadder.update(encrypted_properties_list) + unpadder.finalize() encrypted_properties_list = encrypted_properties_list.decode('utf-8') if isJavaV1: # Strip the square braces from the ends and split string into list. encrypted_properties_list = encrypted_properties_list[1:-1] encrypted_properties_list = encrypted_properties_list.split(', ') else: encrypted_properties_list = loads(encrypted_properties_list) return (encryption_data.content_encryption_IV, encrypted_properties_list, content_encryption_key, isJavaV1)
Extracts the encryption metadata from the given entity, setting them to be utf-8 strings. If no encryption metadata is present, will return None for all return values unless require_encryption is true, in which case the method will throw. :param entity: The entity being retrieved and decrypted. Could be a dict or an entity object. :param bool require_encryption: If set, will enforce that the retrieved entity is encrypted and decrypt it. :param object key_encryption_key: The user-provided key-encryption-key. Must implement the following methods: unwrap_key(key, algorithm)--returns the unwrapped form of the specified symmetric key using the string-specified algorithm. get_kid()--returns a string key id for this key-encryption-key. :param function key_resolver(kid): The user-provided key resolver. Uses the kid string to return a key-encryption-key implementing the interface defined above. :returns: a tuple containing the entity iv, the list of encrypted properties, the entity cek, and whether the entity was encrypted using JavaV1. :rtype: tuple (bytes[], list, bytes[], bool)
entailment
def logical_drives(self): """Gets the resource HPELogicalDriveCollection of ArrayControllers""" return logical_drive.HPELogicalDriveCollection( self._conn, utils.get_subresource_path_by( self, ['Links', 'LogicalDrives']), redfish_version=self.redfish_version)
Gets the resource HPELogicalDriveCollection of ArrayControllers
entailment
def physical_drives(self): """Gets the resource HPEPhysicalDriveCollection of ArrayControllers""" return physical_drive.HPEPhysicalDriveCollection( self._conn, utils.get_subresource_path_by( self, ['Links', 'PhysicalDrives']), redfish_version=self.redfish_version)
Gets the resource HPEPhysicalDriveCollection of ArrayControllers
entailment
def logical_drives_maximum_size_mib(self): """Gets the biggest logical drive :returns the size in MiB. """ return utils.max_safe([member.logical_drives.maximum_size_mib for member in self.get_members()])
Gets the biggest logical drive :returns the size in MiB.
entailment
def physical_drives_maximum_size_mib(self): """Gets the biggest disk :returns the size in MiB. """ return utils.max_safe([member.physical_drives.maximum_size_mib for member in self.get_members()])
Gets the biggest disk :returns the size in MiB.
entailment
def has_ssd(self): """Return true if any of the drive under ArrayControllers is ssd""" for member in self.get_members(): if member.physical_drives.has_ssd: return True return False
Return true if any of the drive under ArrayControllers is ssd
entailment
def has_rotational(self): """Return true if any of the drive under ArrayControllers is ssd""" for member in self.get_members(): if member.physical_drives.has_rotational: return True return False
Return true if any of the drive under ArrayControllers is ssd
entailment
def logical_raid_levels(self): """Gets the raid level for each logical volume :returns the set of list of raid levels configured """ lg_raid_lvls = set() for member in self.get_members(): lg_raid_lvls.update(member.logical_drives.logical_raid_levels) return lg_raid_lvls
Gets the raid level for each logical volume :returns the set of list of raid levels configured
entailment
def array_controller_by_location(self, location): """Returns array controller instance by location :returns Instance of array controller """ for member in self.get_members(): if member.location == location: return member
Returns array controller instance by location :returns Instance of array controller
entailment
def array_controller_by_model(self, model): """Returns array controller instance by model :returns Instance of array controller """ for member in self.get_members(): if member.model == model: return member
Returns array controller instance by model :returns Instance of array controller
entailment
def get_subresource_path_by(resource, subresource_path): """Helper function to find the resource path :param resource: ResourceBase instance from which the path is loaded. :param subresource_path: JSON field to fetch the value from. Either a string, or a list of strings in case of a nested field. It should also include the '@odata.id' :raises: MissingAttributeError, if required path is missing. :raises: ValueError, if path is empty. :raises: AttributeError, if json attr not found in resource """ if isinstance(subresource_path, six.string_types): subresource_path = [subresource_path] elif not subresource_path: raise ValueError('"subresource_path" cannot be empty') body = resource.json for path_item in subresource_path: body = body.get(path_item, {}) if not body: raise exception.MissingAttributeError( attribute='/'.join(subresource_path), resource=resource.path) if '@odata.id' not in body: raise exception.MissingAttributeError( attribute='/'.join(subresource_path)+'/@odata.id', resource=resource.path) return body['@odata.id']
Helper function to find the resource path :param resource: ResourceBase instance from which the path is loaded. :param subresource_path: JSON field to fetch the value from. Either a string, or a list of strings in case of a nested field. It should also include the '@odata.id' :raises: MissingAttributeError, if required path is missing. :raises: ValueError, if path is empty. :raises: AttributeError, if json attr not found in resource
entailment
def get_supported_boot_mode(supported_boot_mode): """Return bios and uefi support. :param supported_boot_mode: Supported boot modes :return: A tuple of 'true'/'false' based on bios and uefi support respectively. """ boot_mode_bios = 'false' boot_mode_uefi = 'false' if (supported_boot_mode == sys_cons.SUPPORTED_LEGACY_BIOS_ONLY): boot_mode_bios = 'true' elif (supported_boot_mode == sys_cons.SUPPORTED_UEFI_ONLY): boot_mode_uefi = 'true' elif (supported_boot_mode == sys_cons.SUPPORTED_LEGACY_BIOS_AND_UEFI): boot_mode_bios = 'true' boot_mode_uefi = 'true' return SupportedBootModes(boot_mode_bios=boot_mode_bios, boot_mode_uefi=boot_mode_uefi)
Return bios and uefi support. :param supported_boot_mode: Supported boot modes :return: A tuple of 'true'/'false' based on bios and uefi support respectively.
entailment
def get_allowed_operations(resource, subresouce_path): """Helper function to get the HTTP allowed methods. :param resource: ResourceBase instance from which the path is loaded. :param subresource_path: JSON field to fetch the value from. Either a string, or a list of strings in case of a nested field. :returns: A list of allowed HTTP methods. """ uri = get_subresource_path_by(resource, subresouce_path) response = resource._conn.get(path=uri) return response.headers['Allow']
Helper function to get the HTTP allowed methods. :param resource: ResourceBase instance from which the path is loaded. :param subresource_path: JSON field to fetch the value from. Either a string, or a list of strings in case of a nested field. :returns: A list of allowed HTTP methods.
entailment
def _set_next_host_location(self, context): ''' A function which sets the next host location on the request, if applicable. :param ~azure.storage.models.RetryContext context: The retry context containing the previous host location and the request to evaluate and possibly modify. ''' if len(context.request.host_locations) > 1: # If there's more than one possible location, retry to the alternative if context.location_mode == LocationMode.PRIMARY: context.location_mode = LocationMode.SECONDARY else: context.location_mode = LocationMode.PRIMARY context.request.host = context.request.host_locations.get(context.location_mode)
A function which sets the next host location on the request, if applicable. :param ~azure.storage.models.RetryContext context: The retry context containing the previous host location and the request to evaluate and possibly modify.
entailment
def _op(self, method, path='', data=None, headers=None): """Overrides the base method to support retrying the operation. :param method: The HTTP method to be used, e.g: GET, POST, PUT, PATCH, etc... :param path: The sub-URI path to the resource. :param data: Optional JSON data. :param headers: Optional dictionary of headers. :returns: The response from the connector.Connector's _op method. """ resp = super(HPEConnector, self)._op(method, path, data, headers, allow_redirects=False) # With IPv6, Gen10 server gives redirection response with new path with # a prefix of '/' so this check is required if resp.status_code == 308: path = urlparse(resp.headers['Location']).path resp = super(HPEConnector, self)._op(method, path, data, headers) return resp
Overrides the base method to support retrying the operation. :param method: The HTTP method to be used, e.g: GET, POST, PUT, PATCH, etc... :param path: The sub-URI path to the resource. :param data: Optional JSON data. :param headers: Optional dictionary of headers. :returns: The response from the connector.Connector's _op method.
entailment
def generate_file_shared_access_signature(self, share_name, directory_name=None, file_name=None, permission=None, expiry=None, start=None, id=None, ip=None, protocol=None, cache_control=None, content_disposition=None, content_encoding=None, content_language=None, content_type=None): ''' Generates a shared access signature for the file. Use the returned signature with the sas_token parameter of FileService. :param str share_name: Name of share. :param str directory_name: Name of directory. SAS tokens cannot be created for directories, so this parameter should only be present if file_name is provided. :param str file_name: Name of file. :param FilePermissions permission: The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Permissions must be ordered read, create, write, delete, list. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. :param expiry: The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC. :type expiry: date or str :param start: The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC. :type start: date or str :param str id: A unique value up to 64 characters in length that correlates to a stored access policy. To create a stored access policy, use set_file_service_properties. :param str ip: Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses. :param str protocol: Specifies the protocol permitted for a request made. Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. Note that HTTP only is not a permitted value. :param str cache_control: Response header value for Cache-Control when resource is accessed using this shared access signature. :param str content_disposition: Response header value for Content-Disposition when resource is accessed using this shared access signature. :param str content_encoding: Response header value for Content-Encoding when resource is accessed using this shared access signature. :param str content_language: Response header value for Content-Language when resource is accessed using this shared access signature. :param str content_type: Response header value for Content-Type when resource is accessed using this shared access signature. :return: A Shared Access Signature (sas) token. :rtype: str ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('self.account_name', self.account_name) _validate_not_none('self.account_key', self.account_key) sas = SharedAccessSignature(self.account_name, self.account_key) return sas.generate_file( share_name, directory_name, file_name, permission, expiry, start=start, id=id, ip=ip, protocol=protocol, cache_control=cache_control, content_disposition=content_disposition, content_encoding=content_encoding, content_language=content_language, content_type=content_type, )
Generates a shared access signature for the file. Use the returned signature with the sas_token parameter of FileService. :param str share_name: Name of share. :param str directory_name: Name of directory. SAS tokens cannot be created for directories, so this parameter should only be present if file_name is provided. :param str file_name: Name of file. :param FilePermissions permission: The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Permissions must be ordered read, create, write, delete, list. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. :param expiry: The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC. :type expiry: date or str :param start: The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC. :type start: date or str :param str id: A unique value up to 64 characters in length that correlates to a stored access policy. To create a stored access policy, use set_file_service_properties. :param str ip: Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses. :param str protocol: Specifies the protocol permitted for a request made. Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. Note that HTTP only is not a permitted value. :param str cache_control: Response header value for Cache-Control when resource is accessed using this shared access signature. :param str content_disposition: Response header value for Content-Disposition when resource is accessed using this shared access signature. :param str content_encoding: Response header value for Content-Encoding when resource is accessed using this shared access signature. :param str content_language: Response header value for Content-Language when resource is accessed using this shared access signature. :param str content_type: Response header value for Content-Type when resource is accessed using this shared access signature. :return: A Shared Access Signature (sas) token. :rtype: str
entailment
def set_file_service_properties(self, hour_metrics=None, minute_metrics=None, cors=None, timeout=None): ''' Sets the properties of a storage account's File service, including Azure Storage Analytics. If an element (ex HourMetrics) is left as None, the existing settings on the service for that functionality are preserved. :param Metrics hour_metrics: The hour metrics settings provide a summary of request statistics grouped by API in hourly aggregates for files. :param Metrics minute_metrics: The minute metrics settings provide request statistics for each minute for files. :param cors: You can include up to five CorsRule elements in the list. If an empty list is specified, all CORS rules will be deleted, and CORS will be disabled for the service. :type cors: list of :class:`~azure.storage.models.CorsRule` :param int timeout: The timeout parameter is expressed in seconds. ''' request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path() request.query = [ ('restype', 'service'), ('comp', 'properties'), ('timeout', _int_to_str(timeout)), ] request.body = _get_request_body( _convert_service_properties_to_xml(None, hour_metrics, minute_metrics, cors)) self._perform_request(request)
Sets the properties of a storage account's File service, including Azure Storage Analytics. If an element (ex HourMetrics) is left as None, the existing settings on the service for that functionality are preserved. :param Metrics hour_metrics: The hour metrics settings provide a summary of request statistics grouped by API in hourly aggregates for files. :param Metrics minute_metrics: The minute metrics settings provide request statistics for each minute for files. :param cors: You can include up to five CorsRule elements in the list. If an empty list is specified, all CORS rules will be deleted, and CORS will be disabled for the service. :type cors: list of :class:`~azure.storage.models.CorsRule` :param int timeout: The timeout parameter is expressed in seconds.
entailment
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. ''' include = 'metadata' if include_metadata else None kwargs = {'prefix': prefix, 'marker': marker, 'max_results': num_results, 'include': include, 'timeout': timeout} resp = self._list_shares(**kwargs) return ListGenerator(resp, self._list_shares, (), kwargs)
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.
entailment
def get_share_properties(self, share_name, timeout=None): ''' Returns all user-defined metadata and system properties for the specified share. The data returned does not include the shares's list of files or directories. :param str share_name: Name of existing share. :param int timeout: The timeout parameter is expressed in seconds. :return: A Share that exposes properties and metadata. :rtype: :class:`.Share` ''' _validate_not_none('share_name', share_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(share_name) request.query = [ ('restype', 'share'), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _parse_share(share_name, response)
Returns all user-defined metadata and system properties for the specified share. The data returned does not include the shares's list of files or directories. :param str share_name: Name of existing share. :param int timeout: The timeout parameter is expressed in seconds. :return: A Share that exposes properties and metadata. :rtype: :class:`.Share`
entailment
def set_share_properties(self, share_name, quota, timeout=None): ''' Sets service-defined properties for the specified share. :param str share_name: Name of existing share. :param int quota: Specifies the maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5 TB (5120 GB). :param int timeout: The timeout parameter is expressed in seconds. ''' _validate_not_none('share_name', share_name) _validate_not_none('quota', quota) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(share_name) request.query = [ ('restype', 'share'), ('comp', 'properties'), ('timeout', _int_to_str(timeout)), ] request.headers = [('x-ms-share-quota', _int_to_str(quota))] self._perform_request(request)
Sets service-defined properties for the specified share. :param str share_name: Name of existing share. :param int quota: Specifies the maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5 TB (5120 GB). :param int timeout: The timeout parameter is expressed in seconds.
entailment
def get_share_metadata(self, share_name, timeout=None): ''' Returns all user-defined metadata for the specified share. :param str share_name: Name of existing share. :param int timeout: The timeout parameter is expressed in seconds. :return: A dictionary representing the share metadata name, value pairs. :rtype: a dict mapping str to str ''' _validate_not_none('share_name', share_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(share_name) request.query = [ ('restype', 'share'), ('comp', 'metadata'), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _parse_metadata(response)
Returns all user-defined metadata for the specified share. :param str share_name: Name of existing share. :param int timeout: The timeout parameter is expressed in seconds. :return: A dictionary representing the share metadata name, value pairs. :rtype: a dict mapping str to str
entailment
def get_share_stats(self, share_name, timeout=None): ''' Gets the approximate size of the data stored on the share, rounded up to the nearest gigabyte. Note that this value may not include all recently created or recently resized files. :param str share_name: Name of existing share. :param int timeout: The timeout parameter is expressed in seconds. :return: the approximate size of the data stored on the share. :rtype: int ''' _validate_not_none('share_name', share_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(share_name) request.query = [ ('restype', 'share'), ('comp', 'stats'), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _convert_xml_to_share_stats(response)
Gets the approximate size of the data stored on the share, rounded up to the nearest gigabyte. Note that this value may not include all recently created or recently resized files. :param str share_name: Name of existing share. :param int timeout: The timeout parameter is expressed in seconds. :return: the approximate size of the data stored on the share. :rtype: int
entailment
def list_directories_and_files(self, share_name, directory_name=None, num_results=None, marker=None, timeout=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 containers, 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. ''' args = (share_name, directory_name) kwargs = {'marker': marker, 'max_results': num_results, 'timeout': timeout} resp = self._list_directories_and_files(*args, **kwargs) return ListGenerator(resp, self._list_directories_and_files, args, kwargs)
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 containers, 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.
entailment
def _list_directories_and_files(self, share_name, directory_name=None, marker=None, max_results=None, timeout=None): ''' Returns a list of the directories and files under the specified share. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str marker: A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a next_marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. :param int max_results: Specifies the maximum number of files to return, including all directory elements. If the request does not specify max_results or specifies a value greater than 5,000, the server will return up to 5,000 items. Setting max_results to a value less than or equal to zero results in error response code 400 (Bad Request). :param int timeout: The timeout parameter is expressed in seconds. ''' _validate_not_none('share_name', share_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(share_name, directory_name) request.query = [ ('restype', 'directory'), ('comp', 'list'), ('marker', _to_str(marker)), ('maxresults', _int_to_str(max_results)), ('timeout', _int_to_str(timeout)), ] response = self._perform_request(request) return _convert_xml_to_directories_and_files(response)
Returns a list of the directories and files under the specified share. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str marker: A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a next_marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. :param int max_results: Specifies the maximum number of files to return, including all directory elements. If the request does not specify max_results or specifies a value greater than 5,000, the server will return up to 5,000 items. Setting max_results to a value less than or equal to zero results in error response code 400 (Bad Request). :param int timeout: The timeout parameter is expressed in seconds.
entailment
def set_file_properties(self, share_name, directory_name, file_name, content_settings, timeout=None): ''' Sets system properties on the file. If one property is set for the content_settings, all properties will be overriden. :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 ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set the file properties. :param int timeout: The timeout parameter is expressed in seconds. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('content_settings', content_settings) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(share_name, directory_name, file_name) request.query = [ ('comp', 'properties'), ('timeout', _int_to_str(timeout)), ] request.headers = None request.headers = content_settings._to_headers() self._perform_request(request)
Sets system properties on the file. If one property is set for the content_settings, all properties will be overriden. :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 ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set the file properties. :param int timeout: The timeout parameter is expressed in seconds.
entailment
def copy_file(self, share_name, directory_name, file_name, copy_source, metadata=None, timeout=None): ''' Copies a blob or file to a destination file within the storage account. :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 str copy_source: Specifies the URL of the source blob or file, up to 2 KB in length. A source file in the same account can be private, but a file in another account must be public or accept credentials included in this URL, such as a Shared Access Signature. Examples: https://myaccount.file.core.windows.net/myshare/mydirectory/myfile :param metadata: Dict containing name, value pairs. :type metadata: A dict mapping str to str. :param int timeout: The timeout parameter is expressed in seconds. :return: Copy operation properties such as status, source, and ID. :rtype: :class:`~azure.storage.file.models.CopyProperties` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('copy_source', copy_source) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(share_name, directory_name, file_name) request.query = [('timeout', _int_to_str(timeout))] request.headers = [ ('x-ms-copy-source', _to_str(copy_source)), ('x-ms-meta-name-values', metadata), ] response = self._perform_request(request) props = _parse_properties(response, FileProperties) return props.copy
Copies a blob or file to a destination file within the storage account. :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 str copy_source: Specifies the URL of the source blob or file, up to 2 KB in length. A source file in the same account can be private, but a file in another account must be public or accept credentials included in this URL, such as a Shared Access Signature. Examples: https://myaccount.file.core.windows.net/myshare/mydirectory/myfile :param metadata: Dict containing name, value pairs. :type metadata: A dict mapping str to str. :param int timeout: The timeout parameter is expressed in seconds. :return: Copy operation properties such as status, source, and ID. :rtype: :class:`~azure.storage.file.models.CopyProperties`
entailment
def create_file(self, share_name, directory_name, file_name, content_length, content_settings=None, metadata=None, timeout=None): ''' Creates a new file. See create_file_from_* for high level functions that handle the creation and upload 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 file to create or update. :param int content_length: Length of the file in bytes. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param int timeout: The timeout parameter is expressed in seconds. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('content_length', content_length) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(share_name, directory_name, file_name) request.query = [('timeout', _int_to_str(timeout))] request.headers = [ ('x-ms-meta-name-values', metadata), ('x-ms-content-length', _to_str(content_length)), ('x-ms-type', 'file') ] if content_settings is not None: request.headers += content_settings._to_headers() self._perform_request(request)
Creates a new file. See create_file_from_* for high level functions that handle the creation and upload 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 file to create or update. :param int content_length: Length of the file in bytes. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param int timeout: The timeout parameter is expressed in seconds.
entailment
def create_file_from_text(self, share_name, directory_name, file_name, text, encoding='utf-8', content_settings=None, metadata=None, timeout=None): ''' Creates a new file from str/unicode, or updates the content of an existing file, 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 file to create or update. :param str text: Text to upload to the file. :param str encoding: Python encoding to use to convert the text to bytes. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('text', text) if not isinstance(text, bytes): _validate_not_none('encoding', encoding) text = text.encode(encoding) self.create_file_from_bytes( share_name, directory_name, file_name, text, 0, len(text), content_settings, metadata, timeout)
Creates a new file from str/unicode, or updates the content of an existing file, 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 file to create or update. :param str text: Text to upload to the file. :param str encoding: Python encoding to use to convert the text to bytes. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually.
entailment
def create_file_from_bytes( self, share_name, directory_name, file_name, file, index=0, count=None, content_settings=None, metadata=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Creates a new file from an array of bytes, or updates the content of an existing file, 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 file to create or update. :param str file: Content of file as an array of bytes. :param int index: Start index in the array of bytes. :param int count: Number of bytes to upload. Set to None or negative value to upload all bytes starting from index. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far and total is the size of the file, or None if the total size is unknown. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Maximum number of parallel connections to use when the file size exceeds 64MB. Set to 1 to upload the file chunks sequentially. Set to 2 or more to upload the file chunks in parallel. This uses more system resources but will upload faster. :param int max_retries: Number of times to retry upload of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('file', file) _validate_type_bytes('file', file) if index < 0: raise TypeError(_ERROR_VALUE_NEGATIVE.format('index')) if count is None or count < 0: count = len(file) - index stream = BytesIO(file) stream.seek(index) self.create_file_from_stream( share_name, directory_name, file_name, stream, count, content_settings, metadata, progress_callback, max_connections, max_retries, retry_wait, timeout)
Creates a new file from an array of bytes, or updates the content of an existing file, 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 file to create or update. :param str file: Content of file as an array of bytes. :param int index: Start index in the array of bytes. :param int count: Number of bytes to upload. Set to None or negative value to upload all bytes starting from index. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far and total is the size of the file, or None if the total size is unknown. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Maximum number of parallel connections to use when the file size exceeds 64MB. Set to 1 to upload the file chunks sequentially. Set to 2 or more to upload the file chunks in parallel. This uses more system resources but will upload faster. :param int max_retries: Number of times to retry upload of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually.
entailment
def create_file_from_stream( self, share_name, directory_name, file_name, stream, count, content_settings=None, metadata=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Creates a new file from a file/stream, or updates the content of an existing file, 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 file to create or update. :param io.IOBase stream: Opened file/stream to upload as the file content. :param int count: Number of bytes to read from the stream. This is required, a file cannot be created if the count is unknown. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far and total is the size of the file, or None if the total size is unknown. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Maximum number of parallel connections to use when the file size exceeds 64MB. Set to 1 to upload the file chunks sequentially. Set to 2 or more to upload the file chunks in parallel. This uses more system resources but will upload faster. Note that parallel upload requires the stream to be seekable. :param int max_retries: Number of times to retry upload of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('stream', stream) _validate_not_none('count', count) if count < 0: raise TypeError(_ERROR_VALUE_NEGATIVE.format('count')) self.create_file( share_name, directory_name, file_name, count, content_settings, metadata, timeout ) _upload_file_chunks( self, share_name, directory_name, file_name, count, self.MAX_RANGE_SIZE, stream, max_connections, max_retries, retry_wait, progress_callback, timeout )
Creates a new file from a file/stream, or updates the content of an existing file, 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 file to create or update. :param io.IOBase stream: Opened file/stream to upload as the file content. :param int count: Number of bytes to read from the stream. This is required, a file cannot be created if the count is unknown. :param ~azure.storage.file.models.ContentSettings content_settings: ContentSettings object used to set file properties. :param metadata: Name-value pairs associated with the file as metadata. :type metadata: a dict mapping str to str :param progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far and total is the size of the file, or None if the total size is unknown. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Maximum number of parallel connections to use when the file size exceeds 64MB. Set to 1 to upload the file chunks sequentially. Set to 2 or more to upload the file chunks in parallel. This uses more system resources but will upload faster. Note that parallel upload requires the stream to be seekable. :param int max_retries: Number of times to retry upload of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually.
entailment
def _get_file(self, share_name, directory_name, file_name, start_range=None, end_range=None, range_get_content_md5=None, timeout=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 range_get_content_md5: When this header 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 = self._get_host() 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=range_get_content_md5) response = self._perform_request(request, None) return _parse_file(file_name, response)
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 range_get_content_md5: When this header 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`
entailment
def get_file_to_path(self, share_name, directory_name, file_name, file_path, open_mode='wb', start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file to a file path, with automatic chunking and progress notifications. Returns an instance of File with properties and metadata. :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 str file_path: Path of file to write to. :param str open_mode: Mode to use when opening the 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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties and metadata. :rtype: :class:`~azure.storage.file.models.File` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('file_path', file_path) _validate_not_none('open_mode', open_mode) with open(file_path, open_mode) as stream: file = self.get_file_to_stream( share_name, directory_name, file_name, stream, start_range, end_range, range_get_content_md5, progress_callback, max_connections, max_retries, retry_wait, timeout) return file
Downloads a file to a file path, with automatic chunking and progress notifications. Returns an instance of File with properties and metadata. :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 str file_path: Path of file to write to. :param str open_mode: Mode to use when opening the 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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties and metadata. :rtype: :class:`~azure.storage.file.models.File`
entailment
def get_file_to_stream( self, share_name, directory_name, file_name, stream, start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file to a stream, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties and metadata. :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 io.IOBase stream: Opened file/stream to write to. :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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties and metadata. :rtype: :class:`~azure.storage.file.models.File` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('stream', stream) if sys.version_info >= (3,) and max_connections > 1 and not stream.seekable(): raise ValueError(_ERROR_PARALLEL_NOT_SEEKABLE) # Only get properties if parallelism will actually be used file_size = None if max_connections > 1 and range_get_content_md5 is None: file = self.get_file_properties(share_name, directory_name, file_name, timeout=timeout) file_size = file.properties.content_length # If file size is large, use parallel download if file_size >= self.MAX_SINGLE_GET_SIZE: _download_file_chunks( self, share_name, directory_name, file_name, file_size, self.MAX_CHUNK_GET_SIZE, start_range, end_range, stream, max_connections, max_retries, retry_wait, progress_callback, timeout ) return file # If parallelism is off or the file is small, do a single download download_size = _get_download_size(start_range, end_range, file_size) if progress_callback: progress_callback(0, download_size) file = self._get_file( share_name, directory_name, file_name, start_range=start_range, end_range=end_range, range_get_content_md5=range_get_content_md5, timeout=timeout) if file.content is not None: stream.write(file.content) if progress_callback: download_size = len(file.content) progress_callback(download_size, download_size) file.content = None # Clear file content since output has been written to user stream return file
Downloads a file to a stream, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties and metadata. :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 io.IOBase stream: Opened file/stream to write to. :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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties and metadata. :rtype: :class:`~azure.storage.file.models.File`
entailment
def get_file_to_bytes(self, share_name, directory_name, file_name, start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file as an array of bytes, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties, metadata, and content. :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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties, content, and metadata. :rtype: :class:`~azure.storage.file.models.File` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) stream = BytesIO() file = self.get_file_to_stream( share_name, directory_name, file_name, stream, start_range, end_range, range_get_content_md5, progress_callback, max_connections, max_retries, retry_wait, timeout) file.content = stream.getvalue() return file
Downloads a file as an array of bytes, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties, metadata, and content. :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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties, content, and metadata. :rtype: :class:`~azure.storage.file.models.File`
entailment
def get_file_to_text( self, share_name, directory_name, file_name, encoding='utf-8', start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file as unicode text, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties, metadata, and content. :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 str encoding: Python encoding to use when decoding the file data. :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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties, content, and metadata. :rtype: :class:`~azure.storage.file.models.File` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('encoding', encoding) file = self.get_file_to_bytes( share_name, directory_name, file_name, start_range, end_range, range_get_content_md5, progress_callback, max_connections, max_retries, retry_wait, timeout) file.content = file.content.decode(encoding) return file
Downloads a file as unicode text, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties, metadata, and content. :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 str encoding: Python encoding to use when decoding the file data. :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 range_get_content_md5: When this header 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 progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties, content, and metadata. :rtype: :class:`~azure.storage.file.models.File`
entailment
def update_range(self, share_name, directory_name, file_name, data, start_range, end_range, content_md5=None, timeout=None): ''' Writes the bytes specified by the request body into the specified range. :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 bytes data: Content of the range. :param int start_range: Start of byte range to use for updating a section of the file. The range can be up to 4 MB in size. 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 updating a section of the file. The range can be up to 4 MB in size. The start_range and end_range params are inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of file. :param str content_md5: An MD5 hash of the range content. This hash is used to verify the integrity of the range during transport. When this header is specified, the storage service compares the hash of the content that has arrived with the header value that was sent. If the two hashes do not match, the operation will fail with error code 400 (Bad Request). :param int timeout: The timeout parameter is expressed in seconds. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('data', data) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(share_name, directory_name, file_name) request.query = [ ('comp', 'range'), ('timeout', _int_to_str(timeout)), ] request.headers = [ ('Content-MD5', _to_str(content_md5)), ('x-ms-write', 'update'), ] _validate_and_format_range_headers( request, start_range, end_range) request.body = _get_request_body_bytes_only('data', data) self._perform_request(request)
Writes the bytes specified by the request body into the specified range. :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 bytes data: Content of the range. :param int start_range: Start of byte range to use for updating a section of the file. The range can be up to 4 MB in size. 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 updating a section of the file. The range can be up to 4 MB in size. The start_range and end_range params are inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of file. :param str content_md5: An MD5 hash of the range content. This hash is used to verify the integrity of the range during transport. When this header is specified, the storage service compares the hash of the content that has arrived with the header value that was sent. If the two hashes do not match, the operation will fail with error code 400 (Bad Request). :param int timeout: The timeout parameter is expressed in seconds.
entailment
def clear_range(self, share_name, directory_name, file_name, start_range, end_range, timeout=None): ''' Clears the specified range and releases the space used in storage for that range. :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 clearing a section of the file. The range can be up to 4 MB in size. 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 clearing a section of the file. The range can be up to 4 MB in size. 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 timeout: The timeout parameter is expressed in seconds. ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = _get_path(share_name, directory_name, file_name) request.query = [ ('comp', 'range'), ('timeout', _int_to_str(timeout)), ] request.headers = [ ('Content-Length', '0'), ('x-ms-write', 'clear'), ] _validate_and_format_range_headers( request, start_range, end_range) self._perform_request(request)
Clears the specified range and releases the space used in storage for that range. :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 clearing a section of the file. The range can be up to 4 MB in size. 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 clearing a section of the file. The range can be up to 4 MB in size. 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 timeout: The timeout parameter is expressed in seconds.
entailment
def list_ranges(self, share_name, directory_name, file_name, start_range=None, end_range=None, timeout=None): ''' Retrieves the valid ranges for a file. :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: Specifies the start offset of bytes over which to list ranges. 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: Specifies the end offset of bytes over which to list ranges. 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 timeout: The timeout parameter is expressed in seconds. :returns: a list of valid ranges :rtype: a list of :class:`.FileRange` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = _get_path(share_name, directory_name, file_name) request.query = [ ('comp', 'rangelist'), ('timeout', _int_to_str(timeout)), ] if start_range is not None: _validate_and_format_range_headers( request, start_range, end_range, start_range_required=False, end_range_required=False) response = self._perform_request(request) return _convert_xml_to_ranges(response)
Retrieves the valid ranges for a file. :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: Specifies the start offset of bytes over which to list ranges. 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: Specifies the end offset of bytes over which to list ranges. 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 timeout: The timeout parameter is expressed in seconds. :returns: a list of valid ranges :rtype: a list of :class:`.FileRange`
entailment
def _get_sushy_system(self, system_id): """Get the sushy system for system_id :param system_id: The identity of the System resource :returns: the Sushy system instance :raises: IloError """ system_url = parse.urljoin(self._sushy.get_system_collection_path(), system_id) try: return self._sushy.get_system(system_url) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish System "%(system)s" was not found. ' 'Error %(error)s') % {'system': system_id, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Get the sushy system for system_id :param system_id: The identity of the System resource :returns: the Sushy system instance :raises: IloError
entailment
def _get_sushy_manager(self, manager_id): """Get the sushy Manager for manager_id :param manager_id: The identity of the Manager resource :returns: the Sushy Manager instance :raises: IloError """ manager_url = parse.urljoin(self._sushy.get_manager_collection_path(), manager_id) try: return self._sushy.get_manager(manager_url) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish Manager "%(manager)s" was not found. ' 'Error %(error)s') % {'manager': manager_id, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Get the sushy Manager for manager_id :param manager_id: The identity of the Manager resource :returns: the Sushy Manager instance :raises: IloError
entailment
def get_host_power_status(self): """Request the power state of the server. :returns: Power State of the server, 'ON' or 'OFF' :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) return GET_POWER_STATE_MAP.get(sushy_system.power_state)
Request the power state of the server. :returns: Power State of the server, 'ON' or 'OFF' :raises: IloError, on an error from iLO.
entailment
def reset_server(self): """Resets the server. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.reset_system(sushy.RESET_FORCE_RESTART) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to reset server. ' 'Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Resets the server. :raises: IloError, on an error from iLO.
entailment
def set_host_power(self, target_value): """Sets the power state of the system. :param target_value: The target value to be set. Value can be: 'ON' or 'OFF'. :raises: IloError, on an error from iLO. :raises: InvalidInputError, if the target value is not allowed. """ if target_value not in POWER_RESET_MAP: msg = ('The parameter "%(parameter)s" value "%(target_value)s" is ' 'invalid. Valid values are: %(valid_power_values)s' % {'parameter': 'target_value', 'target_value': target_value, 'valid_power_values': POWER_RESET_MAP.keys()}) raise exception.InvalidInputError(msg) # Check current power status, do not act if it's in requested state. current_power_status = self.get_host_power_status() if current_power_status == target_value: LOG.debug(self._("Node is already in '%(target_value)s' power " "state."), {'target_value': target_value}) return sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.reset_system(POWER_RESET_MAP[target_value]) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to set power state ' 'of server to %(target_value)s. Error %(error)s') % {'target_value': target_value, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Sets the power state of the system. :param target_value: The target value to be set. Value can be: 'ON' or 'OFF'. :raises: IloError, on an error from iLO. :raises: InvalidInputError, if the target value is not allowed.
entailment
def press_pwr_btn(self): """Simulates a physical press of the server power button. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.push_power_button(sys_cons.PUSH_POWER_BUTTON_PRESS) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to press power button' ' of server. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Simulates a physical press of the server power button. :raises: IloError, on an error from iLO.
entailment
def activate_license(self, key): """Activates iLO license. :param key: iLO license key. :raises: IloError, on an error from iLO. """ sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID) try: sushy_manager.set_license(key) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to update ' 'the license. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Activates iLO license. :param key: iLO license key. :raises: IloError, on an error from iLO.
entailment
def get_one_time_boot(self): """Retrieves the current setting for the one time boot. :returns: Returns boot device that would be used in next boot. Returns 'Normal' if no device is set. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if (sushy_system.boot.enabled == sushy.BOOT_SOURCE_ENABLED_ONCE): return DEVICE_REDFISH_TO_COMMON.get(sushy_system.boot.target) else: # value returned by RIBCL if one-time boot setting are absent return 'Normal'
Retrieves the current setting for the one time boot. :returns: Returns boot device that would be used in next boot. Returns 'Normal' if no device is set.
entailment
def get_pending_boot_mode(self): """Retrieves the pending boot mode of the server. Gets the boot mode to be set on next reset. :returns: either LEGACY or UEFI. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: return BOOT_MODE_MAP.get( sushy_system.bios_settings.pending_settings.boot_mode) except sushy.exceptions.SushyError as e: msg = (self._('The pending BIOS Settings was not found. Error ' '%(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Retrieves the pending boot mode of the server. Gets the boot mode to be set on next reset. :returns: either LEGACY or UEFI. :raises: IloError, on an error from iLO.
entailment
def _validate_virtual_media(self, device): """Check if the device is valid device. :param device: virtual media device :raises: IloInvalidInputError, if the device is not valid. """ if device not in VIRTUAL_MEDIA_MAP: msg = (self._("Invalid device '%s'. Valid devices: FLOPPY or " "CDROM.") % device) LOG.debug(msg) raise exception.IloInvalidInputError(msg)
Check if the device is valid device. :param device: virtual media device :raises: IloInvalidInputError, if the device is not valid.
entailment
def eject_virtual_media(self, device): """Ejects the Virtual Media image if one is inserted. :param device: virual media device :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the device is not valid. """ self._validate_virtual_media(device) manager = self._get_sushy_manager(PROLIANT_MANAGER_ID) try: vmedia_device = ( manager.virtual_media.get_member_device( VIRTUAL_MEDIA_MAP[device])) if not vmedia_device.inserted: LOG.debug(self._("No media available in the device '%s' to " "perform eject operation.") % device) return LOG.debug(self._("Ejecting the media image '%(url)s' from the " "device %(device)s.") % {'url': vmedia_device.image, 'device': device}) vmedia_device.eject_media() except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller failed to eject the virtual" " media device '%(device)s'. Error %(error)s.") % {'device': device, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Ejects the Virtual Media image if one is inserted. :param device: virual media device :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the device is not valid.
entailment
def set_vm_status(self, device='FLOPPY', boot_option='BOOT_ONCE', write_protect='YES'): """Sets the Virtual Media drive status It sets the boot option for virtual media device. Note: boot option can be set only for CD device. :param device: virual media device :param boot_option: boot option to set on the virtual media device :param write_protect: set the write protect flag on the vmedia device Note: It's ignored. In Redfish it is read-only. :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the device is not valid. """ # CONNECT is a RIBCL call. There is no such property to set in Redfish. if boot_option == 'CONNECT': return self._validate_virtual_media(device) if boot_option not in BOOT_OPTION_MAP: msg = (self._("Virtual media boot option '%s' is invalid.") % boot_option) LOG.debug(msg) raise exception.IloInvalidInputError(msg) manager = self._get_sushy_manager(PROLIANT_MANAGER_ID) try: vmedia_device = ( manager.virtual_media.get_member_device( VIRTUAL_MEDIA_MAP[device])) vmedia_device.set_vm_status(BOOT_OPTION_MAP[boot_option]) except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller failed to set the virtual " "media status for '%(device)s'. Error %(error)s") % {'device': device, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Sets the Virtual Media drive status It sets the boot option for virtual media device. Note: boot option can be set only for CD device. :param device: virual media device :param boot_option: boot option to set on the virtual media device :param write_protect: set the write protect flag on the vmedia device Note: It's ignored. In Redfish it is read-only. :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the device is not valid.
entailment
def update_firmware(self, file_url, component_type): """Updates the given firmware on the server for the given component. :param file_url: 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: IloError, on an error from iLO. """ try: update_service_inst = self._sushy.get_update_service() update_service_inst.flash_firmware(self, file_url) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to update firmware ' 'with firmware %(file)s Error %(error)s') % {'file': file_url, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Updates the given firmware on the server for the given component. :param file_url: 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: IloError, on an error from iLO.
entailment
def _is_boot_mode_uefi(self): """Checks if the system is in uefi boot mode. :return: 'True' if the boot mode is uefi else 'False' """ boot_mode = self.get_current_boot_mode() return (boot_mode == BOOT_MODE_MAP.get(sys_cons.BIOS_BOOT_MODE_UEFI))
Checks if the system is in uefi boot mode. :return: 'True' if the boot mode is uefi else 'False'
entailment
def get_persistent_boot_device(self): """Get current persistent boot device set for the host :returns: persistent boot device for the system :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) # Return boot device if it is persistent. if ((sushy_system. boot.enabled) == sushy.BOOT_SOURCE_ENABLED_CONTINUOUS): return PERSISTENT_BOOT_MAP.get(sushy_system.boot.target) # Check if we are in BIOS boot mode. # There is no resource to fetch boot device order for BIOS boot mode if not self._is_boot_mode_uefi(): return None try: boot_device = (sushy_system.bios_settings.boot_settings. get_persistent_boot_device()) return PERSISTENT_BOOT_MAP.get(boot_device) except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller is unable to get " "persistent boot device. Error %(error)s") % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Get current persistent boot device set for the host :returns: persistent boot device for the system :raises: IloError, on an error from iLO.
entailment
def set_pending_boot_mode(self, boot_mode): """Sets the boot mode of the system for next boot. :param boot_mode: either 'uefi' or 'legacy'. :raises: IloInvalidInputError, on an invalid input. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if boot_mode.upper() not in BOOT_MODE_MAP_REV.keys(): msg = (('Invalid Boot mode: "%(boot_mode)s" specified, valid boot ' 'modes are either "uefi" or "legacy"') % {'boot_mode': boot_mode}) raise exception.IloInvalidInputError(msg) try: sushy_system.bios_settings.pending_settings.set_pending_boot_mode( BOOT_MODE_MAP_REV.get(boot_mode.upper())) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to set ' 'pending boot mode to %(boot_mode)s. ' 'Error: %(error)s') % {'boot_mode': boot_mode, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Sets the boot mode of the system for next boot. :param boot_mode: either 'uefi' or 'legacy'. :raises: IloInvalidInputError, on an invalid input. :raises: IloError, on an error from iLO.
entailment
def update_persistent_boot(self, devices=[]): """Changes the persistent boot device order for the host :param devices: ordered list of boot devices :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the given input is not valid. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) # Check if the input is valid for item in devices: if item.upper() not in DEVICE_COMMON_TO_REDFISH: msg = (self._('Invalid input "%(device)s". Valid devices: ' 'NETWORK, HDD, ISCSI or CDROM.') % {'device': item}) raise exception.IloInvalidInputError(msg) try: sushy_system.update_persistent_boot( devices, persistent=True) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to update ' 'persistent boot device %(devices)s.' 'Error: %(error)s') % {'devices': devices, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Changes the persistent boot device order for the host :param devices: ordered list of boot devices :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the given input is not valid.
entailment
def set_one_time_boot(self, device): """Configures a single boot from a specific device. :param device: Device to be set as a one time boot device :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the given input is not valid. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) # Check if the input is valid if device.upper() not in DEVICE_COMMON_TO_REDFISH: msg = (self._('Invalid input "%(device)s". Valid devices: ' 'NETWORK, HDD, ISCSI or CDROM.') % {'device': device}) raise exception.IloInvalidInputError(msg) try: sushy_system.update_persistent_boot( [device], persistent=False) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to set ' 'one time boot device %(device)s. ' 'Error: %(error)s') % {'device': device, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Configures a single boot from a specific device. :param device: Device to be set as a one time boot device :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the given input is not valid.
entailment
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. """ try: acc_service = self._sushy.get_account_service() member = acc_service.accounts.get_member_details(self._username) if member is None: msg = (self._("No account found with username: %s") % self._username) LOG.debug(msg) raise exception.IloError(msg) member.update_credentials(password) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to update ' 'credentials for %(username)s. Error %(error)s') % {'username': self._username, 'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Resets the iLO password. :param password: The password to be set. :raises: IloError, if account not found or on an error from iLO.
entailment
def get_supported_boot_mode(self): """Get the system supported boot modes. :return: 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 :raises: IloError, if account not found or on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: return SUPPORTED_BOOT_MODE_MAP.get( sushy_system.supported_boot_mode) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to get the ' 'supported boot modes. Error: %s') % e) LOG.debug(msg) raise exception.IloError(msg)
Get the system supported boot modes. :return: 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 :raises: IloError, if account not found or on an error from iLO.
entailment
def get_server_capabilities(self): """Returns the server capabilities raises: IloError on an error from iLO. """ capabilities = {} sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID) try: count = len(sushy_system.pci_devices.gpu_devices) boot_mode = rf_utils.get_supported_boot_mode( sushy_system.supported_boot_mode) capabilities.update( {'pci_gpu_devices': count, 'ilo_firmware_version': sushy_manager.firmware_version, 'rom_firmware_version': sushy_system.rom_version, 'server_model': sushy_system.model, 'nic_capacity': sushy_system.pci_devices.max_nic_capacity, 'boot_mode_bios': boot_mode.boot_mode_bios, 'boot_mode_uefi': boot_mode.boot_mode_uefi}) tpm_state = sushy_system.bios_settings.tpm_state all_key_to_value_expression_tuples = [ ('sriov_enabled', sushy_system.bios_settings.sriov == sys_cons.SRIOV_ENABLED), ('cpu_vt', sushy_system.bios_settings.cpu_vt == ( sys_cons.CPUVT_ENABLED)), ('trusted_boot', (tpm_state == sys_cons.TPM_PRESENT_ENABLED or tpm_state == sys_cons.TPM_PRESENT_DISABLED)), ('secure_boot', self._has_secure_boot()), ('iscsi_boot', (sushy_system.bios_settings.iscsi_resource. is_iscsi_boot_supported())), ('hardware_supports_raid', len(sushy_system.smart_storage.array_controllers. members_identities) > 0), ('has_ssd', common_storage.has_ssd(sushy_system)), ('has_rotational', common_storage.has_rotational(sushy_system)), ('has_nvme_ssd', common_storage.has_nvme_ssd(sushy_system)) ] all_key_to_value_expression_tuples += ( [('logical_raid_level_' + x, True) for x in sushy_system.smart_storage.logical_raid_levels]) all_key_to_value_expression_tuples += ( [('drive_rotational_' + str(x) + '_rpm', True) for x in common_storage.get_drive_rotational_speed_rpm(sushy_system)]) capabilities.update( {key: 'true' for (key, value) in all_key_to_value_expression_tuples if value}) memory_data = sushy_system.memory.details() if memory_data.has_nvdimm_n: capabilities.update( {'persistent_memory': ( json.dumps(memory_data.has_persistent_memory)), 'nvdimm_n': ( json.dumps(memory_data.has_nvdimm_n)), 'logical_nvdimm_n': ( json.dumps(memory_data.has_logical_nvdimm_n))}) except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller is unable to get " "resource or its members. Error " "%(error)s)") % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) return capabilities
Returns the server capabilities raises: IloError on an error from iLO.
entailment
def reset_bios_to_default(self): """Resets the BIOS settings to default values. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.bios_settings.update_bios_to_default() except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller is unable to update bios " "settings to default Error %(error)s") % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Resets the BIOS settings to default values. :raises: IloError, on an error from iLO.
entailment
def get_secure_boot_mode(self): """Get the status of secure boot. :returns: True, if enabled, else False :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: secure_boot_enabled = GET_SECUREBOOT_CURRENT_BOOT_MAP.get( sushy_system.secure_boot.current_boot) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to provide ' 'information about secure boot on the server. ' 'Error: %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloCommandNotSupportedError(msg) if secure_boot_enabled: LOG.debug(self._("Secure boot is Enabled")) else: LOG.debug(self._("Secure boot is Disabled")) return secure_boot_enabled
Get the status of secure boot. :returns: True, if enabled, else False :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
entailment
def set_secure_boot_mode(self, secure_boot_enable): """Enable/Disable secure boot on the server. Resetting the server post updating this settings is needed from the caller side to make this into effect. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ if self._is_boot_mode_uefi(): sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.secure_boot.enable_secure_boot(secure_boot_enable) except exception.InvalidInputError as e: msg = (self._('Invalid input. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to set secure ' 'boot settings on the server. Error: %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) else: msg = (self._('System is not in UEFI boot mode. "SecureBoot" ' 'related resources cannot be changed.')) raise exception.IloCommandNotSupportedInBiosError(msg)
Enable/Disable secure boot on the server. Resetting the server post updating this settings is needed from the caller side to make this into effect. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
entailment
def reset_secure_boot_keys(self): """Reset secure boot keys to manufacturing defaults. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ if self._is_boot_mode_uefi(): sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.secure_boot.reset_keys( sys_cons.SECUREBOOT_RESET_KEYS_DEFAULT) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to reset secure ' 'boot keys on the server. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) else: msg = (self._('System is not in UEFI boot mode. "SecureBoot" ' 'related resources cannot be changed.')) raise exception.IloCommandNotSupportedInBiosError(msg)
Reset secure boot keys to manufacturing defaults. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
entailment
def get_essential_properties(self): """Constructs the dictionary of essential properties Constructs the dictionary of essential properties, named cpu, cpu_arch, local_gb, memory_mb. The MACs are also returned as part of this method. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: # TODO(nisha): Add local_gb here and return after # local_gb changes are merged. # local_gb = sushy_system.storage_summary prop = {'memory_mb': (sushy_system.memory_summary.size_gib * 1024), 'cpus': sushy_system.processors.summary.count, 'cpu_arch': sushy_map.PROCESSOR_ARCH_VALUE_MAP_REV.get( sushy_system.processors.summary.architecture), 'local_gb': common_storage.get_local_gb(sushy_system)} return {'properties': prop, 'macs': sushy_system.ethernet_interfaces.summary} except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to get the ' 'resource data. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Constructs the dictionary of essential properties Constructs the dictionary of essential properties, named cpu, cpu_arch, local_gb, memory_mb. The MACs are also returned as part of this method.
entailment
def _change_iscsi_target_settings(self, iscsi_info): """Change iSCSI target settings. :param iscsi_info: A dictionary that contains information of iSCSI target like target_name, lun, ip_address, port etc. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: pci_settings_map = ( sushy_system.bios_settings.bios_mappings.pci_settings_mappings) nics = [] for mapping in pci_settings_map: for subinstance in mapping['Subinstances']: for association in subinstance['Associations']: if 'NicBoot' in association: nics.append(association) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to get the ' 'bios mappings. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) if not nics: msg = ('No nics were found on the system') raise exception.IloError(msg) # Set iSCSI info to all nics iscsi_infos = [] for nic in nics: data = iscsi_info.copy() data['iSCSIAttemptName'] = nic data['iSCSINicSource'] = nic data['iSCSIAttemptInstance'] = nics.index(nic) + 1 iscsi_infos.append(data) iscsi_data = {'iSCSISources': iscsi_infos} try: (sushy_system.bios_settings.iscsi_resource. iscsi_settings.update_iscsi_settings(iscsi_data)) except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller is failed to update iSCSI " "settings. Error %(error)s") % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Change iSCSI target settings. :param iscsi_info: A dictionary that contains information of iSCSI target like target_name, lun, ip_address, port etc. :raises: IloError, on an error from iLO.
entailment
def set_iscsi_info(self, target_name, lun, ip_address, port='3260', auth_method=None, username=None, password=None): """Set iSCSI details of the system in UEFI boot mode. The initiator system is set with the target details like IQN, LUN, IP, Port etc. :param target_name: Target Name for iSCSI. :param lun: logical unit number. :param ip_address: IP address of the target. :param port: port of the target. :param auth_method : either None or CHAP. :param username: CHAP Username for authentication. :param password: CHAP secret. :raises: IloCommandNotSupportedInBiosError, if the system is in the bios boot mode. """ if(self._is_boot_mode_uefi()): iscsi_info = {} iscsi_info['iSCSITargetName'] = target_name iscsi_info['iSCSILUN'] = lun iscsi_info['iSCSITargetIpAddress'] = ip_address iscsi_info['iSCSITargetTcpPort'] = int(port) iscsi_info['iSCSITargetInfoViaDHCP'] = False iscsi_info['iSCSIConnection'] = 'Enabled' if (auth_method == 'CHAP'): iscsi_info['iSCSIAuthenticationMethod'] = 'Chap' iscsi_info['iSCSIChapUsername'] = username iscsi_info['iSCSIChapSecret'] = password self._change_iscsi_target_settings(iscsi_info) else: msg = 'iSCSI boot is not supported in the BIOS boot mode' raise exception.IloCommandNotSupportedInBiosError(msg)
Set iSCSI details of the system in UEFI boot mode. The initiator system is set with the target details like IQN, LUN, IP, Port etc. :param target_name: Target Name for iSCSI. :param lun: logical unit number. :param ip_address: IP address of the target. :param port: port of the target. :param auth_method : either None or CHAP. :param username: CHAP Username for authentication. :param password: CHAP secret. :raises: IloCommandNotSupportedInBiosError, if the system is in the bios boot mode.
entailment
def unset_iscsi_info(self): """Disable iSCSI boot option in UEFI boot mode. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. """ if(self._is_boot_mode_uefi()): iscsi_info = {'iSCSIConnection': 'Disabled'} self._change_iscsi_target_settings(iscsi_info) else: msg = 'iSCSI boot is not supported in the BIOS boot mode' raise exception.IloCommandNotSupportedInBiosError(msg)
Disable iSCSI boot option in UEFI boot mode. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode.
entailment
def set_iscsi_initiator_info(self, initiator_iqn): """Set iSCSI initiator information in iLO. :param initiator_iqn: Initiator iqn for iLO. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if(self._is_boot_mode_uefi()): iscsi_data = {'iSCSIInitiatorName': initiator_iqn} try: (sushy_system.bios_settings.iscsi_resource. iscsi_settings.update_iscsi_settings(iscsi_data)) except sushy.exceptions.SushyError as e: msg = (self._("The Redfish controller has failed to update " "iSCSI settings. Error %(error)s") % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) else: msg = 'iSCSI initiator cannot be updated in BIOS boot mode' raise exception.IloCommandNotSupportedInBiosError(msg)
Set iSCSI initiator information in iLO. :param initiator_iqn: Initiator iqn for iLO. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode.
entailment
def get_iscsi_initiator_info(self): """Give iSCSI initiator information of iLO. :returns: iSCSI initiator information. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if(self._is_boot_mode_uefi()): try: iscsi_initiator = ( sushy_system.bios_settings.iscsi_resource.iscsi_initiator) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller has failed to get the ' 'iSCSI initiator. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) return iscsi_initiator else: msg = 'iSCSI initiator cannot be retrieved in BIOS boot mode' raise exception.IloCommandNotSupportedInBiosError(msg)
Give iSCSI initiator information of iLO. :returns: iSCSI initiator information. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode.
entailment
def inject_nmi(self): """Inject NMI, Non Maskable Interrupt. Inject NMI (Non Maskable Interrupt) for a node immediately. :raises: IloError, on an error from iLO """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if sushy_system.power_state != sushy.SYSTEM_POWER_STATE_ON: raise exception.IloError("Server is not in powered on state.") try: sushy_system.reset_system(sushy.RESET_NMI) except sushy.exceptions.SushyError as e: msg = (self._('The Redfish controller failed to inject nmi to ' 'server. Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Inject NMI, Non Maskable Interrupt. Inject NMI (Non Maskable Interrupt) for a node immediately. :raises: IloError, on an error from iLO
entailment
def get_host_post_state(self): """Get the current state of system POST. Retrieves current state of system POST. :returns: POST state of the server. The valida states are:- null, Unknown, Reset, PowerOff, InPost, InPostDiscoveryComplete and FinishedPost. :raises: IloError, on an error from iLO """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) return GET_POST_STATE_MAP.get(sushy_system.post_state)
Get the current state of system POST. Retrieves current state of system POST. :returns: POST state of the server. The valida states are:- null, Unknown, Reset, PowerOff, InPost, InPostDiscoveryComplete and FinishedPost. :raises: IloError, on an error from iLO
entailment
def read_raid_configuration(self, raid_config=None): """Read the logical drives from the system :param raid_config: None in case of post-delete read or in case of post-create a dictionary containing target raid configuration data. This data stucture should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100, 'physical_disks': ['6I:1:5'], 'controller': 'HPE Smart Array P408i-a SR Gen10'}, <info-for-logical-disk-2>]} :raises: IloError, on an error from iLO. :returns: A dictionary containing list of logical disks """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) return sushy_system.read_raid(raid_config=raid_config)
Read the logical drives from the system :param raid_config: None in case of post-delete read or in case of post-create a dictionary containing target raid configuration data. This data stucture should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100, 'physical_disks': ['6I:1:5'], 'controller': 'HPE Smart Array P408i-a SR Gen10'}, <info-for-logical-disk-2>]} :raises: IloError, on an error from iLO. :returns: A dictionary containing list of logical disks
entailment
def get_current_bios_settings(self, only_allowed_settings=True): """Get current BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of current BIOS settings is returned. Depending on the 'only_allowed_settings', either only the allowed settings are returned or all the supported settings are returned. :raises: IloError, on an error from iLO """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: current_settings = sushy_system.bios_settings.json except sushy.exceptions.SushyError as e: msg = (self._('The current BIOS Settings were not found. Error ' '%(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) attributes = current_settings.get("Attributes") if only_allowed_settings and attributes: return common_utils.apply_bios_properties_filter( attributes, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES) return attributes
Get current BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of current BIOS settings is returned. Depending on the 'only_allowed_settings', either only the allowed settings are returned or all the supported settings are returned. :raises: IloError, on an error from iLO
entailment
def set_bios_settings(self, data=None, only_allowed_settings=True): """Sets current BIOS settings to the provided data. :param: only_allowed_settings: True when only allowed BIOS settings are to be set. If False, all the BIOS settings supported by iLO and present in the 'data' are set. :param: data: a dictionary of BIOS settings to be applied. Depending on the 'only_allowed_settings', either only the allowed settings are set or all the supported settings that are in the 'data' are set. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ if not data: raise exception.IloError("Could not apply settings with" " empty data") sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if only_allowed_settings: unsupported_settings = [key for key in data if key not in ( ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)] if unsupported_settings: msg = ("Could not apply settings as one or more settings are" " not supported. Unsupported settings are %s." " Supported settings are %s." % ( unsupported_settings, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)) raise exception.IloError(msg) try: settings_required = sushy_system.bios_settings.pending_settings settings_required.update_bios_data_by_patch(data) except sushy.exceptions.SushyError as e: msg = (self._('The pending BIOS Settings resource not found.' ' Error %(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg)
Sets current BIOS settings to the provided data. :param: only_allowed_settings: True when only allowed BIOS settings are to be set. If False, all the BIOS settings supported by iLO and present in the 'data' are set. :param: data: a dictionary of BIOS settings to be applied. Depending on the 'only_allowed_settings', either only the allowed settings are set or all the supported settings that are in the 'data' are set. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
entailment
def get_default_bios_settings(self, only_allowed_settings=True): """Get default BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of default BIOS settings(factory settings). Depending on the 'only_allowed_settings', either only the allowed settings are returned or all the supported settings are returned. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: settings = sushy_system.bios_settings.default_settings except sushy.exceptions.SushyError as e: msg = (self._('The default BIOS Settings were not found. Error ' '%(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) if only_allowed_settings: return common_utils.apply_bios_properties_filter( settings, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES) return settings
Get default BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of default BIOS settings(factory settings). Depending on the 'only_allowed_settings', either only the allowed settings are returned or all the supported settings are returned. :raises: IloError, on an error from iLO.
entailment
def create_raid_configuration(self, raid_config): """Create the raid configuration on the hardware. Based on user raid_config input, it will create raid :param raid_config: A dictionary containing target raid configuration data. This data stucture should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100, 'physical_disks': ['6I:1:5'], 'controller': 'HPE Smart Array P408i-a SR Gen10'}, <info-for-logical-disk-2>]} :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) sushy_system.create_raid(raid_config)
Create the raid configuration on the hardware. Based on user raid_config input, it will create raid :param raid_config: A dictionary containing target raid configuration data. This data stucture should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100, 'physical_disks': ['6I:1:5'], 'controller': 'HPE Smart Array P408i-a SR Gen10'}, <info-for-logical-disk-2>]} :raises: IloError, on an error from iLO.
entailment
def get_bios_settings_result(self): """Gets the result of the bios settings applied :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: settings_result = sushy_system.bios_settings.messages except sushy.exceptions.SushyError as e: msg = (self._('The BIOS Settings results were not found. Error ' '%(error)s') % {'error': str(e)}) LOG.debug(msg) raise exception.IloError(msg) status = "failed" if len(settings_result) > 1 else "success" return {"status": status, "results": settings_result}
Gets the result of the bios settings applied :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
entailment
def _get_collection(self, collection_uri, request_headers=None): """Generator function that returns collection members.""" # get the collection status, headers, thecollection = self._rest_get(collection_uri) if status != 200: msg = self._get_extended_error(thecollection) raise exception.IloError(msg) while status < 300: # verify expected type # Don't limit to version 0 here as we will rev to 1.0 at some # point hopefully with minimal changes ctype = self._get_type(thecollection) if (ctype not in ['Collection.0', 'Collection.1']): raise exception.IloError("collection not found") # if this collection has inline items, return those # NOTE: Collections are very flexible in how the represent # members. They can be inline in the collection as members # of the 'Items' array, or they may be href links in the # links/Members array. The could actually be both. Typically, # iLO implements the inline (Items) for only when the collection # is read only. We have to render it with the href links when an # array contains PATCHable items because its complex to PATCH # inline collection members. if 'Items' in thecollection: # iterate items for item in thecollection['Items']: # if the item has a self uri pointer, # supply that for convenience. memberuri = None if 'links' in item and 'self' in item['links']: memberuri = item['links']['self']['href'] yield 200, None, item, memberuri # else walk the member links elif ('links' in thecollection and 'Member' in thecollection['links']): # iterate members for memberuri in thecollection['links']['Member']: # for each member return the resource indicated by the # member link status, headers, member = self._rest_get(memberuri['href']) yield status, headers, member, memberuri['href'] # page forward if there are more pages in the collection if ('links' in thecollection and 'NextPage' in thecollection['links']): next_link_uri = (collection_uri + '?page=' + str( thecollection['links']['NextPage']['page'])) status, headers, thecollection = self._rest_get(next_link_uri) # else we are finished iterating the collection else: break
Generator function that returns collection members.
entailment
def _get_type(self, obj): """Return the type of an object.""" typever = obj['Type'] typesplit = typever.split('.') return typesplit[0] + '.' + typesplit[1]
Return the type of an object.
entailment
def _render_extended_error_message_list(self, extended_error): """Parse the ExtendedError object and retruns the message. Build a list of decoded messages from the extended_error using the message registries. An ExtendedError JSON object is a response from the with its own schema. This function knows how to parse the ExtendedError object and, using any loaded message registries, render an array of plain language strings that represent the response. """ messages = [] if isinstance(extended_error, dict): if ('Type' in extended_error and extended_error['Type'].startswith('ExtendedError.')): for msg in extended_error['Messages']: message_id = msg['MessageID'] x = message_id.split('.') registry = x[0] msgkey = x[len(x) - 1] # if the correct message registry is loaded, # do string resolution if (registry in self.message_registries and msgkey in self.message_registries[registry]['Messages']): rmsgs = self.message_registries[registry]['Messages'] msg_dict = rmsgs[msgkey] msg_str = message_id + ': ' + msg_dict['Message'] for argn in range(0, msg_dict['NumberOfArgs']): subst = '%' + str(argn+1) m = str(msg['MessageArgs'][argn]) msg_str = msg_str.replace(subst, m) if ('Resolution' in msg_dict and msg_dict['Resolution'] != 'None'): msg_str += ' ' + msg_dict['Resolution'] messages.append(msg_str) else: # no message registry, simply return the msg object # in string form messages.append(str(message_id)) return messages
Parse the ExtendedError object and retruns the message. Build a list of decoded messages from the extended_error using the message registries. An ExtendedError JSON object is a response from the with its own schema. This function knows how to parse the ExtendedError object and, using any loaded message registries, render an array of plain language strings that represent the response.
entailment
def _get_host_details(self): """Get the system details.""" # Assuming only one system present as part of collection, # as we are dealing with iLO's here. status, headers, system = self._rest_get('/rest/v1/Systems/1') if status < 300: stype = self._get_type(system) if stype not in ['ComputerSystem.0', 'ComputerSystem.1']: msg = "%s is not a valid system type " % stype raise exception.IloError(msg) else: msg = self._get_extended_error(system) raise exception.IloError(msg) return system
Get the system details.
entailment
def _check_bios_resource(self, properties=[]): """Check if the bios resource exists.""" system = self._get_host_details() if ('links' in system['Oem']['Hp'] and 'BIOS' in system['Oem']['Hp']['links']): # Get the BIOS URI and Settings bios_uri = system['Oem']['Hp']['links']['BIOS']['href'] status, headers, bios_settings = self._rest_get(bios_uri) if status >= 300: msg = self._get_extended_error(bios_settings) raise exception.IloError(msg) # If property is not None, check if the bios_property is supported for property in properties: if property not in bios_settings: # not supported on this platform msg = ('BIOS Property "' + property + '" is not' ' supported on this system.') raise exception.IloCommandNotSupportedError(msg) return headers, bios_uri, bios_settings else: msg = ('"links/BIOS" section in ComputerSystem/Oem/Hp' ' does not exist') raise exception.IloCommandNotSupportedError(msg)
Check if the bios resource exists.
entailment
def _get_pci_devices(self): """Gets the PCI devices. :returns: PCI devices list if the pci resource exist. :raises: IloCommandNotSupportedError if the PCI resource doesn't exist. :raises: IloError, on an error from iLO. """ system = self._get_host_details() if ('links' in system['Oem']['Hp'] and 'PCIDevices' in system['Oem']['Hp']['links']): # Get the PCI URI and Settings pci_uri = system['Oem']['Hp']['links']['PCIDevices']['href'] status, headers, pci_device_list = self._rest_get(pci_uri) if status >= 300: msg = self._get_extended_error(pci_device_list) raise exception.IloError(msg) return pci_device_list else: msg = ('links/PCIDevices section in ComputerSystem/Oem/Hp' ' does not exist') raise exception.IloCommandNotSupportedError(msg)
Gets the PCI devices. :returns: PCI devices list if the pci resource exist. :raises: IloCommandNotSupportedError if the PCI resource doesn't exist. :raises: IloError, on an error from iLO.
entailment
def _get_gpu_pci_devices(self): """Returns the list of gpu devices.""" pci_device_list = self._get_pci_devices() gpu_list = [] items = pci_device_list['Items'] for item in items: if item['ClassCode'] in CLASSCODE_FOR_GPU_DEVICES: if item['SubclassCode'] in SUBCLASSCODE_FOR_GPU_DEVICES: gpu_list.append(item) return gpu_list
Returns the list of gpu devices.
entailment
def _get_storage_resource(self): """Gets the SmartStorage resource if exists. :raises: IloCommandNotSupportedError if the resource SmartStorage doesn't exist. :returns the tuple of SmartStorage URI, Headers and settings. """ system = self._get_host_details() if ('links' in system['Oem']['Hp'] and 'SmartStorage' in system['Oem']['Hp']['links']): # Get the SmartStorage URI and Settings storage_uri = system['Oem']['Hp']['links']['SmartStorage']['href'] status, headers, storage_settings = self._rest_get(storage_uri) if status >= 300: msg = self._get_extended_error(storage_settings) raise exception.IloError(msg) return headers, storage_uri, storage_settings else: msg = ('"links/SmartStorage" section in ComputerSystem/Oem/Hp' ' does not exist') raise exception.IloCommandNotSupportedError(msg)
Gets the SmartStorage resource if exists. :raises: IloCommandNotSupportedError if the resource SmartStorage doesn't exist. :returns the tuple of SmartStorage URI, Headers and settings.
entailment
def _get_array_controller_resource(self): """Gets the ArrayController resource if exists. :raises: IloCommandNotSupportedError if the resource ArrayController doesn't exist. :returns the tuple of SmartStorage URI, Headers and settings. """ headers, storage_uri, storage_settings = self._get_storage_resource() if ('links' in storage_settings and 'ArrayControllers' in storage_settings['links']): # Get the ArrayCOntrollers URI and Settings array_uri = storage_settings['links']['ArrayControllers']['href'] status, headers, array_settings = self._rest_get(array_uri) if status >= 300: msg = self._get_extended_error(array_settings) raise exception.IloError(msg) return headers, array_uri, array_settings else: msg = ('"links/ArrayControllers" section in SmartStorage' ' does not exist') raise exception.IloCommandNotSupportedError(msg)
Gets the ArrayController resource if exists. :raises: IloCommandNotSupportedError if the resource ArrayController doesn't exist. :returns the tuple of SmartStorage URI, Headers and settings.
entailment
def _create_list_of_array_controllers(self): """Creates the list of Array Controller URIs. :raises: IloCommandNotSupportedError if the ArrayControllers doesnt have member "Member". :returns list of ArrayControllers. """ headers, array_uri, array_settings = ( self._get_array_controller_resource()) array_uri_links = [] if ('links' in array_settings and 'Member' in array_settings['links']): array_uri_links = array_settings['links']['Member'] else: msg = ('"links/Member" section in ArrayControllers' ' does not exist') raise exception.IloCommandNotSupportedError(msg) return array_uri_links
Creates the list of Array Controller URIs. :raises: IloCommandNotSupportedError if the ArrayControllers doesnt have member "Member". :returns list of ArrayControllers.
entailment
def _get_drive_type_and_speed(self): """Gets the disk drive type. :returns: A dictionary with the following keys: - has_rotational: True/False. It is True if atleast one rotational disk is attached. - has_ssd: True/False. It is True if at least one SSD disk is attached. - drive_rotational_<speed>_rpm: These are set to true as per the speed of the rotational disks. :raises: IloCommandNotSupportedError if the PhysicalDrives resource doesn't exist. :raises: IloError, on an error from iLO. """ disk_details = self._get_physical_drive_resource() drive_hdd = False drive_ssd = False drive_details = {} speed_const_list = [4800, 5400, 7200, 10000, 15000] if disk_details: for item in disk_details: value = item['MediaType'] if value == "HDD": drive_hdd = True speed = item['RotationalSpeedRpm'] if speed in speed_const_list: var = 'rotational_drive_' + str(speed) + '_rpm' drive_details.update({var: 'true'}) # Note: RIS returns value as 'SDD' for SSD drives. else: drive_ssd = True if drive_hdd: drive_details.update({'has_rotational': 'true'}) if drive_ssd: drive_details.update({'has_ssd': 'true'}) return drive_details if len(drive_details.keys()) > 0 else None
Gets the disk drive type. :returns: A dictionary with the following keys: - has_rotational: True/False. It is True if atleast one rotational disk is attached. - has_ssd: True/False. It is True if at least one SSD disk is attached. - drive_rotational_<speed>_rpm: These are set to true as per the speed of the rotational disks. :raises: IloCommandNotSupportedError if the PhysicalDrives resource doesn't exist. :raises: IloError, on an error from iLO.
entailment
def _get_drive_resource(self, drive_name): """Gets the DiskDrive resource if exists. :param drive_name: can be either "PhysicalDrives" or "LogicalDrives". :returns the list of drives. :raises: IloCommandNotSupportedError if the given drive resource doesn't exist. :raises: IloError, on an error from iLO. """ disk_details_list = [] array_uri_links = self._create_list_of_array_controllers() for array_link in array_uri_links: _, _, member_settings = ( self._rest_get(array_link['href'])) if ('links' in member_settings and drive_name in member_settings['links']): disk_uri = member_settings['links'][drive_name]['href'] headers, disk_member_uri, disk_mem = ( self._rest_get(disk_uri)) if ('links' in disk_mem and 'Member' in disk_mem['links']): for disk_link in disk_mem['links']['Member']: diskdrive_uri = disk_link['href'] _, _, disk_details = ( self._rest_get(diskdrive_uri)) disk_details_list.append(disk_details) else: msg = ('"links/Member" section in %s' ' does not exist', drive_name) raise exception.IloCommandNotSupportedError(msg) else: msg = ('"links/%s" section in ' ' ArrayController/links/Member does not exist', drive_name) raise exception.IloCommandNotSupportedError(msg) if disk_details_list: return disk_details_list
Gets the DiskDrive resource if exists. :param drive_name: can be either "PhysicalDrives" or "LogicalDrives". :returns the list of drives. :raises: IloCommandNotSupportedError if the given drive resource doesn't exist. :raises: IloError, on an error from iLO.
entailment
def _get_logical_raid_levels(self): """Gets the different raid levels configured on a server. :returns a dictionary of logical_raid_levels set to true. Example if raid level 1+0 and 6 are configured, it returns {'logical_raid_level_10': 'true', 'logical_raid_level_6': 'true'} """ logical_drive_details = self._get_logical_drive_resource() raid_level = {} if logical_drive_details: for item in logical_drive_details: if 'Raid' in item: raid_level_var = "logical_raid_level_" + item['Raid'] raid_level.update({raid_level_var: 'true'}) return raid_level if len(raid_level.keys()) > 0 else None
Gets the different raid levels configured on a server. :returns a dictionary of logical_raid_levels set to true. Example if raid level 1+0 and 6 are configured, it returns {'logical_raid_level_10': 'true', 'logical_raid_level_6': 'true'}
entailment
def _is_raid_supported(self): """Get the RAID support on the server. This method returns the raid support on the physical server. It checks for the list of array controllers configured to the Smart Storage. If one or more array controllers available then raid is supported by the server. If none, raid is not supported. :return: Raid support as a dictionary with true/false as its value. """ header, uri, array_resource = self._get_array_controller_resource() return True if array_resource['Total'] > 0 else False
Get the RAID support on the server. This method returns the raid support on the physical server. It checks for the list of array controllers configured to the Smart Storage. If one or more array controllers available then raid is supported by the server. If none, raid is not supported. :return: Raid support as a dictionary with true/false as its value.
entailment
def _get_bios_settings_resource(self, data): """Get the BIOS settings resource.""" try: bios_settings_uri = data['links']['Settings']['href'] except KeyError: msg = ('BIOS Settings resource not found.') raise exception.IloError(msg) status, headers, bios_settings = self._rest_get(bios_settings_uri) if status != 200: msg = self._get_extended_error(bios_settings) raise exception.IloError(msg) return headers, bios_settings_uri, bios_settings
Get the BIOS settings resource.
entailment
def _validate_if_patch_supported(self, headers, uri): """Check if the PATCH Operation is allowed on the resource.""" if not self._operation_allowed(headers, 'PATCH'): msg = ('PATCH Operation not supported on the resource ' '"%s"' % uri) raise exception.IloError(msg)
Check if the PATCH Operation is allowed on the resource.
entailment
def _get_bios_setting(self, bios_property): """Retrieves bios settings of the server.""" headers, bios_uri, bios_settings = self._check_bios_resource([ bios_property]) return bios_settings[bios_property]
Retrieves bios settings of the server.
entailment
def _get_bios_hash_password(self, bios_password): """Get the hashed BIOS password.""" request_headers = {} if bios_password: bios_password_hash = hashlib.sha256((bios_password.encode()). hexdigest().upper()) request_headers['X-HPRESTFULAPI-AuthToken'] = bios_password_hash return request_headers
Get the hashed BIOS password.
entailment